Presently, #715 + #11521 help not permanently keeping parent in memory. In the process we uncovered a hard-but-consistently triggerable problem with the collection of MPolynomialRing_libsingular. We have only observed the problem on bsd.math.washington.edu, MacOSX 10.6 on x86_64.

The present work-around is to permanently store references to these upon creation, thus preventing collection. It would be nice if we could properly solve the problem (or at least establish that the problem is specific to bsd.math)

the order of tests in the file seems fairly important. You can change and

delete some tests but not others. The likely explanation is that a garbage
collection has to be triggered under the right conditions, so that the memory
corruption (which likely happens upon deallocate somewhere) happens in the right
spot.

The segfault happens in the doctest for CachedMethodCaller._instance_call (line 1038 in the sage source; example_27 in the file ~/.sage/tmp/cachefunc_*.py left after doctesting), in the line

sage: P.<a,b,c,d> = QQ[]

Further instrumentation showed that the segfault happens in
sage/libs/singular/ring. pyx, in singular_ring_new, in the part that copies the strings over.

shows that it's actually the omAlloc call segfaulting. For perturb=7 or higher, the segfault does not happen. For perturb a lower value it does. Given that the omAlloc addresses returned on earlier calls do not seem close to a page boundary, the only way omAlloc can fail is basically by a corrupted freelist an 8-byte bin. Likely culprits:

a double free (although I'd expect that would trigger problems on more architectures)

someone writing out-of-bounds in omAlloc-managed memory.

Perhaps someone claiming an <int>,<int> structure and storing a <void *> in the second one?

Note the <char*> to <long> cast in the print statement. With an <int>, the compiler complains
about loss of precision, but not with <long>. I haven't checked whether
<long> is really 64 bits on this machine, though.
I have tried and the problem seems to persist with the old singular (5.4b0 has a
recently upgraded singular).

It would help a lot if someone could build singular to use plain malloc
throughout and then use valgrind or a similar tool, which should be able to
immediately catch a double free or out-of-bounds error. If the root of the
problem is not OSX-specific, this would even show up on other architectures.

OK, I did a little experiment and tried to build singular with plain malloc rather than omalloc. In principle, omalloc has an --with-emulate... flag, but the API offered in that mode is woefully incomplete for singular use. I tried to extend it a little. Very rough result:

One problem is supplying a memdup, which needs to know the size of an allocated block from its pointer. On BSD, you can use malloc_size for that. On linux one could use malloc_usable_size. The rest is a whole swath of routines that need to be supplied.

The package above is very dirty, but on bsd.math it did provide me with an apparently working libsingular. The singular executable produced didn't seem usable, so keep your old one!

The doctest passes! Not exactly what we were hoping for, but it does make a double-free unlikely. That would have been detected. Corruption after freeing could still be possible, since malloc allocates way bigger blocks, so freelist data is likely missed.

There is of course also the possibility of some routine writing out of bounds, which is less likely to trigger problems with malloc too.

Singular people might be interested in incorporating the changes to omalloc (and preferrably extend them a little bit) so that --with-emulate... becomes a viable option for Singular debugging. Then you can valgrind singular code.

I am not sure if changing to malloc is an acceptable option for Singular.

I am sure it is not acceptable for production, but being able to swap out omalloc for debugging can be very useful. That's why I tried. I understand that there are great tools to do memory management debugging and omalloc puts them all out of play because it hides all memory alloc/free activity.

It seems omalloc has its own tools but I wasn't able to get them working, I've seen indications that they don't work on 64 bits, and there's a good chance they're not as good as the general ones because they're for a smaller market.

I'm sure someone more familiar with the Singular and omalloc code bases can make a more informed decision on whether having the option of straight malloc memory management for debugging is worthwhile. My initial finding is that it quite likely can be done with relatively small modifications. I got it to more or less work in an evening, while being unfamiliar with the code.

Both these machines exhibit the same problem that on 5.4b0 + #715 + #11521, the doctest for cachefunc.pyx segfaults in the same spot.
Note that the iMac claims to not have a 64-bit kernel. Sage is compiled to be 64-bit on that machine, though (and seems to work).

Have we actually established that this bug does not occur on newer OSX versions?

Have we actually established that this bug does not occur on newer OSX versions?

And have we actually established that this problem does not occur with older Singular versions? I am not totally sure, but I think the problem with #715+#11521 first emerged in sage-5.4.beta0, when Singular-3-1-5 was merged.

I have tried and the problem seems to persist with the old singular (5.4b0 has a recently upgraded singular).

In the mean time, a bit of googling led me to OSX's "GuardMalloc?". While sage+singular-malloc does not crash on the doctest, it does crash when run with

export DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib

Since gmalloc is a memory manager that places each allocation on its own page with protected/unmapped memory as close as possible around the block and that unmaps the block as soon as freed (I'm just parroting the manpage), a segfault is likely due to an access-after-free or access-out-of-bounds -- the one that would normally cause the corruption and then the segfault much later. (that's the whole idea of replacing omalloc -- I don't think it's doable to get omalloc to segfault on an access-after-free). This all comes at a significant speed penalty of course, so experiments are painful and I wouldn't even be able to interpret the backtrace/coredump if I got it (I'd hope that the gmalloc-induced segfault would be reproducible in gdb). It would really be useful if the test file would be pared down to an absolute minimum. That's basically just a backtracking search on which elements can be removed while still triggering a segfault.

However, I think this is a strong indication that there is a real memory violation at the base of this and that it is tracable.

Then, I ran python -t on the segfaulting test. Observation: It happens precisely twice that "WARNING" is printed, i.e., the __dealloc__ method is called even though there remain multiple references to the underlying libsingular ring.

In both cases it is QQ['a','b','c','d']. Here is a snipped from the output:

However, I am not totally sure whether this indicates a problem, because in both cases the remaining references are immediately removed. Also, it is always the case that 4 references are set to the libsingular ring before actually creating the polynomial ring in Sage.

One last observation: You may notice a libsingular ring at address 4409549416 that is referenced here as well, aparently in the middle of the construction of QQ['a','b','c','d']. It is later used for QQ['x','y','z']. The last report before the segfault is

One last observation: You may notice a libsingular ring at address 4409549416 that is referenced here as well, aparently in the middle of the construction of QQ['a','b','c','d']. It is later used for QQ['x','y','z']. The last report before the segfault is

Now let's run the doctests with singular-using-malloc. Result: No segfault. OSX comes with gmalloc, which is a guarded malloc for debugging purposes. It places every allocation on a separate page and unmaps that page upon freeing. So, any access-after-free leads to a segfault. Now we do get a segfault and it happens a lot sooner than example_27. In fact, now the segfault survives in gdb. The error happens when executing

G = I.groebner_basis()###line 921:_sage_ >>> G = I.groebner_basis()

Here's a session with gdb once the segfault has happened. I think I have been able to extract enough data to point at the probably problem.

The evidence points absolutely to currRingHdl.data.uring pointing to unallocated (probably freed) memory. The access then of course can have all kinds of effects. At this point it is probably doable for a LibSingular expert to reason about the code whether uring should always be valid at this point (I suspect not).

It looks suspicious to me that sage.libs.singular.ring.singular_ring_delete does do a careful dance to zero out the currRing variable but doesn't seem to care about currRngHdl. I also find it worrying that there apparently is a refcount system right on the ring structures (as you can see above) and yet in singular_ring_delete a separate refcounting dict is used. One would think the same refcounting system should be borrowed by singular_ring_new and singular_ring_delete. It looks to me the code above thinks that by increasing ...uring.ref the reference is protected, but singular_ring_delete doesn't seem to take into account this refcount. It could well be that I'm misinterpreting the code and that this is all perfectly safe, though.

Libsingular specialists: Keep in mind that in principle, singular code can get executed in rather awkward moments, possibly as part of clean-ups of circular garbage and call-backs on weakref cleanup, where equality might be tested of objects that are soon to be deallocated themselves.

