I have updated the second patch, which was about fixing segfaults anyway.

As I already stated: I find it weird that the problem is solved by *incrementing* the reference count of the domain and codomain of an action when the action is deallocated. But it works, i.e., the doctests that used to segfault with #12313 and the old version of the patches run fine with the new patch version.

I need an expert opinion, though, and the full test suite is also to be run.

Concerning memleaks, here is the example from the ticket description.

With #12313 and the patches from here:

sage: import sage.structure.unique_representation
sage: len(sage.structure.unique_representation.UniqueRepresentation.__classcall__.cache)
135
sage:
sage: for i in range(2,1000):
....: ring = ZZ.quotient(ZZ(i))
....: vectorspace = ring^2
....:
sage: import gc
sage: gc.collect()
16641
sage: len(sage.structure.unique_representation.UniqueRepresentation.__classcall__.cache)
227

With #12313 only:

sage: import sage.structure.unique_representation
sage: len(sage.structure.unique_representation.UniqueRepresentation.__classcall__.cache)
151
sage:
sage: for i in range(2,1000):
....: ring = ZZ.quotient(ZZ(i))
....: vectorspace = ring^2
....:
sage: import gc
sage: gc.collect()
3805
sage: len(sage.structure.unique_representation.UniqueRepresentation.__classcall__.cache)
5142

So, it is a clear progress, and IIRC the patches comprise tests against at least one memory leak that is fixed. Needs review!

Apply trac12215_weak_cached_function.patch trac12215_segfault_fixes.patch