From d98d46f6c944973fd04f939205692f20ef4c46c2 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:07:06 +0000 Subject: [PATCH 1/5] Refresh args and __cause__ of a __namespace__ exception created from .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 --- src/runtime/Types/ClassDerived.cs | 16 ++++++++++-- tests/test_exceptions.py | 42 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index daeacfcd7..59424f24a 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -904,8 +904,8 @@ public static void InvokeSetProperty(IPythonDerivedType obj, string propertyN public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args) { - var selfRef = GetPyObj(obj); - if (selfRef.Ref == null) + var createdFromDotNet = GetPyObj(obj).Ref == null; + if (createdFromDotNet) { // this might happen when the object is created from .NET using var _ = Py.GIL(); @@ -922,6 +922,18 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec null, obj, args); + + // the Python object of an exception created from .NET got its args and __cause__ + // before the base constructor set its Message and InnerException + if (!createdFromDotNet || obj is not Exception exception) + { + return; + } + using var gil = Py.GIL(); + if (!Exceptions.SetArgsAndCause(GetPyObj(obj).CheckRun(), exception)) + { + throw PythonException.ThrowLastAsClrException(); + } } public static void PyFinalize(IPythonDerivedType obj) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 709ac0feb..a255da17c 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -711,3 +711,45 @@ def test_namespaced_exception_subclass_override_errors(): "inherited str outer KeyError 'inner'", "two-level inherited str outer KeyError 'inner'", ] + + +_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT = """ +from System import Activator, Array, Exception as ClrException, String, Type + +class CreatedError(ClrException): + __namespace__ = "Python.Test.DotNetCreatedExceptions" + def __init__(self): + pass + +class ChildCreatedError(CreatedError): + __namespace__ = "Python.Test.DotNetCreatedExceptions" + def __init__(self): + pass + +def check(name, error): + cause = error.__cause__ + print(name, error.Message, error.args, cause.Message if cause is not None else None, + error.InnerException.Message if error.InnerException is not None else None) + +inner = ClrException("inner") +created = clr.GetClrType(CreatedError) +check("activator", Activator.CreateInstance(created, Array[Object](["custom message", inner]))) +check("constructor info", created.GetConstructor(Array[Type]([String])).Invoke(Array[Object](["message only"]))) +check("parameterless", Activator.CreateInstance(created)) +check("child", Activator.CreateInstance(clr.GetClrType(ChildCreatedError), Array[Object](["child message", inner]))) +""" + + +@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") +def test_namespaced_exception_subclass_created_from_dotnet(): + """The args and __cause__ of a __namespace__ exception subclass constructed from .NET + match the Message and InnerException its base constructor set""" + output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT) + + default = "Exception of type 'Python.Test.DotNetCreatedExceptions.CreatedError' was thrown." + assert output[-4:] == [ + "activator custom message ('custom message',) inner inner", + "constructor info message only ('message only',) None None", + f"parameterless {default} ({default!r},) None None", + "child child message ('child message',) inner inner", + ] From d0b9c19d8b822b40efa945de98284d7db53d8631 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:43:12 +0000 Subject: [PATCH 2/5] Refresh a .NET-created exception's args without running Python overrides .NET construction doesn't run the Python __init__, so a Python Message override may not work yet when the base constructor returns: read Message as .NET implements it, as when the Python object was created. Keep the Python object referenced while setting args and __cause__, and keep the args it was created with when they can't be set. A generated inner exception becomes the __cause__ through its own Python object. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 13 +++++++---- src/runtime/Types/ClassDerived.cs | 27 ++++++++++++++++++++-- tests/test_exceptions.py | 37 ++++++++++++++++++++++++++++++- 3 files changed, 70 insertions(+), 7 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index c3ac889ed..8fa5f718c 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -77,13 +77,15 @@ internal static void Shutdown() /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// - internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) + internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) => SetArgsAndCause(ob, e, e.Message); + + internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string message) { NewReference args; - if (!string.IsNullOrEmpty(e.Message)) + if (!string.IsNullOrEmpty(message)) { args = Runtime.PyTuple_New(1); - using var msg = Runtime.PyString_FromString(e.Message); + using var msg = Runtime.PyString_FromString(message); Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow()); } else @@ -102,7 +104,10 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) if (e.InnerException != null) { // Note: For an AggregateException, InnerException is only the first of the InnerExceptions. - using var cause = CLRObject.GetReference(e.InnerException); + // a generated inner exception keeps its Python object + using var cause = e.InnerException is IPythonDerivedType derived + ? ClassDerivedObject.ToPython(derived) + : CLRObject.GetReference(e.InnerException); Runtime.PyException_SetCause(ob, cause.Steal()); } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 59424f24a..964f00f65 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -929,10 +929,33 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec { return; } + // .NET construction doesn't run the Python __init__, which Python overrides of Message may rely on: + // read it without them, as when the Python object was created + var pyObj = GetPyObj(obj); + SetPyObj(obj, BorrowedReference.Null); + string message; + try + { + message = exception.Message; + } + finally + { + SetPyObj(obj, pyObj.CheckRun()); + } + using var gil = Py.GIL(); - if (!Exceptions.SetArgsAndCause(GetPyObj(obj).CheckRun(), exception)) + // owned while they're set + using var pySelf = new PyObject(pyObj.CheckRun()); + try + { + if (!Exceptions.SetArgsAndCause(pySelf.Reference, exception, message)) + { + Exceptions.Clear(); + } + } + catch (PythonException) { - throw PythonException.ThrowLastAsClrException(); + // such as a message Python can't hold: the exception keeps the args it was created with } } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index a255da17c..c8b205932 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -726,6 +726,23 @@ class ChildCreatedError(CreatedError): def __init__(self): pass +class DelayedError(ClrException): + __namespace__ = "Python.Test.DotNetCreatedExceptions" + @clr.clrmethod(None, [str]) + def __init__(self, text): + self.text = text + def get_Message(self): + return self.text + +class CollectingError(ClrException): + __namespace__ = "Python.Test.DotNetCreatedExceptions" + def __init__(self): + pass + def get_Message(self): + GC.Collect() + GC.WaitForPendingFinalizers() + return "collected" + def check(name, error): cause = error.__cause__ print(name, error.Message, error.args, cause.Message if cause is not None else None, @@ -737,6 +754,21 @@ def check(name, error): check("constructor info", created.GetConstructor(Array[Type]([String])).Invoke(Array[Object](["message only"]))) check("parameterless", Activator.CreateInstance(created)) check("child", Activator.CreateInstance(clr.GetClrType(ChildCreatedError), Array[Object](["child message", inner]))) + +# .NET construction doesn't run __init__: the caller runs it after the constructor +delayed = Activator.CreateInstance(clr.GetClrType(DelayedError), Array[Object](["base message"])) +delayed.GetType().GetMethod("__init__").Invoke(delayed, Array[Object](["initialized"])) +check("delayed", delayed) + +collecting = Activator.CreateInstance(clr.GetClrType(CollectingError), Array[Object](["collecting message"])) +GC.Collect() +GC.WaitForPendingFinalizers() +print("collecting", Object.GetType(collecting).Name, collecting.Message, collecting.args) + +generated_inner = Activator.CreateInstance(created, Array[Object](["generated inner"])) +generated_inner.tag = "tagged" +outer = Activator.CreateInstance(created, Array[Object](["outer", generated_inner])) +print("generated cause", outer.__cause__ is generated_inner, outer.__cause__.tag) """ @@ -747,9 +779,12 @@ def test_namespaced_exception_subclass_created_from_dotnet(): output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT) default = "Exception of type 'Python.Test.DotNetCreatedExceptions.CreatedError' was thrown." - assert output[-4:] == [ + assert output[-7:] == [ "activator custom message ('custom message',) inner inner", "constructor info message only ('message only',) None None", f"parameterless {default} ({default!r},) None None", "child child message ('child message',) inner inner", + "delayed initialized ('base message',) None None", + "collecting CollectingError collected ('collecting message',)", + "generated cause True tagged", ] From 30aa2d0344298c1c6f5640cfa2afe18a7fe7dcea Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:21:47 +0000 Subject: [PATCH 3/5] Keep construction from .NET as on master when the args refresh can't run Read Message best-effort, hold a strong reference to the Python object while refreshing, report a message Python can't hold without a managed exception, keep reading Message on the other callers as before, and reuse a generated cause's Python object only when it has one in this runtime. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 21 +++++++++++++-------- src/runtime/Types/ClassDerived.cs | 17 +++++++++++------ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 8fa5f718c..3ec0a5f83 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -77,15 +77,19 @@ internal static void Shutdown() /// __getattr__ implementation, and thus dereferencing a NULL /// pointer. /// - internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) => SetArgsAndCause(ob, e, e.Message); - - internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string message) + /// the message read by the refresh of an exception created from .NET, + /// which reports a message Python can't hold by returning false + internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string? message = null) { NewReference args; - if (!string.IsNullOrEmpty(message)) + if (!string.IsNullOrEmpty(message ?? e.Message)) { + using var msg = Runtime.PyString_FromString(message ?? e.Message); + if (msg.IsNull() && message != null) + { + return false; + } args = Runtime.PyTuple_New(1); - using var msg = Runtime.PyString_FromString(message); Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow()); } else @@ -104,9 +108,10 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string m if (e.InnerException != null) { // Note: For an AggregateException, InnerException is only the first of the InnerExceptions. - // a generated inner exception keeps its Python object - using var cause = e.InnerException is IPythonDerivedType derived - ? ClassDerivedObject.ToPython(derived) + // a generated inner exception keeps its Python object, when it has one in this runtime + var peer = e.InnerException is IPythonDerivedType derived ? PythonDerivedType.GetPyObj(derived) : default; + using var cause = peer.Ref != null && peer.Run == Runtime.GetRun() + ? ClassDerivedObject.ToPython((IPythonDerivedType)e.InnerException) : CLRObject.GetReference(e.InnerException); Runtime.PyException_SetCause(ob, cause.Steal()); } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 964f00f65..e4e952ed5 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -929,6 +929,9 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec { return; } + using var gil = Py.GIL(); + // a strong reference while it's refreshed: the Python object starts with a weak one + using var pySelf = ClassDerivedObject.ToPython(obj); // .NET construction doesn't run the Python __init__, which Python overrides of Message may rely on: // read it without them, as when the Python object was created var pyObj = GetPyObj(obj); @@ -936,26 +939,28 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec string message; try { - message = exception.Message; + message = exception.Message ?? string.Empty; + } + catch (Exception) + { + // the exception keeps the args it was created with + return; } finally { SetPyObj(obj, pyObj.CheckRun()); } - using var gil = Py.GIL(); - // owned while they're set - using var pySelf = new PyObject(pyObj.CheckRun()); try { - if (!Exceptions.SetArgsAndCause(pySelf.Reference, exception, message)) + if (!Exceptions.SetArgsAndCause(pySelf.Borrow(), exception, message)) { Exceptions.Clear(); } } catch (PythonException) { - // such as a message Python can't hold: the exception keeps the args it was created with + // the exception keeps the args it was created with } } From e109105caf2f67e341ebae13e6be707b6166117b Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:02:37 +0000 Subject: [PATCH 4/5] Release the GIL and keep construction from .NET when the refresh can't convert the inner exception Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 10 +++++++--- src/runtime/Types/ClassDerived.cs | 7 +++++-- src/runtime/Types/ClrObject.cs | 5 +++-- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 3ec0a5f83..8d0cfd7da 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -85,12 +85,16 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string? if (!string.IsNullOrEmpty(message ?? e.Message)) { using var msg = Runtime.PyString_FromString(message ?? e.Message); - if (msg.IsNull() && message != null) + if (msg.IsNull()) { - return false; + if (message != null) + { + return false; + } + throw PythonException.ThrowLastAsClrException(); } args = Runtime.PyTuple_New(1); - Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow()); + Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.Steal()); } else { diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index e4e952ed5..61e23336d 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -939,6 +939,8 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec string message; try { + // a .NET Message may wait on another thread that runs Python code + using var threads = Py.AllowThreads(); message = exception.Message ?? string.Empty; } catch (Exception) @@ -958,9 +960,10 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec Exceptions.Clear(); } } - catch (PythonException) + catch (Exception) { - // the exception keeps the args it was created with + // such as an inner exception whose Message throws: construction succeeds as when + // the exception was created, without a cause } } diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs index 98ceba8f4..f5c8c0136 100644 --- a/src/runtime/Types/ClrObject.cs +++ b/src/runtime/Types/ClrObject.cs @@ -20,7 +20,8 @@ internal sealed class CLRObject : ManagedType static NewReference Create(object ob, BorrowedReference tp) { Debug.Assert(tp != null); - var py = Runtime.PyType_GenericAlloc(tp, 0); + // freed when reading or converting an exception's Message throws + using var py = Runtime.PyType_GenericAlloc(tp, 0); var self = new CLRObject(ob); @@ -32,7 +33,7 @@ static NewReference Create(object ob, BorrowedReference tp) // slot if wrapping a CLR exception if (ob is Exception e) Exceptions.SetArgsAndCause(py.Borrow(), e); - return py; + return py.Move(); } CLRObject(object inst) From e734894b11bef01ed308bed7df6d81cc3f6d1a5a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:38:23 +0000 Subject: [PATCH 5/5] Wrap a generated inner exception again when .NET collected its weak CLR wrapper Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 8d0cfd7da..e7d8f9f0e 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -113,10 +113,15 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string? { // Note: For an AggregateException, InnerException is only the first of the InnerExceptions. // a generated inner exception keeps its Python object, when it has one in this runtime + // whose CLR wrapper is still alive: .NET may have collected the weak wrapper meanwhile var peer = e.InnerException is IPythonDerivedType derived ? PythonDerivedType.GetPyObj(derived) : default; - using var cause = peer.Ref != null && peer.Run == Runtime.GetRun() + var wrapper = peer.Ref != null && peer.Run == Runtime.GetRun() + ? ManagedType.GetManagedObject(peer.CheckRun()) + : null; + using var cause = wrapper != null ? ClassDerivedObject.ToPython((IPythonDerivedType)e.InnerException) : CLRObject.GetReference(e.InnerException); + GC.KeepAlive(wrapper); Runtime.PyException_SetCause(ob, cause.Steal()); }