The fickleness of the bug is consistent with this condition arising during a cyclic garbage collection with just the right amount of junk around. That would make the occurrence of the bug depend on just about everything in memory. Or at least if you depend on the corruption leading to a segfault, it depends on which location exactly gets corrupted.

I think we might be getting close to a badge for debugging excellence here!

OK, two independent patches. Either prevents the segfault. I may just have removed the symptom, but not the cause.

If I'm correctly understanding the problem, trac_13447-consolidated_refcount.patch​ should be the preferred solution. However, my unfamiliarity with (lib)singular's intricacies might have caused an oversight somewhere. I think my interpretation is consistent with the use in sage.lib.singular.function.call_function, which is my main source of inspiration.

If people agree, we can clean out the cruft remaining from the refcounting method implemented locally.

I didn't test the patch yet. However, it seems very straight forward to me: There already is a refcounting, and thus one should use it. I am Cc'ing Volker Braun and Martin von Gagern, the authors of #11339. Does trac_13447-consolidated_refcount.patch​ make sense to you as well?

With the new refcounting, I think it could be that currRingHdl.data.uring holds the last reference to a ring. In fact, it seems that was the source of the segfaults. If that reference is removed in call_function, shouldn't we delete the ring? The naive solution

seems to have no ill effect (I put a print statement there that did produce some output, so it does happen), but perhaps I'm overlooking something. Are there other places where references are liable to be lost?

Hence, the way how one refcounts libsingular rings influences the dimension of Hecke modules. Strange at least...

Note, however, that the value returned by the "dimension()" method above is not constant, because it only returns a lower bound (if I recall correctly) that is increased when one learns more about the Hecke module. Hence, it could very well be that ModularSymbols(20,2).boundary_space() used to be cached but is now garbage collected, so that information on the dimension is lost.

I have seen that error before, with other work-arounds (and I think also with singular-malloc), so if it's indeed only a lower bound, then sage has merely changed. It's not an error. If you're worried you can see where that dimension is computed and put a hard ref in the creation of the relevant object. If garbage collection is the cause of the observed amnesia, a hard ref should "solve" it. In that case you can just change the doctest answer.

The second error is apparently ignored and only printed to stderr:

Exception AttributeError: AttributeError('PolynomialRing_field_with_category' object has no attribute '_modulus',) in ignored
Exception AttributeError: AttributeError('PolynomialRing_field_with_category' object has no attribute '_modulus',) in ignored

This is a worrisome error because it's fickle. One a linux x86_64 box, get this reliably in sage/rings/polynomial/multi_polynomial_libsingular.pyx. When I let it print the lines it's doctesting I get:

so it happens when doctesting line 1923. These are probably errors encountered during a dealloc, so it might be happening in a garbage collection. It could also be a WeakValueDict deletion callback that's trying to do a comparison that fails. Googling shows that you've asked about that exact error message on cython-users on 27 January, 2012, so if you solved the bug that led to that question then, perhaps you can also solve this one. It could also be a straight memory corruption. [edit:] OK that was on #11521. You didn't really find that error. You just made it go away by inserting a garbage collection. The good news is that this makes it not so likely that the patch here is causing a new memory corruption. It's more likely a lingering issue that once again gets triggered.

I have seen that error before, with other work-arounds (and I think also with singular-malloc), so if it's indeed only a lower bound, then sage has merely changed. It's not an error.

I am not a number theorist, but I have learnt from the code that the dimension is computed from the number of "cusps". Hence, if one adds the compution of cusps to that test and assigns the involved Hecke modules to variables, then the tests pass:

Exception AttributeError: AttributeError('PolynomialRing_field_with_category' object has no attribute '_modulus',) in ignored
Exception AttributeError: AttributeError('PolynomialRing_field_with_category' object has no attribute '_modulus',) in ignored

This is a worrisome error because it's fickle.
...
so it happens when doctesting line 1923. These are probably errors encountered during a dealloc, so it might be happening in a garbage collection. It could also be a WeakValueDict deletion callback that's trying to do a comparison that fails.

Agreed.

Googling shows that you've asked about that exact error message on cython-users on 27 January, 2012, so if you solved the bug that led to that question then, perhaps you can also solve this one.

Yes, but that question was a pure Cython question, namely like: "Wouldn't it be a good idea to print the function name in which an error was ignored, rather than printing an empty string? That would help debugging."

It could also be a straight memory corruption. [edit:] OK that was on #11521. You didn't really find that error.

Yes. But if it surfaces again, we should now solve it for good. I guess deletion from a weak dictionary is a likely candidate.

A polynomial p in a polynomial ring R is about to be garbage collected.

All python stuff is deleted first. In particular, p's reference to its parent R is gone.

Incidentally, because the reference from p to R is gone, R can now be collected as well.

When R gets deleted, its underlying libsingular ring is deallocated.

Now, p.__dealloc__ is finally called, and tries to access the underlying libsingular ring - but it is too late.

Question: If a polynomial is created, will the reference counter to the underlying libsingular ring be incremented?

From what I understand, __dealloc__ methods cannot assume that python attributes are still valid. They fundamentally cannot, because otherwise it wouldn't be possible to clean up cyclic garbage (__del__ methods are run when all attributes are valid and hence if they are present in cyclic garbage, it is not cleared).

So, I think that if the libsingular ring pointer is necessary during deallocation of a polynomial, then it should store it in a c-variable. Then it would indeed need to increase the reference counter.

You'd initially think that you could store a "c level" pointer to the python polynomial ring and manually increase the refcount. That would ensure that the python polynomial ring is still alive when __alloc__ gets called. However, it would also mean that there is an extra refcount that the cyclic garbage detector wouldn't be able to explain, so polynomial rings would always appear to have an "external" reference and hence never be eligible for garbage collection. Since rings tend to cache 0 and 1, such references would always be present and all you work would be for naught: Polynomial rings would exist forever.

So I think you have to bite the bullet and ensure that get_cparent doesn't access any python attributes or that you can avoid calling it in a __dealloc__.

EDIT: Or perhaps not. While looking at the code a bit I concluded I don't understand a bit of it, due to the templating. I think what I wrote above has some truth to it, but I honestly cannot say whether it has any relevance to the problem at hand. It seems to explain what you're experiencing.

The _parent attribute is a cython slot. However, it holds a reference to a python-managed object, so I think cython ensures it's properly taken into account in GC cycle counting. But that would suggest to me python could clear this slot to break cycles! So in that case, Polynomial_template is never safe. It could be I'm wrong, however.

I haven't been able to locate what parent._modulus is in this case. However,

I guess we've just found that this is not a very good place to store _modulus. Where else, though? Would it be enough to have a cythonized version of PolynomialRing_field so that _modulus can be tied a little tighter to the parent? It seems to me the parent is the right place to store this information. We just need to convince the parent to hold on to its information for a bit longer.

Interestingly, there is no complaint about a missing attribute _parent. It is _modulus that is missing.

However, it holds a reference to a python-managed object, so I think cython ensures it's properly taken into account in GC cycle counting. But that would suggest to me python could clear this slot to break cycles! So in that case, Polynomial_template is never safe. It could be I'm wrong, however.

I think you are right. The __dealloc__ of Polynomial_template is unsafe, unless polynomial rings will stay in memory forever. But I'd love to hear that we are wrong, because otherwise each polynomial would need a pointer to the c-data expected to be returned by get_cparent((<Polynomial_template>self)._parent), and we'd need to take into account reference counting for the c-parent during creation and deletion of polynomials.

Or perhaps there is a way out. We have a polynomial ring R and we have some elements a,b,c,... Each element points to R, and R points to some of its elements, namely to its generators. The problem is that deallocation of the elements is only possible as long as R is alive.

If we'd manually incref R upon creation of an element x, decrefing R when x gets deallocated, then we would ensure that R will survive until the last of its elements is deleted. Or would that mean that the elements will survive as well, because of the reference from R to its generators? Edit: Yes it would.

