From 55abecc9c6550718c6605d182d0c3134e74c7694 Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 11:44:31 -0400 Subject: [PATCH 1/7] Fix crashes when str() fails in a conversion or an error is raised at the recursion limit --- src/embed_tests/TestConverter.cs | 76 +++++++++++++++++++ .../TestImplicitNumericOperators.cs | 21 +++++ src/embed_tests/TestPythonException.cs | 35 +++++++++ src/runtime/Converter.cs | 12 +++ src/runtime/PythonException.cs | 42 ++++++++++ src/runtime/Runtime.Delegates.cs | 4 + src/runtime/Runtime.cs | 4 + src/runtime/Util/ImplicitNumericOps.cs | 24 ++++-- 8 files changed, 212 insertions(+), 6 deletions(-) diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index 746d13044..b57e85aaa 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -809,6 +809,82 @@ public void FailedConversionOfNonClrValueManagedTypesOnlyLeavesErrorWhenSettingE Exceptions.Clear(); } } + + [TestCase(typeof(decimal), true)] + [TestCase(typeof(decimal), false)] + [TestCase(typeof(DateTime), true)] + [TestCase(typeof(DateTime), false)] + [TestCase(typeof(TimeSpan), true)] + [TestCase(typeof(TimeSpan), false)] + public void ConversionFailsWhenStrRaises(Type type, bool setError) + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Exec(@" +class BadStr: + def __str__(self): + raise ValueError('boom') +"); + using var value = scope.Eval("BadStr()"); + + Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError)); + Assert.AreEqual(setError, Exceptions.ErrorOccurred()); + if (setError) + { + Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError)); + } + Exceptions.Clear(); + } + } + + [Test] + public void FloatToDecimalAtTheRecursionLimitRaisesPythonError() + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Set("target", new DecimalConsumer().ToPython()); + // str(float) itself fails at the recursion limit, so sweep the depth to land exactly on it + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(200) +errors = set() + +# a first failed call warms up the lazy state the mismatch diagnosis needs +try: + target.Take('not a number') +except TypeError: + pass + +def call(depth): + if depth == 0: + target.Take(1.5) + else: + call(depth - 1) + +try: + for depth in range(100, 260): + try: + call(depth) + except (RecursionError, TypeError) as e: + errors.add(type(e).__name__) +finally: + sys.setrecursionlimit(limit) +errors = sorted(errors) +"); + var errors = scope.Get("errors").As(); + CollectionAssert.AreEqual(new[] { "RecursionError", "TypeError" }, errors); + } + } + } + + public class DecimalConsumer + { + public void Take(decimal value) + { + } } public interface IGetList diff --git a/src/embed_tests/TestImplicitNumericOperators.cs b/src/embed_tests/TestImplicitNumericOperators.cs index cd9de7470..f68d7a14c 100644 --- a/src/embed_tests/TestImplicitNumericOperators.cs +++ b/src/embed_tests/TestImplicitNumericOperators.cs @@ -332,6 +332,27 @@ public void UnsupportedOperandsRaisePythonsTypeError() StringAssert.Contains("unsupported operand type(s) for -", messages[3]); } + [Test] + public void IntOperandWhoseStrRaisesIsUnsupported() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + // beyond long, the int is read through its str() + scope.Exec(@" +class BadInt(int): + def __str__(self): + raise ValueError('boom') + +try: + count + BadInt(10 ** 25) + error = '' +except Exception as e: + error = type(e).__name__ +"); + Assert.AreEqual("TypeError", scope.Get("error")); + } + [Test] public void InheritedOperatorsKeepWinning() { diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 9a3343460..c8ecebdd8 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -349,6 +349,41 @@ def CallThrow(): } } + [Test] + public void ErrorRaisedAtTheRecursionLimitReachesPython() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("target", new ReentrantCaller().ToPython()); + // managed code calls back into Python until the recursion limit, so the error is decoded right at it + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(200) + +def handler(): + target.Call(handler) + +try: + target.Call(handler) + error = '' +except RecursionError as e: + error = str(e) +finally: + sys.setrecursionlimit(limit) +"); + StringAssert.Contains("maximum recursion depth exceeded", scope.Get("error")); + } + + public class ReentrantCaller + { + public void Call(PyObject callback) + { + using var _ = Py.GIL(); + callback.Invoke().Dispose(); + } + } + public class TestClass { public void ThrowException() diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index 47e592d16..50a81d2e2 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -1034,6 +1034,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec if (obType == typeof(TimeSpan)) { op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } TimeSpan ts; var arr = Runtime.GetManagedString(op.Borrow()).Split(','); op.Dispose(); @@ -1370,6 +1374,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec } case TypeCode.Decimal: op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } decimal m; var sm = Runtime.GetManagedSpan(op.Borrow(), out var newReference); if (!Decimal.TryParse(sm, NumberStyles.Number | NumberStyles.AllowExponent, nfi, out m)) @@ -1391,6 +1399,10 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec // fallback to string parsing for types such as numpy op = Runtime.PyObject_Str(value); + if (op.IsNull()) + { + goto type_error; + } var sdt = Runtime.GetManagedSpan(op.Borrow(), out var reference); if (!DateTime.TryParse(sdt, out var dt)) { diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 9f26e3a8d..7ff874243 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -91,6 +91,7 @@ internal static PythonException FetchCurrentRaw() return null; } + using var headroom = RecursionHeadroom.Enter(); try { if (TryDecodePyErr(type.Borrow(), value.BorrowNullable(), traceback.BorrowNullable()) is { } pyErr) @@ -129,6 +130,47 @@ internal static Exception FetchCurrent() => FetchCurrentOrNull(out _) ?? throw new InvalidOperationException("No exception is set"); + [ThreadStatic] + private static bool _hasRecursionHeadroom; + + /// + /// Decoding an error runs Python code, which fails again when the error was raised at the + /// recursion limit. Raises the limit while the outermost decode of the thread runs. Requires the GIL. + /// + private readonly ref struct RecursionHeadroom + { + private const int ExtraFrames = 100; + + private readonly int _limit; + + private RecursionHeadroom(int limit) + { + _limit = limit; + } + + public static RecursionHeadroom Enter() + { + if (_hasRecursionHeadroom) + { + return default; + } + + _hasRecursionHeadroom = true; + var limit = Runtime.Py_GetRecursionLimit(); + Runtime.Py_SetRecursionLimit(limit + ExtraFrames); + return new RecursionHeadroom(limit); + } + + public void Dispose() + { + if (_limit > 0) + { + Runtime.Py_SetRecursionLimit(_limit); + _hasRecursionHeadroom = false; + } + } + } + private static ExceptionDispatchInfo? TryGetDispatchInfo(BorrowedReference exception) { if (exception.IsNull) return null; diff --git a/src/runtime/Runtime.Delegates.cs b/src/runtime/Runtime.Delegates.cs index 1e6c91f97..c60462011 100644 --- a/src/runtime/Runtime.Delegates.cs +++ b/src/runtime/Runtime.Delegates.cs @@ -19,6 +19,8 @@ static Delegates() Py_InitializeEx = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_InitializeEx), GetUnmanagedDll(_PythonDll)); Py_IsInitialized = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_IsInitialized), GetUnmanagedDll(_PythonDll)); Py_Finalize = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_Finalize), GetUnmanagedDll(_PythonDll)); + Py_GetRecursionLimit = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_GetRecursionLimit), GetUnmanagedDll(_PythonDll)); + Py_SetRecursionLimit = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_SetRecursionLimit), GetUnmanagedDll(_PythonDll)); Py_NewInterpreter = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_NewInterpreter), GetUnmanagedDll(_PythonDll)); Py_EndInterpreter = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_EndInterpreter), GetUnmanagedDll(_PythonDll)); PyThreadState_New = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(PyThreadState_New), GetUnmanagedDll(_PythonDll)); @@ -324,6 +326,8 @@ static Delegates() internal static delegate* unmanaged[Cdecl] Py_InitializeEx { get; } internal static delegate* unmanaged[Cdecl] Py_IsInitialized { get; } internal static delegate* unmanaged[Cdecl] Py_Finalize { get; } + internal static delegate* unmanaged[Cdecl] Py_GetRecursionLimit { get; } + internal static delegate* unmanaged[Cdecl] Py_SetRecursionLimit { get; } internal static delegate* unmanaged[Cdecl] Py_NewInterpreter { get; } internal static delegate* unmanaged[Cdecl] Py_EndInterpreter { get; } internal static delegate* unmanaged[Cdecl] PyThreadState_New { get; } diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index 50cd73bb6..b7f4e65cb 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -732,6 +732,10 @@ internal static T TryUsingDll(Func op) internal static void Py_Finalize() => Delegates.Py_Finalize(); + internal static int Py_GetRecursionLimit() => Delegates.Py_GetRecursionLimit(); + + internal static void Py_SetRecursionLimit(int limit) => Delegates.Py_SetRecursionLimit(limit); + internal static PyThreadState* Py_NewInterpreter() => Delegates.Py_NewInterpreter(); diff --git a/src/runtime/Util/ImplicitNumericOps.cs b/src/runtime/Util/ImplicitNumericOps.cs index d53259f14..54f3d3860 100644 --- a/src/runtime/Util/ImplicitNumericOps.cs +++ b/src/runtime/Util/ImplicitNumericOps.cs @@ -234,7 +234,11 @@ private static bool TryGetOperand(PyObject? value, out Number number) var reference = value.Reference; if (Runtime.PyInt_Check(reference)) { - number = new Number(ToBigInteger(reference)); + if (!TryToBigInteger(reference, out var big)) + { + return false; + } + number = new Number(big); return true; } if (Runtime.PyObject_TypeCheck(reference, Runtime.PyFloatType)) @@ -245,9 +249,9 @@ private static bool TryGetOperand(PyObject? value, out Number number) if (Runtime.PyObject_HasAttrString(reference, "__index__") != 0) { using var integer = Runtime.PyNumber_Long(reference); - if (!integer.IsNull()) + if (!integer.IsNull() && TryToBigInteger(integer.Borrow(), out var big)) { - number = new Number(ToBigInteger(integer.Borrow())); + number = new Number(big); return true; } } @@ -266,18 +270,26 @@ private static bool TryGetOperand(PyObject? value, out Number number) return false; } - private static BigInteger ToBigInteger(BorrowedReference integer) + private static bool TryToBigInteger(BorrowedReference integer, out BigInteger result) { var value = Runtime.PyLong_AsLongLong(integer); if (value.HasValue) { - return value.Value; + result = value.Value; + return true; } // beyond long, parse its digits Exceptions.Clear(); using var digits = Runtime.PyObject_Str(integer); - return BigInteger.Parse(Runtime.GetManagedString(digits.Borrow())!, CultureInfo.InvariantCulture); + if (digits.IsNull()) + { + // str() itself can raise, the operand is then not a number + Exceptions.Clear(); + result = default; + return false; + } + return BigInteger.TryParse(Runtime.GetManagedString(digits.Borrow()), NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } /// From 5a0f6f208e9c898d637ae3a180c44b7940a50509 Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 11:55:34 -0400 Subject: [PATCH 2/7] Do not require a TypeError at the recursion limit, it depends on the Python version --- src/embed_tests/TestConverter.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index b57e85aaa..1048eaeb2 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -875,7 +875,8 @@ def call(depth): errors = sorted(errors) "); var errors = scope.Get("errors").As(); - CollectionAssert.AreEqual(new[] { "RecursionError", "TypeError" }, errors); + // str(float) only fails at the limit on some Python versions, so a TypeError is optional + CollectionAssert.Contains(errors, "RecursionError"); } } } From 0ada6a07fab2b0413a8d4090d57a095f7746a69c Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 13:14:27 -0400 Subject: [PATCH 3/7] Fail the conversion when the text of str() cannot be read, and read str subclasses --- src/embed_tests/TestConverter.cs | 58 ++++++++++++++++++++++++++++++++ src/runtime/Converter.cs | 3 +- src/runtime/Runtime.cs | 10 ++++-- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index 1048eaeb2..90f3d54c0 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -838,6 +838,64 @@ raise ValueError('boom') } } + [TestCase(typeof(decimal), true)] + [TestCase(typeof(decimal), false)] + [TestCase(typeof(DateTime), true)] + [TestCase(typeof(DateTime), false)] + [TestCase(typeof(TimeSpan), true)] + [TestCase(typeof(TimeSpan), false)] + public void ConversionFailsWhenStrCannotBeEncoded(Type type, bool setError) + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + // a lone surrogate has no UTF-16 form + scope.Exec(@" +class Unreadable: + def __str__(self): + return chr(0xD800) +"); + using var value = scope.Eval("Unreadable()"); + + Assert.IsFalse(Converter.ToManaged(value, type, out var result, setError)); + Assert.AreEqual(setError, Exceptions.ErrorOccurred()); + if (setError) + { + Assert.IsTrue(Exceptions.ExceptionMatches(Exceptions.TypeError)); + } + Exceptions.Clear(); + } + } + + [Test] + public void StrSubclassTextIsParsed() + { + using (Py.GIL()) + { + using var scope = Py.CreateScope(); + scope.Exec(@" +class Text(str): + pass + +class Value: + def __init__(self, text): + self.text = text + def __str__(self): + return Text(self.text) +"); + using var amount = scope.Eval("Value('1.5')"); + using var duration = scope.Eval("Value('1:30:00')"); + using var moment = scope.Eval("Value('2020-01-02 03:04:05')"); + + Assert.IsTrue(Converter.ToManaged(amount, typeof(decimal), out var result, false)); + Assert.AreEqual(1.5m, result); + Assert.IsTrue(Converter.ToManaged(duration, typeof(TimeSpan), out result, false)); + Assert.AreEqual(new TimeSpan(1, 30, 0), result); + Assert.IsTrue(Converter.ToManaged(moment, typeof(DateTime), out result, false)); + Assert.AreEqual(new DateTime(2020, 1, 2, 3, 4, 5), result); + } + } + [Test] public void FloatToDecimalAtTheRecursionLimitRaisesPythonError() { diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index 50a81d2e2..6c7d3554f 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -1039,7 +1039,8 @@ internal static bool ToPrimitive(BorrowedReference value, Type obType, out objec goto type_error; } TimeSpan ts; - var arr = Runtime.GetManagedString(op.Borrow()).Split(','); + var arr = Runtime.GetManagedSpan(op.Borrow(), out var timeSpanText).ToString().Split(','); + timeSpanText.Dispose(); op.Dispose(); string sts = arr.Length == 1 ? arr[0] : arr[1]; if (!TimeSpan.TryParse(sts, out ts)) diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index b7f4e65cb..f2f06327c 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -1443,11 +1443,15 @@ static string GetManagedStringFromUnicodeObject(BorrowedReference op) internal static ReadOnlySpan GetManagedSpan(BorrowedReference op, out NewReference reference) { - var type = PyObject_TYPE(op); - - if (type == PyUnicodeType) + if (PyObject_TypeCheck(op, PyUnicodeType)) { reference = PyUnicode_AsUTF16String(op); + if (reference.IsNull()) + { + // no UTF-16 form (lone surrogates): reads as empty, like a non-str + Exceptions.Clear(); + return null; + } int bytesLength = checked((int)PyBytes_Size(reference.Borrow())); var codePoints = PyBytes_AsString(reference.Borrow()); return new ReadOnlySpan(IntPtr.Add(codePoints, sizeof(char)).ToPointer(), length: bytesLength / 2 - 1); From 9f716de2884f58799d118717c42ca799317e9c6a Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 13:43:19 -0400 Subject: [PATCH 4/7] Undo the recursion headroom instead of restoring a saved limit --- src/embed_tests/TestPythonException.cs | 56 ++++++++++++++++++++++++++ src/runtime/PythonException.cs | 16 ++++---- 2 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index c8ecebdd8..971a2118a 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Linq; +using System.Threading; using NUnit.Framework; using Python.Runtime; @@ -375,6 +376,61 @@ def handler(): StringAssert.Contains("maximum recursion depth exceeded", scope.Get("error")); } + [Test] + public void DecodingOnTwoThreadsRestoresTheRecursionLimit() + { + var limit = Runtime.Runtime.Py_GetRecursionLimit(); + using var scope = Py.CreateScope(); + // decoding reads attributes of the error: this one sleeps, releasing the GIL, so the decodes overlap + scope.Exec(@" +import time + +class SlowError(Exception): + def __getattr__(self, name): + time.sleep(self.args[0]) + raise AttributeError(name) +"); + var decoded = 0; + void Raise(string seconds) + { + using var _ = Py.GIL(); + try + { + scope.Exec($"raise SlowError({seconds})"); + } + catch (PythonException) + { + Interlocked.Increment(ref decoded); + } + } + + // the first decode to start is also the first to finish, the order that used to leak the headroom + var threads = new[] { new Thread(() => Raise("0.1")), new Thread(() => Raise("0.3")) }; + // the fixture initializes the engine with the GIL held on this thread + var ts = PythonEngine.BeginAllowThreads(); + try + { + foreach (var thread in threads) + { + thread.Start(); + Thread.Sleep(30); + } + foreach (var thread in threads) + { + thread.Join(); + } + } + finally + { + PythonEngine.EndAllowThreads(ts); + } + + var limitAfter = Runtime.Runtime.Py_GetRecursionLimit(); + Runtime.Runtime.Py_SetRecursionLimit(limit); + Assert.AreEqual(2, decoded); + Assert.AreEqual(limit, limitAfter); + } + public class ReentrantCaller { public void Call(PyObject callback) diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 7ff874243..b1392a328 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -141,11 +141,11 @@ private readonly ref struct RecursionHeadroom { private const int ExtraFrames = 100; - private readonly int _limit; + private readonly bool _entered; - private RecursionHeadroom(int limit) + private RecursionHeadroom(bool entered) { - _limit = limit; + _entered = entered; } public static RecursionHeadroom Enter() @@ -156,16 +156,16 @@ public static RecursionHeadroom Enter() } _hasRecursionHeadroom = true; - var limit = Runtime.Py_GetRecursionLimit(); - Runtime.Py_SetRecursionLimit(limit + ExtraFrames); - return new RecursionHeadroom(limit); + Runtime.Py_SetRecursionLimit(Runtime.Py_GetRecursionLimit() + ExtraFrames); + return new RecursionHeadroom(true); } public void Dispose() { - if (_limit > 0) + if (_entered) { - Runtime.Py_SetRecursionLimit(_limit); + // undo the increment, a saved limit would be stale when another thread is decoding too + Runtime.Py_SetRecursionLimit(Runtime.Py_GetRecursionLimit() - ExtraFrames); _hasRecursionHeadroom = false; } } From f2fb1dc2ba05dee78739e0f54870157a76f729d0 Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 15:04:59 -0400 Subject: [PATCH 5/7] Read big int digits through the checked span reader, and pin the culture of a parsing test --- src/embed_tests/TestConverter.cs | 1 + .../TestImplicitNumericOperators.cs | 40 +++++++++++++++++++ src/runtime/Util/ImplicitNumericOps.cs | 5 ++- 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index 90f3d54c0..cc961ad2b 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -868,6 +868,7 @@ def __str__(self): } [Test] + [SetCulture("en-US")] public void StrSubclassTextIsParsed() { using (Py.GIL()) diff --git a/src/embed_tests/TestImplicitNumericOperators.cs b/src/embed_tests/TestImplicitNumericOperators.cs index f68d7a14c..8c9942482 100644 --- a/src/embed_tests/TestImplicitNumericOperators.cs +++ b/src/embed_tests/TestImplicitNumericOperators.cs @@ -353,6 +353,46 @@ raise ValueError('boom') Assert.AreEqual("TypeError", scope.Get("error")); } + [Test] + public void IntOperandWhoseStrCannotBeEncodedIsUnsupported() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + // a lone surrogate has no UTF-16 form + scope.Exec(@" +class BadInt(int): + def __str__(self): + return chr(0xD800) + +try: + count + BadInt(10 ** 25) + error = '' +except Exception as e: + error = type(e).__name__ +"); + Assert.AreEqual("TypeError", scope.Get("error")); + } + + [Test] + public void IntOperandWhoseStrIsAStrSubclassIsRead() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Set("count", new ConvertibleCount(1).ToPython()); + scope.Exec(@" +class Text(str): + pass + +class BigInt(int): + def __str__(self): + return Text(int(self)) + +matches = count + BigInt(10 ** 25) == 10 ** 25 + 1 +"); + Assert.IsTrue(scope.Get("matches")); + } + [Test] public void InheritedOperatorsKeepWinning() { diff --git a/src/runtime/Util/ImplicitNumericOps.cs b/src/runtime/Util/ImplicitNumericOps.cs index 54f3d3860..5285a66df 100644 --- a/src/runtime/Util/ImplicitNumericOps.cs +++ b/src/runtime/Util/ImplicitNumericOps.cs @@ -289,7 +289,10 @@ private static bool TryToBigInteger(BorrowedReference integer, out BigInteger re result = default; return false; } - return BigInteger.TryParse(Runtime.GetManagedString(digits.Borrow()), NumberStyles.Integer, CultureInfo.InvariantCulture, out result); + var text = Runtime.GetManagedSpan(digits.Borrow(), out var reference); + var parsed = BigInteger.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); + reference.Dispose(); + return parsed; } /// From 94fb1c680060f8e6e4f54926dfdd8610239a5313 Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 15:16:41 -0400 Subject: [PATCH 6/7] Keep an error as fetched when decoding it fails, instead of raising the recursion limit --- src/embed_tests/TestPythonException.cs | 66 ++++++++--------- src/runtime/PythonException.cs | 98 ++++++++++++++------------ src/runtime/Runtime.Delegates.cs | 4 -- src/runtime/Runtime.cs | 4 -- 4 files changed, 82 insertions(+), 90 deletions(-) diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 971a2118a..748f46655 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Linq; -using System.Threading; using NUnit.Framework; using Python.Runtime; @@ -377,58 +376,51 @@ def handler(): } [Test] - public void DecodingOnTwoThreadsRestoresTheRecursionLimit() + public void DecodingKeepsARecursionLimitSetWhileItRuns() { - var limit = Runtime.Runtime.Py_GetRecursionLimit(); + using var _ = Py.GIL(); using var scope = Py.CreateScope(); - // decoding reads attributes of the error: this one sleeps, releasing the GIL, so the decodes overlap + // decoding reads attributes of the error, and this one changes the limit when it is read scope.Exec(@" -import time +import sys +limit = sys.getrecursionlimit() -class SlowError(Exception): +class LimitError(Exception): def __getattr__(self, name): - time.sleep(self.args[0]) + sys.setrecursionlimit(250) raise AttributeError(name) "); - var decoded = 0; - void Raise(string seconds) + try { - using var _ = Py.GIL(); - try - { - scope.Exec($"raise SlowError({seconds})"); - } - catch (PythonException) - { - Interlocked.Increment(ref decoded); - } + Assert.Throws(() => scope.Exec("raise LimitError('boom')")); + Assert.AreEqual(250, scope.Eval("sys.getrecursionlimit()")); } + finally + { + scope.Exec("sys.setrecursionlimit(limit)"); + } + } - // the first decode to start is also the first to finish, the order that used to leak the headroom - var threads = new[] { new Thread(() => Raise("0.1")), new Thread(() => Raise("0.3")) }; - // the fixture initializes the engine with the GIL held on this thread - var ts = PythonEngine.BeginAllowThreads(); + [Test] + public void ErrorIsDecodedAtTheHighestRecursionLimit() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Exec(@" +import sys +limit = sys.getrecursionlimit() +sys.setrecursionlimit(2147483647) +"); try { - foreach (var thread in threads) - { - thread.Start(); - Thread.Sleep(30); - } - foreach (var thread in threads) - { - thread.Join(); - } + var error = Assert.Throws(() => scope.Exec("raise ValueError('boom')")); + Assert.AreEqual("boom", error.Message); + Assert.AreEqual(2147483647, scope.Eval("sys.getrecursionlimit()")); } finally { - PythonEngine.EndAllowThreads(ts); + scope.Exec("sys.setrecursionlimit(limit)"); } - - var limitAfter = Runtime.Runtime.Py_GetRecursionLimit(); - Runtime.Runtime.Py_SetRecursionLimit(limit); - Assert.AreEqual(2, decoded); - Assert.AreEqual(limit, limitAfter); } public class ReentrantCaller diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index b1392a328..0966915a1 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -91,86 +91,94 @@ internal static PythonException FetchCurrentRaw() return null; } - using var headroom = RecursionHeadroom.Enter(); + if (_decodingError) + { + // raised by the decoding below: decoding it too could fail the same way, without end + return ToUndecoded(ref type, ref value, ref traceback); + } + + _decodingError = true; try { if (TryDecodePyErr(type.Borrow(), value.BorrowNullable(), traceback.BorrowNullable()) is { } pyErr) { - type.Dispose(); - value.Dispose(); - traceback.Dispose(); return pyErr; } - } - catch - { - type.Dispose(); - value.Dispose(); - traceback.Dispose(); - throw; - } - try - { // an error set without a value, as PyErr_SetNone does, only gets one once normalized var normalizedValue = new NewReference(value.BorrowNullable(), canBeNull: true); Runtime.PyErr_NormalizeException(type: ref type, val: ref normalizedValue, tb: ref traceback); return FromPyErr(typeRef: type.Borrow(), valRef: value.IsNull() ? normalizedValue.Borrow() : value.Borrow(), nValRef: normalizedValue.Borrow(), tbRef: traceback.BorrowNullable(), out dispatchInfo); } + catch (PythonException) + { + // decoding runs Python code, which fails too at the recursion limit: keep the error as fetched + Exceptions.Clear(); + dispatchInfo = null; + return ToUndecoded(ref type, ref value, ref traceback); + } finally { + _decodingError = false; type.Dispose(); value.Dispose(); traceback.Dispose(); } } - internal static Exception FetchCurrent() - => FetchCurrentOrNull(out _) - ?? throw new InvalidOperationException("No exception is set"); - [ThreadStatic] - private static bool _hasRecursionHeadroom; + private static bool _decodingError; /// - /// Decoding an error runs Python code, which fails again when the error was raised at the - /// recursion limit. Raises the limit while the outermost decode of the thread runs. Requires the GIL. + /// Wraps a fetched error as it is, without running any Python code. /// - private readonly ref struct RecursionHeadroom + private static PythonException ToUndecoded(ref NewReference type, ref NewReference value, ref NewReference traceback) { - private const int ExtraFrames = 100; - - private readonly bool _entered; - - private RecursionHeadroom(bool entered) - { - _entered = entered; - } + var message = GetUndecodedMessage(type.Borrow(), value.BorrowNullable()); + return new PythonException(new PyType(type.Steal()), value.MoveToPyObjectOrNull(), + traceback.MoveToPyObjectOrNull(), message, innerException: null); + } - public static RecursionHeadroom Enter() + /// + /// The message of an error, read without str(): the text of an error that is not normalized + /// yet, or the only argument of an exception when it is a string. Else the name of its type. + /// + private static string GetUndecodedMessage(BorrowedReference type, BorrowedReference value) + { + try { - if (_hasRecursionHeadroom) + if (!value.IsNull) { - return default; - } + if (Runtime.GetManagedString(value) is { } text) + { + return text; + } - _hasRecursionHeadroom = true; - Runtime.Py_SetRecursionLimit(Runtime.Py_GetRecursionLimit() + ExtraFrames); - return new RecursionHeadroom(true); + using var args = Runtime.PyObject_GetAttrString(value, "args"); + if (args.IsNull()) + { + Exceptions.Clear(); + } + else if (Runtime.PyTuple_Check(args.Borrow()) && Runtime.PyTuple_Size(args.Borrow()) == 1 + && Runtime.GetManagedString(Runtime.PyTuple_GetItem(args.Borrow(), 0)) is { } argument) + { + return argument; + } + } } - - public void Dispose() + catch (PythonException) { - if (_entered) - { - // undo the increment, a saved limit would be stale when another thread is decoding too - Runtime.Py_SetRecursionLimit(Runtime.Py_GetRecursionLimit() - ExtraFrames); - _hasRecursionHeadroom = false; - } + Exceptions.Clear(); } + + return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(Util.ReadIntPtr(type, TypeOffset.tp_name)) ?? "Python error"; } + internal static Exception FetchCurrent() + => FetchCurrentOrNull(out _) + ?? throw new InvalidOperationException("No exception is set"); + private static ExceptionDispatchInfo? TryGetDispatchInfo(BorrowedReference exception) { if (exception.IsNull) return null; diff --git a/src/runtime/Runtime.Delegates.cs b/src/runtime/Runtime.Delegates.cs index c60462011..1e6c91f97 100644 --- a/src/runtime/Runtime.Delegates.cs +++ b/src/runtime/Runtime.Delegates.cs @@ -19,8 +19,6 @@ static Delegates() Py_InitializeEx = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_InitializeEx), GetUnmanagedDll(_PythonDll)); Py_IsInitialized = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_IsInitialized), GetUnmanagedDll(_PythonDll)); Py_Finalize = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_Finalize), GetUnmanagedDll(_PythonDll)); - Py_GetRecursionLimit = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_GetRecursionLimit), GetUnmanagedDll(_PythonDll)); - Py_SetRecursionLimit = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_SetRecursionLimit), GetUnmanagedDll(_PythonDll)); Py_NewInterpreter = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_NewInterpreter), GetUnmanagedDll(_PythonDll)); Py_EndInterpreter = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(Py_EndInterpreter), GetUnmanagedDll(_PythonDll)); PyThreadState_New = (delegate* unmanaged[Cdecl])GetFunctionByName(nameof(PyThreadState_New), GetUnmanagedDll(_PythonDll)); @@ -326,8 +324,6 @@ static Delegates() internal static delegate* unmanaged[Cdecl] Py_InitializeEx { get; } internal static delegate* unmanaged[Cdecl] Py_IsInitialized { get; } internal static delegate* unmanaged[Cdecl] Py_Finalize { get; } - internal static delegate* unmanaged[Cdecl] Py_GetRecursionLimit { get; } - internal static delegate* unmanaged[Cdecl] Py_SetRecursionLimit { get; } internal static delegate* unmanaged[Cdecl] Py_NewInterpreter { get; } internal static delegate* unmanaged[Cdecl] Py_EndInterpreter { get; } internal static delegate* unmanaged[Cdecl] PyThreadState_New { get; } diff --git a/src/runtime/Runtime.cs b/src/runtime/Runtime.cs index f2f06327c..c8719ee40 100644 --- a/src/runtime/Runtime.cs +++ b/src/runtime/Runtime.cs @@ -732,10 +732,6 @@ internal static T TryUsingDll(Func op) internal static void Py_Finalize() => Delegates.Py_Finalize(); - internal static int Py_GetRecursionLimit() => Delegates.Py_GetRecursionLimit(); - - internal static void Py_SetRecursionLimit(int limit) => Delegates.Py_SetRecursionLimit(limit); - internal static PyThreadState* Py_NewInterpreter() => Delegates.Py_NewInterpreter(); From fd602bb67613399466cc6e8c0c609badffce85e0 Mon Sep 17 00:00:00 2001 From: Jhonathan Abreu Date: Fri, 27 Nov 2026 17:02:25 -0400 Subject: [PATCH 7/7] Test an error whose decoding fails, and read its type name as UTF-8 --- src/embed_tests/TestPythonException.cs | 26 ++++++++++++++++++++++++++ src/runtime/PythonException.cs | 9 +++++---- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 748f46655..2bb1d3272 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -423,6 +423,32 @@ import sys } } + [Test] + public void ErrorWhoseStrRaisesArrivesAsItself() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Exec(@" +class Unprintable(Exception): + def __str__(self): + raise KeyError('from str') +"); + var error = Assert.Throws(() => scope.Exec("raise Unprintable('original')")); + Assert.AreEqual("Unprintable", error.Type.Name); + Assert.AreEqual("original", error.Message); + } + + [Test] + public void ErrorWhoseStrRaisesIsNamedAfterItsTypeWithoutATextArgument() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + // the type name is not ASCII + scope.Exec("class D\u00e9faut(Exception):\n def __str__(self):\n raise KeyError('from str')\n"); + var error = Assert.Throws(() => scope.Exec("raise D\u00e9faut(1, 2)")); + Assert.AreEqual("D\u00e9faut", error.Message); + } + public class ReentrantCaller { public void Call(PyObject callback) diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 0966915a1..2f9fe6384 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -135,8 +135,9 @@ internal static PythonException FetchCurrentRaw() /// private static PythonException ToUndecoded(ref NewReference type, ref NewReference value, ref NewReference traceback) { - var message = GetUndecodedMessage(type.Borrow(), value.BorrowNullable()); - return new PythonException(new PyType(type.Steal()), value.MoveToPyObjectOrNull(), + var pyType = new PyType(type.Steal()); + var message = GetUndecodedMessage(pyType, value.BorrowNullable()); + return new PythonException(pyType, value.MoveToPyObjectOrNull(), traceback.MoveToPyObjectOrNull(), message, innerException: null); } @@ -144,7 +145,7 @@ private static PythonException ToUndecoded(ref NewReference type, ref NewReferen /// The message of an error, read without str(): the text of an error that is not normalized /// yet, or the only argument of an exception when it is a string. Else the name of its type. /// - private static string GetUndecodedMessage(BorrowedReference type, BorrowedReference value) + private static string GetUndecodedMessage(PyType type, BorrowedReference value) { try { @@ -172,7 +173,7 @@ private static string GetUndecodedMessage(BorrowedReference type, BorrowedRefere Exceptions.Clear(); } - return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(Util.ReadIntPtr(type, TypeOffset.tp_name)) ?? "Python error"; + return type.Name; } internal static Exception FetchCurrent()