Skip to content

Fix crashes when str() fails in a conversion or an error is raised at the recursion limit - #181

Open
jhonabreul wants to merge 7 commits into
QuantConnect:masterfrom
jhonabreul:bug-null-str-in-conversion
Open

jhonabreul wants to merge 7 commits into
QuantConnect:masterfrom
jhonabreul:bug-null-str-in-conversion

Conversation

@jhonabreul

@jhonabreul jhonabreul commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • A value is converted to decimal, DateTime or TimeSpan and its str() raises or returns text that cannot be read.
  • A Python error is raised at the recursion limit while .NET code is on the stack.
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Python.Runtime.NewReferenceExtensions.Borrow(NewReference& reference)
   at Python.Runtime.Converter.ToPrimitive(...)

Cause: the conversions use the results of PyObject_Str and 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.ToPrimitive fails the conversion when str() returns null in the decimal, DateTime and TimeSpan string parsing, so the caller gets the usual TypeError.
  • Runtime.GetManagedSpan accepts str subclasses and returns an empty span for text with no UTF-16 form; the TimeSpan parsing reads through it.
  • ImplicitNumericOps.TryToBigInteger replaces ToBigInteger and reads digits through GetManagedSpan: an int whose str() raises or cannot be read is not a number.
  • PythonException.FetchCurrentOrNull returns the error as fetched (ToUndecoded) when decoding it fails with a Python error of its own.
  • An error raised on a thread while it is decoding another one is wrapped as fetched and never decoded, which ends the loop.
  • GetUndecodedMessage reads that message without str(): the text of an error not normalized yet, or an exception's only string argument, else PyType.Name.
  • The interpreter's recursion limit is never changed.

Tests:

  • TestConverter.ConversionFailsWhenStrRaises: an object whose __str__ raises, to each of the three types; asserts a failed conversion and a TypeError.
  • TestConverter.ConversionFailsWhenStrCannotBeEncoded: __str__ returns a lone surrogate, to each of the three types; asserts a failed conversion and a TypeError.
  • TestConverter.StrSubclassTextIsParsed: __str__ returns a str subclass; asserts the parsed decimal, TimeSpan and DateTime.
  • TestConverter.FloatToDecimalAtTheRecursionLimitRaisesPythonError: a float passed to a decimal parameter across the recursion limit; asserts a RecursionError and no crash.
  • TestImplicitNumericOperators.IntOperandWhoseStrRaisesIsUnsupported and IntOperandWhoseStrCannotBeEncodedIsUnsupported: an int beyond long with a bad __str__; assert TypeError.
  • TestImplicitNumericOperators.IntOperandWhoseStrIsAStrSubclassIsRead: __str__ returns a str subclass of digits; asserts the sum.
  • TestPythonException.ErrorRaisedAtTheRecursionLimitReachesPython: .NET calls back into Python up to the limit; asserts Python catches a RecursionError.
  • TestPythonException.DecodingKeepsARecursionLimitSetWhileItRuns: the error's __getattr__ sets the limit to 250 during the decode; asserts it is still 250.
  • TestPythonException.ErrorIsDecodedAtTheHighestRecursionLimit: a ValueError with the limit at 2147483647; asserts the message and the limit.
  • TestPythonException.ErrorWhoseStrRaisesArrivesAsItself: an exception whose __str__ raises KeyError; asserts its own type and the message original.
  • TestPythonException.ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument: the same with a non-ASCII type name and two arguments; asserts the type name as message.
  • Full embedding test suite on Python 3.11: 1070 passed, 0 failed, 8 skipped.
  • End to end, a Lean backtest on Linux: an order event handler places an order that fills at once, so it recurses through .NET up to the limit.
  • That run aborted the process before (exit code 134) and now ends with Runtime Error: maximum recursion depth exceeded.

Does this close any currently open issues?

N/A

Any other comments?

  • Errors that decode without failing are unchanged: 11 cases compared against master gave the same exception type, message, inner exception and traceback.
  • Behavior change: an error whose decoding fails at any depth, for example because its __str__ raises, now arrives as itself, with its message read from its args.
  • On master the caller received the error raised by the decoding instead (the KeyError from __str__), and the original one was lost.
  • At the recursion limit the fallback keeps the Python type, value and traceback, but a .NET exception raised exactly there can arrive as a PythonException.
  • Text returned as a str subclass now parses like a plain str in these conversions.
  • Not included: disposing normalizedValue in FetchCurrentOrNull. That reference leaks on master too and is unrelated to this change.

Checklist

Check all those that are applicable and complete.

  • Make sure to include one or more tests for your change
  • If an enhancement PR, please create docs and at best an example
  • Ensure you have signed the .NET Foundation CLA
  • Add yourself to AUTHORS
  • Updated the CHANGELOG

@jhonabreul jhonabreul added the kronos:review Request review label Nov 27, 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 27, 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: 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 ValueError through PyModule.Exec 3000 times, leave sys.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.

Comment thread src/runtime/PythonException.cs Resolved
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:high High risk and removed kronos:review:working review: in progress labels Nov 27, 2026
@jhonabreul

Copy link
Copy Markdown
Collaborator Author

On the description (point 2): updated.

  • It now says how the limit is restored: lowered by the same 100 frames, so overlapping decodes leave it unchanged.
  • It now records the end-to-end run: a Lean backtest on Linux whose order event handler recurses through .NET up to the limit. It aborted the process with exit code 134 on the released runtime, and ends with Runtime Error: maximum recursion depth exceeded on this head (9f716de).

