Fix a memory leak due to a cycle in refcounts of custom entities.

The faulty code will be simplified anyway, but for now the leak is
fixed.