Repository navigation
Fix crashes when str() fails in a conversion or an error is raised at the recursion limit - #181
jhonabreul wants to merge 7 commits into
Conversation
… the recursion limit
There was a problem hiding this comment.
Requesting changes: when two threads decode a Python error at the same time, the recursion-limit headroom leaves the limit 100 frames higher for good.
The null checks fix the crashes. All six new tests fail or crash the test host on master and pass on this head, and the touched fixtures pass locally on Python 3.11. Adding the headroom costs nothing measurable per decode (about 10 µs either way over 50,000 decodes).
1. The headroom leaks across threads (inline): Dispose restores the limit it saved, but the flag is per thread and the decode runs Python code, so the GIL can switch to another thread during it. Thread A saves 1000 and sets 1100. Thread B saves 1100 and sets 1200. A finishes and restores 1000, then B finishes and restores 1100. Each overlap adds another 100 frames.
- Reproduced locally: 4 threads, each raising a plain
ValueErrorthroughPyModule.Exec3000 times, leavesys.getrecursionlimit()at 1100 when it started at 1000. An exception whose__getattr__sleeps does it every time with two threads. - Impact: Python 3.11 and earlier run Python frames on the native stack. A limit that keeps rising lets deep recursion overflow that stack and kill the process instead of raising
RecursionError, which is the crash this PR fixes. - Fix (one line): undo the +100 instead of restoring the saved value,
Runtime.Py_SetRecursionLimit(Runtime.Py_GetRecursionLimit() - ExtraFrames);. With it, both reproductions stay at 1000 and the PR's tests pass. Please add a test that decodes on two threads at once and asserts the limit afterwards. No new test checks the limit after a decode.
2. Description: this changes how every Python error that reaches .NET is handled, so please add that it was tested end to end and the outcome. For example: a Python algorithm that recurses through a .NET callback up to the limit now ends with a RecursionError instead of aborting the process. Once 1 is fixed, please also update the RecursionHeadroom line to describe how the limit is restored.
Risk: I set risk:high. The change alters a process-wide interpreter setting on every error decode, the leak above is open, and there's no end-to-end outcome yet. The fix, a concurrency test and an end-to-end outcome would lower it.
|
On the description (point 2): updated.
|
There was a problem hiding this comment.
Approving. The recursion-limit leak when two threads decode at once is fixed in 9f716de: Dispose now undoes the +100 instead of restoring a saved value. Against the previous Dispose, DecodingOnTwoThreadsRestoresTheRecursionLimit fails in 3 of 3 runs (the limit goes from 1000 to 1100). It passes on this head, and so do the touched fixtures (110 passed, Python 3.11).
I also tested it end to end. The algorithm is a Lean backtest whose order event handler places a market order that fills at once. On pythonnet 2.0.70 it aborts the process with exit code 134. With this head's runtime it ends with Runtime Error: maximum recursion depth exceeded, and Lean exits normally.
Risk: I lowered it to risk:low. The leak is fixed and no public API changes. Paths that work today only get the limit raised by 100 while an error is decoded. Tests reproduce each crash, CI passes, and the end-to-end outcome is confirmed.
|
The review of 9f716de failed. It's requested again. |
|
On the review as a whole: Decision: option B, in this PR (94fb1c6). The recursion fix stays, without touching the recursion limit.
Evidence:
Small fix 1 (big int text reader): done in f2fb1dc. Small fix 2 (dispose The description is updated to match. |
There was a problem hiding this comment.
Requesting changes: the new fallback in FetchCurrentOrNull also changes what .NET receives for errors raised in normal conditions, and no test covers that.
Removing the headroom fixes both recursion-limit regressions from the last round, and TryToBigInteger now reads through the checked reader. The touched fixtures pass locally on Python 3.11 (116 passed), and CI is green.
1. A failed decode now returns the original error, at any depth (inline). catch (PythonException) catches any Python error raised while decoding, not only the ones at the recursion limit. I compared master and this head with an exception class whose __str__ raises KeyError('from str'):
raise E('original'): master delivers aKeyErrorwith message'from str'. This head deliversEwith messageoriginal.raise ValueError('outer') from E('cause'): master delivers theKeyError. This head deliversValueError('outer')with no inner exception.
Keeping the user's error looks like the better result. But the description says errors in normal conditions "decode exactly as before", and no test covers this case or the message GetUndecodedMessage builds. Please add a test for the first case that asserts the type and message. Also say in the description that an error whose decoding fails, for example because its __str__ raises, now arrives as itself, with its message read from its args.
2. Reuse PyType.Name (inline) instead of reading tp_name again.
Risk: risk:high stays. This changes what every Python error reaching .NET decodes to whenever decoding fails, and that path has no test yet. The test above would give it the evidence it lacks.
|
Both points are addressed in fd602bb. 1. A failed decode returns the original error at any depth
2. Reuse
Full embedding test suite on Python 3.11: 1070 passed, 0 failed, 8 skipped. |
There was a problem hiding this comment.
Approving. Both findings from my last review are resolved in fd602bb:
- An error whose
__str__raises is now pinned byErrorWhoseStrRaisesArrivesAsItself, which asserts its own type and message, and the description states this behavior change. GetUndecodedMessagefalls back toPyType.Name, which reads the type name as UTF-8.
The touched fixtures pass locally (115 passed, Python 3.11).
Risk: I lowered it to risk:low. The decoder no longer changes the interpreter's recursion limit, and errors that decode today decode as before. The one changed result, an error whose decoding fails arriving as itself instead of as the decoding's own error, is now tested. Each crash has a test that reproduces it, and the end-to-end backtest outcome is confirmed.
There was a problem hiding this comment.
Requesting changes: a large Python int can now silently produce the wrong arithmetic result, and the exception fallback can still run user code and return the wrong exception.
- Large integers: an
intsubclass holding10**25whose__str__returns astrsubclass containing1now yields2when added to a managed value of1.masterrejects the operand instead of returning a wrong sum. Read the integer value rather than its overridable display text. - Exception fallback: a custom
argsproperty re-entered the fallback five times in my test. Separately, the thread-wide guard changed a CLR exception caught by a nested callback fromClrBubbledExceptiontoPythonExceptionat ordinary stack depth, and normalization could attach the original arguments to a different exception type. Keep the fallback free of user code, preserve the fetched error as a unit, and keep ordinary CLR exception recovery working.
The three touched embedding fixtures passed locally (115 tests, Python 3.11). Tested end to end: the recursive Lean backtest now reports Runtime Error: maximum recursion depth exceeded instead of overflowing before reporting it. A separate shutdown error also occurred with master in the same test setup.
Setting risk:high: silent wrong arithmetic and regressions in exception propagation remain.
|
Decision: we are not making the changes requested in the last review, and the PR stays as it is at fd602bb. This PR exists to fix one reported problem: a Python call into .NET that kills the process when The four findings need classes built on purpose, which users do not run into in practice:
If one of these is ever hit in practice, we will handle it then, in its own PR. Please treat findings of this kind as out of scope for this PR. |
Declined by decision: this PR only fixes the reported crash. The findings need classes built on purpose and are not real-world cases. See the PR comment.
What does this implement/fix? Explain your changes.
A Python call into .NET could kill the process instead of raising a Python error, in two cases:
decimal,DateTimeorTimeSpanand itsstr()raises or returns text that cannot be read.Cause: the conversions use the results of
PyObject_Strand of the string read without a null check, and decoding a Python error runs Python code that fails again at the recursion limit until the stack overflows.The fix:
Converter.ToPrimitivefails the conversion whenstr()returns null in thedecimal,DateTimeandTimeSpanstring parsing, so the caller gets the usualTypeError.Runtime.GetManagedSpanacceptsstrsubclasses and returns an empty span for text with no UTF-16 form; theTimeSpanparsing reads through it.ImplicitNumericOps.TryToBigIntegerreplacesToBigIntegerand reads digits throughGetManagedSpan: an int whosestr()raises or cannot be read is not a number.PythonException.FetchCurrentOrNullreturns the error as fetched (ToUndecoded) when decoding it fails with a Python error of its own.GetUndecodedMessagereads that message withoutstr(): the text of an error not normalized yet, or an exception's only string argument, elsePyType.Name.Tests:
TestConverter.ConversionFailsWhenStrRaises: an object whose__str__raises, to each of the three types; asserts a failed conversion and aTypeError.TestConverter.ConversionFailsWhenStrCannotBeEncoded:__str__returns a lone surrogate, to each of the three types; asserts a failed conversion and aTypeError.TestConverter.StrSubclassTextIsParsed:__str__returns astrsubclass; asserts the parseddecimal,TimeSpanandDateTime.TestConverter.FloatToDecimalAtTheRecursionLimitRaisesPythonError: a float passed to adecimalparameter across the recursion limit; asserts aRecursionErrorand no crash.TestImplicitNumericOperators.IntOperandWhoseStrRaisesIsUnsupportedandIntOperandWhoseStrCannotBeEncodedIsUnsupported: an int beyondlongwith a bad__str__; assertTypeError.TestImplicitNumericOperators.IntOperandWhoseStrIsAStrSubclassIsRead:__str__returns astrsubclass of digits; asserts the sum.TestPythonException.ErrorRaisedAtTheRecursionLimitReachesPython: .NET calls back into Python up to the limit; asserts Python catches aRecursionError.TestPythonException.DecodingKeepsARecursionLimitSetWhileItRuns: the error's__getattr__sets the limit to 250 during the decode; asserts it is still 250.TestPythonException.ErrorIsDecodedAtTheHighestRecursionLimit: aValueErrorwith the limit at 2147483647; asserts the message and the limit.TestPythonException.ErrorWhoseStrRaisesArrivesAsItself: an exception whose__str__raisesKeyError; asserts its own type and the messageoriginal.TestPythonException.ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument: the same with a non-ASCII type name and two arguments; asserts the type name as message.Runtime Error: maximum recursion depth exceeded.Does this close any currently open issues?
N/A
Any other comments?
mastergave the same exception type, message, inner exception and traceback.__str__raises, now arrives as itself, with its message read from its args.masterthe caller received the error raised by the decoding instead (theKeyErrorfrom__str__), and the original one was lost.PythonException.strsubclass now parses like a plainstrin these conversions.normalizedValueinFetchCurrentOrNull. That reference leaks onmastertoo and is unrelated to this change.Checklist
Check all those that are applicable and complete.
AUTHORSCHANGELOG