This should really only be happening upon deletion anyway and I I'd be surprised if having the correct _modulus is very important at that point. It's a dirty hack but alternatives probably mean a full reimplementation of these polynomial rings.

YAY! indeed, returning NULL seems to solve the problem. I don't know whether there are any other ill effects, but since NULL was already returned upon missing parent, I think that with an incomplete parent it's an appropriate value too. It seems the NTL wrapper was already written with the possibility in mind of not having a valid parent around.

Report Upstream
changed from Reported upstream. No feedback yet. to None of the above - read trac for reasoning.

Great! I didn't expect that NULL would work here, because, after all, c-data of a polynomial is supposed to be deallocated with the help of c-data of a polynomial ring celement_destruct(&self.x, get_cparent((<Polynomial_template>self)._parent)) - but if someone has already thought of the possibility that the parent is invalid, then doing the same with an invalid parent._modulus seems the right thing to do.

While we are at it, I changed the "Reported Upstream" field, because it isn't an upstream bug, after all.

A bit later today, I will also provide a patch fixing the Hecke module dimensions, as in comment:23. Do you want me to ask a number theorists whether the fix ("Compute the cusps, which implies that the dimension is computed as well") is mathematically correct? Or is it enough for you that the same number as before (dimension 6) is obtained?

Work issues
changed from Input from libsingular experts to Input from a libsingular expert

I have provided a new patch, that removes the custom refcounter, using Singular's refcounter (ring.ref) instead.

As I have announced, I also fixed the failing modular symbols test, by computing the dimension before displaying it: The test previously worked only because a computation happened in a different test that happened to be executed early enough, that side effect being possible because Hecke modules would stay in memory permanently.

I did not run the full test suite yet. But sage/rings/polynomial/plural.pyx and sage/rings/polynomial/multi_polynomial_libsingular.pyx and sage/modular/modsym/ambient.py all work.

Problems for the release manager and the reviewer:

I removed the custom refcounting. But there were tests using the custom refcounters. The original tests demonstrated that the underlying c-data (the libsingular ring) is properly deleted. I replaced them by tests showing that the MPolynomialRing_libsingular get garbage collected. Is that OK from your point of view?

The mentioned tests will only work with #715 and #11521, because they are responsible for making polynomial rings garbage collectable. Hence, #13447 and #715 and #11521 need to be merged together; just having #715 and #11521 would result in the OS X problem we encountered, and #13447 alone would have two failing tests.

#13145 has already been merged in sage-5.4.beta1. I suggest to unmerge it, because it uses the old unreliable "double refcount" approach. My new patch also takes care of refcounting of plural rings.

Of course, the question is whether we really need to incref the ring if we create an element. I think, in the commutative case, it is needed, because deallocation of an element refers to the cparent.

It could be that in the non-commutative case we have already a work-around:

def __dealloc__(self):
# TODO: Warn otherwise!
# for some mysterious reason, various things may be NULL in some cases
if self._parent is not <ParentWithBase>None and (<NCPolynomialRing_plural>self._parent)._ring != NULL and self._poly != NULL:
p_Delete(&self._poly, (<NCPolynomialRing_plural>self._parent)._ring)

I think we could leave it like that, for now. If someone feels it is needed, then he/she may change NCPolynomial_plural to use templates.

I think all the wrap_ring and ring_wrapper stuff can go from polynomial_libsingular. I think this was only there to provide a dictionary key for the ring_refcount_dictionary. Any code that uses it is liable to require change anyway, so deleting it is probably a good thing.

I think all the wrap_ring and ring_wrapper stuff can go from polynomial_libsingular. I think this was only there to provide a dictionary key for the ring_refcount_dictionary. Any code that uses it is liable to require change anyway, so deleting it is probably a good thing.

Sure. I am about to prepare a new patch version, that uses singular_ring_reference and singular_ring_delete consequently (and not with a manual ..._ring.ref += 1, as in sage.libs.singular.function).

There is one nasty detail with singular_function. If one sets ring = singular_function('ring') and then uses the singular_function to create a ring, then its reference counter is not incremented, even though the following function is called in this case:

Patches look good to me, so a positive review from me for Simon's patches.

I've attached a further patch to clean up some more details. Doctests pass for me, but Simon should look at it and decide if he's happy with it. Please go ahead and amend as you see necessary. I also have no problem with the patches being unified (we have some very small patches here now)

For the record: Apparently it is impossible to use the "proper" singular_ring_delete function in the code snipped mentioned in comment:44. I guess the problem is that singular_ring_delete will set currRing=None in certain situations - hence, the next line currRingHdl.data.uring = singular_ring_reference(currRing) will fail with a segfault.

On the other hand: I'd really like to understand why it doesn't work with singular_ring_delete in this case.

I found that the segfault occurs inside singular_ring_delete(currRingHdl.data.uring) when attempting to change to currRingHdl.data.uring. So, apparently, currRingHdl.data.uring is invalid at that point. And this is hardly surprising, because it is created by the following lines, which look like a hack to me:

currRingHdl = enterid("my_awesome_sage_ring", 0, RING_CMD, &IDROOT, 1) has the purpose to create currRingHdl (it is only called if currRingHdl==NULL), but the value assigned to currRingHdl.data.uring is invalid. In particular, the attempt to change to currRingHdl.data.uring results in a segfault. Hence, singular_ring_delete(currRingHdl.data.uring) would not work.

Solution: We create currRingHdl, but we immediately delete the invalid currRingHdl.data.uring and replace it by a new reference to currRing. If there is no currRing then I print a warning, but I hope that we will never see that warning...

I'd assume IDRING(newRingHdl) is newRingHdl.data.uring, so the assignment above does not assume anything about that field being initialized. So who knows where newRingHdl.data.uring.ref points!

I get the impression that indeed, currRing is set to something valid nearly always, so your assumption that it is during SingularFunction.__init__ (that's earlier than calling!) might be OK. The singular code does contain an awful lot of currRing!=NULL checks though, so I'm not so sure that's really guaranteed.

OK, a little searching of the Singular source shows that enterid (which takes 6 arguments but we call it with 5 and so does the above example) apparently calls idrec::set, in our case with init=1 and the example above with init=0. The init=1 causes a call idrecDataInit and for a ring command that does omAlloc0Bin(sip_sring_bin). The resulting pointer gets indeed assigned to what I think is ...data.uring (although not in a very typerespecting way, but I guess that's par for C code).

So my guess is that by calling with init=1 we indeed get a block that we can delete. Since that's all we do with it I think the cleaner way for us would be

which is in step with our use of the ref field. But the code is commented out! There is such a thing as an intrusive_ptr in Boost and I think it needs exactly those two functions declared to function. If this is what is intended then we're OK. If this is commented out because now a different scheme is used, we may be in trouble.

I find the ptr_release a little worrisome: Do the singular people believe that r->ref ==0 means that there is still a reference? Do they really want to count references "-1"-based? I guess one can count it as "additional" references. I'm afraid they might. From
Singular/ipshell.cc:

this code all indicates that special action is required only if ref<=0 'before' decreasing. Can you check with singular people if that's the correct usage of the ref field? If we use it in a different way I image nasty bugs could arise later (our use would prevent singular from ever deleting a ring we've had our hands on (if it would ever do that) and if we get a ring that singular initially constructed, we could delete it prematurely, due to an off-by-one.

In that case we should probably ensure that singular_ring_ref and singular_delete_ring are somehow aliased to boost::intrusive_ptr_add_ref and intrusive_ptr_release from kernel/Number.h.

According to the code snipped, the ring is deleted if r->ref==0. So, apparently r->ref==0 means that there is no reference.

Indeed, but this is tested before decrement. So for this to work, you'd need

R=create_ring_with_appropriate_refcount
// here R.ref should be 0
//for the following to cause deletion.
intrusive_ptr_release(R)

We initialize R.ref=1 in singular_ring_new.

If ref<=0 then no reference is left, hence, the ring is deleted. Otherwise, the reference counter is decremented. I really don't understand the problem.

If ref<=0 BEFORE the reference count is decreased. The difference is that intrusive_ptr_release happily leaves a ring in memory that AFTER the call has R.ref==0. Our singular_ring_delete will only abstain from calling rDelete(doomed) if after the call we have doomed.ref > 0.

401 doomed.ref = doomed.ref-1
402 if doomed.ref > 0:
403 return

The two behaviours are off-by-one.

Singular tests whether ref<=0; if it is, then the ring is deleted, but if it isn't then the counter is decremented.

We first decrement the counter, and then test whether ref<0; if it is, then the ring is deleted, but if it isn't then no further action is taken.

We don't. We test whether ref<=0 (or rather whether ref>0 to see if we should do an early exit).

As our doctests show, apparently we're never calling singular_ring_delete on rings we haven't initialized the ref field on ourselves and that singular expects to to survive after we do, since that would probably lead to an error (Singular would try to access a deallocated ring).

A mismatch in the other direction would be milder: Singular takes a reference on a ring we initialized the ref field on, we lose our last reference via a singular_ring_delete (no rDelete gets called because Singular correctly increased the refcount). However, Singular will never delete the ring because we originally initialized the ref field to 1 whereas Singular apparently expects it to be initialized to 0.

I am sure that it is not safe: One can't even call singular_ring_delete on it. That's why I removed it, unless currRing==NULL.

I think that's because singular_ring_delete does a changeCurrentRing on it. Calling rDelete seems to work just fine. I think that thanks to the init=1 the memory for the ring is allocated, but initialized to 0 thanks to the omAlloc0. My failure to locate a ref = 1 anywhere in Singular's code also makes me believe that they're happy giving back a ring where ref = 0.

I'm not so sure the rChangeCurrRing dance is necessary in singular_ring_delete. The code in intrusive_ptr_release doesn't need it. I suspect Volker put it in as an extra precaution while he was trying to debug other issues. A cursory reading of the code of rDelete doesn't seem to indicate its operation is affected in any way by whether the current ring is equal to the one being deleted.

There are locally generated rings (in std, for example), unbeknownst to the interpreter - they have ref zero.

Singular uses r->ref only in rKill - it makes me wonder why we use rDelete and not rKill, by the way. In fact, rKill deletes local data, but rDelete doesn't.

Generally, one should have currRingHdl.ring == currRing, or currRing==NULL and currRingHdl==NULL. I just notice that he wrote currRingHdl.ring, not currRingHdl.data.uring - is that a difference?

Concerning debugging: If one builds Singular so that OM_NDEBUG is not defined, then a debug version of omalloc is used. In that way, we would have more easily detected the original problem with omStrDup.

Conclusions

I am not sure if you agree with my conclusions, but here we go:

Since r->ref does not play a rôle in libsingular, we are free to use r->ref to count the number of pointers to r (not "number of pointers minus one"). However, when calling singular interpreter functions, we must make sure that r->ref>0. With our patch, we already do so - hence, that's fine.

Since we apply singular_ring_delete to non-commutative (quotient) rings, and we do not call rKill but only rDelete, we currently have a memory leak for non-commutative rings. rKill will first test that r->ref==0, then kills local data, then kills the ring, and sets currRing and friends to NULL if the to-be-deleted ring is currRing. Hence, we should use rKill in singular_ring_delete, but probably without the rChangeCurrRing dance.

If currRing==NULL, we should not create currRingHdl. If currRing!=NULL then we should let uring point to it. the latter is already done in my patch, the former should be done.

So far I forgot to ask Hans about enterid("my_awesome_sage_ring", 0, RING_CMD, &IDROOT, 1).

Since we apply singular_ring_delete to non-commutative (quotient) rings, and we do not call rKill but only rDelete, we currently have a memory leak for non-commutative rings.

Or perhaps we do not have a leak. Namely, the internal data are also referenced via python, and thus will be deleted when the ring is deleted.
Well, let's see if rKill results in segfaults (due to the attempt to deallocate the internal data twice)...

currRingHdl is only created if currRing!=NULL, and currRingHdl.data.uring is subsequently set to currRing.

singular_ring_delete is now using rKill in lieu of rDelete, so that local data are guaranteed to be deallocated.

In my previous comment, I was a bit sceptical about the second point. However, all doctests pass on bsd.math, hence, using rKill does not result in a segfault. In other words, the local data are not double-freed, und thus rKill is better than rDelete.

global currRingHdl
if currRingHdl == NULL and currRing!=NULL:
# Create an invalid mock ring - it would not be possible
# to make that ring currRing!
# The only aim is to create currRingHdl
currRingHdl = enterid("my_awesome_sage_ring", 0, RING_CMD, &IDROOT, 1)
# Now we assign proper data to currRingHdl
rDelete(currRingHdl.data.uring)
currRingHdl.data.uring = singular_ring_reference(currRing)

He says that it is ok like that. However, it would be better to do

global currRingHdl
if currRingHdl == NULL and currRing!=NULL:
# Create an invalid mock ring - it would not be possible
# to make that ring currRing!
# The only aim is to create currRingHdl
currRingHdl = enterid("my_awesome_sage_ring", 0, RING_CMD, &IDROOT, 0)
# Now we assign proper data to currRingHdl
currRingHdl.data.uring = singular_ring_reference(currRing)

The difference between enterid(...,0) and enterid(...,1) is that the former does not allocate memory for currRingHdl.data.uring, while the latter does. Hence, using enterid(..., 0), one avoids the useless call to rDelete.

If we init with currRing == NULL we may be leaving currRingHdl == NULL. If a subsequent invocation of call happens after currRing has a new value and currRingHdl is not updated (if that would never happen we wouldn't need this code) we'd be calling

which will segfault (OK, this error is much better than the original).

From what you describe, rKill can set currRingHdl=NULL as well, in which case we definitely get an error in the above code. Thus it seems to me it's theoretically possible that __call__ happens when currRingHdl=NULL and currRing!=NULL. In that case you should recreate a handle:

I think that without extra assumptions you must be prepared to deal with all those conditions. Also note that you might be creating a new ringhandle an arbitrary number of times, so knowing whether you leak becomes important. The sequence I use above is what i think the libsingular examples that are shipped with singular do.

You can already see here that the use of rKill (which does look at reference counts) forces us to follow Singular's conventions of what the ref field. At this point we're assuming that if currRingHdl holds the last reference to a ring, we should probably delete it.

I think the convention is that currRingHdl (if it's relevant) is pointing to the same ring as currRing, so they are treated as one reference: currRingHdl.data.uring = currRing does not increase a refcount. That obviously leads to problems when currRing diverges from currRingHdl.

Either you attach memory management ONLY to currRingHdl and trust that when currRing is changed, someone else will still have a reference to the original value, who can throw away the ring (so, currRing is only changed by straight assignments -- no increfs or decrefs. It's always a borrowed reference) or you always ensure that currRingHdl gets updated (or at least cleared) when currRing changes. My impression is that refcounting in singular is only an interpreter thing, so that the former is the model used by Singular itself.

Double free implies segfault: Have you verified this is true with omAlloc?

Refcounting base: I agree that as long as our created rings and rings created internally live separate lives, it doesn't matter what semantics we attach to the ref field. I just think it's dangerous to implicitly assume these rings do live separate lives. They do now, but who's to guarantee that they do in the future? And even then it may take a long time for a visible error to occur, which by then might be difficult to track down. I think we should adjust to the semantics Singular uses in other places (and document the slightly unusual refcounting semantics of Singular in our code!) to make the libsingular interface as robust as possible. You know how extensions/modifications are going to happen: people will just copy/paste what's already there.

There are locally generated rings (in std, for example), unbeknownst to the interpreter - they have ref zero.

Singular uses r->ref only in rKill - it makes me wonder why we use rDelete and not rKill, by the way. In fact, rKill deletes local data, but rDelete doesn't.

If we do that, we should ensure that rKill has an accurate view of the number of references. That means adjusting to Singular's conventions. If we rKill with our current code, we'd leak because we'd call with a positive refcount. I guess you could manually decref before calling rKill but that's silly and misleading to future maintainers of the code.

Generally, one should have currRingHdl.ring == currRing, or currRing==NULL and currRingHdl==NULL. I just notice that he wrote currRingHdl.ring, not currRingHdl.data.uring - is that a difference?

I don't think the former actually exists. A macro is used in the singular code base, so Hans would not usually spell it out in full.

Concerning debugging: If one builds Singular so that OM_NDEBUG is not defined, then a debug version of omalloc is used. In that way, we would have more easily detected the original problem with omStrDup.

Didn't work for me but I might have just failed to properly (de)activate those flags. Anyway, I doubt an access-after-free would be immediately detected. That really involves unmapping or protecting memory in order to force a segfault. I didn't see evidence that omAlloc reaches that deep into the system. It may be that omAlloc in debugging mode does consistency checks on every use. In that case we might have found the corruption a little earlier. I doubt we would have had gdb point exactly at the offending instruction. I think it would be nice for singular to update the omAlloc headers with my changes so that (at least on linux and OSX) they can build it with the malloc underneath. I found it very useful for this particular issue.

Conclusions
Since r->ref does not play a rôle in libsingular, we are free to use r->ref to count the number of pointers to r (not "number of pointers minus one"). However, when calling singular interpreter functions, we must make sure that r->ref>0. With our patch, we already do so - hence, that's fine.

In principle yes, but not if we use rKill and I think it's a bad idea in general because it might cause unforeseen problems in the future. Better to stick with one interpretation of what the ref field means.

If currRing==NULL, we should not create currRingHdl. If currRing!=NULL then we should let uring point to it. the latter is already done in my patch, the former should be done.

As you indicate, currRingHdl can be NULLed again by rKill. We need to correct that if we need currRingHdl later.

In fact, without extra infrastructure to clean up after it, it seems that rKill leaks ringhandles. Is it the case that ring handles are registered in some global data structure that allows them to be deleted? This loop might be the candidate:

while (r->idroot!=NULL)
{
killhdl2(r->idroot,&(r->idroot),r);
}

that might do this. In any case, rKill just does a straight currRingHdl=NULL if (r==currRing), so currRingHdl is definitely gone.

Is it really necessary to use rKill? It seems it is more part of the interpreter layer and that the libsingular interface itself is largely one level lower. Have we initialized enough of the interpreter to let rKill function as advertised?

It is by now clear that up to now, the Sage-libsingular interface was largely based on empirically verified guesses. Now that Simon has good contact with Hans, perhaps we can ensure the interface follows official protocol?

Singular uses r->ref only in rKill - it makes me wonder why we use rDelete and not rKill, by the way. In fact, rKill deletes local data, but rDelete doesn't.

If we do that, we should ensure that rKill has an accurate view of the number of references. That means adjusting to Singular's conventions. If we rKill with our current code, we'd leak because we'd call with a positive refcount.

No, we don't. With the current patch, rKill is only called if ref==0.

Conclusions
Since r->ref does not play a rôle in libsingular, we are free to use r->ref to count the number of pointers to r (not "number of pointers minus one"). However, when calling singular interpreter functions, we must make sure that r->ref>0. With our patch, we already do so - hence, that's fine.

In principle yes, but not if we use rKill

I disagree, since we only call rKill with r->ref==0.

and I think it's a bad idea in general because it might cause unforeseen problems in the future. Better to stick with one interpretation of what the ref field means.

In a way, we do. Namely, one could argue that a Sage polynomial ring MPolynomialRing_libsingular is an interpreter variable (roughly, it is an object that does not live in the Singular kernel but points to a ring in the Singular kernel). Hence, when creating a polynomial ring, it agrees with Singular's conventions to increase the refcount.

As you indicate, currRingHdl can be NULLed again by rKill. We need to correct that if we need currRingHdl later.

currRingHdl is only NULLed if currRing is deleted. So, that should be fine.

In any case, rKill just does a straight currRingHdl=NULL if (r==currRing), so currRingHdl is definitely gone.

You mean, it doesn't free it before assigning NULL? Yes, that would seem to be a leak.

Is it really necessary to use rKill? It seems it is more part of the interpreter layer and that the libsingular interface itself is largely one level lower.

I'll try rKill versus rDelete in singular_ring_delete and will try to see if there is a leak when creating and deleting super commutative rings (SCA).

The singular function rKill seems to do what we want in singular_ring_delete. Hence, to keep it simple, singular_ring_delete should call rKill, and nothing more (unless we want a sanity test, such as printing a warning if singular_ring_delete is called on NULL).

rKill only takes action if r->ref is zero when it is called. Indeed, according to Hans, r->ref is the number of interpreter variables pointing to a ring, minus one. In order to avoid confusion, we should follow the same idea.

So, what means "interpreter variables" for us? I think this should be "any Sage object whose deallocation needs the libsingular ring being alive". This is every polynomial ring, every Gröbner strategy, and any element of a polynomial ring.

Since ref is -1 based, when a Sage ring R is created then ref shall be zero, so that the underlying libsingular ring can be properly deleted if R is deallocated. And if any element or Gröbner strategy on that ring is created, ref needs to be incremented. The deallocation of an element or Gröbner strategy must involve a call to singular_ring_delete.

A complication arises when calling a singular_function. When we call a Singular interpreter function, then we should have ref>0, again according to Hans. Hence, at the begin of a call, ref must be incremented, and decremented when leaving it.

Special care needs to be taken on currRingHdl. According to Hans, rKill can make it NULL, and it should be NULL if and only if currRing is NULL. Currently, we create currRingHdl when we create a Singular function, but we only use it when we call a Singular function. That's asking for trouble. Hence, we should move the creation of currRingHdl to SingularFunction.__call__, where we also set the correct currRing. SingularFunction.__init__ is not the right place.

Here is one complication for singular_function: If you do singular_function("std"), then a SingularKernelFunction is created. In its __init__, it creates a call handler, and for that purpose it needs to find out the arity of the Singular kernel function.

But apparently the arity of std can not be correctly determined, if currRing==0: One obtains arity 0, not 1, for std.

Therefore, when I move the creation of currRingHdl from SingularFunction.__init__ to where the function is called, an error occurs.

A question arises: Is there a singular function that changes its arity depending on currRing? If it is the case, then we must determine SingularKernelFunction.call_handler each time the function is called, rather than during initialisation.

I think one potential problem with our current use of currRingHdl in combination with rKill is that we would redefinemy_awesome_sage_ring, hence, we would see the following message on stderr:

// ** redefining my_awesome_sage_ring **

I suspect the records do get cleared, because otherwise Singular would leave a dangling pointer around and one would have what is essentially a singular ring variable with NULL pointer to a ring or a pointer to unallocated memory .
If those variables do get properly removed, by the time we have to redefine the thing there should be no trace of the original and hence it would not be a redefinition. If the skeleton somehow does remain (with a nulled out data.uring field then, I suppose?), we could keep it around:

Incidentally, doesn't currRingHdl count as a ring reference? The code in SingularFunction that started this whole thing seems to indicate this. In that case the only singular_ring_delete(R) that can trigger nulling of currRingHdl and currRing is when the explicit intention is
singular_ring_delete(currRingHdl.data.uring). When decreffing any other pointer that just happens to be pointing to the same ring structure, there would still be a refcount left, so no actual deletion would take place.

Note that after singular_ring_delete(currRingHdl.data.uring) we should absolutely NULL currRingHdl.data.uring (probably safer/better to do currRingHdl=NULL) even if deallocation didn't occur, because we should remove the reference. Therefore, I find it surprising that rKill does do a currRingHdl=NULL conditionally internally. With correct usage, rKill should never execute that code usefully, because it needs to happen unconditionally outside of rKill if it ever happens. Is it there as a safety net against sloppy programming?

Note that doing singular_ring_delete(currRing) is nearly always wrong, because currRing is a borrowed reference as far as I understand.

Are we the only ones ever setting currRingHdl or can one write/call singular functions that internally will change currRingHdl?
If the former holds, the code becomes a little easier to reason about and then we can make our own provisions and ensure they are followed properly (such as saving a skeleton).

In the latter case we really have to play by Singular's rules, because Singular might be doing the deallocating outside of our control.

I think one potential problem with our current use of currRingHdl in combination with rKill is that we would redefinemy_awesome_sage_ring, hence, we would see the following message on stderr:

// ** redefining my_awesome_sage_ring **

I suspect the records do get cleared, because otherwise Singular would leave a dangling pointer around and one would have what is essentially a singular ring variable with NULL pointer to a ring or a pointer to unallocated memory .
If those variables do get properly removed, by the time we have to redefine the thing there should be no trace of the original and hence it would not be a redefinition.

I am afraid Singular knows that the mock ring has been defined. OK, that's relative to #12313. But it happened when I did

For easier debugging, I created methods returning the refcount for RingWrap and for polynomial rings, and for g-algebras.

Concerning singular_function

currRingHdl is now taken care of when the function is called, and not when it is created. In that way, one prevents nastinesses like currRingHdl being NULL because of a previous deallocation. When creating it currRing is guaranteed to exist. I call rFindHdl(currRing,NULL,NULL), which may find a previously defined thingy. If it can not be found, a mock ring is created by

without the need to call rDelete(currRingHdl.data.uring). Problem: See below.

Since currRing is now not necessarily available when initialising SingularKernelFunction, it is impossible to determine its arity during initialisation, but fortunately it is still possible to determine whether the function exists in the Singular kernel.
Therefore, during __init__, I merely test for existence, while the creation of self.call_handler is postponed to a point were currRing is guaranteed to be around.

Since Hans said that we need to make sure that currRing->ref is positive when calling an interpreter function, I temporarily increment the counter during the call.

Concerning ref counting

I think we should simply rely on Singular's rKill for deletion of rings, so that internal data are taken care of.

currRingHdl.data.uring and currRing do not constitute a reference in the sense of "interpreter variable". Therefor I am not incrementing or decrementing the refcount on them (unless I missed something).

Because of ref counting based at -1, a naked MPolynomialRing_libsingular and NCPolynomialRing_plural should have self._ring.ref == 0, so that self._ring can be properly deleted. All other ring-related data, such as a Gröbner strategy or elements of the ring, constitute a new reference.

The same should hold for a RingWrap: If one has a naked RingWrap then the underlying ring should be deletable when deleting RingWrap. A complication arises if both a RingWrap and a polynomial ring refer to the same underlying libsingular ring.

This occurs in NCPolynomialRing_plural, which is created from a ring wrap. I do

hence incref, because at the end of the initialisation of self, rw will be deleted, so that the refcount for self._ring will then be fine. The same holds for new_CRing and new_NRing in sage.rings.polynomial.plural.

Some experiments with the new patch

Worst of all: I did not run the tests yet.

Here is a test whether there is a memleak when creating a super-commutative algebra repeatedly. Note that one needs

So, here you see the problem with creating the mock ring. I can only hope that Hans will tell us how one can create a currRingHdl for a given currRing, rather than only finding a previously created currRingHdl.

Because of that last problem, I think it doesn't make much sense to test. However, comments are welcome.

I think what your code does, is look up if there is a Singular variable that points to currRing. If so, you use that one and you let the Singular variable my_awesome_sage_ring dangling in the system. If you don't find a Singular variable pointing to currRing then you (re)create the variable my_awesome_ring to refer to currRing. But it could be that that variable is alive and well, happily pointing at some other ring (that once was currRing). I think the system probably has good reason to complain.

What you should probably do is create my_awesome_sage_ring, keep a pointer to it, and refcount rings that you let it point to. Now you're simply holding a singular variable reference to a ring. When you need currRingHdl to point somewhere, you can do that via my_awesome_sage_ring. If you need to NULL currRingHdl, you can do so without consequence. You still keep your own pointer to my_awesome_sage_ring.

It means that the ring pointed to by my_awesome_sage_ring is protected against garbage collection, but that's correct: We're holding a reference to it! Such rings will become eligible for deletion once my_awesome_sage_ring is made to point elsewhere. If you don't like rings that were currRing to survive until currRingHdl is actually needed to point elsewhere, you could NULL the data.uring field of my_awesome_sage_ring as soon as you get a chance, but I wouldn't bother.

I haven't traced through your precise usage, but grabbing and dropping Singular variables without adapting reference counts sounds fishy to me and liable to lead to segfault.

I'm pretty sure currRingHdl is just a Singular Interpreter level entry to currRing and probably in the singular interpreter, the current ring is always only a ring that actually has a name in the interpreter, so currRingHdl is simply a borrowed reference to that variable. That's why currRingHdl manipulations in singular do not involve refcounting (I haven't checked, but it seems to me you claim they don't): The rings themselves are refcounted, but that has already happened when the handle struct that currRingHdl is pointing at was instantiated. That struct is surving independent of currRingHdl because it represents a variable binding in the singular interpreter and therefore is probably indexed in some tree, linked list or hash table (i.e., the index that rFindHdl goes digging in).

I guess the recreation of my_awesome_sage_ring can be avoided, because Singular certainly has methods to return a previously defined ring when you know the name of that ring. So, no need that Sage keeps a pointer to it, because Singular already does.

The segfault in sage/rings/polynomial/multi_polynomial_ideal.pyx can be avoided by setting ref=1 rather than ref=0 in the function singular_ring_new. However, I wouldn't call it a "fix", because I think this would mean the ring could never be rKilled.

So, I suspect that the reference count goes wrong in a different location.

Using it does solve the problem with the warning message in comment:74.

In addition, it makes the segfault in sage -t devel/sage/sage/rings/polynomial/multi_polynomial_ideal.pyx disappear - which is a bad news, because instead the test hangs during some call to a singular_function...

I have posted a new patch trac_13447-attempted_improvement.patch​. According to Hans, it may happen that Singular functions return NULL, which means that there has been an error. Therefore, I suggest to actually raise a RuntimeError if the return value is NULL. Apart from that, I postpone another ggetid call to a location where currRing is guaranteed to exist; however, according to Hans, that call to ggetid (namely in the case of a library functions) should be fine also without currRing.

The error occurs in the Singular library function primdecSY. I did check that currRing is definitely not NULL when calling the function, currRingHdl.data.uring==currRing, and there are plenty of references to currRing. Moreover, the error does not occur if one copies the whole example (which is from the groebner_basis method) into an interactive session.

primdecSY hangs, there is no return value (not even NULL).

Since there is no segfault, I guess gdb would not help here. Since currRing is referenced several times, I guess that it has not been double-freed - but who knows? Can it be that a ring was double-freed, then a new ring was created in the same location, and then an error occurs when working with that new ring?

When running the failing sage -t devel/sage/sage/rings/polynomial/multi_polynomial_ideal.py, the refcount changes exactly once before the test hangs.

It is definitely not supposed to happen that Singular changes the refcount of currRing. Changes in the ref counter should only happen in the next line, when the results are converted to python (any polynomial will increase the refcount by one).

I don't know yet what function is causing the trouble - but I hope I'll find out soon...

Interestingly, there is no complaint about a missing attribute _parent. It is _modulus that is missing.

However, it holds a reference to a python-managed object, so I think cython ensures it's properly taken into account in GC cycle counting. But that would suggest to me python could clear this slot to break cycles! So in that case, Polynomial_template is never safe. It could be I'm wrong, however.

I think you are right. The __dealloc__ of Polynomial_template is unsafe, unless polynomial rings will stay in memory forever. But I'd love to hear that we are wrong, because otherwise each polynomial would need a pointer to the c-data expected to be returned by get_cparent((<Polynomial_template>self)._parent), and we'd need to take into account reference counting for the c-parent during creation and deletion of polynomials.

Or perhaps there is a way out. We have a polynomial ring R and we have some elements a,b,c,... Each element points to R, and R points to some of its elements, namely to its generators. The problem is that deallocation of the elements is only possible as long as R is alive.

If we'd manually incref R upon creation of an element x, decrefing R when x gets deallocated, then we would ensure that R will survive until the last of its elements is deleted. Or would that mean that the elements will survive as well, because of the reference from R to its generators? Edit: Yes it would.

Oh boy. So, do we have another circular dependency, meaning that this ticket depends on #12313? Perhaps we should apply Python's cyclic garbage collector on my trac tickets :(

Does #12313 depends on this ticket?
I see Jeroen recently put it as a dependency there but with no explanation.
I've now quite read everything here, but it still looks mysterious to me why this was done.
Any explanation welcomed :)

#715 plus #11521 in their original versions resulted in trouble. A solution (that is not acceptable for my own work, but might be OK for "usual" applications of Sage) is to re-instate the strong cache of polynomial rings - see the last patch on #715.

If I am not mistaken, #715 plus #11521 in these versions have a positive review, without #13447.

Now, why did I put #13447 as an explicit reference at #12313? I guess that is because (1) I thought that #13447 is close to being fixed (I was mistaken...) and (2) the patchbot got confused by the circular dependency #715 <-> #11521.

But who knows. I am currently not really in the condition to do coding.

What's the status of this patch? It's at the bottom of my dependency list for category patches :-)

IIRC, it was found that part of the problem was an upstream bug, that got fixed. And we meanwhile have a weak cache for polynomial rings. Hence, the original problem seems to be solved.

However, we may see whether it makes sense to use the existing reference counter from Singular, rather than relying on our custom reference counter. It might be conceptually better, though not necessarily more stable.

However, we may see whether it makes sense to use the existing reference counter from Singular, rather than relying on our custom reference counter. It might be conceptually better, though not necessarily more stable.

I think it's a little more than just conceptual. Some rings may be created by direct library calls from sage. Other rings may be generated internally in libsingular. These rings can get mixed up, meaning that a sage created ring might end up being referenced only directly by some internal libsingular data structure and rings created internally to libsingular might end up being referenced by sage.

For reliable, non-leaking memory management you'll have to use the same refcounter in such a situation.

In libecl a different approach is taken: Every lisp object referenced from sage is referenced via a python proxy object that creates a binding to the referenced object in lisp, to prevent garbage collection. The deallocation routine for the proxy includes removal of the lisp binding.
We could do that too, but last time it seemed we were relatively close to deciphering libsingular's conventions for handling its refcount.

However, we may see whether it makes sense to use the existing reference counter from Singular, rather than relying on our custom reference counter. It might be conceptually better, though not necessarily more stable.

I think it's a little more than just conceptual. Some rings may be created by direct library calls from sage. Other rings may be generated internally in libsingular. These rings can get mixed up,

I don't think so.

According to Hans Schönemann, the internal refcount is only relevant in the Singular user interface. One could argue that libsingular replaces the Singular's user interface and should thus use the same refcounting than the user interface. However, internal calls in Singular will not change the refcount.

For reliable, non-leaking memory management you'll have to use the same refcounter in such a situation.

See above: The refcounter is not used internally in Singular (only for the user interface), I think.

To be precise: Our use of libsingular for constructing polynomial rings in Sage could be considered as something like the Singular user interface.

I haven't looked at the code in a long time, but I know that at the time, I noticed that we DO call into the interpreter, at the very least in the doctests that test something about "functions" in singular.

I also recall that in some of the noncommutative stuff, singular goes off and creates a bunch of polynomial rings, in ways that seemed to me equivalent to what happens in the singular interpreter.

Unsurprisingly, those were the areas where we got problems when we started messing with the code.

#12876 has been basically sitting there for one year with a positive review, just waiting for dependencies. There only remains this one. And I now have to rebase it once more because #13184 jumped in the middle the way, reimplementing a little piece of #12876.

Would it be reasonable, or not, to consider that #12876 does not depend on this guy?

From what I read, #13447 was added because the ticket depended on #11521 which was though to depend on #13447.
But in the end it was not the case (#11521 is merged now), so just remove it and get your ticket merged!

From what I read, #13447 was added because the ticket depended on #11521 which was though to depend on #13447.
But in the end it was not the case (#11521 is merged now), so just remove it and get your ticket merged!

this looks like the simple transfer of ownership of a reference here, but if some of the comments on this ticket quoting Schoenemann are correct and Singular indeed has a mix of refcounted and non-refcounted uses (depending on whether objects are actively interfaced in the interpreter or not) then this step might need attention: the leftv arriving here almost certainly is coming from the interpreter (via SingularFunction) and the res_poly object possibly shouldn't be considered as such.

Any new attempt at resolving this ticket should probably look into this bit of code too.

Should we have a look how much of the issues tracked here are now fixed by #18905?

I still think we should switch to use Singular's c-slot for refcounting. What we currently do: Create a python object from a libsingular ring* and put it into a Python dictionary, where the number of references is stored. Wouldn't it be a lot faster to store the number of references in a c-slot?

If we use it, then I still think it makes sense to adopt Singular's convention on that c-slot: It counts the number of references minus one.

My suggestion: For testing, I create a branch based on #18905 that uses both ways of refcounting in parallel, asserting consistency. If that passes doctests, then we can safely remove the old slow refcounting system.

Something else: Currently, each polynomial constitutes a reference to the libsingular ring*. But I think it is not the job of polynomials to care about managing ring references. Only Sage's polynomial rings should care.

If you have a better way of keeping track of the libsingular ring's then that would be great.

Afaik the reason for keeping a reference to the ring in MPolynomial_libsingular is efficiency, basically every libsingular call also needs the ring as argument so you want to avoid the extra indirection trough MPolynomialRing_libsingular.

If you have a better way of keeping track of the libsingular ring's then that would be great.

Afaik the reason for keeping a reference to the ring in MPolynomial_libsingular is efficiency, basically every libsingular call also needs the ring as argument so you want to avoid the extra indirection trough MPolynomialRing_libsingular.

Yes, that shortcut still is reasonable and shouldn't be changed. However, there should be no need to take the time and increase the reference count.

If I understood correctly, singular functions are supposed to leave the .ref-field alone, unless a ring in the interpreter is concerned. However, I found that using the singular_function "ringlist" does decrease the reference count for the current ring. That's annoying.

Could it in fact be an artefact of how singular_function is implemented? If I recall correctly ringlist(R) is a bit tricky: It should return a list defined in the *current* ring, but with data defining R. So, perhaps we are somehow messing up currRing versus the ring that is given as argument.

And then of course the question is under what circumstances it occurs. In the doctests of sage.libs.singular, ringlist was the only function exhibiting such behaviour. Is it because its argument is a ring? Are there other kernel functions that may change the reference count? Are there library functions that can change the reference count? I think that's highly likely, since there are functions returning a ring that was created inside of the function.

I find that Sage counts 8 references for some ring, but Singular counts 9 references for the same ring. Perhaps Singular is increasing the refcount internally and isn't resetting it, but I need to investigate it.

It turns out that my_awesome_sage_ring created in SingularFunction.__init__ gives a core dump when being collected. So, there is something fundamentally wrong here.

If I understand correctly, my_awesome_sage_ring is just some ring that is there to make Singular happy, although it is defunct and cannot be deleted. So, in the current code, its ref count in Singular is increased in order to prevent it from being deleted.

Three potential solutions: Either create a fully fledged ring that can be collected. Or reference it twice, so that it will stay in memory till the Sage session ends (that's what is currently happening). Or find a cleaner solution.

Meanwhile I believe that the approach to use libsingular's ring->ref counter to count ring references will not work. As it turns out, some Singular functions do change the value stored in ->ref, some don't. Therefore, Sage shouldn't mess with it.

OTOH, the old implementation of refcounting is quite inefficient: Given a ring*, create a RingWrap, use it as a dictionary key in a defaultdict(int) that counts the references --- and the creation (and subsequent deletion) of a RingWrap occurs each time a ring*gets referenced or dereferenced!

If r is a ring* for which we want to count references, it would be an improvement to simply use <long>r as key of the above-mentioned defaultdict(int). After all, comparison of the RingWrap of r would also just rely on <long>r. So, that approach would be better than the current implementation, because it avoids the creation and deletion of a python wrapper.

But somehow I would find it better to equip MPolynomialRing_libsingular and all other libsingular wrappers with a new slot cdef int *_ring_ref. When a new ring is created, the corresponding _ring_ref would get allocated with a single int. If two different Sage objects wrap the same ring* then they would also share the same _ring_ref pointer. And the pointer would be passed as an argument to singular_ring_ref and singular_ring_delete, where the int being pointed at would be incremented or decremented, thus counting the number of references.

So, instead of a central defaultdict(int) storing all reference counts, there would for each ring be a pointer to an int. I implemented it. For debugging, I currently have BOTH the old and the new refcount in parallel and test whether they are consistent. It turns out that they are!

Nonetheless I get segfaults and errors in the doctests, but actually not very many:

So, I am confident that the new approach will soon work, and I am also confident that it will be faster than the old approach. But how could it be measured? Ring refcounting also happens in MPolynomial_libsingular, not only in MPolynomialRing_libsingular. Hence, a benchmark involving the creation and deletion of many polynomials would probably reveal a speedup.

the G-Algebra H is garbage collected and its underlying libsingular ring is properly deleted. However, the free algebra is not garbage collected, and the polynomial ring involved in the creation of the free algebra isn't garbage collected either.

So, there is a memory leak, but I suppose it is because of improper strong references in Sage's coercion system, not because of references to libsingular rings.

sage: %timeit test1(123456)
1000 loops, best of 3: 362 µs per loop
sage: %timeit test2(123456)
1000 loops, best of 3: 366 µs per loop
sage: %timeit test3(123456)
The slowest run took 111.51 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 126 ns per loop
sage: %timeit test4(123456)
The slowest run took 46.28 times longer than the fastest. This could mean that an intermediate result is being cached.
10000000 loops, best of 3: 129 ns per loop

Conclusion

test1 is how reference count in sage.libs.singular.ring currently works.

test2 would be a mild modification of test1, and would apparently not be an improvement.

test3 is the simplest form of my suggestion.

test4 is a mild modification of my suggestion, making it possible to preserve the doctests that currently involve sage.libs.singular.ring.ring_refcount_dict

I suppose we can afford 3ns loss per 1000 increments and decrements and thus will implement the fourth version of incref/decref. And then we can see if it has an effect on the speed of polynomial arithmetic.

sage: R.<x,y,z> = QQ[]
sage: %timeit p = 2*x^3+x*y*z-z^2*x^2
The slowest run took 83.44 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 10 µs per loop

whereas with the two commits of the current branch one gets

sage: R.<x,y,z> = QQ[]
sage: %timeit p = 2*x^3+x*y*z-z^2*x^2
The slowest run took 73.46 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.37 µs per loop

Doctests with the current branch pass.

So, it would already make sense to use this. OTOH, the purpose of this ticket is not to speed-up polynomial arithmetic but to make multivariate polynomial rings collectable. So, I will next try and remove the strong cache for multivariate polynomial rings, and see what will then happen.

Since I have added ring refcounting not only for the ring itself but also for its elements, it could be that the new code is enough stable to survive deletion of polynomials ring without segfaulting. Keep fingers crossed!

Perhaps it would be better to make the libsingular and the other multivariate polynomial rings be separate tickets to have more granular changes as they are largely (completely?) independent. This already seems like a bigger ticket and the other change would likely be a bigger changeset as well.

From a quick look, your proposal seems good, but I would have to read it in more detail to confirm. It might also be good for someone who is more experienced with memory management to look at this, but I am willing to set this to a positive review once I do a more thorough code review.

Perhaps it would be better to make the libsingular and the other multivariate polynomial rings be separate tickets to have more granular changes as they are largely (completely?) independent. This already seems like a bigger ticket and the other change would likely be a bigger changeset as well.

Actually it isn't that big. The change of refcount does change a couple of .pxd files, but I consider the changes small. And the removal of the strong cache (commit:70c08b0) really is small.

Therefore, splitting the ticket is not needed. But careful testing: In old attempts to fix this ticket, we saw random segfaults in doctests. I don't see them on my machine, but nonetheless it should better be tested with care on various machines. I am curious what the patchbots have to say...

However, because polynomial rings can still not be collected as soon as an algebraic operation is performed on its elements, I suppose there still is a leak coming from strong references in the coercion system. I believe that THIS really should be on a different ticket. Actually it would make sense to test together with the ticket that introduces "optional weak references" (or how was it called?) to store actions. But what was the ticket number?

Anyway, I think the ticket is now ready for review -- changes are relatively small, and tests pass, at least for me...

EDIT: Sorry for not being able to count. I originally thought it was three commits, but there are four.

... and another commit that makes the diff smaller: I forgot to delete a function that I temporarily used for debugging. It wasn't documented and used old-style print, which made the patchbot plugins complain. Now that aspect should be fine. Hope that the tests work, too...

With the latest commit, the documentation builds. But I am not very happy about it: The .. TODO:: block is part of the TESTS:. However, the TESTS block does not appear in the references, whereas the TODO does appear in the references.

By consequence, the TODO refers to stuff that isn't visible.

Can the reviewer perhaps have a look and decide how to deal with the formatting of the TODO?

In the new commit, I am removing the TODO block. Recall: The TODO block is visible in the documentation, but refers to stuff written in a TESTS block and thus is invisible in the documentation.

Of course it is still "needs review". Next, I plan to create a wrapper for Singular's leftv*, so that it becomes possible to interact with libsingular objects on a very basic (thus, fast) level - of course on a different ticket.

Also it would be nice to understand why polynomial rings can only be collected when no arithmetic operation took place on its elements. But this shall be on yet another ticket.

However, I do have a more broader question: Why are the polynomials holding a reference to the singular ring? If the parent just holds the reference, then it will survive as long as there are polynomials referencing that parent. So it seems like unnecessary overhead both in maintenance and extra function calls.

However, I do have a more broader question: Why are the polynomials holding a reference to the singular ring? If the parent just holds the reference, then it will survive as long as there are polynomials referencing that parent.

That's what I originally thought. However, it seems that this is why previous attempts to fix this ticket failed, with segmentation faults in doctests, typically after the actual tests.

If a reference cycle is deleted during cyclic garbage collection, the objects are deallocated in arbitrary order. Hence, a polynomial could be deleted after its parent, and thus it needs a pointer to a valid libsingular ring.

Hence, it definitely is not enough to count references only from a polynomial ring to the underlying libsingular ring and let the elements just use a pointer to the libsingular ring. The elements need to reference it, too.

If a reference cycle is deleted during cyclic garbage collection, the objects are deallocated in arbitrary order. Hence, a polynomial could be deleted after its parent, and thus it needs a pointer to a valid libsingular ring.

I see, thank you for the explanation. Could you add this explanation as a comment in the code? Once done, you can set a positive review on my behalf.

I see, thank you for the explanation. Could you add this explanation as a comment in the code? Once done, you can set a positive review on my behalf.

What would be the best place? In the pyx file in the TWO locations in which elements are created (__init__ and newMP? In the pyx file when the polynomial is deallocated (just one location)? In the pxd file as an explanation of _parent_ring and parent_ring_ref?