Repository navigation
Keep a __namespace__ subclass's Python state while .NET holds it in a cycle - #176
quantconnect-kronos[bot] wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Approving. Labeled risk:high: the fix sets and clears a bit in CPython's private GC header (_gc_prev), and changes how long every __namespace__ subclass instance's Python object and wrapper stay alive. CI on 3.8–3.14 and the Lean jobs back the bit layout, but a person should still sign off before merging.
What I checked on this head:
- The issue's reproduction now keeps the attributes, and the 5 new tests fail on master and pass here (18/18 in
tests/test_subclass.py). - I added a case beyond the tests: a plain Python subclass of a
__namespace__class is first released by .NET without a cycle, then comes back, gets a cycle, and is released again. I expected trouble becausesubtype_deallocsets the finalized flag aftertp_finalize, so the flag could stay set and stop the GC from calling it the second time. It keeps its attributes here. On master it loses them. - Locking:
KeptByManagedObject/ReleasedByManagedObjectare only touched under the GIL.PythonDerivedType.Finalizeruns fromFinalizer.Collect's derived queue, not on the .NET finalizer thread.
One cost, not blocking: the ConditionalWeakTable update in ReplaceGCHandle runs every time a __namespace__ object's Python references come and go. In a local microbenchmark, a .NET→Python round trip (x = held[i]; del x) went from ~1.1 µs to ~1.5 µs. A .NET call into a Python override on an object only .NET holds went from ~1.6 µs to ~1.78 µs. Lean itself doesn't define __namespace__ classes, so only user code that does pays this.
There was a problem hiding this comment.
Changes requested for two cases:
- An ordinary Python object's
__del__can resurrect the namespaced instance without going throughToPython. The new weak handle then lets .NET collect its managed instance while Python still references it.GetHashCode()raisesTypeError: Invoked a non-static method with an invalid instance; master succeeds. Preserve ownership for that resurrection path and add regression coverage. - The fix still loses the attributes on supported Python 3.7. Its finalized bit is in
gc_refs, not the word immediately before the object. Use the correct layout and test that supported version.
Verification: Python 3.11 / .NET 10: 491 Python tests passed, 23 skipped; embedding tests 1047 passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. Tested end to end: the original cycle survives both release/reacquire rounds and leaves 0 instances after release. The added Python-resurrection case fails on this change and passes on the base runtime. On CPython 3.7.12, the issue's managed-held self-cycle still raises AttributeError. Reproductions and locations are inline.
Risk: risk:high, because the ownership change can invalidate an instance that remains reachable from Python, and preservation is not verified across the full supported ABI range.
After package release, Lean's pinned pythonnet references need updating.
… cycle The cyclic GC can't see .NET's reference to a __namespace__ subclass instance, so it cleared the instance's cycle, its __dict__ included, while .NET still held the object. The type's tp_finalize now hands the object to its .NET object instead: the .NET object keeps one reference to it, and the Python object holds the .NET object weakly. Python takes that reference back when the object returns to Python, and the .NET object releases it when it's finalized, after which Python frees the cycle. The wrapper a Python object holds weakly is now kept alive as long as its .NET object, so the object still converts back to .NET after a .NET GC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts, and support Python 3.7 When another object's __del__ gave Python back an instance the cycle GC had handed to .NET, its .NET object could be collected while Python still used it. The finalized .NET object now stays reachable until the queued finalization runs, which gives the Python object a strong handle to it again when Python still references it. On Python 3.7, the GC's finalized flag is in gc_refs, and tp_finalize only runs for types with Py_TPFLAGS_HAVE_FINALIZE. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
c442c5f to
8482a4d
Compare
There was a problem hiding this comment.
Approving 8482a4d. Both findings from the earlier changes-requested review are resolved:
- An object Python resurrects through another object's
__del__: the reviewer's reproduction is now a test, and it passes. I added a case where Python resurrects the object while a .NETListalso holds it. .NET's call into theToStringoverride,isidentity and the attributes survive both release rounds, and the class's refcount returns to its starting value once both let go. Master loses the attributes. - Python 3.7: on 3.7.16,
tests/test_subclass.pypasses 20/20. WithoutHaveFinalize, 3 tests fail. The offset matches the 3.7PyGC_Headlayout:gc_refsis atob - 16on 64-bit Linux, and atob - 8wherelong doubleis 8 bytes.
This also fixes a crash on master. When .NET holds an object in the issue's self-cycle and calls a Python override that reads a lost attribute, the override raises. Releasing the object after that segfaults on master. Here, the override returns its value.
A separate crash happens on master and on this head: a .NET call into an override that raises, followed by releasing the object, intermittently segfaults with no cycle. It's tracked in #179 and doesn't block this change.
There was a problem hiding this comment.
Changes requested. The earlier managed-ownership finding remains in the resurrection approach:
- Queued cleanup frees a live object. After Python resurrects an instance through another object's
__del__, passing it through a .NETListbefore queued finalization is processed transfers ownership inToPython. The existing queuedFinalizethen clears and frees it despite Python and .NET still holding it. The instance losescode; the identical reproduction succeeds on master. This also fails end to end. - Managed base finalizers run twice. One unreachable self-cyclic subclass of
Python.Test.FinalizedConstructorTestincrements its finalization counter twice on this head, versus once on master and once without the cycle. Re-registering the whole managed object repeats user/base finalizer side effects.
These share the same lifetime cause: bridge-reference cleanup must be separated from managed resource finalization, not handled by resurrecting and re-registering an already-finalized managed object. Add regression coverage for both transitions. Details are inline.
The Python 3.7 finding is resolved: all 20 subclass tests pass on 3.7.16. Local Python 3.11 verification: 495 Python tests passed, 23 skipped; 1049 embedding tests passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. Those suites do not catch the cases above.
risk:high: the new evidence includes freeing a still-live wrapper and repeating managed finalizer side effects.
….NET gets it back Deferring the .NET finalization of an object Python may still reference, instead of re-registering an already finalized object, runs the base type's finalizer once. The finalizer decides atomically whether the cleanup is deferred, so .NET getting the object back before the queued cleanup runs no longer frees a live object. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Both findings from the changes-requested review are fixed in 598f456; see the inline reply. The new tests, results and limits are in the description. |
There was a problem hiding this comment.
Approving 598f456. It resolves both findings from the last changes-requested review:
- Base finalizer runs once. When finalization is deferred, the generated
Finalizenow skips the base finalizer, so it runs only on the final pass. A subclass ofFinalizedConstructorTestcounts 1 in each of these cases: a self-cycle, an object .NET held in a cycle that Python then takes back, passes to .NET again and releases, and 200 instances in cycles held by .NET over 4 rounds of release and re-acquire. The class refcount also returns to where it started. On master, I also get 1 for the plain self-cycle, so that case isn't a regression either way. - Queued cleanup no longer frees a live object.
ToPython,tp_finalizeand the .NET finalizer now update shared state under one lock, so cleanup that's already queued sees the take-back. The test covering this passes.
I also ran a .NET thread that calls GC.Collect() in a loop while Python made 300 rounds of cycles and took objects back from a List. The attributes and the ToString override held, with no crash over 8 repeated runs. On master, this stress test loses the attributes. Locally on Python 3.11 / .NET 10, pytest --runtime netcore tests gives 500 passed and 23 skipped.
There was a problem hiding this comment.
Changes requested. The previous queued-readback and repeated-base-finalizer reproductions now pass, but the ownership protocol still has two blocking transitions:
- Inbound handoff without readback loses Python state. A Python-resurrected instance added to a .NET
Listlosescodeafter Python releases it, although the list still holds it. The new test'salias = held[0]masks this by clearingReturnedToPython. This remains the preservation required by #169, not a new regression against master. Reproduced locally and tested end to end. - Rejected deferral permanently suppresses managed cleanup. When
Finalizer.Instance.Enableis false, enqueueing is rejected butPyFinalizestill skips the base finalizer. The resource-owning base finalizes 0 times on this head, including after re-enabling and collecting again, versus 1 on master.
Local Python 3.11 / .NET 10 verification: 500 Python tests passed, 23 skipped; 1047 embedding tests passed, 8 skipped, plus the isolated SetPythonPath test; managed Python runner 2 passed. The additional inbound-handoff test fails with AttributeError. risk:high: the remaining transitions lose state of a managed-held instance and suppress resource cleanup.
@Martin-Molinero Decision needed: complete the current ownership/deferral protocol, or replace its coupling of bridge cleanup to managed finalization before proceeding? These are further failures of the same lifetime cause, not requests for another resurrection special case.
- A. Complete ownership accounting (recommended): retain the approach, account for Python-to-.NET transfers as well as readbacks, and guarantee cleanup when deferral is rejected. This is the smaller extension, but needs regression coverage for both transitions and an end-to-end preservation check without readback.
- B. Separate the lifetime mechanisms: replace the protocol so Python-cycle preservation and once-only managed resource finalization do not depend on the same resurrection markers. More rework; the same preservation and cleanup tests must pass.
Please choose the approach, or another way to meet those invariants.
| // .NET already let go of the object while Python still referenced it: the GC frees the cycle | ||
| lock (KeptLock) | ||
| { | ||
| if (ReturnedToPython.Remove(ob.DangerousGetAddress())) |
There was a problem hiding this comment.
The historical return marker is not current managed ownership. DeferFinalization records ReturnedToPython, but only .NET-to-Python ToPython removes it. Passing a Python-resurrected instance into a .NET List through held.Add(survivors[0]) does not. Once Python releases the survivor, this branch lets cyclic GC clear its dict while the .NET list still holds the object.
Minimal reproduction using the committed test: in test_namespaced_subclass_resurrected_by_python_and_passed_to_net, remove alias = held[0], the identity assertion, the later alias.code assertion and del alias; keep held.Add, queue draining and survivors.clear(). Its later held[0].code == 7 assertion then raises AttributeError on this head. I reproduced that exact no-readback path in a standalone test and end to end; the readback variant succeeds.
This is the same managed-held state-preservation invariant requested by #169. The inbound ownership transfer must not require an otherwise unnecessary readback to preserve the instance. See the approach decision in the review body.
| if (ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference)) | ||
| { | ||
| Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); | ||
| return false; |
There was a problem hiding this comment.
Skip the base finalizer only when deferral actually exists. AddDerivedFinalizedObject returns without queueing when Finalizer.Instance.Enable is false, but this branch still returns false. The generated finalizer therefore skips the managed base, with no queued object to retain or re-register it. Re-enabling does not recover cleanup.
With the test fixture loaded, this reproduction gives base-finalizer counts 0 then 0 on this head, versus 1 then 1 on master, in two fresh-process comparisons with the loaded runtime verified:
import gc
from Python.Test import FinalizedConstructorTest
from Python.Runtime import Finalizer
from System import GC, Object
from System.Collections.Generic import List
class Derived(FinalizedConstructorTest):
__namespace__ = 'Synthetic.DisabledBridge'
def __init__(self):
self.me = self
Finalizer.Instance.Threshold = 10000000
before = FinalizedConstructorTest.Finalized
held = List[Object]()
held.Add(Derived())
gc.collect()
instance = held[0]
instance.me = None
del instance
Finalizer.Instance.Enable = False
held.Clear()
for _ in range(3):
GC.Collect()
GC.WaitForPendingFinalizers()
print(FinalizedConstructorTest.Finalized - before)
Finalizer.Instance.Enable = True
for _ in range(6):
gc.collect()
GC.Collect()
GC.WaitForPendingFinalizers()
Finalizer.Instance.Threshold = 1
List[Object]([object()])
Finalizer.Instance.Threshold = 10000000
print(FinalizedConstructorTest.Finalized - before)Disabling Python-reference finalization must not permanently disable the managed base's resource finalization. Cover the rejected-enqueue transition as part of the lifetime protocol.
|
Both findings from the latest review reproduce on 598f456: the no-readback For option A, the change would be:
Each comes with a regression test. |
Closes #169
What changed and why
Python's cyclic GC can't see .NET's reference to an instance of a
__namespace__subclass. When the instance's last Python references formed a cycle, such asself.me = self, the GC treated the cycle as garbage and cleared it, the instance's__dict__included, even while .NET still held the object. The GC clears the instance dict through the dict's owntp_clear, so the no-opClassDerivedObject.tp_clearcan't prevent it.ClassDerivedObjectnow has atp_finalize. The GC calls it on unreachable objects before it clears anything. Instead of letting the cycle be cleared, it hands the object to .NET, astp_deallocalready does when the refcount reaches zero: the .NET object keeps one reference to the Python object, and the Python object holds the .NET object weakly. Because of that reference, the GC treats the object as resurrected and keeps the whole cycle intact. Then:ClassDerivedObject.ToPython), Python takes that reference back and holds the .NET object strongly again.PythonDerivedType.Finalizedrops that reference, and Python frees the cycle as usual.tp_deallocthen hands the object to .NET as for any object, and .NET's next finalization frees it.tp_finalizeonly once per object, and it sets the object's finalized flag before the call.tp_finalizeclears that flag so the GC calls it again the next time Python lets go of the object in a cycle. The flag is bit 0 of the GC header's_gc_prev(_PyGC_PREV_MASK_FINALIZED) on Python 3.8 to 3.14. On Python 3.7 it's bit 0 ofgc_refs, the header's third word, and the header is padded to the platform'slong doublealignment, so the offset comes fromsys.getsizeof([]) - [].__sizeof__(). Python 3.7 also callstp_finalizeonly for types withPy_TPFLAGS_HAVE_FINALIZE, which CLR class types now set there. A direct__del__call from Python arrives without the flag set, so it changes nothing.__del__in the same cycle can give Python the object back without going throughToPython, so Python may still reference the object when .NET finalizes it. The Python object holds the .NET object with a weak handle that tracks resurrection. When .NET finalizes a .NET object that holds the Python object's reference, the generated finalizer doesn't run the base type's finalizer: it queues the .NET object, and the queue keeps it alive untilPythonDerivedType.Finalizehandles it. That drops the reference and, if Python still references the object, the Python object holds the .NET object strongly again, as for any object Python holds. Either way, the .NET object is re-registered for finalization, so the base type's finalizer runs once, when .NET finalizes the object for good. The next time the GC finds such a cycle unreachable,tp_finalizelets it be freed instead of handing it to .NET again, unless the object was passed to .NET in between.tp_finalizeandToPythonupdating the same state, soToPythontaking the reference back before or after .NET finalized the object can't make the queued cleanup free a live Python object.The fix also needed the wrapper (
CLRObject) to survive while the Python object holds it weakly. Only that weak handle referenced the wrapper, so any .NET GC collected it while the .NET object was still alive. The object then came back from .NET with no wrapper: its .NET members raisedTypeError: invalid object, and the nexttp_finalizecouldn't hand it to .NET. The weak handle now goes with aConditionalWeakTableentry that keeps the wrapper alive exactly as long as its .NET object. This also fixes that error on master's existing path, for an object without a cycle that comes back from .NET after a .NET GC. All three handle swaps (tp_dealloc,tp_finalize,ToPython) share one helper,ReplaceGCHandle.Known limits:
__namespace__objects where .NET holds only some of them, each object's Python state lasts as long as its own .NET object. The attributes of an object .NET doesn't hold stay reachable from the held ones, but its .NET members raiseTypeErrorafter .NET collects it. On master, the held objects lose all their attributes in this case.__del__replacestp_finalizeand keeps master's behavior.Tests
New tests in
tests/test_subclass.py. They release objects by running Python's GC and .NET's GC, then passing Python objects to .NET to drain the queue of Python objects .NET released:test_namespaced_subclass_held_by_net_keeps_its_cycle: an instance in a cycle through its dict and through a self-referencing list, and a plain Python subclass of it, held in a .NETList. Over two rounds of release and re-acquire, .NET reaches the PythonToStringoverride while only .NET holds them, and the attributes, the cycle and the identity survive. After the list is cleared, every instance is freed (checked with the class's refcount, since freed objects aren't GC-tracked).test_namespaced_subclass_cycle_is_collected: 300 unreferenced instances in self-cycles and pair cycles are freed. In a pair .NET holds one side of, the other side's attributes stay reachable, and both are freed once .NET lets go.test_namespaced_subclass_direct_del_call_keeps_net_object: a direct__del__()call doesn't release the .NET object.test_namespaced_subclass_held_by_net_keeps_its_wrapper[in_cycle]: with and without a cycle, the object returned from .NET still converts back to .NET (List.Contains,GetType()) after a .NET GC.test_namespaced_subclass_resurrected_by_python_keeps_net_object: an instance dropped in a cycle whose other member's__del__appends it to a list keeps its .NET object, both right after .NET's GC and after the finalized object is handled. The previous version of this change failed it withTypeError: Invoked a non-static method with an invalid instance.test_namespaced_subclass_resurrected_by_python_is_collected: that instance keeps its cycle, and it's freed once the list is cleared.test_namespaced_subclass_resurrected_by_python_and_passed_to_net: that instance is passed through a .NETListbefore the finalized .NET object is handled; it keeps its attributes after Python lets go of it while the list holds it, and it's freed once the list is cleared. The previous version of this change crashed on it.test_namespaced_subclass_taken_back_by_python_then_released: an instance .NET held in a cycle is taken back by Python, then released by Python and .NET, and it's freed.test_namespaced_subclass_runs_base_finalizer_once[none|self|resurrected]: a subclass ofPython.Test.FinalizedConstructorTestruns its base finalizer once, without a cycle, in a self-cycle, and after Python gets it back through__del__. The previous version of this change counted 2 for the last two.On master, the first five fail. With each part of the change removed in turn, at least one fails: without clearing the finalized flag, the second round loses the attributes; without the
__del__guard,TypeError: Invoked a non-static method with an invalid instance; without the wrapper table, a segmentation fault; without thetp_deallocfree, the refcount checks fail (leak); without theFinalizebranch, a cycle's attributes are lost. Without the resurrection-tracking handle,TypeError: Invoked a non-static method with an invalid instance. Without deferring the base finalizer, a segmentation fault and a finalizer count of 2. Without re-registering the .NET object, without giving it back to Python, or without thetp_finalizecheck that frees a cycle .NET already let go of, the refcount checks fail. Treating every deferred object as still referenced by Python fails the taken-back test (leak). IfToPythondoesn't clear that check, the passed-to-.NET test loses the attributes. Recording thatToPythontook the reference back only matters when it races .NET's finalizer, which no test can trigger deterministically. On Python 3.7, with the 3.8 flag location or withoutPy_TPFLAGS_HAVE_FINALIZE, three tests lose the attributes.The CI steps, Python 3.11 / .NET 10:
dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 500 passed, 23 skippeddotnet test src/python_tests_runner/: 2 passedpytest --runtime netcore tests/test_subclass.pyalso passes, 25 tests, on Python 3.7.16, 3.8.20, 3.12.16, 3.13.18 and 3.14.10, andpytest --runtime netcore testspasses on 3.7.16 (500 passed, 23 skipped). On 3.7.16, the issue's reproduction prints 7.Also tested end to end in a Lean Python backtest. An algorithm holds the instance above (cycle through its dict and a self-referencing list) in a .NET
List, releases it over two rounds, and checks the attributes and theToStringoverride reached from .NET. It also creates 100 unreferenced instances, clears the list, and checks that no instance is left. It also drops an instance in a cycle whose other member's__del__gives it back to Python, callsGetHashCode()on it before and after the finalized .NET object is handled, then checks that such an instance is freed once released. Last, it passes such an instance through a .NETListbefore the finalized .NET object is handled, lets go of it in Python, and checks its attributes from the list. With this change it loggedcode=7in both rounds, 0 instances left,resurrected by Python: code=7 type=Resurrected, 0 resurrected instances left,passed to .NET after Python got it back, then released by Python: code=7and 0 such instances left. Without it, the backtest failed with'CycleHolder' object has no attribute 'code', as the issue describes.