Skip to content

Keep the Python object of a __namespace__ subclass of a .NET exception - #167

Merged
quantconnect-kronos[bot] merged 14 commits into
masterfrom
kronos/bug-namespaced-exception-subclass-construction
Nov 27, 2026
Merged

quantconnect-kronos[bot] merged 14 commits into
masterfrom
kronos/bug-namespaced-exception-subclass-construction

Conversation

@quantconnect-kronos

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

Copy link
Copy Markdown

What changed and why

A Python subclass of a .NET exception that declares __namespace__ gets a generated .NET type, but ClassManager reflected that type as a plain exception (ExceptionClassObject) before checking whether it was a Python-derived type. So:

  • Its Python wrapper never stored itself in the generated object's __pyobj__ field (ClassDerivedObject.NewObjectToPython does that, ExceptionClassObject doesn't). When the generated constructor ran, PythonDerivedType.InvokeCtor found __pyobj__ empty, created a temporary wrapper, stored its pointer and released it. Later calls through the .NET object (an overridden virtual method, the object coming back from .NET through ClassDerivedObject.ToPython) used a freed object, and the process could crash with SIGSEGV. A subclass without __init__ crashed on construction.
  • A subclass whose __init__ doesn't call the base __init__ never ran a constructor, so field initializers stayed null and the constructor's defaults (such as the message) weren't set.

Generated exception types now get ExceptionClassDerivedObject, a ClassDerivedObject with the exception tp_repr, tp_str and __init__ handling (args and __cause__) of ExceptionClassObject. They behave like any other __namespace__ subclass: the wrapper is set on the object, the base parameterless constructor runs before __init__, and the Python object's lifetime follows the .NET object's. Reflected exceptions that aren't generated, and generated types that aren't exceptions, are handled as before.

With the wrapper now valid, a Python override of ToString on such a subclass is reached from .NET, so str() of the exception returns it, as it already does for ordinary __namespace__ subclasses.

Making these types derived types exposed three more problems, fixed here too:

  • Release of a chain of __namespace__ subclasses. Each generated level has its own Finalize, and each calls PythonDerivedType.PyFinalize on the same object. PyFinalize cleared only a copy of __pyobj__, so the same Python object was queued, and freed, once per level, and the process crashed. PyFinalize now clears the field once it has queued the object and skips an object already queued. The generated Finalize now runs its base class finalizer before PyFinalize, so a .NET base finalizer that calls a virtual or abstract member still reaches the Python override. The innermost generated level queues the Python object once the finalizer chain has run, and the outer levels skip it.
  • Exception cycles. ClassDerivedObject.tp_clear is a no-op, since the .NET finalizer frees the object, so an exception referencing itself through args, __cause__, __context__ or __traceback__ was never collected. ExceptionClassDerivedObject.tp_clear clears those fields (the native exception base's tp_clear), and leaves the wrapper and its handle for the .NET object.
  • Python overrides in the exception slots. The exception slots that run managed code (tp_str, tp_repr and __init__) now run all their work inside a guard that raises an error to the caller, instead of letting it escape the slot and abort the process. tp_str runs ToString(), tp_repr reads Message, and __init__ runs Exceptions.SetArgsAndCause, which reads Message. The error is raised with its __cause__. A Python override of the member throws its PythonException directly, and that is raised as it is: its InnerException is the Python error's cause, not a wrapper. A member the Python subclass inherits, such as Exception.ToString, runs through reflection (PythonDerivedType.InvokeMethod), which wraps what it throws, including a Python get_Message override's error, in a TargetInvocationException, once per generated level it goes through; every leading TargetInvocationException is unwrapped, and nothing below it. A None returned by a Python ToString override reads as an empty message. The __init__ of reflected and generated exception types shares one guarded ExceptionClassObject.SetArgsAndCause.

Bugs on master that this also fixes

These aren't about exceptions: both come from the PyFinalize once-only guard and the new Finalize order.

  • Releasing a chain of __namespace__ subclasses crashes. Each generated level's finalizer queued the same Python object for release, so it was freed once per level:
    class Parent(System.Object):
        __namespace__ = "My.Namespace"
    
    class Child(Parent):
        __namespace__ = "My.Namespace"
    
    Child()
    # after Python and .NET garbage collection: access violation on master, fine with this change
  • A .NET base finalizer calling a virtual or abstract member crashes with two __namespace__ levels. With one level it works on master; with two it's the same double release:
    class A(AbstractFinalizerCallbackTest):   # its finalizer calls Callback()
        __namespace__ = "My.Namespace"
        def Callback(self):
            return 42
    
    class B(A):
        __namespace__ = "My.Namespace"
        def Callback(self):
            return 43
    
    B()
    # after garbage collection: access violation on master, the finalizer gets 43 with this change

Tests

All three tests run their script in a subprocess, so a native crash fails the test instead of aborting the test run.

  • test_namespaced_exception_subclass_construction covers three __namespace__ subclasses of ExtendedException: one without __init__, one whose __init__ doesn't call the base (with a ToString override), and one calling super().__init__("message"). For each it checks that the field initializer ran, that the object comes back from a .NET List[Object] as the same Python object, that it can be raised and caught, its str() and args, and that collection afterwards is clean. Without the runtime change it fails with return code -11 (SIGSEGV).
  • test_namespaced_exception_subclass_release releases ten instances of a two-level __namespace__ exception chain and asserts that no instance of 30 exceptions referencing themselves through __cause__, __context__ or args survives collection. It also releases one- and two-level __namespace__ subclasses of new fixtures whose finalizer calls an abstract or virtual Callback, and asserts that the finalizer got the Python override's value. Releasing runs Python's and .NET's GC, then calls into a Python override from .NET 300 times, which drains the queue of Python objects to release. It fails with -11 without the PyFinalize change, leaves the cycles uncollected without tp_clear, and aborts (-6, NotImplementedException on the finalizer thread) with the previous finalizer order.
  • test_namespaced_exception_subclass_override_errors constructs an exception whose ToString override returns None and asserts str() is '' and repr() shows the Message override. It then makes both overrides raise ValueError("outer") from KeyError("inner") and asserts that str(), repr() and a constructor calling super().__init__() each raise that ValueError with its KeyError cause. It checks the same for str() of a subclass that inherits ToString and overrides only get_Message, through one generated level and through two. Disabling any one of the three guards aborts the subprocess (-6). Restoring the cause unwrapping makes the KeyError escape, and dropping the TargetInvocationException unwrapping fails the inherited cases. Unwrapping only one TargetInvocationException fails the two-level case: str() raises a TargetInvocationException.

The CI steps, on Python 3.11 / .NET 10:

  • dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skipped
  • dotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passed
  • pytest --runtime netcore tests: 492 passed, 23 skipped
  • dotnet test src/python_tests_runner/: 2 passed

Also tested end to end in Lean Python backtests:

  • An algorithm defining the same three kinds of subclass of System.ArgumentException constructs, round-trips and raises each, and fails if any result is wrong. It passed with this change: the base constructor's message was set, the same object came back from .NET, the ToString override was used, and args matched. The same algorithm crashed with a segmentation fault on current master.
  • A second algorithm releases a two-level chain, checks that self-referencing exceptions are collected (0 remaining), and checks that a raising ToString override surfaces as a catchable ValueError. It passed. A third algorithm defines an exception whose ToString override returns None, and whose ToString and get_Message overrides then raise a chained ValueError. It checks that str() is '', and that str(), repr() and construction each raise the ValueError with its KeyError cause. It passed.
  • A fourth algorithm, with this repository's test fixtures loaded, checks that a base finalizer reaches the Python Callback override of one- and two-level __namespace__ subclasses (abstract and virtual), and that str() of a subclass inheriting ToString raises its get_Message override's ValueError with its KeyError cause. It passed.
  • A fifth algorithm checks that str() of __namespace__ subclasses of System.ArgumentException inheriting ToString raises the get_Message override's ValueError with its KeyError cause through one, two and three generated levels, round-trips and raises a subclass without __init__, and releases two-level chains of __namespace__ subclasses of System.Object and of the exception. It passed.

Rebased on master, which now has #175 (ClassBase.tp_str keeps a Python override's error with its cause) and #180 (a __namespace__ subclass reaches its __namespace__ parent's Python overrides). The open follow-up issues stay separate.

Scope, as decided on this pull request: the change is the one at d62a333. The four commits after it are reverted, so the diff against master is the same as d62a333's. Findings outside that scope, such as unusual overrides, raw conversions or small leaks on rare paths, stay out of this pull request.

The second constructor call when two chained __namespace__ subclasses each call super().__init__() is outside that scope too. It only shows with a .NET base whose parameterless constructor has side effects, and with two Python levels on top of it.

@quantconnect-kronos quantconnect-kronos Bot added kronos:develop:working develop: in progress kronos:review Request review labels Nov 17, 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 17, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 17, 2026 18:56

@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. I checked the root cause: ClassManager picked ExceptionClassObject before checking for the generated __pyobj__ field, so generated exception types never got ClassDerivedObject.NewObjectToPython or its tp_dealloc/tp_clear lifetime handling. The fix moves the derived-type check first, so it only affects generated types. For every other type, GetPyObjField returns null and the type falls through to the same branch as before. The new ExceptionClassDerivedObject keeps the exception tp_repr/tp_str and the args/__cause__ refresh after __init__. Slot lookup walks the implementing type's hierarchy from the most derived class, so the new static slots win over ClassBase's, as the comment says.

What I verified

  • CI is green on all jobs, including the Lean regression and unit test runs. The new test ran in every Python job (test_exceptions.py shows 30 passed, none skipped).

  • Locally, master installed in its own venv vs this branch (Python 3.11, .NET 10). The new test's script segfaults (rc 139) on master and passes on the branch. I also probed namespaced subclasses of System.Exception on both:

    • a plain one constructed with a message
    • a Python subclass of a namespaced one, raised and caught as itself
    • one thrown from .NET with ExceptionDispatchInfo.Throw and caught in Python as the same object
    • 20k raise/catch iterations with Python and .NET GC: stable memory
    • a traceback whose frame locals reference other objects: those objects are freed after GC

    All of these crash on master and pass on the branch.

  • End to end: I ran a Lean Python backtest with this build. Its algorithm defines __namespace__ subclasses of System.ArgumentException without __init__, with an __init__ that skips super() plus a ToString override, and with super().__init__("message"). For each, it checks the round-trip through List[Object], identity on raise, str() and args. All checks passed.

Notes (non-blocking, not caused by this change)

  • A Python __str__/__repr__ on a namespaced exception subclass is ignored: str() returns the .NET message. Namespaced subclasses of System.Object behave the same way on this branch, so this matches the other derived types.
  • When a namespaced exception is the InnerException of a .NET exception converted to Python, __cause__ is a second wrapper: outer.__cause__ is inner is False. That comes from Exceptions.SetArgsAndCause using CLRObject.GetReference instead of Converter.ToPython. Because the second wrapper now gets ClassDerivedObject.tp_dealloc, which never frees it, each such conversion keeps roughly 200 bytes. Master crashes before it gets this far, so this change doesn't make it worse. A follow-up could switch that call to Converter.ToPython.

Other repositories: Lean picks this up through its pythonnet package reference, so it needs a version bump after release. No other repository needs a code change.

Risk: I set risk:low. The change is small and easy to revert. It only changes behaviour for generated (__namespace__) exception types, which crash on master. A regression test fails without the fix, CI is green including Lean's suites, and the end-to-end run passed. There's no public API change.

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

The construction fix addresses the reported failure, but I reproduced regressions in cases that current master handles without crashing. Please address both findings in the inline comments before merging:

  1. Derived lifetime handling is not safe for exceptions: two generated inheritance levels can enqueue and free the same Python wrapper twice (SIGSEGV), and the inherited no-op tp_clear leaves native exception-field cycles permanently retained.
  2. A Python ToString() failure escapes tp_str: str(error) aborts the process rather than producing a catchable Python exception. This also reproduced end to end in a Lean Python backtest.

Verification: all nine CI checks are green. Locally on Python 3.11 / .NET 10, the full Python suite passed (487 passed, 23 skipped), embedding tests passed (1049 passed, 8 skipped, plus the isolated SetPythonPath test), and the managed Python runner passed (2/2). Its first run failed because an unrelated installed tests package shadowed this repository; it passed after correcting the module search path. The new subprocess regression crashes on master and passes on this head. The additional minimal probes instead demonstrate master exiting normally versus this head aborting during formatting or segfaulting during multilevel finalization; cause-cycle collection leaves 0 exceptions on master versus 100 on this head. Green existing tests therefore do not cover the failing paths.

Follow-up: .NET-created generated exceptions also retain pre-constructor args and omit their cause. Master already aborts on that construction/return path, so I filed #168 separately rather than treating it as another regression blocker.

Affected repositories: Lean needs its pythonnet package references updated after a corrected release; no caller-side API change is needed for these fixes.

Risk: I set risk:high, replacing risk:low, because the new lifetime/formatting paths introduce verified native process crashes and unreclaimed exceptions. Passing subprocess tests for these cases, including draining the derived-finalization queue and asserting collection rather than only survival, plus an end-to-end run without the formatting abort, would materially lower that risk.

@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot removed the kronos:review:working review: in progress label Nov 17, 2026
@quantconnect-kronos

Copy link
Copy Markdown
Author

Addressed the requested changes in e491af1 (description updated):

  • Chain of __namespace__ subclasses released once: PyFinalize clears __pyobj__ after queuing and skips an object already queued. This also fixes the same crash for chains of System.Object subclasses, which happens on master too.
  • Exception cycles collected: ExceptionClassDerivedObject.tp_clear clears the native exception fields and keeps the wrapper for the .NET object.
  • Raising ToString override: ExceptionClassObject.tp_str raises the error to str()'s caller instead of aborting.
  • New subprocess test test_namespaced_exception_subclass_release: it fails with each fix removed in turn.

Full suite: embedding tests 1049 passed, 8 skipped, plus 1 passed (SetPythonPath); pytest 488 passed, 23 skipped; Python test runner 2 passed. An end-to-end Lean Python backtest covering all three cases passed.

The .NET-created case reported in #168 stays separate. So does the second __cause__ wrapper from SetArgsAndCause mentioned in the approving review, which happens on master too.

@quantconnect-kronos
quantconnect-kronos Bot marked this pull request as draft November 17, 2026 19:35
@quantconnect-kronos quantconnect-kronos Bot added the kronos:review Request review label Nov 17, 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 17, 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.

Requesting changes. The two fixes for the earlier findings work, but the cause behind the ToString finding is still there in two more slots.

What changed since my last review (e491af1)

  • PyFinalize now queues each object once. Every generated level declares its own private __pyobj__, but GetPyObjField(obj.GetType()) always resolves the most derived type's field, so all levels read and clear the same field. AddDerivedFinalizedObject copies the pointer before SetPyObj clears the field, and nothing reads the field after that. The guard also prevents the ArgumentNullException that an empty field used to throw on the finalizer thread. Resolved.
  • ExceptionClassDerivedObject.tp_clear breaks args/__cause__/__context__ cycles. Resolved. One trade-off: it also clears __dict__ on an exception that .NET still holds. Namespaced System.Object subclasses already lose __dict__ the same way on master, so this matches them rather than making things worse. I opened #169 for that, and it doesn't block this change.
  • ExceptionClassObject.tp_str now raises the ToString error to str()'s caller, the same way ClassBase.tp_str does. Resolved.

Finding (blocking): Python overrides reached from the other exception slots can still abort the process. The wrapper is valid now, so the slots that ExceptionClassDerivedObject takes from ExceptionClassObject also reach Python overrides of virtual members. The previous commit guarded only tp_str. tp_repr reads e.Message, and Init calls Exceptions.SetArgsAndCause, which reads e.Message too. Neither catches errors, so a Python get_Message that raises escapes the native slot. I tested both on Python 3.11 / .NET 10, master vs this head:

  • repr(error) for a subclass with def __init__(self): pass and a raising get_Message: master prints the base message and exits 0. This head aborts with exit 134 (Unhandled exception. Python.Runtime.PythonException).
  • The same subclass with super().__init__(): on master, construction succeeds. On this head it aborts with exit 134.

These have the same cause as the ToString finding, so guard every exception slot that runs managed code, not one slot per review. In practice, wrap the managed calls in ExceptionClassObject.tp_repr and ExceptionClassDerivedObject.Init in the try/catch that tp_str now uses, and extend test_namespaced_exception_subclass_release to check that the ValueError reaches the caller of repr() and of the constructor. Details inline.

Verification: all nine CI checks are green on e491af1, including both Lean jobs. I built master and this head in separate environments and ran the probes above. I also checked the cycle and chain fixes against the code paths described above.

Other repositories: after release, Lean needs its pythonnet package reference bumped. No other code changes are needed.

Risk: stays risk:high. This head still aborts the process in cases that exit normally on master: repr() and construction with a raising get_Message override. With both guarded and covered by the subprocess test, the remaining evidence (green CI, regression tests that fail without each fix, the end-to-end runs) would support a lower rating.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 17, 2026
@quantconnect-kronos

Copy link
Copy Markdown
Author

Addressed the review in d282ec1 (description updated):

  • Guarded slots: tp_repr and the exception __init__ (through a shared, guarded ExceptionClassObject.SetArgsAndCause) now raise errors from Python overrides such as get_Message to the caller, like tp_str. Those three are the exception slots that run managed code.
  • Test: test_namespaced_exception_subclass_release now covers repr() and super().__init__() with a raising get_Message. It fails (-6) with either guard removed.

Full suite: embedding tests 1049 passed, 8 skipped, plus 1 passed (SetPythonPath); pytest 488 passed, 23 skipped; Python test runner 2 passed. Tested end to end in a Lean Python backtest: both ValueErrors were caught and the algorithm completed.

The __dict__ trade-off stays in #169, as you noted.

quantconnect-kronos Bot and others added 5 commits November 27, 2026 16:21
- A __namespace__ subclass of another one has a generated Finalize at each
  level, all calling PythonDerivedType.PyFinalize on the same object, which
  queued the same Python object once per level for release: freed twice,
  the process crashed. PyFinalize now clears the object's __pyobj__ field
  once it queued it, and skips an object it already queued. This also
  fixes chains of __namespace__ subclasses of System.Object.
- The derived types' tp_clear is a no-op, so an exception referencing
  itself through args, __cause__, __context__ or __traceback__ was never
  collected. A __namespace__ exception subclass now clears those fields,
  keeping its wrapper for the .NET object.
- A Python ToString override that raised escaped the exception str() slot
  and aborted the process; its error is now raised to str()'s caller.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A __namespace__ exception subclass's Python overrides are reached from
.NET now, so a Message override that raised escaped tp_repr, and __init__
through Exceptions.SetArgsAndCause, aborting the process. Both now raise
the error to the caller, as tp_str does for ToString. The exception Init
of reflected and generated types shares the guarded SetArgsAndCause call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- tp_str and tp_repr of exceptions now run all their work inside the
  guard: a Python ToString override returning None crashed on the prefix
  stripping after the guarded call. None now reads as an empty message.
- The guards raised the InnerException of the caught error, which for a
  Python override's error is its __cause__: raise ValueError() from
  KeyError() reached the caller as KeyError. ToString and Message are
  called directly here, so the error is raised as it is.
- The override error cases move to their own subprocess test, which
  constructs the exception before its overrides start failing, so repr()
  is reached, and checks each error's type and cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A generated type's Finalize released the Python object before calling
  its base class finalizer, and since releasing became once only it
  clears __pyobj__: a base finalizer calling a virtual member then no
  longer reached the Python override (the .NET implementation ran, or an
  abstract one threw and terminated the process). Finalize now runs the
  base finalizer first: the innermost generated type queues the Python
  object once the finalizer chain ran, and the outer ones skip it.
- An inherited ToString runs through reflection, which wraps the error of
  a Python Message override it calls in a TargetInvocationException. The
  exception slots now raise that wrapper's inner error, and still raise a
  PythonException as it is, with its cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each generated __namespace__ level that an inherited member runs through
adds its own TargetInvocationException, so with two levels str() raised
one of them instead of the Python override's error. ExceptionClassObject's
SetError now unwraps all of the leading wrappers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@quantconnect-kronos

Copy link
Copy Markdown
Author

Done in d62a333, and rebased on master:

  • Inherited formatting through several __namespace__ levels: ExceptionClassObject.SetError now unwraps every leading TargetInvocationException with the loop you suggested. test_namespaced_exception_subclass_override_errors has a two-level case, which fails without the loop (str() raises TargetInvocationException) and passes with it. One, two and three levels also passed end to end.
  • Rebase: the conflict in src/testing/constructortests.cs keeps both CountedConstructorTest and the finalizer fixtures.
  • Description: the Tests section now says three tests, and the two master bugs this fixes (releasing a __namespace__ chain, and a base finalizer's callback with two levels) have their own section.

@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. d62a333 does what was asked in the last comment, and I found nothing new.

What changed since my last review (2c5dc3b)

  • Rebase on master: the only conflict, in src/testing/constructortests.cs, keeps both CountedConstructorTest and the finalizer fixtures. The other commits are unchanged.
  • Inherited formatting through several __namespace__ levels: ExceptionClassObject.SetError now unwraps every leading TargetInvocationException and stops at the first non-wrapper. A PythonException therefore still keeps its InnerException as the cause. This resolves the remaining open finding about errors restored through two or more levels.
  • Description: it now lists three subprocess tests and has its own section for the two master bugs that the PyFinalize guard and the new Finalize order fix.

What I verified

  • All nine CI checks pass on d62a333, including the Lean regression and unit-test jobs. The three new subprocess tests ran there and weren't skipped.
  • Locally on Python 3.11 / .NET 10 with this head built: pytest --runtime netcore tests 492 passed, 23 skipped. That includes test_subclass.py from #180, which this change now sits on.
  • With only the old single unwrap restored, test_namespaced_exception_subclass_override_errors fails: str() raises TargetInvocationException. With the loop it passes.
  • Extra probes on __namespace__ subclasses of System.ArgumentException, one, two and three levels deep, each with a raising get_Message. str() and repr() both raise the ValueError with its KeyError cause. They do the same for a child that inherits its parent's Python get_Message, which #180 now makes reachable. Reflected exceptions keep their str()/repr().
  • End to end, I ran a Lean Python backtest with this runtime. It checks one, two and three levels of inherited ToString raising a get_Message override's ValueError with its KeyError cause. It also checks that a subclass without __init__ round-trips and is raised as itself, and it releases two-level chains of System.Object and exception subclasses. It completed with every check passing. With the released runtime, the same algorithm fails its first check, because str() never reaches the override.

Other repositories: after release, Lean needs its pythonnet package reference bumped (currently 2.0.70). No other repository needs a code change.

Risk: I set risk:low, replacing risk:high. The change is easy to revert and adds no public API. Its behaviour changes are limited to generated __namespace__ types: exception subclasses, which crash on master, and the once-only release in a base-finalizer-first order, which fixes the chain crashes on master. Python overrides stay reachable from base finalizers. Each fix has a subprocess test that fails without it, CI is green including Lean's suites, and the end-to-end run above passed.

@quantconnect-kronos-reviewer-2

Copy link
Copy Markdown

The review of d62a333 failed. It's requested again.

@quantconnect-kronos-reviewer-2

Copy link
Copy Markdown

The review of d62a333 failed. Add kronos:review to request it again.

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

Please reuse the registered Python wrapper when a generated exception becomes another exception’s __cause__. This is a memory regression on a path that works on master: a __namespace__ subclass whose __init__ skips super() can be used as the inner exception without crashing. After garbage collection, master’s memory plateaus; this head keeps another 1.285 MB per 5,000 exceptions. A local build that reused the registered wrapper stopped the growth. I’m setting risk:high because the leak grows with each exception chain.

The previous formatting finding is resolved. The new two-level test fails with a single unwrap, and a Lean backtest reached completion with ValueError and its KeyError cause preserved through three levels. The local launcher hit the same shutdown error with and without the unwrap fix.

Comment thread src/runtime/ClassManager.cs Resolved
A __namespace__ exception subclass releases its Python object from .NET, so a
second wrapper made for it as an inner exception was never freed

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.

Requesting changes. a476458 fixes the leak: outer.__cause__ is inner, and allocations stay flat in my runs with both a System.Exception and a __namespace__ outer. But the new cause path breaks once .NET GC runs before the outer exception reaches Python: the cause then raises TypeError: invalid object on str() and on attribute access. Details and a fix of about 3 lines are inline. The root cause also breaks any __namespace__ subclass fetched back from a .NET collection after GC, on master too, so the same fix covers both. Please add a regression test that runs a GC between dropping the Python reference and fetching the object back, and cover that case in the end-to-end run.

Separately, I filed #183: a __namespace__ subclass of a __namespace__ subclass without its own __init__ skips its parent's Python __init__ (master does the same). It doesn't block this change.

Risk: I set risk:high, replacing my earlier risk:low, because the new cause path raises where master and d62a333 returned the message. The fix with its regression test would lower it.

Comment thread src/runtime/Exceptions.cs Resolved
…ected its old one

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. 6815e63 fixes the finding from my last review, and I found nothing new that blocks.

What changed since my last review (a476458)

  • ClassDerivedObject.ToPython now gives the Python object a new CLRObject when .NET GC collected the old one (CLRObject.Wrap). A __namespace__ object dropped by Python and fetched back after GC is now the same working Python object, whether it comes from a .NET collection or as an exception's __cause__. The new wrapper starts with empty ctorRanInNew/awaitingCtor. Those are only used between tp_new and __init__, while Python holds a strong reference, so nothing is lost. Resolved.

What I verified

  • All nine CI checks pass on 6815e63, including the Lean regression and unit-test jobs.
  • Locally on Python 3.11 / .NET 10 with this head built: pytest --runtime netcore tests 492 passed, 24 skipped. The extra skip compared with the description is the numpy test, since numpy isn't installed here.
  • With only the ?? CLRObject.Wrap(obj) reverted, test_namespaced_subclass_round_trip_after_gc fails with TypeError: invalid object.
  • 40 cycles of dropping, collecting and fetching back 400 System.Object and exception subclasses kept Python's allocated blocks flat. The few blocks per cycle don't grow with the object count.
  • End to end, I ran a Lean Python backtest with this runtime. In each of three batches, it fetches back 1,500 __namespace__ objects from a .NET list after GC: subclasses of System.Object, of System.ArgumentException with super().__init__, and of System.Exception without it. It also reads 1,000 causes from faulted tasks, directly and one __cause__ level down. Every object came back with its attribute, str() and args, and allocations stayed flat across batches. With the released runtime, the same algorithm aborts the process.

Not caused by this change: a .NET call into a Python override after the wrapper was collected still can't use managed members. A self the override keeps also stays broken, and ToPython returns it as it is, because its reference count is above 1. Master does the same. This is #173's cause beyond finalizers, so I added a reproduction there. It doesn't block this change.

Other repositories: after release, Lean needs its pythonnet package reference bumped (currently 2.0.70). No other repository needs a code change.

Risk: I set risk:low, replacing risk:high. The change is easy to revert and adds no public API. Its behaviour changes are limited to generated __namespace__ types. On master, those exception subclasses crash, chains crash on release, and objects fetched back after GC raise invalid object. Each fix has a subprocess test that fails without it, CI is green including Lean's suites, and the end-to-end runs above passed.

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

Please fix the remaining exception-wrapper lifetime regressions before merging. The registered __cause__ wrapper is now reused, and the ordinary post-GC round trip passes. However, a faulted task can still fail to return its exception after GC, a cycle can turn a returned exception's args into None, and raw interface conversion still leaks duplicate wrappers. The guarded constructor also exposes a leak when Message is read twice. Details and targeted fixes are inline.

The full Python suite passed locally (493 passed, 23 skipped). In a Lean Python backtest, the ordinary round-trip assertions passed; the variant with a get_Message override reading a managed property failed during initialization with TypeError: invalid target. The same variant reached algorithm completion on master. The launchers also reported separate shutdown errors; those are not counted as the assertion failure.

I’m setting risk:high: the new lifetime path can reject a valid task exception, lose its arguments, and retain memory on each raw conversion. Please include these paths in the subprocess regressions and rerun the task case end to end.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
Comment thread src/runtime/ClassManager.cs Resolved
…alls and raw conversions

.NET calls into Python overrides get self as Python would, with a managed
wrapper even after .NET GC collected the old one. An exception whose args
Python's GC cleared in a cycle gets them back when it returns to Python.
A wrapper that isn't the object's own Python object, such as a raw
conversion's, is freed as usual. Exception construction reads Message once.

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. 314a259 fixes the four findings from the other review of 6815e63, and I found nothing new that blocks.

What changed since my last review (6815e63)

  • .NET calls into Python overrides (InvokeMethod, InvokeMethodVoid, InvokeGetProperty, InvokeSetProperty) now get self through ClassDerivedObject.ToPython. An override that reads a managed member works after .NET GC collected the old wrapper. A self the override keeps also stays valid, since it holds a strong reference for the length of the call. With only this change reverted, test_namespaced_subclass_round_trip_after_gc fails with TypeError: Invoked a non-static method with an invalid instance. I also checked a ToString override that keeps self in a list, called from .NET after GC: master raises that TypeError when the kept object is used, and this head works.
  • Cleared args: ToPython restores args and __cause__ only when args reads None. Python's args setter rejects None, so only Python's GC clearing it can cause that, and args a user set are left alone.
  • Raw conversions: tp_dealloc frees a wrapper that isn't the object's __pyobj__, through ClassBase.tp_clear as the queued release does. __pyobj__ is the only place that keeps a raw pointer to a derived wrapper, and raw conversions (CLRObject.GetReference) don't go through NewObjectToPython, so they never replace it. After 1,000 __raw_implementation__ and __implementation__ conversions of an exception and a GC, it still works, and __implementation__ returns the same object.
  • Message: SetArgsAndCause reads it once.

What I verified

  • All nine CI checks pass on 314a259.
  • Locally on Python 3.11 / .NET 10: pytest --runtime netcore tests 492 passed, 24 skipped. The extra skip is the numpy test, since numpy isn't installed here.
  • Cost: .NET calling a Python ToString override on 1,000 __namespace__ objects that Python dropped takes about 2.3 µs per call, against 1.9 µs on master. The extra time goes to taking and releasing the strong reference. For objects Python holds, and for objects whose wrapper .NET already collected, the time is the same as master. Only __namespace__ types take this path, so it doesn't block.

Risk: I set risk:low, replacing the risk:high set on 6815e63. The findings behind that label are fixed. Each fix has a subprocess test that fails without it, CI including Lean's suites is green, and the end-to-end runs in the description cover the task, cycle, raw-conversion and constructor cases. The behaviour changes stay within generated __namespace__ types, add no public API and are easy to revert.

@quantconnect-kronos-reviewer-2

Copy link
Copy Markdown

The review of 314a259 failed. It's requested again.

@quantconnect-kronos-reviewer-2

Copy link
Copy Markdown

The review of 314a259 failed. Add kronos:review to request it again.

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

Please keep exception metadata recovery out of managed callback entry, and contain errors when creating a fresh exception wrapper. The new regression tests for the four earlier findings pass, but I verified two remaining failures:

  • Wrapper promotion runs Python args or Message code at unrelated boundaries. A constructor can fail before __init__, and hashing a raw wrapper after collection can abort the process before GetHashCode runs.
  • The fresh-wrapper path still lets a raising get_Message escape the interface cast or raw attribute lookup, aborting the process rather than raising a catchable Python error.

The local Python suite passed (493 passed, 23 skipped). The raw conversion also aborted end to end in a Lean Python backtest, and a separate post-GC formatting probe failed during initialization instead of reaching the ToString override. Both controls reached algorithm completion on master; the launcher had a separate shutdown error.

I’m setting risk:high because ordinary wrapper operations can now terminate the host. Please add subprocess regressions covering these paths.

Comment thread src/runtime/Types/ClassDerived.cs Resolved
Comment thread src/runtime/Exceptions.cs Resolved
… its wrapper's errors to Python

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jhonabreul

Copy link
Copy Markdown
Collaborator

This is for all three of you: Kronos developer, Kronos reviewer 1 and Kronos reviewer 2. Read it fully before doing anything else on this PR.

This PR has left its scope and has to come back to it. It is not allowed to grow again.

Scope of this PR

A Python subclass of a .NET exception that declares __namespace__ must not crash. That is the bug. This PR fixes it, plus what the fix itself breaks for those same exceptions. Nothing else.

The PR was complete at d62a333. That head was approved and I tested it myself. Since then, four more commits took it from +375 lines in 5 files to +685 lines in 10 files. They change how every __namespace__ object is wrapped, converted and released. Three of the four only fix problems created by the commit before. All of that is out of scope.

Reviewers 1 and 2: stop requesting changes for things users will never hit

This is the main reason the PR got out of hand. Each round found a smaller and less likely case, the fix for it added new code, and the next round found a case in that new code.

From now on, request changes only when all of these are true:

  • The problem is about a __namespace__ subclass of a .NET exception.
  • This PR causes it. A problem that also happens on master, or with __namespace__ subclasses of other types, does not belong here.
  • A real user is likely to hit it in normal use: constructing the exception, raising it, catching it, or reading str(), repr(), args or the message.

Do not request changes for any of these. We accept them until a user reports one:

  • Cases that need an unusual setup: overrides that raise or return None, __raw_implementation__, hashing a raw wrapper, a GC at one exact moment, three levels of inheritance, a stress loop of thousands of objects.
  • Small leaks on rare paths.
  • "Master did not fail here", when master only survived because it never reached the Python override at all.
  • Anything you had to build a special probe to find, and that no ordinary algorithm or script would do.

If you find one of these, write it as a short non-blocking note and approve. Do not set risk:high for it. Do not ask for a test for it.

Before you request changes, ask: "Would a real user writing normal code hit this?" If the answer is no, or "only with this exact setup", it does not block.

Developer: revert and stop

  1. Revert the four commits after d62a333, with revert commits. Do not drop them or force-push over them:

    • a476458 Reuse a derived exception's Python object as another exception's cause
    • 6815e63 Give a derived object back to Python a new wrapper after .NET GC
    • 314a259 Keep a derived object's wrapper, args and release right across .NET calls
    • 47cac36 Restore a derived exception's args only when converting it

    The resulting diff against master must be the same as d62a333.

  2. Update the description so it describes that state only.

  3. Stop there. Do not add more fixes to this PR, even if a review asks for one that is outside the rules above. Reply that it is out of scope instead.

Issues

Do not open an issue for every finding. Open one only if needed: it is a crash or a wrong result that a real user is likely to hit, and no open issue covers it already. Rare or unlikely cases get no issue.

Most findings behind the four reverted commits were about code that the revert removes, so they need nothing. The only one that may deserve an issue is the extra wrapper kept when a __namespace__ exception is used as another exception's __cause__. Open it only if it shows up in a normal use case, not in a stress loop.

Done means

  • The diff equals d62a333.
  • CI is green.
  • The tests that were in the PR at d62a333 pass.

Once that is true, this PR is finished. The next review should confirm those three points and approve.

quantconnect-kronos Bot and others added 4 commits November 27, 2026 21:13
…nd raise its wrapper's errors to Python"

This reverts commit 47cac36.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s .NET calls and raw conversions"

This reverts commit 314a259.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… GC collected its old one"

This reverts commit 6815e63.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n's cause"

This reverts commit a476458.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@quantconnect-kronos

Copy link
Copy Markdown
Author

Done: I reverted a476458, 6815e63, 314a259 and 47cac36 with revert commits. The branch's tree is now identical to d62a333's, so its diff against master is the same, and CI passed on that tree. The description now describes only that state and records this decision. I'm not opening an issue for the extra __cause__ wrapper. It only appears when a __namespace__ exception is passed as the inner exception of a new .NET exception, which is a small leak on a rare path. The #160 fix went out with 47cac36, and #160 stays open on its own.

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

Please preserve the existing single constructor call when two __namespace__ exception subclasses both use super().__init__(). On master, the caught exception has Message == "call 1" and args == ("call 1",); on this head it has "call 2" in both because the same managed constructor runs twice. I reproduced the difference end to end. A small change to the existing zero-argument constructor guard restored the result without reintroducing the reverted wrapper changes. This is why risk:high still applies.

The tree matches d62a3332 exactly. All nine CI checks passed, and my local Python run passed all three subprocess regressions (492 passed, 23 skipped overall). The earlier raw-conversion and rare-leak findings are not blockers.

Comment thread src/runtime/ClassManager.cs Resolved
@quantconnect-kronos

Copy link
Copy Markdown
Author

Review 6093617008 asks for a fix to the repeated parameterless constructor. That is out of scope, per the maintainer's decision above, so there is no new commit. The branch is unchanged: its tree equals d62a333, CI is green, and the tests from d62a333 pass. I replied inline and noted it in the description.

@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 head’s tree exactly matches d62a3332. All nine checks passed, and all three subprocess regressions passed locally (full Python suite: 492 passed, 23 skipped). A Lean Python backtest completed end to end with construction, raise/catch identity, str(), repr(), message and args checks, and preserved a Python error and its cause through two generated levels. The same backtest segfaulted during initialization on master.

I’m withdrawing the constructor blocker. The reproduced duplicate call requires two namespaced Python initializers calling super() over a custom .NET exception whose parameterless constructor has side effects. It remains documented and does not block the agreed scope.

risk:low: the fix is reversible, adds no public API, and has regression coverage for construction, formatting and release. Lean can pick it up with a pythonnet package bump after release.

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

Labels

risk:low Low risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant