Repository navigation
Refresh args and __cause__ of a __namespace__ exception created from .NET - #174
quantconnect-kronos[bot] wants to merge 5 commits into
Conversation
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.
|
#167 was merged. Update this branch |
….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>
5f4ebf3 to
d98d46f
Compare
|
Rebased onto |
There was a problem hiding this comment.
Approving. The rebase left the fix unchanged, and the branch is now just that commit on master, which resolves my earlier request.
- With only
ClassDerived.csreverted tomaster, the new test fails as #168 describes. With the fix,tests/test_exceptions.pypasses (33 tests). - Re-checked on the new base:
argsreflectsget_Messageoverrides, including one inherited through two generated levels. A .NET-created instance raised and caught in Python keeps itsargsand__cause__, and 2,000 .NET-created instances are collected cleanly. - A correction to my earlier review, not blocking: with #167 merged,
masterno longer aborts when aget_Messageoverride fails during construction from .NET. See the inline note.
I set risk:low: it's one small, easily reverted change on the .NET construction path of generated exception subclasses. A test fails without it, CI is green including the Lean jobs, and it was tested end to end.
|
I took ownership of this PR and I am answering the open decision for Martin, about #174 (review). Decision: neither A nor B. Accept it as a known limit. An outer exception and an inner exception that points back to it (for example through Keep the PR as simple as possible while fixing the original issue. No wrapper lifecycle change, here or as a prerequisite. Developer, please: move the "Open decision" in the description to "Known limits". No code changes for it. Reviewers: do not block on this case or on other cases that need this kind of specialized code. Report them as non-blocking. |
|
Done: the back-reference case is now under Known limits in the description, linking your decision, and the "Open decision" section is removed. No code changes. |
There was a problem hiding this comment.
Approving 30aa2d0. It fixes the regressions the last change request found in d0b9c19, and I found no new ones. It still does what #168 asks.
I compared head with master (Python 3.11 / .NET 10), using exceptions constructed from .NET with Activator.CreateInstance:
- A .NET base
Messagethat throws once the constructor has run: construction succeeds on both, andargsis('pre',)on both. - A .NET base
Messagethat passesthisto a Python delegate: construction succeeds on both with the sameargs. ReadingMessageafterwards passes the same Python object on both. - A .NET base
Messagethat runs garbage collection: the object stays valid. Head gives('msg',),masterthe default message. new Exception("outer", <generated exception created without a constructor>):('outer',)with a cause of the generated type, on both.- A Python-created exception whose
get_Messagecounts its calls:('2',)on both. - 15,000 constructions with an unpaired UTF-16 surrogate in the message: all succeed, and memory retained is the same on both.
- 5,000 outer/inner pairs, with a generated inner exception: head gives
args == ('o<i>',)and__cause__ is inner. Once queued finalizers are drained, all 10,000 objects are collected on both builds, with the same memory retained. - The #168 case, and a generated cause raised and caught in Python, give the right
argsand the cause by identity on head.mastergives no cause.
pytest --runtime netcore tests gives 493 passed, 23 skipped on head. The new test fails on master.
I set risk:low in place of risk:high. Each behavior the earlier risk:high named, a constructor that throws, an invalid object, and an abort on a cause without a Python object, now matches master. The back-reference lifetime case is a known limit a maintainer accepted. The change is small, easy to revert and limited to generated exception subclasses. Its test fails without it, CI is green including the Lean jobs, and it was tested end to end.
There was a problem hiding this comment.
Requesting changes: the post-constructor refresh can deadlock while reading Message, or throw and retain objects while converting InnerException. In both cases the same constructor returns on master. I verified small fixes for both without changing wrapper ownership.
The #168 backtest reached algorithm completion on this head with the updated args, the original generated cause, and working delayed __init__. On master, args still held the default message and the cause was absent. Both runs hit the same separate shutdown error. The local Python suite passed (493 passed, 23 skipped).
I’m setting risk:high because the refresh can hang or fail otherwise successful .NET construction. The maintainer-accepted back-reference case is not a blocker.
…t convert the inner exception Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Decision: this PR is done at e109105. No more changes, and no more change requests for cases like the ones raised so far. #168 is fixed: a generated exception constructed from .NET now has the right Why we stop here:
This replaces the earlier rule for this PR. I said a regression against master always blocks. For this PR it no longer does when the code needed to trigger it is like the cases above. Developer, please:
Reviewers:
|
There was a problem hiding this comment.
Approving e109105. It fixes both regressions found in 30aa2d0, and in each case the result now matches master. I found nothing else in it that changes behavior.
I compared head with master (Python 3.11 / .NET 10), constructing __namespace__ exception subclasses with Activator.CreateInstance:
- A .NET base
Messagethat waits on a worker running a Python delegate: construction returns in about 10 ms on both builds, and head stores the worker's result inargs. - A CLR inner exception whose
Messagethrows: construction succeeds on both builds without a__cause__, and the inner exception is collected on both. Head'sargsholds the constructor's message. - A message plus a generated inner exception that has a Python attribute: head gives
('out',)and__cause__ is inner, with the attribute kept.mastergives the default message and no cause.
Releasing the GIL around the Message read matches what MethodBinder already does by default around .NET calls made from Python. The using in CLRObject.Create only matters when SetArgsAndCause throws. On master, that case kept the wrapper and its exception alive.
tests/test_exceptions.py and tests/test_subclass.py pass on head (47 tests). CI is green, including the Lean regression and unit test jobs, which run this head's Python.Runtime.dll.
I set risk:low in place of risk:high. The two problems behind the last risk:high, a construction that hangs and one that fails, now behave as on master. The change is small, easy to revert and limited to exceptions. Its test fails on master, and it was tested end to end on 30aa2d0.
There was a problem hiding this comment.
Requesting changes: keep __cause__ readable when Python constructs, raises, and catches a generated exception whose cause chain contains an exception retained by .NET. After ordinary .NET collection, the same code reads the inner message on master but raises TypeError: invalid target here. It needs no custom CLR type, reflection, worker thread, forced collection, or overrides.
Tested end to end: #168 now gives the constructor message in args and preserves the generated cause by identity. The Python-created case below fails on this head and passes on master and with the small fallback guard. I'm setting risk:high because the existing Python exception-handling path can no longer read a previously readable cause.
Non-blocking known limit: a custom CLR inner exception whose Message waits for a Python callback can still stall while the cause is wrapped; this does not affect the ordinary constructor case.
…LR wrapper Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Approving e734894. It fixes the regression the last change request found in e109105. When a generated inner exception's CLR wrapper has been collected, __cause__ now gets a new wrapper, as on master. I found no new regression.
What I compared across head, master and e109105 (Python 3.11 / .NET 10):
- The change request's repro:
raise Error("workflow failed", failed.Exception), withfailed = Task.FromException(Error("inner")), after ordinary allocations.__cause__.__cause__.Messageis'inner'on head and onmaster. e109105 raisesTypeError: invalid target. - The same inner exception wrapped by a plain
System.Exception("outer", failed.Exception): the cause reads the inner message on head and onmaster. e109105 raises the sameTypeError. - A live generated inner exception:
outer.__cause__ is inneron head, keeping its attributes.mastergives a second wrapper without them. - #168's case,
Activator.CreateInstance(Error, ["custom message", inner]): head gives('custom message',)with__cause__ is inner.mastergives the default message and no cause. Across 2,000 such pairs, with collections in between, all match on head. tests/test_exceptions.pyandtests/test_subclass.py: 47 passed on head. CI is green on head, including the Lean jobs.
Non-blocking: the fix in SetArgsAndCause has no test in the suite. If the decision against more tests changes, the change request's repro would make one.
Not caused by this change: on master and head alike, reading failed.Exception.InnerException.Message from Python raises TypeError: invalid target. Any __namespace__ object that only .NET holds loses its CLR wrapper after a .NET collection. Opened #187 for it.
I'm keeping risk:high, in place of the risk:low of my last review. My approval of e109105 missed the regression above. The change now affects how every .NET exception with an inner exception is converted to Python. Its end-to-end run was on 30aa2d0, before the last two commits. An end-to-end run on this head that covers #168's case and a chained exception raised from Python would lower it.
There was a problem hiding this comment.
Approving. Tested this head end to end: a generated exception constructed from .NET keeps the constructor message in args and preserves a live generated cause by identity after raise/catch. A Python-constructed, raised and caught exception again exposes the message of a cause held only by .NET, matching master; e109105 raised TypeError: invalid target. All three runs completed the algorithm checks before the same unrelated shutdown error. The Python suite passed locally (493 passed, 23 skipped).
The inline note records a non-blocking fallback lifetime limit: the new .NET-construction path can retain replacement cause wrappers. It does not worsen the Python-construction path. risk:high stays.
| : null; | ||
| using var cause = wrapper != null | ||
| ? ClassDerivedObject.ToPython((IPythonDerivedType)e.InnerException) | ||
| : CLRObject.GetReference(e.InnerException); |
There was a problem hiding this comment.
Known limit, not blocking: ordinary .NET GC can collect a generated inner exception's weak CLR wrapper before Activator.CreateInstance constructs the outer exception. The fallback makes the cause readable, but the replacement isn't the peer that the CLR finalizer frees. After dropping the outers and draining finalizers, 20,000 constructions retained about 4.15 MB here versus effectively zero on master, which left the cause unset. Python-created outers using the same fallback retained the same amount on both. Please record the .NET-construction case under Known limits; no wrapper lifecycle change requested.
There was a problem hiding this comment.
Recorded under Known limits, per the maintainer decision on exotic cases, with no code change.
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 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.__init__; a caller may run it afterwards (the two-step pattern oftest_construction_from_clr). So the refresh readsMessageas .NET implements it, without Python overrides, the same wayCLRObject.Createread it: with the Python object unset for that read.argsthen holds the message passed to the constructor, and no Python code runs during construction.Messageuntilargsand__cause__are set, so a collection during it leaves a valid object. It releases the GIL while .NET readsMessage, so a getter that waits on another thread running Python code doesn't deadlock.Message(a .NET override that throws), or can't setargs(a message Python can't hold, anargssetter that rejects it), the exception keeps theargsit was created with, and construction succeeds as onmaster. A message Python can't hold is reported without a managed exception. When it can't convert the inner exception (itsMessagethrows, or Python can't hold it), construction succeeds without a__cause__.CLRObject.Createfrees the Python object it allocated when reading or converting the wrapped exception'sMessagethrows, which kept that exception alive, andSetArgsAndCausechecks the message before allocating theargstuple.Exceptions.SetArgsAndCauseconverts a generated inner exception withClassDerivedObject.ToPython, so__cause__is the inner exception's own Python object (outer.__cause__ is inner) instead of a second wrapper. It does so only while that object's CLR wrapper is alive: when .NET has collected it (a Python-created exception held only by .NET, such as a faultedTask's), the inner exception gets a new wrapper as onmaster. This also applies to construction from Python, which had the same problem. An inner exception without a Python object in this runtime, such as one created without a constructor, gets a wrapper as onmaster. The other callers ofSetArgsAndCausereadMessageas onmaster.Known limits
As decided in #174 (comment), these stay as they are:
argsholds the message the .NET constructor received, not the value of a Pythonget_Messageoverride.argscan't be set again, the exception keeps theargsit was created with, and__cause__isn't set (as onmaster).Messagethrows after construction, or needs the exception's Python object, the exception keeps theargsit was created with.As decided in #174 (comment), this is accepted too:
InnerExceptionrefers back to it, such as throughinner.Data, stays alive with its inner exception, as an exception constructed from Python with the same back-reference already does onmaster: the outer Python object's__cause__holds the inner one, which holds the outer.As decided in #174 (comment), this pull request stays at e109105, apart from e734894: that fixes a regression in an exception constructed, raised, caught and read from Python, which the decision still treats as blocking. A new finding that needs a custom C# exception class, reflection beyond the plain constructor call, threads, forced garbage collection, or unusual
Messageorargsbehaviour goes here as a known limit instead of a change. Known limits under it:__cause__gets a new wrapper, which stays alive after the outer exception is dropped: 20,000 such constructions keep about 4 MB, wheremasterleaves__cause__unset. An exception constructed from Python with such a cause keeps the same amount as onmaster.Messagethat waits on Python code running on another thread, can stall while__cause__is set.Tests
test_namespaced_exception_subclass_created_from_dotnet(subprocess, like #167's tests) constructs__namespace__subclasses ofSystem.Exceptionfrom .NET and checks:argsand__cause__matchMessageandInnerExceptionforActivator.CreateInstance(type, [message, inner]),ConstructorInfo.Invoke([message]), the parameterless constructor, and a two-level__namespace__chain.get_Messageoverride that returns state set by aclrmethod__init__constructs, and returns"initialized"once the caller invokes__init__.get_MessagerunsGC.Collect()stays a valid object after construction and another collection.outer.__cause__itself.It fails on
master(__cause__is a different object, without the attribute) and on the previous head of this branch (DelayedErrorconstruction throws'DelayedError' object has no attribute 'text').A separate probe also covers the reviews' other cases, each as on
masteror better:get_Messagethat returns a string and thenNone:('m',)argssetter that rejects a second assignment: it keeps the firstmasterMessageoverride that throws after construction, or passes the exception to a Python delegate: constructs, with theargsit was created with, as onmasterMessageoverride, or a Pythonargssetter that keepsself, followed by collections: the object stays validnew Exception("outer", <generated exception created without a constructor>): converts as onmasterget_Messagecounts its calls:('2',), as onmasterMessagethat waits on a worker running a Python delegate: constructs in about 20 ms, with the worker's result inargsMessagethrows, or holds an unpaired surrogate: constructs, and the inner exception is collected, as onmasterraise Error("workflow failed", failed.Exception)wherefailed = Task.FromException(Error("inner")), after ordinary allocations:error.__cause__.__cause__.Message == 'inner', as onmaster(e109105 raisedTypeError: invalid target)The CI steps on this head, Python 3.11 / .NET 10:
dotnet test src/embed_tests/ --filter "FullyQualifiedName!~SetPythonPath": 1047 passed, 8 skippeddotnet test src/embed_tests/ --filter "FullyQualifiedName~SetPythonPath": 1 passedpytest --runtime netcore tests: 493 passed, 23 skippeddotnet test src/python_tests_runner/: 2 passedAlso tested end to end on e734894, with the
CLRObject.Createchange left out of that build (none of these cases reaches it). An algorithm passed every check:args == ('custom message',), with a cause whoseMessageis'inner'args == ('message only',)with no cause;argsis kept after raising and catching it in Python__init__:Message == 'initialized'withargs == ('base message',)get_MessagerunningGC.Collect(): still a validCollectingErrorouter.__cause__ is inner, keeping its attributeargssetter keepingself, followed by a collection: still a valid object with('saving',)get_Messagecounts its calls:('2',)raise Error("workflow failed", failed.Exception)withfailed = Task.FromException(Error("inner")), after allocations and collections, then caught:args == ('workflow failed',)and__cause__.__cause__.Message == 'inner'raise Error("outer", inner)with a live generatedinner, then caught:__cause__ is inner, keeping its attribute