Skip to content

Keep a __namespace__ subclass's Python state while .NET holds it in a cycle - #176

Open
quantconnect-kronos[bot] wants to merge 8 commits into
masterfrom
kronos/bug-169-namespace-subclass-cycle-attributes
Open

quantconnect-kronos[bot] wants to merge 8 commits into
masterfrom
kronos/bug-169-namespace-subclass-cycle-attributes

Conversation

@quantconnect-kronos

@quantconnect-kronos quantconnect-kronos Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

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 as self.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 own tp_clear, so the no-op ClassDerivedObject.tp_clear can't prevent it.

ClassDerivedObject now has a tp_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, as tp_dealloc already 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:

  • When the object returns to Python (ClassDerivedObject.ToPython), Python takes that reference back and holds the .NET object strongly again.
  • When .NET finalizes the object, the queued cleanup drops that reference, and Python frees the cycle as usual. tp_dealloc then hands the object to .NET as for any object, and .NET's next finalization frees it.
  • The GC calls tp_finalize only once per object, and it sets the object's finalized flag (bit 0 of the GC header's _gc_prev) before the call. tp_finalize clears 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.
  • Another object's __del__ in the same cycle can give Python the object back without going through ToPython. 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 calls PythonDerivedType.PyDeferFinalization: it queues the .NET object and skips the base type's finalizers and PyFinalize. 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 by PyFinalize as on master. The next time the GC finds such a cycle unreachable, tp_finalize lets 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.
  • While Finalizer.Instance.Enable is false, nothing is queued, so the finalization isn't deferred: the base type's finalizers run at once, as on master.
  • tp_finalize makes CPython expose a __del__ wrapper on these types. MetaType.tp_setattro lets 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.
  • The .NET finalizer decides under a lock whether to defer, with tp_finalize and ToPython updating the same state, so ToPython taking 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 raised TypeError: invalid object, and the next tp_finalize couldn't hand it to .NET. The weak handle now goes with a ConditionalWeakTable entry 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:

  • Not the same as master, left out of this PR on purpose and tracked in A closed __namespace__ stream subclass in a reference cycle is never freed #186:
    • A __namespace__ instance whose .NET base type suppresses its own finalizer, such as a stream after Close(), 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 raise TypeError: invalid target, where master keeps it.
    • A cycle Python lets go of keeps its Python objects until .NET's GC confirms .NET no longer holds the __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).
  • An object .NET finalized while Python held it in a cycle, which then stores itself in .NET through one of its own .NET methods rather than as an argument, loses its attributes when Python lets go of the cycle again, as on master.
  • No longer a limit: an object Python gets back through another object's __del__, then passes to .NET (such as List.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).
  • In a cycle of several __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 raise TypeError after .NET collects it. On master, the held objects lose all their attributes in this case.
  • Python weakrefs to an object in such a cycle are cleared when the GC finds the cycle, as for any garbage the GC resurrects.
  • A Python subclass that defines __del__ replaces tp_finalize and keeps master's behavior.
  • An object .NET held in a cycle is freed one .NET finalization later than on master, since its first finalization only drops Python's reference.
  • While Finalizer.Instance.Enable is 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) gains PyDeferFinalization, which the generated finalizers call. PyFinalize keeps 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 .NET List. Over two rounds of release and re-acquire, .NET reaches the Python ToString override 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 .NET List and 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 .NET List without being read back from .NET, the first list is cleared, and the child keeps code == 41 and 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 of Python.Test.FinalizedConstructorTest runs 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: with Finalizer.Instance.Enable false, 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 raises AttributeError: 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 FinalizedConstructorTest subclass instance with instance.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 prints 1 then 1 on 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 skipped
  • dotnet test --runtime any-x64 src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passed
  • pytest --runtime netcore tests: 507 passed, 23 skipped
  • dotnet test --runtime any-x64 src/python_tests_runner/: 2 passed

pytest --runtime netcore tests also 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, kept code=7 and the ToString override 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 .NET List and read back kept code=8 after Python let go of it, and was freed once the list was cleared. A child moved from one .NET List to another kept code=41 and 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 keeps code=0 and its cycle), and a closed stream given back by __del__ raises TypeError: invalid target. Without this change, the child loses its parent's reference before the move, and the algorithm fails in the first round with invalid object when .NET formats the held instance.

@quantconnect-kronos quantconnect-kronos Bot added kronos:develop:working develop: in progress kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 23, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 23, 2026 16:52

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 because subtype_dealloc sets the finalized flag after tp_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/ReleasedByManagedObject are only touched under the GIL. PythonDerivedType.Finalize runs from Finalizer.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.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:high High risk and removed kronos:review:working review: in progress labels Nov 23, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 23, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 23, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested for two cases:

  • An ordinary Python object's __del__ can resurrect the namespaced instance without going through ToPython. The new weak handle then lets .NET collect its managed instance while Python still references it. GetHashCode() raises TypeError: 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.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
Comment thread src/runtime/Types/ClassDerived.cs Resolved
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 23, 2026
quantconnect-kronos Bot and others added 2 commits November 23, 2026 17:23
… 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>
@quantconnect-kronos
quantconnect-kronos Bot force-pushed the kronos/bug-169-namespace-subclass-cycle-attributes branch from c442c5f to 8482a4d Compare November 23, 2026 17:40
@quantconnect-kronos
quantconnect-kronos Bot marked this pull request as draft November 23, 2026 17:42
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 23, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 23, 2026 18:21

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 .NET List also holds it. .NET's call into the ToString override, is identity 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.py passes 20/20. Without HaveFinalize, 3 tests fail. The offset matches the 3.7 PyGC_Head layout: gc_refs is at ob - 16 on 64-bit Linux, and at ob - 8 where long double is 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.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 23, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 23, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 30, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 30, 2026 15:03

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 30, 2026
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 30, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued and removed kronos:review Request review labels Nov 30, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 30, 2026

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
Comment thread src/runtime/Types/ClassDerived.cs Resolved
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 30, 2026
…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>
@quantconnect-kronos

Copy link
Copy Markdown
Author

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.

  • Closed stream keeps its payload: fixed. tp_finalize now also ties a small finalizable object to the .NET object. When .NET collects that object without finalizing it, the finalizable object releases the reference, and if Python still references the object, it gives the .NET object back to Python. Close() stays suppressed and nothing re-registers the stream. Your 10-stream case now leaves 0 payloads and 0 streams, the same as master, and a held closed stream keeps its attributes.
    • The same path also fixes a case you didn't report. A closed stream that another object's __del__ gives back to Python raised TypeError: invalid target on 288df02. It now keeps its .NET object, as on master.
  • Allocation pressure: not changed. Python can't see .NET's references, so payloads in an unreachable cycle wait for a .NET GC. This is the open part of the decision you asked @Martin-Molinero for, and it's listed under Known limits.
  • __del__ assigned after the class is defined: fixed in MetaType.tp_setattro. A __del__ wrapper descriptor no longer blocks the type-dictionary path. Tested on the __namespace__ class and on a plain Python subclass.
  • Child moved from one .NET owner to another: fixed. Converting a __namespace__ object to .NET clears the mark that let the GC free its cycle. Your case now keeps children[0].code == 41, and both objects are freed after children.Clear(). A new test covers it without reading the child back from .NET first.

@jhonabreul

Copy link
Copy Markdown
Collaborator

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 __namespace__ classes that derive from streams, reassign __del__, or move cyclic object graphs between .NET owners.

Developer, please:

  1. Fix the __del__ assignment (C.__del__ = ... raising AttributeError) with the narrow fix the review describes.
  2. Fix the stale marker in the parent and child handoff with the fix the review describes: clear ReturnedToPython when the instance is converted to .NET, under the existing lock.
  3. Add one regression test for each. Nothing else.
  4. Do not change anything for the closed stream case. It is tracked in A closed __namespace__ stream subclass in a reference cycle is never freed #186. List it under "Known limits" with that link, together with the delayed release of unreferenced cycles until a .NET GC runs.
  5. If fix 2 also solves the no-readback List limit, update "Known limits" to say so. Do not add code for it.

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>
@quantconnect-kronos

Copy link
Copy Markdown
Author

@jhonabreul Done in fe5f809, following your decision:

  1. __del__ assignment: the narrow fix. MetaType.tp_setattro lets the type-dictionary path handle __del__ only when the wrapper descriptor's declaring class (__objclass__) is a __namespace__ class. Other wrapper descriptors stay read-only.
  2. Handoff: converting a __namespace__ instance to .NET clears ReturnedToPython under the existing lock.
  3. Tests: test_namespaced_subclass_del_can_be_assigned and test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another. Both fail on 288df02 and pass now.
  4. Closed stream: I removed the release path and its bookkeeping that 35c457d had added for it, so the code is back to 288df02 apart from fixes 1 and 2. The closed-stream case and the delayed release of unreferenced cycles until a .NET GC are now listed under Known limits with A closed __namespace__ stream subclass in a reference cycle is never freed #186. A related closed-stream case is listed there too: a closed stream in a cycle that another object's __del__ gives back to Python raises TypeError: invalid target, while master keeps it.
  5. No-readback List limit: fix 2 also solves it. With the conversion hook disabled, an object Python got back through __del__ and passed to a List without reading it back loses code; with the hook it keeps it. Known limits now says so. I added no code or test for it.

CI steps on Python 3.11 / .NET 10 pass: embedding tests 1049 passed (8 skipped), SetPythonPath 1 passed, pytest 507 passed (23 skipped), managed runner 2 passed. pytest also passes on Python 3.8 and 3.14 (506 passed, 24 skipped each). Tested end to end: #169's case keeps code=7 and the ToString override over two rounds and frees the 100 unreferenced instances, the moved child keeps code=41 and its cycle, the assigned __del__ is called, and the closed-stream cases behave as listed under Known limits.

@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 30, 2026
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added kronos:review:queued review: queued kronos:review:working review: in progress and removed kronos:review Request review kronos:review:queued review: queued labels Nov 30, 2026

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving fe5f809. The two fixes since 288df02 do what the scope decision asks, and #169's goal holds.

  • __del__ assignment: MetaType.tp_setattro lets only a __del__ declared by a __namespace__ class through. Other wrapper descriptors stay read-only. With the MetaType.cs change reverted, test_namespaced_subclass_del_can_be_assigned fails with AttributeError.
  • Moving an object between .NET owners: converting the object to .NET clears the ReturnedToPython mark under the existing lock, the same way ToPython does when the object comes back from .NET. With the Converter.cs change reverted, test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another fails with AttributeError. The hook runs only for IPythonDerivedType objects and takes no GIL under the lock. List.Add of 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.

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/test_subclass.py Resolved
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kronos:develop:working develop: in progress risk:high High risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

__namespace__ subclass held by .NET loses its Python attributes when it is part of a reference cycle

1 participant