@jhonabreul jhonabreul added the kronos:review Request review label Nov 27, 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 27, 2026
@quantconnect-kronos-reviewer
quantconnect-kronos-reviewer Bot marked this pull request as ready for review November 27, 2026 18:00

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

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:low Low risk kronos:review Request review kronos:review:queued review: queued and removed risk:high High risk kronos:review:working review: in progress kronos:review Request review labels Nov 27, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 27, 2026
@quantconnect-kronos-reviewer-2

Copy link
Copy Markdown

The review of 9f716de failed. It's requested again.

@jhonabreul

Copy link
Copy Markdown
Collaborator Author

On the review as a whole:

Decision: option B, in this PR (94fb1c6). The recursion fix stays, without touching the recursion limit.

  • FetchCurrentOrNull decodes as before. If decoding fails with a Python error of its own, it returns the original error as fetched, without running Python code.
  • An error raised on a thread while it is decoding another one is wrapped as fetched and never decoded, which ends the loop.
  • The fallback message is read without str().

Evidence:

  • Errors in normal conditions are unchanged: 11 cases compared against master gave the same exception type, message, inner exception and traceback.
  • At the recursion limit master overflows the stack in all six cases I tried; this head delivers the error. One difference: a .NET exception raised exactly at the limit can arrive as a PythonException.
  • Full embedding suite on Python 3.11: 1068 passed, 0 failed, 8 skipped.
  • The end-to-end Lean backtest on Linux was repeated on this decoder: it ends with Runtime Error: maximum recursion depth exceeded, as before.

Small fix 1 (big int text reader): done in f2fb1dc.

Small fix 2 (dispose normalizedValue): declined, by decision. That reference leaks on master too and is unrelated to this change, so it stays out of this PR. Please do not raise it again here.

The description is updated to match.

@jhonabreul jhonabreul added the kronos:review Request review label Nov 27, 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 27, 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 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 a KeyError with message 'from str'. This head delivers E with message original.
  • raise ValueError('outer') from E('cause'): master delivers the KeyError. This head delivers ValueError('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.

Comment thread src/runtime/PythonException.cs Resolved
Comment thread src/runtime/PythonException.cs Resolved
@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot removed the kronos:review:working review: in progress label Nov 27, 2026
@jhonabreul

Copy link
Copy Markdown
Collaborator Author

Both points are addressed in fd602bb.

1. A failed decode returns the original error at any depth

  • Confirmed: with master's PythonException.cs the new test receives the KeyError; on this branch it receives the original error.
  • New test TestPythonException.ErrorWhoseStrRaisesArrivesAsItself: an exception whose __str__ raises KeyError('from str'), raised with 'original'. Asserts the type Unprintable and the message original.
  • The description no longer says normal errors decode exactly as before. It now states the behavior change: an error whose decoding fails, for example because its __str__ raises, arrives as itself with its message read from its args.

2. Reuse PyType.Name

  • Done: ToUndecoded builds the PyType first and GetUndecodedMessage falls back to its Name.
  • This was a visible defect, not only a cleanup: a type named Défaut gave the message Défaut on Windows.
  • New test TestPythonException.ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument failed with that text before the change and passes now.

Full embedding test suite on Python 3.11: 1070 passed, 0 failed, 8 skipped.

@jhonabreul jhonabreul added the kronos:review Request review label Nov 27, 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 27, 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.

Approving. Both findings from my last review are resolved in fd602bb:

  • An error whose __str__ raises is now pinned by ErrorWhoseStrRaisesArrivesAsItself, which asserts its own type and message, and the description states this behavior change.
  • GetUndecodedMessage falls back to PyType.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.

@quantconnect-kronos-reviewer quantconnect-kronos-reviewer Bot added risk:low Low risk kronos:review Request review kronos:review:queued review: queued and removed risk:high High risk kronos:review:working review: in progress kronos:review Request review labels Nov 27, 2026
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added kronos:review:working review: in progress and removed kronos:review:queued review: queued labels Nov 27, 2026

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

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 int subclass holding 10**25 whose __str__ returns a str subclass containing 1 now yields 2 when added to a managed value of 1. master rejects the operand instead of returning a wrong sum. Read the integer value rather than its overridable display text.
  • Exception fallback: a custom args property re-entered the fallback five times in my test. Separately, the thread-wide guard changed a CLR exception caught by a nested callback from ClrBubbledException to PythonException at 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.

Comment thread src/runtime/Util/ImplicitNumericOps.cs Resolved
Comment thread src/runtime/PythonException.cs Resolved
Comment thread src/runtime/PythonException.cs Resolved
Comment thread src/runtime/PythonException.cs Resolved
@quantconnect-kronos-reviewer-2 quantconnect-kronos-reviewer-2 Bot added risk:high High risk and removed risk:low Low risk kronos:review:working review: in progress labels Nov 27, 2026
@jhonabreul

Copy link
Copy Markdown
Collaborator Author

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 str() fails or when an error is raised at the recursion limit. That is fixed and tested here, and the review confirms it end to end.

The four findings need classes built on purpose, which users do not run into in practice:

  • Large integers: an int subclass beyond long whose __str__ returns other digits in a str subclass. master trusts __str__ in the same way for a plain str.
  • args property: an exception that redefines args as a property that calls .NET, which calls Python, which raises the same error.
  • Normalization: a raw error set through the C API whose constructor raises and whose argument has a failing __repr__.
  • .NET exception type: an exception whose __str__ calls .NET code that calls a Python callback raising a .NET exception.

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.

@jhonabreul
jhonabreul dismissed quantconnect-kronos-reviewer-2[bot]’s stale review November 27, 2026 21:39

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.

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

risk:high High risk

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant