Repository navigation
Refresh args and __cause__ of a __namespace__ exception created from .NET - #174
quantconnect-kronos[bot] wants to merge 6 commits into
Conversation
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>
There was a problem hiding this comment.
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
InvokeCtorcreated 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 fromExceptionClassDerivedObject.Init. - A raising
get_Messageoverride now makes construction from .NET throw:Activator.CreateInstanceraises aTargetInvocationExceptionwrapping 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 onlyClassDerived.csreverted to #167's head,test_namespaced_exception_subclass_created_from_dotnetfails, with the stale default message inargsand no__cause__.- Extra checks, all exiting normally:
- with a
get_Messageoverride,argsis('overridden',) - a raising override reaches the caller as a catchable error
- a .NET-created instance raised and caught in Python keeps its
argsand__cause__ - 2,000 instances created from .NET, followed by .NET and Python garbage collection
- with a
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.
Closes #168
What changed and why
When .NET constructs a generated (
__namespace__) exception subclass, for example throughActivator.CreateInstanceorConstructorInfo.Invoke,PythonDerivedType.InvokeCtorcreates its Python object before the base constructor runs.CLRObject.Createsets the exception'sargsand__cause__at that point, from aMessageandInnerExceptionthe base constructor hasn't set yet, soargsheld the default message and__cause__stayedNone.InvokeCtornow setsargsand__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.Initalready refreshes them there. Non-exception types are unchanged.Builds on #167. On current
masterthis 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 ofSystem.Exceptionfrom .NET withActivator.CreateInstance(type, [message, inner]),ConstructorInfo.Invoke([message]), the parameterless constructor, and a two-level__namespace__chain, and checks thatargsand__cause__matchMessageandInnerException. Without the runtime change (on #167's head) it fails:argsis("Exception of type '...CreatedError' was thrown.",)and__cause__isNone.The CI steps, on Python 3.11 / .NET 10:
dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1049 passed, 8 skippeddotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 490 passed, 23 skippeddotnet test src/python_tests_runner/: 2 passedAlso tested end to end in a Lean Python backtest: an algorithm constructing such a subclass of
System.Exceptionfrom .NET, with a message and inner exception and with a message only, loggedargs == ('custom message',)with a cause whoseMessageis'inner', andargs == ('message only',)with no cause, and passed.