Skip to content

Refresh args and __cause__ of a __namespace__ exception created from .NET - #174

Draft
quantconnect-kronos[bot] wants to merge 6 commits into
masterfrom
kronos/bug-168-refresh-dotnet-exception-args
Draft

quantconnect-kronos[bot] wants to merge 6 commits into
masterfrom
kronos/bug-168-refresh-dotnet-exception-args

Conversation

@quantconnect-kronos

Copy link
Copy Markdown

Closes #168

What changed and why

When .NET constructs a generated (__namespace__) exception subclass, for example through Activator.CreateInstance or ConstructorInfo.Invoke, PythonDerivedType.InvokeCtor creates its Python object before the base constructor runs. CLRObject.Create sets the exception's args and __cause__ at that point, from a Message and InnerException the base constructor hasn't set yet, so args held the default message and __cause__ stayed None.

InvokeCtor now sets args and __cause__ again from the constructed exception once the base constructor has run, only on that .NET path (where it created the Python object itself). The registered Python object is kept, and the constructor runs once. Construction from Python is unchanged: ExceptionClassDerivedObject.Init already refreshes them there. Non-exception types are unchanged.

Builds on #167. On current master this path aborts the process as soon as the generated instance returns from .NET; #167 fixes that. This branch therefore contains #167's five commits unchanged, and only the last commit (Refresh args and __cause__ of a __namespace__ exception created from .NET) is this change. Once #167 merges, this branch rebases to that one commit.

Tests

test_namespaced_exception_subclass_created_from_dotnet (subprocess, like #167's tests) constructs a __namespace__ subclass of System.Exception from .NET with Activator.CreateInstance(type, [message, inner]), ConstructorInfo.Invoke([message]), the parameterless constructor, and a two-level __namespace__ chain, and checks that args and __cause__ match Message and InnerException. Without the runtime change (on #167's head) it fails: args is ("Exception of type '...CreatedError' was thrown.",) and __cause__ is None.

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: 490 passed, 23 skipped
  • dotnet test src/python_tests_runner/: 2 passed

Also tested end to end in a Lean Python backtest: an algorithm constructing such a subclass of System.Exception from .NET, with a message and inner exception and with a message only, logged args == ('custom message',) with a cause whose Message is 'inner', and args == ('message only',) with no cause, and passed.

quantconnect-kronos Bot and others added 6 commits November 17, 2026 18:22
A Python subclass of System.Exception, or of any exception type, that
declares __namespace__ gets a generated .NET type, but that type was
reflected as a plain exception rather than as a Python-derived type. Its
Python wrapper never stored itself on the .NET object, so the generated
constructor created a temporary wrapper, kept its pointer and released it:
later calls through the .NET object, such as an overridden virtual method
or the object coming back from .NET, used a freed object and could crash
the process. An __init__ that didn't call the base __init__ also left the
base constructor unrun, so field initializers stayed null.

Generated exception types now get the derived-type handling of ordinary
__namespace__ subclasses (the wrapper set on the object, the base
constructor run before __init__, the object's lifetime tied to the .NET
object) together with the exception repr, str and args.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- 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>
….NET

When .NET constructs a generated exception subclass, its Python object is
created before the base constructor runs, so its args and __cause__ describe
the exception before Message and InnerException were set. Set them again
once the base constructor has run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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 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 because of how the branch is stacked, not because of the fix itself. The fix (5f4ebf3) does what #168 asks, and I found nothing in it that blocks.

Blocking: this branch can't merge before #167. It contains #167's five commits, and #167 still has an open change request: a get_Message override error reached through an inherited ToString with two or more generated levels comes back to Python wrapped in a TargetInvocationException. #167 is also waiting for a person to decide how to continue. If this pull request were approved and merged now, it would bring in all of #167 with that finding still open. Once #167 merges, rebase this onto just the last commit and I'll review that.

The fix itself (5f4ebf3)

  • The refresh runs only when InvokeCtor created the Python object itself, and only after the base constructor has run. The registered wrapper stays, and the constructor runs once. With a two-level chain, the inner generated constructor finds __pyobj__ already set and skips the refresh, so only the outermost level refreshes.
  • From Python, nothing changes, because __pyobj__ is set before the constructor runs. That path still gets its refresh from ExceptionClassDerivedObject.Init.
  • A raising get_Message override now makes construction from .NET throw: Activator.CreateInstance raises a TargetInvocationException wrapping the Python error. Construction from Python already fails the same way, and on master this path aborted the process, so nothing gets worse.

What I verified (Python 3.11 / .NET 10)

  • All nine CI checks pass, including the Lean regression and unit test jobs.
  • tests/test_exceptions.py: 33 passed on this head. With only ClassDerived.cs reverted to #167's head, test_namespaced_exception_subclass_created_from_dotnet fails, with the stale default message in args and no __cause__.
  • Extra checks, all exiting normally:
    • with a get_Message override, args is ('overridden',)
    • a raising override reaches the caller as a catchable error
    • a .NET-created instance raised and caught in Python keeps its args and __cause__
    • 2,000 instances created from .NET, followed by .NET and Python garbage collection

I set risk:high because, as it stands, merging this pull request would ship #167's changes, which are risk:high and not yet approved. Once the branch is just the one commit, the label can be judged on that commit alone.

@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 kronos:develop:idle develop: paused and removed kronos:develop:working develop: in progress labels Nov 23, 2026

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:idle develop: paused risk:high High risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Generated exceptions constructed from .NET retain stale args and omit their cause

0 participants