Repository navigation
Keep a __namespace__ subclass's Python state while .NET holds it in a cycle - #176
quantconnect-kronos[bot] wants to merge 8 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.
Approving 288df02. The two changes since 598f456, the fix for Finalizer.Instance.Enable = false and the merge of master's finalizer order, do what the decision on this PR asks. I found no regression against master 865d592.
Results on master and on this head, Python 3.11 / .NET 10:
| Case | master | head |
|---|---|---|
| The issue's reproduction | AttributeError |
7 |
| The disabled-finalizer script from the earlier review: base finalizer count while disabled, then after re-enabling | 1, 1 |
1, 1 |
A __namespace__ subclass of a __namespace__ subclass of FinalizedConstructorTest, in a self-cycle and held by a .NET List: attribute, then base finalizer count and instances freed once released |
AttributeError, then 2 for 2 instances, both freed |
7, then 2 for 2 instances, both freed |
A __namespace__ subclass of System.Exception in a self-cycle, held by .NET |
AttributeError |
7 |
| 200 such exceptions raised and caught in Python, which puts each one in a traceback cycle | all freed | all freed |
| A base finalizer calling a Python override that returns a constant, with and without a cycle, abstract and virtual base | 42 |
42 |
With master's finalizer order, a chain of generated types calls PyDeferFinalization at each level, but only the outermost call can defer. A deferred finalization skips every inner level, and the next one runs master's sequence unchanged. Locally, pytest --runtime netcore tests gives 505 passed and 23 skipped, and CI passes on Python 3.8 to 3.14 and on the Lean jobs.
Non-blocking, and the same on master: an object in a self-cycle whose .NET base finalizer calls a Python override that reads an instance attribute crashes the process once it's released, because the cycle's dict is already cleared by then. This needs a .NET finalizer that calls a virtual member, which algorithm code doesn't have, so I'd list it under Known limits rather than fix it here.
I'm keeping risk:high. The fix still writes a bit in CPython's private GC header and changes how long every __namespace__ subclass instance and its wrapper stay alive.
There was a problem hiding this comment.
Changes requested. Closing a cyclic __namespace__ stream now keeps its Python payload alive indefinitely. Assigning __del__ after class creation now raises AttributeError. And an ordinary cyclic object graph still loses a child's attributes when Python moves it from one .NET owner to another; this does not require custom __del__ code. Reproductions and narrow fixes where available are inline.
@Martin-Molinero Decision needed: should Python cycle cleanup be decoupled from the generated .NET finalizer, or should #169 wait for a narrower design? Stream.Close() legitimately suppresses .NET finalization, so the new Python reference has no release path. Re-registering the stream would undo .NET's suppression.
- A. Separate the release path for the Python cycle reference (recommended). Keep state while .NET holds the instance, collect the cycle after .NET releases it, and preserve
Close()semantics. This requires a new lifetime notification or equivalent bookkeeping, and should not depend on .NET allocation pressure to release large Python payloads. - B. Defer this fix until there is a smaller way to preserve both behaviors. That leaves #169 open rather than introducing a leak for disposed objects.
Reply with the option you choose, or another way to go.
On master and this head, the earlier base-finalizer probe now counts 1 with and without a cycle, and 1 both before and after re-enabling the bridge finalizer. Tested end to end: the original reproduction preserves code=7, identity, and override dispatch on this head and frees the unreferenced instances; master loses code. The disposal and handoff results below also reproduced end to end. Both builds hit the same shutdown error after the probes, so these runs do not establish clean shutdown.
|
|
||
| // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again | ||
| FinalizedFlagWord(ob) &= ~FinalizedFlag; | ||
| Runtime.XIncref(ob); |
There was a problem hiding this comment.
Closing a stream prevents release of the reference taken here. Stream.Close() suppresses its .NET finalizer. For class S(MemoryStream): __namespace__ = 'Repro', create 10 instances with s.me = s and s.payload = Payload() (a plain Python class), call s.Close(), and drop s each time. After seven rounds of Python GC, .NET GC, pending-finalizer wait and queue drain, master has 0 payloads and 0 GC-tracked streams; this head has 10 of each. Without Close(), both have 0. I reproduced the same counts end to end. The extra Python reference survives even though neither side holds the stream anymore. The same dependency also delays ordinary collection under Python allocation pressure: 6,000 throwaway self-cycles with a 64 KiB bytearray each retained about 8 MB on master and 395 MB on head after 17 automatic Python GC passes and no .NET GC on either build. Both dropped to about 0.55 MB after explicitly running both collectors and draining the queue. Collect cycles without re-enabling a suppressed managed finalizer, and preserve state when .NET still holds the instance, including a closed stream.
…lized, and keep its state across .NET owners A closed stream's .NET finalizer is suppressed, so the reference its .NET object kept in tp_finalize was never released: a finalizable object tied to the .NET object now releases it once .NET collects that object, and gives the .NET object back to Python if Python still references it. Passing the object to .NET again keeps its cycle from being cleared, and __del__ can be assigned after the class is defined again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Fixed in 35c457d. All three findings were regressions against master, so under the scope decision they're fixed. The description has the details and results.
|
|
This answers the decision asked in #176 (review). Decision: neither A nor B. Fix the two small bugs, and this PR is done. Please keep things within scope. This PR exists to fix #169, and that is all it needs to do. If users are not likely to write the code that reproduces a bug, it is not worth fixing here. Our users write Lean (QuantConnect) algorithms in Python, and those do not declare Developer, please:
No redesign, no new release path, no new bookkeeping. Reviewers:
|
As decided on the pull request, the closed stream case is left for #186: this removes the finalizable object that released a .NET object's Python reference when .NET collected it unfinalized, and the deferred finalizer's re-registration goes back to the queued cleanup. Assigning __del__ is allowed only over the wrapper a __namespace__ class declares, since its tp_finalize adds it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@jhonabreul Done in fe5f809, following your decision:
CI steps on Python 3.11 / .NET 10 pass: embedding tests 1049 passed (8 skipped), SetPythonPath 1 passed, |
There was a problem hiding this comment.
Approving fe5f809. The two fixes since 288df02 do what the scope decision asks, and #169's goal holds.
__del__assignment:MetaType.tp_setattrolets only a__del__declared by a__namespace__class through. Other wrapper descriptors stay read-only. With theMetaType.cschange reverted,test_namespaced_subclass_del_can_be_assignedfails withAttributeError.- Moving an object between .NET owners: converting the object to .NET clears the
ReturnedToPythonmark under the existing lock, the same wayToPythondoes when the object comes back from .NET. With theConverter.cschange reverted,test_namespaced_subclass_cycle_passed_from_one_net_owner_to_anotherfails withAttributeError. The hook runs only forIPythonDerivedTypeobjects and takes no GIL under the lock.List.Addof a__namespace__object takes about 0.93 µs with or without it.
Python 3.11 / .NET 10, locally: #169's reproduction prints 7, and pytest --runtime netcore tests gives 507 passed, 23 skipped.
I'm keeping risk:high. The fix writes a bit in CPython's private GC header and changes how long __namespace__ instances live. It also keeps the closed-stream and delayed-release differences from master that were accepted for #186.
Once a package with this change is released, Lean's pythonnet version needs a bump.
There was a problem hiding this comment.
Approving the scoped fix for #169. Tested end to end: the managed-held cycle kept code=7, object identity, and the Python ToString override across two collection rounds. None of 100 unreferenced instances remained after both collectors ran. The child kept code=41 and its cycle when moved between .NET owners, and __del__ could be assigned and called on both class forms. The last two probes failed on 288df02c; on master, #169 still raises AttributeError and assigning __del__ works. The earlier no-readback case also kept code=7 on this head and raised AttributeError on master. Both master and this head hit the same shutdown error after the backtest probes, so this does not verify clean shutdown.
One optional test tweak is inline. The accepted disposal and delayed-release limits remain tracked in #186. Lean needs the updated pythonnet package after release.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approving 5ab558b. The only change since fe5f809 is the test reorder: PlainSubclass.__del__ is now assigned first, so it replaces the inherited wrapper rather than a function assigned in Python. With the MetaType.cs change reverted, test_namespaced_subclass_del_can_be_assigned now fails on that first assignment with AttributeError: attribute is read-only. With the change, tests/test_subclass.py gives 29 passed (Python 3.11 / .NET 10).
There was a problem hiding this comment.
Approving 5ab558b9. The reordered test now replaces the inherited __del__ wrapper before the base class gets a Python __del__. That first assignment raises AttributeError on 288df02c and succeeds here. The runtime code is unchanged from the end-to-end-tested revision. Locally, 507 Python tests passed (23 skipped).
Closes #169
Scope, as decided by a QuantConnect member in #176 (comment): a regression against master always gets fixed. A bug that isn't a regression gets fixed only if realistic algorithm code can hit it; otherwise it's listed under Known limits. Only the Python versions CI runs are supported, 3.8 to 3.14. The scope was then narrowed in #176 (comment): this fixes #169, the two review findings realistic code can hit (
__del__assignment and the .NET owner handoff), and nothing more.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.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 (bit 0 of the GC header's_gc_prev) 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. 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 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 first callsPythonDerivedType.PyDeferFinalization: it queues the .NET object and skips the base type's finalizers andPyFinalize. The queue keeps the .NET object alive until the cleanup handles it: that drops the reference and, if Python still references the object, the Python object holds the .NET object strongly again. Either way, the .NET object is re-registered for finalization, so the base type's finalizers run once, when .NET finalizes the object for good, followed byPyFinalizeas on master. 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: converting it to .NET (Converter) clears that mark.Finalizer.Instance.Enableis false, nothing is queued, so the finalization isn't deferred: the base type's finalizers run at once, as on master.tp_finalizemakes CPython expose a__del__wrapper on these types.MetaType.tp_setattrolets Python code assign__del__over the wrapper a__namespace__class declares, as on master, where the types have none. Other wrapper descriptors stay read-only.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, each the same as or better than master unless noted:
__namespace__instance whose .NET base type suppresses its own finalizer, such as a stream afterClose(), is never freed if it's in a Python cycle when Python lets go of it, nor is anything it holds. Master frees it. A closed stream in a cycle that another object's__del__gives back to Python also loses its .NET object: its .NET members raiseTypeError: invalid target, where master keeps it.__namespace__object, which Python can't see. Under Python allocation with no .NET GC, payloads in such cycles build up until the next .NET GC; master frees them at once (and loses the attributes of those .NET still holds).__del__, then passes to .NET (such asList.Add) and lets go of without reading it back from .NET, keeps its attributes while .NET holds it. The .NET owner handoff fix covers it, since passing the object to .NET clears the mark. Master loses them (AttributeError).__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.Finalizer.Instance.Enableis false, a Python object .NET held in a cycle isn't freed, as master doesn't free any Python object .NET finalizes then.The backwards-compatible API change:
PythonDerivedType(public, marked for internal use) gainsPyDeferFinalization, which the generated finalizers call.PyFinalizekeeps its signature.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.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 .NETListand read back before 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.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_cycle_passed_from_one_net_owner_to_another: a parent and child in a cycle, the parent held by .NET; the child is moved to another .NETListwithout being read back from .NET, the first list is cleared, and the child keepscode == 41and its cycle. Both are freed once the second list is cleared.test_namespaced_subclass_del_can_be_assigned:__del__assigned after the class is defined, on the__namespace__class and on a plain Python subclass, is called directly.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__.test_namespaced_subclass_runs_base_finalizer_while_finalizer_disabled: withFinalizer.Instance.Enablefalse, an instance Python took back from .NET and released runs its base finalizer once. Without the fix it counts 0.On master, the first five fail. On 288df02, the cycle handoff test fails, and the
__del__assignment test raisesAttributeError: attribute is read-only. With each part of the change removed in turn, at least one test fails.Base finalizer counts, with the self-cycle script of the review on 598f456 (one
FinalizedConstructorTestsubclass instance withinstance.me = instance, released over 6 rounds), on master 865d592 and on this head: 1 and 1. Without the cycle: 1 and 1. The disabled-finalizer script of that review prints1then1on both (0 and 0 on 598f456).The CI steps, Python 3.11 / .NET 10:
dotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 507 passed, 23 skippeddotnet test --runtime any-x64 src/python_tests_runner/: 2 passedpytest --runtime netcore testsalso passes on Python 3.8.20 and 3.14.10 (506 passed, 24 skipped each).Also tested end to end in a Python algorithm: an instance in a cycle through its dict and a self-referencing list, held in a .NET
List, keptcode=7and theToStringoverride reached from .NET over two rounds of release and re-acquire, and 100 unreferenced instances left 0 behind. An instance Python got back through another object's__del__kept its .NET object (GetHashCode()before and after the finalized .NET object was handled) and was freed once released; one passed through a .NETListand read back keptcode=8after Python let go of it, and was freed once the list was cleared. A child moved from one .NETListto another keptcode=41and its cycle, and__del__assigned after the class was defined was called. The closed stream cases behave as described for #186: of 20 closed streams in self-cycles, all 20 payloads stay alive (the held one keepscode=0and its cycle), and a closed stream given back by__del__raisesTypeError: invalid target. Without this change, the child loses its parent's reference before the move, and the algorithm fails in the first round withinvalid objectwhen .NET formats the held instance.