From 13eb3e3e18d4e4703d5fc396f6f4c6591ffb413d Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:22:29 +0000 Subject: [PATCH 01/14] Keep the Python object of a __namespace__ subclass of a .NET exception A Python subclass of System.Exception, or of any exception type, that declares __namespace__ gets a generated .NET type, but that type was reflected as a plain exception rather than as a Python-derived type. Its Python wrapper never stored itself on the .NET object, so the generated constructor created a temporary wrapper, kept its pointer and released it: later calls through the .NET object, such as an overridden virtual method or the object coming back from .NET, used a freed object and could crash the process. An __init__ that didn't call the base __init__ also left the base constructor unrun, so field initializers stayed null. Generated exception types now get the derived-type handling of ordinary __namespace__ subclasses (the wrapper set on the object, the base constructor run before __init__, the object's lifetime tied to the .NET object) together with the exception repr, str and args. Co-Authored-By: Claude Opus 5.5 --- src/runtime/ClassManager.cs | 16 ++--- src/runtime/Types/ExceptionClassObject.cs | 27 ++++++++ tests/test_exceptions.py | 75 ++++++++++++++++++++++- 3 files changed, 110 insertions(+), 8 deletions(-) diff --git a/src/runtime/ClassManager.cs b/src/runtime/ClassManager.cs index b4aefacc2..a796424e4 100644 --- a/src/runtime/ClassManager.cs +++ b/src/runtime/ClassManager.cs @@ -190,17 +190,19 @@ internal static ClassBase CreateClass(Type type) impl = new InterfaceObject(type); } - else if (type == typeof(Exception) || - type.IsSubclassOf(typeof(Exception))) - { - impl = new ExceptionClassObject(type); - } - #pragma warning disable CS0618 // Type or member is obsolete. OK for internal use. else if (null != PythonDerivedType.GetPyObjField(type)) #pragma warning restore CS0618 // Type or member is obsolete { - impl = new ClassDerivedObject(type); + impl = type.IsSubclassOf(typeof(Exception)) + ? new ExceptionClassDerivedObject(type) + : new ClassDerivedObject(type); + } + + else if (type == typeof(Exception) || + type.IsSubclassOf(typeof(Exception))) + { + impl = new ExceptionClassObject(type); } else if (typeof(IDynamicMetaObjectProvider).IsAssignableFrom(type)) diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 762c9255a..037b53df5 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -76,3 +76,30 @@ public override bool Init(BorrowedReference obj, BorrowedReference args, Borrowe return Exceptions.SetArgsAndCause(obj, (Exception)e.inst); } } + +/// +/// Implementation for the managed types generated for Python subclasses of exceptions +/// that declare __namespace__: the generated object keeps its Python object as derived +/// types do, while it still reads as an exception from Python. +/// +[Serializable] +internal class ExceptionClassDerivedObject : ClassDerivedObject +{ + internal ExceptionClassDerivedObject(Type tp) : base(tp) + { + } + + // Type slots are looked up on the implementing type's hierarchy, which here is ClassDerivedObject's + public new static NewReference tp_repr(BorrowedReference ob) => ExceptionClassObject.tp_repr(ob); + + public new static NewReference tp_str(BorrowedReference ob) => ExceptionClassObject.tp_str(ob); + + public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) + { + if (!base.Init(obj, args, kw)) return false; + + var e = (CLRObject)GetManagedObject(obj)!; + + return Exceptions.SetArgsAndCause(obj, (Exception)e.inst); + } +} diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 5334c06a7..1a050c459 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -2,6 +2,8 @@ """Test exception support.""" +import os +import subprocess import sys import System @@ -447,4 +449,75 @@ def test_dont_leak_exceptions_inner(): except TypeError: print('type error, as expected') except System.ArgumentException: - print('type error, also expected') \ No newline at end of file + print('type error, also expected') + + +_NAMESPACED_EXCEPTION_SCRIPT = """ +import os, sys +bin_path = sys.argv[1] +sys.path.append(bin_path) +from clr_loader import get_coreclr +from pythonnet import set_runtime +set_runtime(get_coreclr(runtime_config=os.path.join(bin_path, "Python.Test.runtimeconfig.json"))) +import clr +clr.AddReference("Python.Test") +import gc +from Python.Test import ExtendedException +from System import GC, Object +from System.Collections.Generic import List + +class WithoutInit(ExtendedException): + __namespace__ = "Python.Test.NamespacedExceptions" + +class InitWithoutSuper(ExtendedException): + __namespace__ = "Python.Test.NamespacedExceptions" + def __init__(self): + pass + def ToString(self): + return "overridden" + +class InitWithSuper(ExtendedException): + __namespace__ = "Python.Test.NamespacedExceptions" + def __init__(self): + super().__init__("message") + +def check(cls): + error = cls() + held = List[Object]() + held.Add(error) + try: + raise error + except ExtendedException as caught: + raised = caught is error + print(cls.__name__, error.extra, held[0] is error, raised, str(error), error.args) + +check(WithoutInit) +check(InitWithoutSuper) +check(InitWithSuper) +gc.collect() +for _ in range(2): + GC.Collect() + GC.WaitForPendingFinalizers() +print("collected") +""" + + +@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") +def test_namespaced_exception_subclass_construction(): + """A Python subclass of a .NET exception declaring __namespace__ runs its base + constructor, keeps its Python object for .NET and its overrides, and still + reads as an exception; it runs in a subprocess so a native crash fails the test""" + from Python.Test import ExtendedException + + bin_path = os.path.dirname(ExtendedException().GetType().Assembly.Location) + result = subprocess.run([sys.executable, "-c", _NAMESPACED_EXCEPTION_SCRIPT, bin_path], + capture_output=True, text=True, timeout=300) + + assert result.returncode == 0, result.stderr + overflow = "Arithmetic operation resulted in an overflow." + assert result.stdout.splitlines()[-4:] == [ + f"WithoutInit extra True True {overflow} ('{overflow}',)", + f"InitWithoutSuper extra True True overridden ('{overflow}',)", + "InitWithSuper extra True True message ('message',)", + "collected", + ] From b2cafc09896ca41471c743ec2f85007b336504eb Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:34:21 +0000 Subject: [PATCH 02/14] Release __namespace__ exception subclasses safely - A __namespace__ subclass of another one has a generated Finalize at each level, all calling PythonDerivedType.PyFinalize on the same object, which queued the same Python object once per level for release: freed twice, the process crashed. PyFinalize now clears the object's __pyobj__ field once it queued it, and skips an object it already queued. This also fixes chains of __namespace__ subclasses of System.Object. - The derived types' tp_clear is a no-op, so an exception referencing itself through args, __cause__, __context__ or __traceback__ was never collected. A __namespace__ exception subclass now clears those fields, keeping its wrapper for the .NET object. - A Python ToString override that raised escaped the exception str() slot and aborted the process; its error is now raised to str()'s caller. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ClassDerived.cs | 7 ++ src/runtime/Types/ExceptionClassObject.cs | 16 +++- tests/test_exceptions.py | 102 ++++++++++++++++++++-- 3 files changed, 115 insertions(+), 10 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 6c2c81b13..32326451e 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -928,7 +928,14 @@ public static void PyFinalize(IPythonDerivedType obj) // the C# object is being destroyed which must mean there are no more // references to the Python object as well var self = GetPyObj(obj); + // every generated type in a chain of Python subclasses has its own Finalize calling this on the + // same object: only the first one queues its Python object + if (self.Ref == null) + { + return; + } Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run); + SetPyObj(obj, BorrowedReference.Null); } internal static void Finalize(IntPtr derived) diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 037b53df5..77808c119 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -53,7 +53,16 @@ internal ExceptionClassObject(Type tp) : base(tp) return Exceptions.RaiseTypeError("invalid object"); } - string message = e.ToString(); + string message; + try + { + message = e.ToString(); + } + catch (Exception error) + { + Exceptions.SetError(error.InnerException ?? error); + return default; + } string fullTypeName = e.GetType().FullName; string prefix = fullTypeName + ": "; if (message.StartsWith(prefix)) @@ -94,6 +103,11 @@ internal ExceptionClassDerivedObject(Type tp) : base(tp) public new static NewReference tp_str(BorrowedReference ob) => ExceptionClassObject.tp_str(ob); + // ClassDerivedObject's tp_clear leaves the object to the .NET finalizer, but the exception's own fields + // (args, __cause__, __context__, __traceback__, __dict__) can form cycles that only clearing them breaks. + // The wrapper and its handle stay, as the .NET object may still use them. + public new static int tp_clear(BorrowedReference ob) => BaseUnmanagedClear(ob); + public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) { if (!base.Init(obj, args, kw)) return false; diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 1a050c459..bb17c381c 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -452,7 +452,7 @@ def test_dont_leak_exceptions_inner(): print('type error, also expected') -_NAMESPACED_EXCEPTION_SCRIPT = """ +_NAMESPACED_EXCEPTION_SCRIPT_SETUP = """ import os, sys bin_path = sys.argv[1] sys.path.append(bin_path) @@ -464,6 +464,22 @@ def test_dont_leak_exceptions_inner(): import gc from Python.Test import ExtendedException from System import GC, Object +""" + + +def _run_namespaced_exception_script(script): + """Runs the script in a subprocess, so a native crash fails the test instead of the test run""" + from Python.Test import ExtendedException + + bin_path = os.path.dirname(ExtendedException().GetType().Assembly.Location) + result = subprocess.run([sys.executable, "-c", _NAMESPACED_EXCEPTION_SCRIPT_SETUP + script, bin_path], + capture_output=True, text=True, timeout=300) + + assert result.returncode == 0, result.stderr + return result.stdout.splitlines() + + +_NAMESPACED_EXCEPTION_SCRIPT = """ from System.Collections.Generic import List class WithoutInit(ExtendedException): @@ -506,18 +522,86 @@ def check(cls): def test_namespaced_exception_subclass_construction(): """A Python subclass of a .NET exception declaring __namespace__ runs its base constructor, keeps its Python object for .NET and its overrides, and still - reads as an exception; it runs in a subprocess so a native crash fails the test""" - from Python.Test import ExtendedException - - bin_path = os.path.dirname(ExtendedException().GetType().Assembly.Location) - result = subprocess.run([sys.executable, "-c", _NAMESPACED_EXCEPTION_SCRIPT, bin_path], - capture_output=True, text=True, timeout=300) + reads as an exception""" + output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_SCRIPT) - assert result.returncode == 0, result.stderr overflow = "Arithmetic operation resulted in an overflow." - assert result.stdout.splitlines()[-4:] == [ + assert output[-4:] == [ f"WithoutInit extra True True {overflow} ('{overflow}',)", f"InitWithoutSuper extra True True overridden ('{overflow}',)", "InitWithSuper extra True True message ('message',)", "collected", ] + + +_NAMESPACED_EXCEPTION_RELEASE_SCRIPT = """ +class Probe(Object): + __namespace__ = "Python.Test.ReleasedExceptions" + def ToString(self): + return "probe" + +class ParentError(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + pass + +class ChildError(ParentError): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + pass + +class CycleError(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + pass + +class FailingToString(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + pass + def ToString(self): + raise ValueError("ToString failed") + +def release(): + for _ in range(3): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + # each call from .NET into the Python override creates Python objects, which + # periodically release the queued Python objects of finalized .NET objects + for _ in range(300): + str(probe) + +probe = Probe() + +for _ in range(10): + ChildError() +release() +print("released") + +for _ in range(10): + error = CycleError() + error.__cause__ = error + error = CycleError() + error.__context__ = error + error = CycleError() + error.args = (error,) +del error +release() +print(sum(1 for o in gc.get_objects() if type(o) is CycleError)) + +try: + str(FailingToString()) +except ValueError as error: + print(error) +""" + + +@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") +def test_namespaced_exception_subclass_release(): + """A __namespace__ exception subclass of another one is released once, exceptions + referencing themselves through args, __cause__ or __context__ are collected, and + an error raised by a Python ToString override reaches str()'s caller""" + output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) + + assert output[-3:] == ["released", "0", "ToString failed"] From d872f731b6dd1ec6b2b2b3c9a6e151abeae5649c Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:07:24 +0000 Subject: [PATCH 03/14] Raise errors from Message overrides in exception repr() and __init__ A __namespace__ exception subclass's Python overrides are reached from .NET now, so a Message override that raised escaped tp_repr, and __init__ through Exceptions.SetArgsAndCause, aborting the process. Both now raise the error to the caller, as tp_str does for ToString. The exception Init of reflected and generated types shares the guarded SetArgsAndCause call. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ExceptionClassObject.cs | 42 ++++++++++++++++------- tests/test_exceptions.py | 23 +++++++++++-- 2 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 77808c119..1597d5c6a 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -30,10 +30,20 @@ internal ExceptionClassObject(Type tp) : base(tp) return Exceptions.RaiseTypeError("invalid object"); } string name = e.GetType().Name; + string exceptionMessage; + try + { + exceptionMessage = e.Message; + } + catch (Exception error) + { + Exceptions.SetError(error.InnerException ?? error); + return default; + } string message; - if (e.Message != String.Empty) + if (exceptionMessage != String.Empty) { - message = String.Format("{0}('{1}')", name, e.Message); + message = String.Format("{0}('{1}')", name, exceptionMessage); } else { @@ -77,12 +87,24 @@ internal ExceptionClassObject(Type tp) : base(tp) } public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) - { - if (!base.Init(obj, args, kw)) return false; + => base.Init(obj, args, kw) && SetArgsAndCause(obj); + /// + /// Sets the args and __cause__ of the constructed exception, raising to Python an error + /// its members throw, such as a Python override of Message + /// + internal static bool SetArgsAndCause(BorrowedReference obj) + { var e = (CLRObject)GetManagedObject(obj)!; - - return Exceptions.SetArgsAndCause(obj, (Exception)e.inst); + try + { + return Exceptions.SetArgsAndCause(obj, (Exception)e.inst); + } + catch (Exception error) + { + Exceptions.SetError(error.InnerException ?? error); + return false; + } } } @@ -109,11 +131,5 @@ internal ExceptionClassDerivedObject(Type tp) : base(tp) public new static int tp_clear(BorrowedReference ob) => BaseUnmanagedClear(ob); public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) - { - if (!base.Init(obj, args, kw)) return false; - - var e = (CLRObject)GetManagedObject(obj)!; - - return Exceptions.SetArgsAndCause(obj, (Exception)e.inst); - } + => base.Init(obj, args, kw) && ExceptionClassObject.SetArgsAndCause(obj); } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index bb17c381c..b68c5d168 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -594,6 +594,24 @@ def release(): str(FailingToString()) except ValueError as error: print(error) + +class FailingMessage(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self, call_base): + if call_base: + super().__init__() + def get_Message(self): + raise ValueError("Message failed") + +try: + repr(FailingMessage(False)) +except ValueError as error: + print("repr", error) + +try: + FailingMessage(True) +except ValueError as error: + print("init", error) """ @@ -601,7 +619,8 @@ def release(): def test_namespaced_exception_subclass_release(): """A __namespace__ exception subclass of another one is released once, exceptions referencing themselves through args, __cause__ or __context__ are collected, and - an error raised by a Python ToString override reaches str()'s caller""" + an error raised by a Python ToString or Message override reaches the caller of + str(), repr() or the constructor""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) - assert output[-3:] == ["released", "0", "ToString failed"] + assert output[-5:] == ["released", "0", "ToString failed", "repr Message failed", "init Message failed"] From e9ebba48b60bea396aca3c4af6c41bd0c6581e44 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:29:57 +0000 Subject: [PATCH 04/14] Keep exception formatting and its override errors inside the slot guards - tp_str and tp_repr of exceptions now run all their work inside the guard: a Python ToString override returning None crashed on the prefix stripping after the guarded call. None now reads as an empty message. - The guards raised the InnerException of the caught error, which for a Python override's error is its __cause__: raise ValueError() from KeyError() reached the caller as KeyError. ToString and Message are called directly here, so the error is raised as it is. - The override error cases move to their own subprocess test, which constructs the exception before its overrides start failing, so repr() is reached, and checks each error's type and cause. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ExceptionClassObject.cs | 54 +++++++-------- tests/test_exceptions.py | 80 ++++++++++++++--------- 2 files changed, 74 insertions(+), 60 deletions(-) diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 1597d5c6a..422612447 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -29,27 +29,22 @@ internal ExceptionClassObject(Type tp) : base(tp) { return Exceptions.RaiseTypeError("invalid object"); } - string name = e.GetType().Name; - string exceptionMessage; + // Message may be a Python override: its error is raised to the caller as it is try { - exceptionMessage = e.Message; + string name = e.GetType().Name; + string message = e.Message; + if (!string.IsNullOrEmpty(message)) + { + return Runtime.PyString_FromString(String.Format("{0}('{1}')", name, message)); + } + return Runtime.PyString_FromString(String.Format("{0}()", name)); } catch (Exception error) { - Exceptions.SetError(error.InnerException ?? error); + Exceptions.SetError(error); return default; } - string message; - if (exceptionMessage != String.Empty) - { - message = String.Format("{0}('{1}')", name, exceptionMessage); - } - else - { - message = String.Format("{0}()", name); - } - return Runtime.PyString_FromString(message); } /// @@ -63,27 +58,28 @@ internal ExceptionClassObject(Type tp) : base(tp) return Exceptions.RaiseTypeError("invalid object"); } - string message; + // ToString may be a Python override: its error is raised to the caller as it is, and a None + // it returns reads as an empty message try { - message = e.ToString(); + string message = e.ToString() ?? string.Empty; + string fullTypeName = e.GetType().FullName; + string prefix = fullTypeName + ": "; + if (message.StartsWith(prefix)) + { + message = message.Substring(prefix.Length); + } + else if (message.StartsWith(fullTypeName)) + { + message = message.Substring(fullTypeName.Length); + } + return Runtime.PyString_FromString(message); } catch (Exception error) { - Exceptions.SetError(error.InnerException ?? error); + Exceptions.SetError(error); return default; } - string fullTypeName = e.GetType().FullName; - string prefix = fullTypeName + ": "; - if (message.StartsWith(prefix)) - { - message = message.Substring(prefix.Length); - } - else if (message.StartsWith(fullTypeName)) - { - message = message.Substring(fullTypeName.Length); - } - return Runtime.PyString_FromString(message); } public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) @@ -102,7 +98,7 @@ internal static bool SetArgsAndCause(BorrowedReference obj) } catch (Exception error) { - Exceptions.SetError(error.InnerException ?? error); + Exceptions.SetError(error); return false; } } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index b68c5d168..7dd777492 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -555,13 +555,6 @@ class CycleError(ExtendedException): def __init__(self): pass -class FailingToString(ExtendedException): - __namespace__ = "Python.Test.ReleasedExceptions" - def __init__(self): - pass - def ToString(self): - raise ValueError("ToString failed") - def release(): for _ in range(3): gc.collect() @@ -590,37 +583,62 @@ def release(): release() print(sum(1 for o in gc.get_objects() if type(o) is CycleError)) -try: - str(FailingToString()) -except ValueError as error: - print(error) +""" -class FailingMessage(ExtendedException): - __namespace__ = "Python.Test.ReleasedExceptions" - def __init__(self, call_base): - if call_base: + +@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") +def test_namespaced_exception_subclass_release(): + """A __namespace__ exception subclass of another one is released once, and exceptions + referencing themselves through args, __cause__ or __context__ are collected""" + output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) + + assert output[-2:] == ["released", "0"] + + +_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT = """ +class OverridingError(ExtendedException): + __namespace__ = "Python.Test.OverridingExceptions" + def __init__(self, failing=False): + self.failing = failing + if failing: super().__init__() + def fail(self): + raise ValueError("outer") from KeyError("inner") def get_Message(self): - raise ValueError("Message failed") + if self.failing: + self.fail() + return "message" + def ToString(self): + if self.failing: + self.fail() + return None + +error = OverridingError() +print(repr(str(error)), repr(error)) +error.failing = True -try: - repr(FailingMessage(False)) -except ValueError as error: - print("repr", error) +def check(name, call): + try: + call() + except ValueError as raised: + print(name, raised, type(raised.__cause__).__name__, raised.__cause__) -try: - FailingMessage(True) -except ValueError as error: - print("init", error) +check("str", lambda: str(error)) +check("repr", lambda: repr(error)) +check("init", lambda: OverridingError(failing=True)) """ @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") -def test_namespaced_exception_subclass_release(): - """A __namespace__ exception subclass of another one is released once, exceptions - referencing themselves through args, __cause__ or __context__ are collected, and - an error raised by a Python ToString or Message override reaches the caller of - str(), repr() or the constructor""" - output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) +def test_namespaced_exception_subclass_override_errors(): + """str(), repr() and the constructor of a __namespace__ exception subclass read None + from a Python ToString override as an empty message, and raise the error of a Python + ToString or Message override to their caller as it is, with its cause""" + output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-5:] == ["released", "0", "ToString failed", "repr Message failed", "init Message failed"] + assert output[-4:] == [ + "'' OverridingError('message')", + "str outer KeyError 'inner'", + "repr outer KeyError 'inner'", + "init outer KeyError 'inner'", + ] From 87cc5f45b39f868601303965c7861966ebd96912 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:38:54 +0000 Subject: [PATCH 05/14] Release a derived object's Python object after its base finalizers - A generated type's Finalize released the Python object before calling its base class finalizer, and since releasing became once only it clears __pyobj__: a base finalizer calling a virtual member then no longer reached the Python override (the .NET implementation ran, or an abstract one threw and terminated the process). Finalize now runs the base finalizer first: the innermost generated type queues the Python object once the finalizer chain ran, and the outer ones skip it. - An inherited ToString runs through reflection, which wraps the error of a Python Message override it calls in a TargetInvocationException. The exception slots now raise that wrapper's inner error, and still raise a PythonException as it is, with its cause. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ClassDerived.cs | 9 ++-- src/runtime/Types/ExceptionClassObject.cs | 22 +++++--- src/testing/constructortests.cs | 24 +++++++++ tests/test_exceptions.py | 65 +++++++++++++++++++++-- 4 files changed, 105 insertions(+), 15 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 32326451e..daeacfcd7 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -269,7 +269,8 @@ internal static Type CreateDerivedType(string name, } } - // add the destructor so the python object created in the constructor gets destroyed + // add the destructor so the python object created in the constructor gets destroyed, + // after the base class finalizers, which may still call the Python overrides MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize", MethodAttributes.Family | MethodAttributes.Virtual | @@ -279,11 +280,11 @@ internal static Type CreateDerivedType(string name, Type.EmptyTypes); ILGenerator il = methodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance)); + il.Emit(OpCodes.Ldarg_0); #pragma warning disable CS0618 // PythonDerivedType is for internal use only il.Emit(OpCodes.Call, typeof(PythonDerivedType).GetMethod(nameof(PyFinalize))); #pragma warning restore CS0618 // PythonDerivedType is for internal use only - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance)); il.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); @@ -929,7 +930,7 @@ public static void PyFinalize(IPythonDerivedType obj) // references to the Python object as well var self = GetPyObj(obj); // every generated type in a chain of Python subclasses has its own Finalize calling this on the - // same object: only the first one queues its Python object + // same object, once the finalizers of its base classes ran: only the first one queues its Python object if (self.Ref == null) { return; diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 422612447..672d8c86a 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -1,4 +1,5 @@ using System; +using System.Reflection; namespace Python.Runtime; @@ -29,7 +30,6 @@ internal ExceptionClassObject(Type tp) : base(tp) { return Exceptions.RaiseTypeError("invalid object"); } - // Message may be a Python override: its error is raised to the caller as it is try { string name = e.GetType().Name; @@ -42,7 +42,7 @@ internal ExceptionClassObject(Type tp) : base(tp) } catch (Exception error) { - Exceptions.SetError(error); + SetError(error); return default; } } @@ -58,8 +58,7 @@ internal ExceptionClassObject(Type tp) : base(tp) return Exceptions.RaiseTypeError("invalid object"); } - // ToString may be a Python override: its error is raised to the caller as it is, and a None - // it returns reads as an empty message + // a None returned by a Python override of ToString reads as an empty message try { string message = e.ToString() ?? string.Empty; @@ -77,11 +76,22 @@ internal ExceptionClassObject(Type tp) : base(tp) } catch (Exception error) { - Exceptions.SetError(error); + SetError(error); return default; } } + /// + /// Raises to Python the error of an exception member, as it is: a Python override of the member + /// throws its PythonException directly, whose InnerException is its cause, while a member the + /// Python subclass inherits runs through reflection, which wraps what it throws + /// + static void SetError(Exception error) + { + var raised = error is TargetInvocationException { InnerException: { } invoked } ? invoked : error; + Exceptions.SetError(raised); + } + public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) => base.Init(obj, args, kw) && SetArgsAndCause(obj); @@ -98,7 +108,7 @@ internal static bool SetArgsAndCause(BorrowedReference obj) } catch (Exception error) { - Exceptions.SetError(error); + SetError(error); return false; } } diff --git a/src/testing/constructortests.cs b/src/testing/constructortests.cs index d1007b150..f36157948 100644 --- a/src/testing/constructortests.cs +++ b/src/testing/constructortests.cs @@ -118,4 +118,28 @@ public CountedConstructorTest() ++Calls; } } + + public abstract class AbstractFinalizerCallbackTest + { + public static int Result; + + public abstract int Callback(); + + ~AbstractFinalizerCallbackTest() + { + Result = Callback(); + } + } + + public class VirtualFinalizerCallbackTest + { + public static int Result; + + public virtual int Callback() => 7; + + ~VirtualFinalizerCallbackTest() + { + Result = Callback(); + } + } } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 7dd777492..0337e7a28 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -583,16 +583,56 @@ def release(): release() print(sum(1 for o in gc.get_objects() if type(o) is CycleError)) +from Python.Test import AbstractFinalizerCallbackTest, VirtualFinalizerCallbackTest + +class AbstractCallback(AbstractFinalizerCallbackTest): + __namespace__ = "Python.Test.ReleasedExceptions" + def Callback(self): + return 42 + +class AbstractCallbackChild(AbstractCallback): + __namespace__ = "Python.Test.ReleasedExceptions" + def Callback(self): + return 43 + +class VirtualCallback(VirtualFinalizerCallbackTest): + __namespace__ = "Python.Test.ReleasedExceptions" + def Callback(self): + return 42 + +class VirtualCallbackChild(VirtualCallback): + __namespace__ = "Python.Test.ReleasedExceptions" + def Callback(self): + return 43 + +for cls, base in ((AbstractCallback, AbstractFinalizerCallbackTest), + (AbstractCallbackChild, AbstractFinalizerCallbackTest), + (VirtualCallback, VirtualFinalizerCallbackTest), + (VirtualCallbackChild, VirtualFinalizerCallbackTest)): + base.Result = 0 + cls() + release() + print(cls.__name__, base.Result) + """ @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") def test_namespaced_exception_subclass_release(): - """A __namespace__ exception subclass of another one is released once, and exceptions - referencing themselves through args, __cause__ or __context__ are collected""" + """A __namespace__ exception subclass of another one is released once, exceptions + referencing themselves through args, __cause__ or __context__ are collected, and + the finalizer of a .NET base class still reaches the Python overrides of its + __namespace__ subclasses, before their Python object is released""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) - assert output[-2:] == ["released", "0"] + assert output[-6:] == [ + "released", + "0", + "AbstractCallback 42", + "AbstractCallbackChild 43", + "VirtualCallback 42", + "VirtualCallbackChild 43", + ] _NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT = """ @@ -626,6 +666,19 @@ def check(name, call): check("str", lambda: str(error)) check("repr", lambda: repr(error)) check("init", lambda: OverridingError(failing=True)) + +class InheritedToStringError(ExtendedException): + __namespace__ = "Python.Test.OverridingExceptions" + def __init__(self): + self.failing = False + def get_Message(self): + if self.failing: + raise ValueError("outer") from KeyError("inner") + return "message" + +inherited = InheritedToStringError() +inherited.failing = True +check("inherited str", lambda: str(inherited)) """ @@ -633,12 +686,14 @@ def check(name, call): def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python - ToString or Message override to their caller as it is, with its cause""" + ToString or Message override to their caller as it is, with its cause, also when an + inherited ToString calls the Message override""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-4:] == [ + assert output[-5:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", "init outer KeyError 'inner'", + "inherited str outer KeyError 'inner'", ] From d62a3332eda2e2b50e718bce97299e7a40d49a6a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:22:41 +0000 Subject: [PATCH 06/14] Unwrap every reflection wrapper of an exception slot's error Each generated __namespace__ level that an inherited member runs through adds its own TargetInvocationException, so with two levels str() raised one of them instead of the Python override's error. ExceptionClassObject's SetError now unwraps all of the leading wrappers. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ExceptionClassObject.cs | 10 +++++++--- tests/test_exceptions.py | 18 ++++++++++++++++-- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/runtime/Types/ExceptionClassObject.cs b/src/runtime/Types/ExceptionClassObject.cs index 672d8c86a..7a082f8a8 100644 --- a/src/runtime/Types/ExceptionClassObject.cs +++ b/src/runtime/Types/ExceptionClassObject.cs @@ -84,12 +84,16 @@ internal ExceptionClassObject(Type tp) : base(tp) /// /// Raises to Python the error of an exception member, as it is: a Python override of the member /// throws its PythonException directly, whose InnerException is its cause, while a member the - /// Python subclass inherits runs through reflection, which wraps what it throws + /// Python subclass inherits runs through reflection, which wraps what it throws once per + /// generated level it goes through /// static void SetError(Exception error) { - var raised = error is TargetInvocationException { InnerException: { } invoked } ? invoked : error; - Exceptions.SetError(raised); + while (error is TargetInvocationException { InnerException: { } inner }) + { + error = inner; + } + Exceptions.SetError(error); } public override bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 0337e7a28..709ac0feb 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -679,6 +679,19 @@ def get_Message(self): inherited = InheritedToStringError() inherited.failing = True check("inherited str", lambda: str(inherited)) + +class TwoLevelInheritedToStringError(InheritedToStringError): + __namespace__ = "Python.Test.OverridingExceptions" + def __init__(self): + self.failing = False + def get_Message(self): + if self.failing: + raise ValueError("outer") from KeyError("inner") + return "message" + +two_level = TwoLevelInheritedToStringError() +two_level.failing = True +check("two-level inherited str", lambda: str(two_level)) """ @@ -687,13 +700,14 @@ def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python ToString or Message override to their caller as it is, with its cause, also when an - inherited ToString calls the Message override""" + inherited ToString calls the Message override, through one or two generated levels""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-5:] == [ + assert output[-6:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", "init outer KeyError 'inner'", "inherited str outer KeyError 'inner'", + "two-level inherited str outer KeyError 'inner'", ] From a47645898e0363410bfe537abd4bf876d14b1dc8 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:30:41 +0000 Subject: [PATCH 07/14] Reuse a derived exception's Python object as another exception's cause A __namespace__ exception subclass releases its Python object from .NET, so a second wrapper made for it as an inner exception was never freed Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 9 ++++++++- tests/test_exceptions.py | 14 ++++++++------ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index c3ac889ed..0c1898a59 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -102,7 +102,14 @@ 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 Python subclass's exception is its own Python object, whose release .NET handles + using var cause = e.InnerException is IPythonDerivedType derived + ? ClassDerivedObject.ToPython(derived) + : CLRObject.GetReference(e.InnerException); + if (cause.IsNull()) + { + return false; + } Runtime.PyException_SetCause(ob, cause.Steal()); } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 709ac0feb..b96745080 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -480,6 +480,7 @@ def _run_namespaced_exception_script(script): _NAMESPACED_EXCEPTION_SCRIPT = """ +from System import Exception as ClrException from System.Collections.Generic import List class WithoutInit(ExtendedException): @@ -505,7 +506,8 @@ def check(cls): raise error except ExtendedException as caught: raised = caught is error - print(cls.__name__, error.extra, held[0] is error, raised, str(error), error.args) + outer = ClrException("outer", error) + print(cls.__name__, error.extra, held[0] is error, raised, str(error), error.args, outer.__cause__ is error) check(WithoutInit) check(InitWithoutSuper) @@ -521,15 +523,15 @@ def check(cls): @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") def test_namespaced_exception_subclass_construction(): """A Python subclass of a .NET exception declaring __namespace__ runs its base - constructor, keeps its Python object for .NET and its overrides, and still - reads as an exception""" + constructor, keeps its Python object for .NET and its overrides, still reads + as an exception, and is itself the __cause__ of an exception it is the inner one of""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_SCRIPT) overflow = "Arithmetic operation resulted in an overflow." assert output[-4:] == [ - f"WithoutInit extra True True {overflow} ('{overflow}',)", - f"InitWithoutSuper extra True True overridden ('{overflow}',)", - "InitWithSuper extra True True message ('message',)", + f"WithoutInit extra True True {overflow} ('{overflow}',) True", + f"InitWithoutSuper extra True True overridden ('{overflow}',) True", + "InitWithSuper extra True True message ('message',) True", "collected", ] From 6815e635654c5db73897bd18a6b9de200be5bf0d Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:03:51 +0000 Subject: [PATCH 08/14] Give a derived object back to Python a new wrapper after .NET GC collected its old one Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ClassDerived.cs | 3 +- src/runtime/Types/ClrObject.cs | 3 ++ tests/test_exceptions.py | 53 +++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index daeacfcd7..eb6e6b9ae 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -124,7 +124,8 @@ internal static NewReference ToPython(IPythonDerivedType obj) { Runtime._Py_NewReference(self); GCHandle weak = GetGCHandle(self); - var clrObject = GetManagedObject(self); + // the weak handle's wrapper is gone after a .NET GC, while the object itself still lives + var clrObject = GetManagedObject(self) ?? CLRObject.Wrap(obj); GCHandle gc = GCHandle.Alloc(clrObject, GCHandleType.Normal); SetGCHandle(self, gc); weak.Free(); diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs index 98ceba8f4..8887c75f4 100644 --- a/src/runtime/Types/ClrObject.cs +++ b/src/runtime/Types/ClrObject.cs @@ -40,6 +40,9 @@ static NewReference Create(object ob, BorrowedReference tp) this.inst = inst; } + // A wrapper for an object whose Python object already exists + internal static CLRObject Wrap(object inst) => new CLRObject(inst); + internal static NewReference GetReference(object ob, BorrowedReference pyType) => Create(ob, pyType); diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index b96745080..63fbabc09 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -536,6 +536,59 @@ def test_namespaced_exception_subclass_construction(): ] +_NAMESPACED_ROUND_TRIP_SCRIPT = """ +from System import Exception as ClrException +from System.Collections.Generic import List +from System.Threading.Tasks import Task + +class Plain(Object): + __namespace__ = "Python.Test.RoundTrips" + def __init__(self): + self.tag = "plain" + +class Inner(ExtendedException): + __namespace__ = "Python.Test.RoundTrips" + def __init__(self): + super().__init__("inner") + self.tag = "inner" + +def collect(): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + +held = List[Object]() +held.Add(Plain()) +held.Add(Inner()) +task = Task.FromException(Inner()) +collect() + +plain, inner = held[0], held[1] +print(type(plain).__name__, plain.tag, held[0] is plain) +print(type(inner).__name__, inner.tag, str(inner), held[1] is inner) +cause = task.Exception.__cause__ +print(type(cause).__name__, cause.tag, str(cause), cause.args) +del plain, inner, cause, task +collect() +print("collected") +""" + + +@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") +def test_namespaced_subclass_round_trip_after_gc(): + """A __namespace__ subclass that Python dropped, and .NET garbage collected around + while still holding it, comes back to Python as its own working Python object, + from a .NET collection and as an exception's __cause__""" + output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) + + assert output[-4:] == [ + "Plain plain True", + "Inner inner inner True", + "Inner inner inner ('inner',)", + "collected", + ] + + _NAMESPACED_EXCEPTION_RELEASE_SCRIPT = """ class Probe(Object): __namespace__ = "Python.Test.ReleasedExceptions" From 314a259286fc313482c89fa8f4c666fc5effd473 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:48:32 +0000 Subject: [PATCH 09/14] Keep a derived object's wrapper, args and release right across .NET calls and raw conversions .NET calls into Python overrides get self as Python would, with a managed wrapper even after .NET GC collected the old one. An exception whose args Python's GC cleared in a cycle gets them back when it returns to Python. A wrapper that isn't the object's own Python object, such as a raw conversion's, is freed as usual. Exception construction reads Message once. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 6 ++- src/runtime/Types/ClassDerived.cs | 41 ++++++++++++++-- tests/test_exceptions.py | 79 +++++++++++++++++++++++++++---- 3 files changed, 112 insertions(+), 14 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 0c1898a59..615441cf6 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -80,10 +80,12 @@ internal static void Shutdown() internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) { NewReference args; - if (!string.IsNullOrEmpty(e.Message)) + // read once: a Python override of Message may return something else, or raise, on another call + string message = 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 diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index eb6e6b9ae..9e08b58b5 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -76,6 +76,16 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); + // a wrapper that isn't the object's own Python object, such as a raw conversion's, is freed as usual. + // Once finalized, the object no longer names its own, which its finalizer queued to release. + if (self?.inst is IPythonDerivedType derived + && GetPyObj(derived).Ref is var own && own != null && own != ob.Borrow()) + { + ClassBase.tp_clear(ob.Borrow()); + DecrefTypeAndFree(ob.Steal()); + return; + } + // self may be null after Shutdown begun if (self is not null) { @@ -113,6 +123,14 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } + return ToPython(obj, self); + } + + /// + /// Gives Python , the Python object of . + /// + internal static NewReference ToPython(IPythonDerivedType obj, BorrowedReference self) + { var result = new NewReference(self); // when the C# constructor creates the python object it starts as a weak @@ -132,6 +150,17 @@ internal static NewReference ToPython(IPythonDerivedType obj) // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); + + // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it + if (obj is Exception) + { + using var args = Runtime.PyObject_GetAttrString(self, "args"); + if (args.IsNull() || args.Borrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) + { + result.Dispose(); + return default; + } + } } return result; @@ -721,7 +750,8 @@ public class PythonDerivedType PyGILState gs = Runtime.PyGILState_Ensure(); try { - using var pyself = new PyObject(self.CheckRun()); + // as Python would get it, with a managed wrapper even after .NET collected the old one + using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); using PyObject method = pyself.GetAttr(methodName, Runtime.None); if (method.Reference != Runtime.PyNone) { @@ -776,7 +806,8 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s PyGILState gs = Runtime.PyGILState_Ensure(); try { - using var pyself = new PyObject(self.CheckRun()); + // as Python would get it, with a managed wrapper even after .NET collected the old one + using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); using PyObject method = pyself.GetAttr(methodName, Runtime.None); if (method.Reference != Runtime.None) { @@ -869,7 +900,8 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s PyGILState gs = Runtime.PyGILState_Ensure(); try { - using var pyself = new PyObject(self.CheckRun()); + // as Python would get it, with a managed wrapper even after .NET collected the old one + using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); using (PyObject pyvalue = pyself.GetAttr(propertyName)) { return pyvalue.As(); @@ -893,7 +925,8 @@ public static void InvokeSetProperty(IPythonDerivedType obj, string propertyN PyGILState gs = Runtime.PyGILState_Ensure(); try { - using var pyself = new PyObject(self.CheckRun()); + // as Python would get it, with a managed wrapper even after .NET collected the old one + using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); using var pyvalue = Converter.ToPythonImplicit(value).MoveToPyObject(); pyself.SetAttr(propertyName, pyvalue); } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 63fbabc09..326b97b86 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -539,6 +539,7 @@ def test_namespaced_exception_subclass_construction(): _NAMESPACED_ROUND_TRIP_SCRIPT = """ from System import Exception as ClrException from System.Collections.Generic import List +from System import String from System.Threading.Tasks import Task class Plain(Object): @@ -552,6 +553,18 @@ def __init__(self): super().__init__("inner") self.tag = "inner" +class ManagedPlain(Object): + __namespace__ = "Python.Test.RoundTrips" + def ToString(self): + return self.GetType().Name + +class ManagedMessage(ExtendedException): + __namespace__ = "Python.Test.RoundTrips" + def __init__(self): + super().__init__("unused") + def get_Message(self): + return self.GetType().Name + def collect(): gc.collect() GC.Collect() @@ -561,14 +574,25 @@ def collect(): held.Add(Plain()) held.Add(Inner()) task = Task.FromException(Inner()) +managed = List[Object]() +managed.Add(ManagedPlain()) +managed_task = Task.FromException(ManagedMessage()) +cyclic = Inner() +cyclic.link = cyclic +cyclic_task = Task.FromException(cyclic) +del cyclic collect() +# .NET calls the Python overrides, which read managed members, before Python gets the objects back +print(String.Join(",", managed.ToArray()), managed_task.Exception.__cause__.Message) +print(cyclic_task.Exception.__cause__.args) + plain, inner = held[0], held[1] print(type(plain).__name__, plain.tag, held[0] is plain) print(type(inner).__name__, inner.tag, str(inner), held[1] is inner) cause = task.Exception.__cause__ print(type(cause).__name__, cause.tag, str(cause), cause.args) -del plain, inner, cause, task +del plain, inner, cause, task, managed_task, cyclic_task collect() print("collected") """ @@ -578,10 +602,13 @@ def collect(): def test_namespaced_subclass_round_trip_after_gc(): """A __namespace__ subclass that Python dropped, and .NET garbage collected around while still holding it, comes back to Python as its own working Python object, - from a .NET collection and as an exception's __cause__""" + from a .NET collection and as an exception's __cause__, with its args also after Python's + GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members""" output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) - assert output[-4:] == [ + assert output[-6:] == [ + "ManagedPlain ManagedMessage", + "('inner',)", "Plain plain True", "Inner inner inner True", "Inner inner inner ('inner',)", @@ -638,6 +665,25 @@ def release(): release() print(sum(1 for o in gc.get_objects() if type(o) is CycleError)) +from System.Runtime.Serialization import ISerializable + +class RawError(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + pass + +raw = RawError() +def convert_raw(): + for _ in range(2000): + ISerializable(raw).__raw_implementation__ + release() + return sys.getallocatedblocks() + +convert_raw() +before = convert_raw() +# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one +print(convert_raw() - before < 1000) + from Python.Test import AbstractFinalizerCallbackTest, VirtualFinalizerCallbackTest class AbstractCallback(AbstractFinalizerCallbackTest): @@ -675,14 +721,15 @@ def Callback(self): @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") def test_namespaced_exception_subclass_release(): """A __namespace__ exception subclass of another one is released once, exceptions - referencing themselves through args, __cause__ or __context__ are collected, and - the finalizer of a .NET base class still reaches the Python overrides of its + referencing themselves through args, __cause__ or __context__ are collected, as are + the Python objects of raw conversions, and the finalizer of a .NET base class still reaches the Python overrides of its __namespace__ subclasses, before their Python object is released""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) - assert output[-6:] == [ + assert output[-7:] == [ "released", "0", + "True", "AbstractCallback 42", "AbstractCallbackChild 43", "VirtualCallback 42", @@ -747,6 +794,20 @@ def get_Message(self): two_level = TwoLevelInheritedToStringError() two_level.failing = True check("two-level inherited str", lambda: str(two_level)) + +class ReadOnceError(ExtendedException): + __namespace__ = "Python.Test.OverridingExceptions" + def __init__(self): + self.reads = 0 + super().__init__() + def get_Message(self): + self.reads += 1 + if self.reads > 1: + raise ValueError("read again") + return "once" + +read_once = ReadOnceError() +print(read_once.args) """ @@ -755,14 +816,16 @@ def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python ToString or Message override to their caller as it is, with its cause, also when an - inherited ToString calls the Message override, through one or two generated levels""" + inherited ToString calls the Message override, through one or two generated levels. + The constructor reads the Message override once""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-6:] == [ + assert output[-7:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", "init outer KeyError 'inner'", "inherited str outer KeyError 'inner'", "two-level inherited str outer KeyError 'inner'", + "('once',)", ] From 47cac361abafc06c096218ea9fb498887f8bef03 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:43:39 +0000 Subject: [PATCH 10/14] Restore a derived exception's args only when converting it, and raise its wrapper's errors to Python Co-Authored-By: Claude Opus 5.5 --- src/embed_tests/TestPythonException.cs | 20 ++++++ src/runtime/PythonException.cs | 5 +- src/runtime/Types/ClassDerived.cs | 39 +++++++---- src/runtime/Types/ClassObject.cs | 4 ++ src/runtime/Types/ClrObject.cs | 8 ++- tests/test_exceptions.py | 90 +++++++++++++++++++++++--- 6 files changed, 140 insertions(+), 26 deletions(-) diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 9a3343460..9443792b2 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -222,6 +222,26 @@ public void TestPythonException_Normalize_ThrowsWhenErrorSet() Exceptions.Clear(); } + [Test] + public void TestThrowLastAsClrExceptionKeepsNoReference() + { + using var _ = Py.GIL(); + using var scope = Py.CreateScope(); + scope.Exec("instance = ValueError('x')\nimport sys"); + using var instance = scope.Get("instance"); + using var sys = scope.Get("sys"); + long before = sys.InvokeMethod("getrefcount", instance).As(); + for (int i = 0; i < 10; i++) + { + Runtime.Runtime.PyErr_SetObject(Exceptions.ValueError.Reference, instance.Reference); + var error = Assert.Throws(() => throw PythonException.ThrowLastAsClrException()); + error.Value?.Dispose(); + error.Type.Dispose(); + error.Traceback?.Dispose(); + } + Assert.AreEqual(before, sys.InvokeMethod("getrefcount", instance).As()); + } + [Test] public void TestGetsPythonCodeInfoInStackTrace() { diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 9f26e3a8d..09627c63a 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -109,10 +109,10 @@ internal static PythonException FetchCurrentRaw() throw; } + // an error set without a value, as PyErr_SetNone does, only gets one once normalized + var normalizedValue = new NewReference(value.BorrowNullable(), canBeNull: true); 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); @@ -121,6 +121,7 @@ internal static PythonException FetchCurrentRaw() { type.Dispose(); value.Dispose(); + normalizedValue.Dispose(); traceback.Dispose(); } } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 9e08b58b5..bfc9d5d4a 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -53,6 +53,10 @@ internal ClassDerivedObject(Type tp) : base(tp) protected override NewReference NewObjectToPython(object obj, BorrowedReference tp) { var self = base.NewObjectToPython(obj, tp); + if (self.IsNull()) + { + return default; + } SetPyObj((IPythonDerivedType)obj, self.Borrow()); @@ -109,7 +113,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo /// Called from Converter.ToPython for types that are python subclasses of managed types. /// The referenced python object is returned instead of a new wrapper. /// - internal static NewReference ToPython(IPythonDerivedType obj) + internal static unsafe NewReference ToPython(IPythonDerivedType obj) { // derived types have a __pyobj__ field that gets set to the python // object in the overridden constructor @@ -123,7 +127,25 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } - return ToPython(obj, self); + var result = ToPython(obj, self); + if (obj is not Exception || result.IsNull()) + { + return result; + } + + // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it: + // converting it sets them again, as converting a .NET exception does. BaseException's own + // descriptor reads them as None then, without running a Python override of args + using var descriptor = Runtime.PyObject_GetAttrString(Exceptions.BaseException.Reference, "args"); + var getArgs = (delegate* unmanaged[Cdecl]) + Util.ReadIntPtr(Runtime.PyObject_TYPE(descriptor.BorrowOrThrow()), TypeOffset.tp_descr_get); + using var args = getArgs(descriptor.Borrow(), self, Runtime.PyObject_TYPE(self)); + if (args.BorrowOrThrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) + { + result.Dispose(); + return default; + } + return result; } /// @@ -150,17 +172,6 @@ internal static NewReference ToPython(IPythonDerivedType obj, BorrowedReference // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); - - // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it - if (obj is Exception) - { - using var args = Runtime.PyObject_GetAttrString(self, "args"); - if (args.IsNull() || args.Borrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) - { - result.Dispose(); - return default; - } - } } return result; @@ -947,7 +958,7 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec // This doesn't actually destroy the object, it just sets the reference to this object // to be a weak reference and it will be destroyed when the C# object is destroyed. using var self = CLRObject.GetReference(obj, obj.GetType()); - SetPyObj(obj, self.Borrow()); + SetPyObj(obj, self.BorrowOrThrow()); } // call the base constructor diff --git a/src/runtime/Types/ClassObject.cs b/src/runtime/Types/ClassObject.cs index 2aa8ad7aa..dfb51831b 100644 --- a/src/runtime/Types/ClassObject.cs +++ b/src/runtime/Types/ClassObject.cs @@ -112,6 +112,10 @@ static NewReference tp_new_impl(BorrowedReference tp, BorrowedReference args, Bo object obj = FormatterServices.GetUninitializedObject(type); var pythonObj = self.NewObjectToPython(obj, tp); + if (pythonObj.IsNull()) + { + return default; + } // Constructing the reflected type itself always continues with __init__ (MetaType.tp_call), // which binds and runs the matching constructor: running one here too would run a constructor diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs index 8887c75f4..8565e4e3d 100644 --- a/src/runtime/Types/ClrObject.cs +++ b/src/runtime/Types/ClrObject.cs @@ -29,8 +29,12 @@ static NewReference Create(object ob, BorrowedReference tp) // Fix the BaseException args (and __cause__ in case of Python 3) - // slot if wrapping a CLR exception - if (ob is Exception e) Exceptions.SetArgsAndCause(py.Borrow(), e); + // slot if wrapping a CLR exception, raising to Python what its members throw + if (ob is Exception && !ExceptionClassObject.SetArgsAndCause(py.Borrow())) + { + py.Dispose(); + return default; + } return py; } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 326b97b86..5536e4228 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -581,8 +581,31 @@ def collect(): cyclic.link = cyclic cyclic_task = Task.FromException(cyclic) del cyclic + +from System.Runtime.Serialization import ISerializable + +class Hashed(ExtendedException): + __namespace__ = "Python.Test.RoundTrips" + armed = False + def __init__(self): + pass + def GetHashCode(self): + return 7 + def get_Message(self): + if Hashed.armed: + raise ValueError("armed") + return "hashed" + +hashed = Hashed() +hashed_raw = ISerializable(hashed).__raw_implementation__ +hashed.link = hashed +del hashed collect() +# a .NET call into an override doesn't read its other members, which may raise +Hashed.armed = True +print(hash(hashed_raw)) + # .NET calls the Python overrides, which read managed members, before Python gets the objects back print(String.Join(",", managed.ToArray()), managed_task.Exception.__cause__.Message) print(cyclic_task.Exception.__cause__.args) @@ -603,10 +626,12 @@ def test_namespaced_subclass_round_trip_after_gc(): """A __namespace__ subclass that Python dropped, and .NET garbage collected around while still holding it, comes back to Python as its own working Python object, from a .NET collection and as an exception's __cause__, with its args also after Python's - GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members""" + GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members, + and don't read its other members""" output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) - assert output[-6:] == [ + assert output[-7:] == [ + "7", "ManagedPlain ManagedMessage", "('inner',)", "Plain plain True", @@ -672,16 +697,33 @@ class RawError(ExtendedException): def __init__(self): pass +class FailingRawError(ExtendedException): + __namespace__ = "Python.Test.ReleasedExceptions" + def __init__(self): + self.armed = False + def get_Message(self): + if self.armed: + raise ValueError("armed") + return "message" + raw = RawError() +failing_raw = FailingRawError() +failing_interface = ISerializable(failing_raw) +failing_raw.armed = True def convert_raw(): - for _ in range(2000): + for _ in range(1000): ISerializable(raw).__raw_implementation__ + try: + failing_interface.__raw_implementation__ + except ValueError: + pass release() return sys.getallocatedblocks() convert_raw() before = convert_raw() -# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one +# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one, +# nor is one whose Message override raised print(convert_raw() - before < 1000) from Python.Test import AbstractFinalizerCallbackTest, VirtualFinalizerCallbackTest @@ -722,7 +764,7 @@ def Callback(self): def test_namespaced_exception_subclass_release(): """A __namespace__ exception subclass of another one is released once, exceptions referencing themselves through args, __cause__ or __context__ are collected, as are - the Python objects of raw conversions, and the finalizer of a .NET base class still reaches the Python overrides of its + the Python objects of raw conversions, also of failed ones, and the finalizer of a .NET base class still reaches the Python overrides of its __namespace__ subclasses, before their Python object is released""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) @@ -808,6 +850,34 @@ def get_Message(self): read_once = ReadOnceError() print(read_once.args) + +class ArgsLookupError(ExtendedException): + __namespace__ = "Python.Test.OverridingExceptions" + def __getattribute__(self, name): + if name == "args": + raise LookupError("args") + return object.__getattribute__(self, name) + def __init__(self): + super().__init__("constructed") + +print(str(ArgsLookupError())) + +from System.Runtime.Serialization import ISerializable + +class RawFailingError(ExtendedException): + __namespace__ = "Python.Test.OverridingExceptions" + def __init__(self): + self.failing = False + def get_Message(self): + if self.failing: + raise ValueError("outer") from KeyError("inner") + return "message" + +raw_failing = RawFailingError() +interface = ISerializable(raw_failing) +raw_failing.failing = True +check("raw", lambda: interface.__raw_implementation__) +check("cast", lambda: ISerializable(raw_failing)) """ @@ -816,11 +886,12 @@ def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python ToString or Message override to their caller as it is, with its cause, also when an - inherited ToString calls the Message override, through one or two generated levels. - The constructor reads the Message override once""" + inherited ToString calls the Message override, through one or two generated levels, + and when a raw conversion or an interface cast reads it. + The constructor reads the Message override once, and no Python override of args""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-7:] == [ + assert output[-10:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", @@ -828,4 +899,7 @@ def test_namespaced_exception_subclass_override_errors(): "inherited str outer KeyError 'inner'", "two-level inherited str outer KeyError 'inner'", "('once',)", + "constructed", + "raw outer KeyError 'inner'", + "cast outer KeyError 'inner'", ] From 7353259444ef66d4ededd71acc36979001bc5df3 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:13:06 +0000 Subject: [PATCH 11/14] Revert "Restore a derived exception's args only when converting it, and raise its wrapper's errors to Python" This reverts commit 47cac361abafc06c096218ea9fb498887f8bef03. Co-Authored-By: Claude Opus 5.5 --- src/embed_tests/TestPythonException.cs | 20 ------ src/runtime/PythonException.cs | 5 +- src/runtime/Types/ClassDerived.cs | 39 ++++------- src/runtime/Types/ClassObject.cs | 4 -- src/runtime/Types/ClrObject.cs | 8 +-- tests/test_exceptions.py | 90 +++----------------------- 6 files changed, 26 insertions(+), 140 deletions(-) diff --git a/src/embed_tests/TestPythonException.cs b/src/embed_tests/TestPythonException.cs index 9443792b2..9a3343460 100644 --- a/src/embed_tests/TestPythonException.cs +++ b/src/embed_tests/TestPythonException.cs @@ -222,26 +222,6 @@ public void TestPythonException_Normalize_ThrowsWhenErrorSet() Exceptions.Clear(); } - [Test] - public void TestThrowLastAsClrExceptionKeepsNoReference() - { - using var _ = Py.GIL(); - using var scope = Py.CreateScope(); - scope.Exec("instance = ValueError('x')\nimport sys"); - using var instance = scope.Get("instance"); - using var sys = scope.Get("sys"); - long before = sys.InvokeMethod("getrefcount", instance).As(); - for (int i = 0; i < 10; i++) - { - Runtime.Runtime.PyErr_SetObject(Exceptions.ValueError.Reference, instance.Reference); - var error = Assert.Throws(() => throw PythonException.ThrowLastAsClrException()); - error.Value?.Dispose(); - error.Type.Dispose(); - error.Traceback?.Dispose(); - } - Assert.AreEqual(before, sys.InvokeMethod("getrefcount", instance).As()); - } - [Test] public void TestGetsPythonCodeInfoInStackTrace() { diff --git a/src/runtime/PythonException.cs b/src/runtime/PythonException.cs index 09627c63a..9f26e3a8d 100644 --- a/src/runtime/PythonException.cs +++ b/src/runtime/PythonException.cs @@ -109,10 +109,10 @@ internal static PythonException FetchCurrentRaw() throw; } - // an error set without a value, as PyErr_SetNone does, only gets one once normalized - var normalizedValue = new NewReference(value.BorrowNullable(), canBeNull: true); 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); @@ -121,7 +121,6 @@ internal static PythonException FetchCurrentRaw() { type.Dispose(); value.Dispose(); - normalizedValue.Dispose(); traceback.Dispose(); } } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index bfc9d5d4a..9e08b58b5 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -53,10 +53,6 @@ internal ClassDerivedObject(Type tp) : base(tp) protected override NewReference NewObjectToPython(object obj, BorrowedReference tp) { var self = base.NewObjectToPython(obj, tp); - if (self.IsNull()) - { - return default; - } SetPyObj((IPythonDerivedType)obj, self.Borrow()); @@ -113,7 +109,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo /// Called from Converter.ToPython for types that are python subclasses of managed types. /// The referenced python object is returned instead of a new wrapper. /// - internal static unsafe NewReference ToPython(IPythonDerivedType obj) + internal static NewReference ToPython(IPythonDerivedType obj) { // derived types have a __pyobj__ field that gets set to the python // object in the overridden constructor @@ -127,25 +123,7 @@ internal static unsafe NewReference ToPython(IPythonDerivedType obj) return default; } - var result = ToPython(obj, self); - if (obj is not Exception || result.IsNull()) - { - return result; - } - - // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it: - // converting it sets them again, as converting a .NET exception does. BaseException's own - // descriptor reads them as None then, without running a Python override of args - using var descriptor = Runtime.PyObject_GetAttrString(Exceptions.BaseException.Reference, "args"); - var getArgs = (delegate* unmanaged[Cdecl]) - Util.ReadIntPtr(Runtime.PyObject_TYPE(descriptor.BorrowOrThrow()), TypeOffset.tp_descr_get); - using var args = getArgs(descriptor.Borrow(), self, Runtime.PyObject_TYPE(self)); - if (args.BorrowOrThrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) - { - result.Dispose(); - return default; - } - return result; + return ToPython(obj, self); } /// @@ -172,6 +150,17 @@ internal static NewReference ToPython(IPythonDerivedType obj, BorrowedReference // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); + + // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it + if (obj is Exception) + { + using var args = Runtime.PyObject_GetAttrString(self, "args"); + if (args.IsNull() || args.Borrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) + { + result.Dispose(); + return default; + } + } } return result; @@ -958,7 +947,7 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec // This doesn't actually destroy the object, it just sets the reference to this object // to be a weak reference and it will be destroyed when the C# object is destroyed. using var self = CLRObject.GetReference(obj, obj.GetType()); - SetPyObj(obj, self.BorrowOrThrow()); + SetPyObj(obj, self.Borrow()); } // call the base constructor diff --git a/src/runtime/Types/ClassObject.cs b/src/runtime/Types/ClassObject.cs index dfb51831b..2aa8ad7aa 100644 --- a/src/runtime/Types/ClassObject.cs +++ b/src/runtime/Types/ClassObject.cs @@ -112,10 +112,6 @@ static NewReference tp_new_impl(BorrowedReference tp, BorrowedReference args, Bo object obj = FormatterServices.GetUninitializedObject(type); var pythonObj = self.NewObjectToPython(obj, tp); - if (pythonObj.IsNull()) - { - return default; - } // Constructing the reflected type itself always continues with __init__ (MetaType.tp_call), // which binds and runs the matching constructor: running one here too would run a constructor diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs index 8565e4e3d..8887c75f4 100644 --- a/src/runtime/Types/ClrObject.cs +++ b/src/runtime/Types/ClrObject.cs @@ -29,12 +29,8 @@ static NewReference Create(object ob, BorrowedReference tp) // Fix the BaseException args (and __cause__ in case of Python 3) - // slot if wrapping a CLR exception, raising to Python what its members throw - if (ob is Exception && !ExceptionClassObject.SetArgsAndCause(py.Borrow())) - { - py.Dispose(); - return default; - } + // slot if wrapping a CLR exception + if (ob is Exception e) Exceptions.SetArgsAndCause(py.Borrow(), e); return py; } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 5536e4228..326b97b86 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -581,31 +581,8 @@ def collect(): cyclic.link = cyclic cyclic_task = Task.FromException(cyclic) del cyclic - -from System.Runtime.Serialization import ISerializable - -class Hashed(ExtendedException): - __namespace__ = "Python.Test.RoundTrips" - armed = False - def __init__(self): - pass - def GetHashCode(self): - return 7 - def get_Message(self): - if Hashed.armed: - raise ValueError("armed") - return "hashed" - -hashed = Hashed() -hashed_raw = ISerializable(hashed).__raw_implementation__ -hashed.link = hashed -del hashed collect() -# a .NET call into an override doesn't read its other members, which may raise -Hashed.armed = True -print(hash(hashed_raw)) - # .NET calls the Python overrides, which read managed members, before Python gets the objects back print(String.Join(",", managed.ToArray()), managed_task.Exception.__cause__.Message) print(cyclic_task.Exception.__cause__.args) @@ -626,12 +603,10 @@ def test_namespaced_subclass_round_trip_after_gc(): """A __namespace__ subclass that Python dropped, and .NET garbage collected around while still holding it, comes back to Python as its own working Python object, from a .NET collection and as an exception's __cause__, with its args also after Python's - GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members, - and don't read its other members""" + GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members""" output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) - assert output[-7:] == [ - "7", + assert output[-6:] == [ "ManagedPlain ManagedMessage", "('inner',)", "Plain plain True", @@ -697,33 +672,16 @@ class RawError(ExtendedException): def __init__(self): pass -class FailingRawError(ExtendedException): - __namespace__ = "Python.Test.ReleasedExceptions" - def __init__(self): - self.armed = False - def get_Message(self): - if self.armed: - raise ValueError("armed") - return "message" - raw = RawError() -failing_raw = FailingRawError() -failing_interface = ISerializable(failing_raw) -failing_raw.armed = True def convert_raw(): - for _ in range(1000): + for _ in range(2000): ISerializable(raw).__raw_implementation__ - try: - failing_interface.__raw_implementation__ - except ValueError: - pass release() return sys.getallocatedblocks() convert_raw() before = convert_raw() -# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one, -# nor is one whose Message override raised +# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one print(convert_raw() - before < 1000) from Python.Test import AbstractFinalizerCallbackTest, VirtualFinalizerCallbackTest @@ -764,7 +722,7 @@ def Callback(self): def test_namespaced_exception_subclass_release(): """A __namespace__ exception subclass of another one is released once, exceptions referencing themselves through args, __cause__ or __context__ are collected, as are - the Python objects of raw conversions, also of failed ones, and the finalizer of a .NET base class still reaches the Python overrides of its + the Python objects of raw conversions, and the finalizer of a .NET base class still reaches the Python overrides of its __namespace__ subclasses, before their Python object is released""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) @@ -850,34 +808,6 @@ def get_Message(self): read_once = ReadOnceError() print(read_once.args) - -class ArgsLookupError(ExtendedException): - __namespace__ = "Python.Test.OverridingExceptions" - def __getattribute__(self, name): - if name == "args": - raise LookupError("args") - return object.__getattribute__(self, name) - def __init__(self): - super().__init__("constructed") - -print(str(ArgsLookupError())) - -from System.Runtime.Serialization import ISerializable - -class RawFailingError(ExtendedException): - __namespace__ = "Python.Test.OverridingExceptions" - def __init__(self): - self.failing = False - def get_Message(self): - if self.failing: - raise ValueError("outer") from KeyError("inner") - return "message" - -raw_failing = RawFailingError() -interface = ISerializable(raw_failing) -raw_failing.failing = True -check("raw", lambda: interface.__raw_implementation__) -check("cast", lambda: ISerializable(raw_failing)) """ @@ -886,12 +816,11 @@ def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python ToString or Message override to their caller as it is, with its cause, also when an - inherited ToString calls the Message override, through one or two generated levels, - and when a raw conversion or an interface cast reads it. - The constructor reads the Message override once, and no Python override of args""" + inherited ToString calls the Message override, through one or two generated levels. + The constructor reads the Message override once""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-10:] == [ + assert output[-7:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", @@ -899,7 +828,4 @@ def test_namespaced_exception_subclass_override_errors(): "inherited str outer KeyError 'inner'", "two-level inherited str outer KeyError 'inner'", "('once',)", - "constructed", - "raw outer KeyError 'inner'", - "cast outer KeyError 'inner'", ] From a7e8c6fd21c368934d98bc3727ae5f1720bbc6e0 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:13:06 +0000 Subject: [PATCH 12/14] Revert "Keep a derived object's wrapper, args and release right across .NET calls and raw conversions" This reverts commit 314a259286fc313482c89fa8f4c666fc5effd473. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 6 +-- src/runtime/Types/ClassDerived.cs | 41 ++-------------- tests/test_exceptions.py | 79 ++++--------------------------- 3 files changed, 14 insertions(+), 112 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 615441cf6..0c1898a59 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -80,12 +80,10 @@ internal static void Shutdown() internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) { NewReference args; - // read once: a Python override of Message may return something else, or raise, on another call - string message = e.Message; - if (!string.IsNullOrEmpty(message)) + if (!string.IsNullOrEmpty(e.Message)) { args = Runtime.PyTuple_New(1); - using var msg = Runtime.PyString_FromString(message); + using var msg = Runtime.PyString_FromString(e.Message); Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow()); } else diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 9e08b58b5..eb6e6b9ae 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -76,16 +76,6 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); - // a wrapper that isn't the object's own Python object, such as a raw conversion's, is freed as usual. - // Once finalized, the object no longer names its own, which its finalizer queued to release. - if (self?.inst is IPythonDerivedType derived - && GetPyObj(derived).Ref is var own && own != null && own != ob.Borrow()) - { - ClassBase.tp_clear(ob.Borrow()); - DecrefTypeAndFree(ob.Steal()); - return; - } - // self may be null after Shutdown begun if (self is not null) { @@ -123,14 +113,6 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } - return ToPython(obj, self); - } - - /// - /// Gives Python , the Python object of . - /// - internal static NewReference ToPython(IPythonDerivedType obj, BorrowedReference self) - { var result = new NewReference(self); // when the C# constructor creates the python object it starts as a weak @@ -150,17 +132,6 @@ internal static NewReference ToPython(IPythonDerivedType obj, BorrowedReference // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); - - // Python's GC clears the args of an exception in a cycle, as it doesn't see .NET holding it - if (obj is Exception) - { - using var args = Runtime.PyObject_GetAttrString(self, "args"); - if (args.IsNull() || args.Borrow() == Runtime.PyNone && !ExceptionClassObject.SetArgsAndCause(self)) - { - result.Dispose(); - return default; - } - } } return result; @@ -750,8 +721,7 @@ public class PythonDerivedType PyGILState gs = Runtime.PyGILState_Ensure(); try { - // as Python would get it, with a managed wrapper even after .NET collected the old one - using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); + using var pyself = new PyObject(self.CheckRun()); using PyObject method = pyself.GetAttr(methodName, Runtime.None); if (method.Reference != Runtime.PyNone) { @@ -806,8 +776,7 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s PyGILState gs = Runtime.PyGILState_Ensure(); try { - // as Python would get it, with a managed wrapper even after .NET collected the old one - using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); + using var pyself = new PyObject(self.CheckRun()); using PyObject method = pyself.GetAttr(methodName, Runtime.None); if (method.Reference != Runtime.None) { @@ -900,8 +869,7 @@ public static void InvokeMethodVoid(IPythonDerivedType obj, string methodName, s PyGILState gs = Runtime.PyGILState_Ensure(); try { - // as Python would get it, with a managed wrapper even after .NET collected the old one - using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); + using var pyself = new PyObject(self.CheckRun()); using (PyObject pyvalue = pyself.GetAttr(propertyName)) { return pyvalue.As(); @@ -925,8 +893,7 @@ public static void InvokeSetProperty(IPythonDerivedType obj, string propertyN PyGILState gs = Runtime.PyGILState_Ensure(); try { - // as Python would get it, with a managed wrapper even after .NET collected the old one - using var pyself = new PyObject(ClassDerivedObject.ToPython(obj, self.CheckRun()).StealOrThrow()); + using var pyself = new PyObject(self.CheckRun()); using var pyvalue = Converter.ToPythonImplicit(value).MoveToPyObject(); pyself.SetAttr(propertyName, pyvalue); } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 326b97b86..63fbabc09 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -539,7 +539,6 @@ def test_namespaced_exception_subclass_construction(): _NAMESPACED_ROUND_TRIP_SCRIPT = """ from System import Exception as ClrException from System.Collections.Generic import List -from System import String from System.Threading.Tasks import Task class Plain(Object): @@ -553,18 +552,6 @@ def __init__(self): super().__init__("inner") self.tag = "inner" -class ManagedPlain(Object): - __namespace__ = "Python.Test.RoundTrips" - def ToString(self): - return self.GetType().Name - -class ManagedMessage(ExtendedException): - __namespace__ = "Python.Test.RoundTrips" - def __init__(self): - super().__init__("unused") - def get_Message(self): - return self.GetType().Name - def collect(): gc.collect() GC.Collect() @@ -574,25 +561,14 @@ def collect(): held.Add(Plain()) held.Add(Inner()) task = Task.FromException(Inner()) -managed = List[Object]() -managed.Add(ManagedPlain()) -managed_task = Task.FromException(ManagedMessage()) -cyclic = Inner() -cyclic.link = cyclic -cyclic_task = Task.FromException(cyclic) -del cyclic collect() -# .NET calls the Python overrides, which read managed members, before Python gets the objects back -print(String.Join(",", managed.ToArray()), managed_task.Exception.__cause__.Message) -print(cyclic_task.Exception.__cause__.args) - plain, inner = held[0], held[1] print(type(plain).__name__, plain.tag, held[0] is plain) print(type(inner).__name__, inner.tag, str(inner), held[1] is inner) cause = task.Exception.__cause__ print(type(cause).__name__, cause.tag, str(cause), cause.args) -del plain, inner, cause, task, managed_task, cyclic_task +del plain, inner, cause, task collect() print("collected") """ @@ -602,13 +578,10 @@ def collect(): def test_namespaced_subclass_round_trip_after_gc(): """A __namespace__ subclass that Python dropped, and .NET garbage collected around while still holding it, comes back to Python as its own working Python object, - from a .NET collection and as an exception's __cause__, with its args also after Python's - GC cleared them in a cycle. .NET calls into its Python overrides can use its managed members""" + from a .NET collection and as an exception's __cause__""" output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) - assert output[-6:] == [ - "ManagedPlain ManagedMessage", - "('inner',)", + assert output[-4:] == [ "Plain plain True", "Inner inner inner True", "Inner inner inner ('inner',)", @@ -665,25 +638,6 @@ def release(): release() print(sum(1 for o in gc.get_objects() if type(o) is CycleError)) -from System.Runtime.Serialization import ISerializable - -class RawError(ExtendedException): - __namespace__ = "Python.Test.ReleasedExceptions" - def __init__(self): - pass - -raw = RawError() -def convert_raw(): - for _ in range(2000): - ISerializable(raw).__raw_implementation__ - release() - return sys.getallocatedblocks() - -convert_raw() -before = convert_raw() -# a raw conversion's own Python object isn't kept for .NET, which only knows the registered one -print(convert_raw() - before < 1000) - from Python.Test import AbstractFinalizerCallbackTest, VirtualFinalizerCallbackTest class AbstractCallback(AbstractFinalizerCallbackTest): @@ -721,15 +675,14 @@ def Callback(self): @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") def test_namespaced_exception_subclass_release(): """A __namespace__ exception subclass of another one is released once, exceptions - referencing themselves through args, __cause__ or __context__ are collected, as are - the Python objects of raw conversions, and the finalizer of a .NET base class still reaches the Python overrides of its + referencing themselves through args, __cause__ or __context__ are collected, and + the finalizer of a .NET base class still reaches the Python overrides of its __namespace__ subclasses, before their Python object is released""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_RELEASE_SCRIPT) - assert output[-7:] == [ + assert output[-6:] == [ "released", "0", - "True", "AbstractCallback 42", "AbstractCallbackChild 43", "VirtualCallback 42", @@ -794,20 +747,6 @@ def get_Message(self): two_level = TwoLevelInheritedToStringError() two_level.failing = True check("two-level inherited str", lambda: str(two_level)) - -class ReadOnceError(ExtendedException): - __namespace__ = "Python.Test.OverridingExceptions" - def __init__(self): - self.reads = 0 - super().__init__() - def get_Message(self): - self.reads += 1 - if self.reads > 1: - raise ValueError("read again") - return "once" - -read_once = ReadOnceError() -print(read_once.args) """ @@ -816,16 +755,14 @@ def test_namespaced_exception_subclass_override_errors(): """str(), repr() and the constructor of a __namespace__ exception subclass read None from a Python ToString override as an empty message, and raise the error of a Python ToString or Message override to their caller as it is, with its cause, also when an - inherited ToString calls the Message override, through one or two generated levels. - The constructor reads the Message override once""" + inherited ToString calls the Message override, through one or two generated levels""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_OVERRIDES_SCRIPT) - assert output[-7:] == [ + assert output[-6:] == [ "'' OverridingError('message')", "str outer KeyError 'inner'", "repr outer KeyError 'inner'", "init outer KeyError 'inner'", "inherited str outer KeyError 'inner'", "two-level inherited str outer KeyError 'inner'", - "('once',)", ] From e25aba32d829c63648979bfe8b8c774d486c5ced Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:13:06 +0000 Subject: [PATCH 13/14] Revert "Give a derived object back to Python a new wrapper after .NET GC collected its old one" This reverts commit 6815e635654c5db73897bd18a6b9de200be5bf0d. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ClassDerived.cs | 3 +- src/runtime/Types/ClrObject.cs | 3 -- tests/test_exceptions.py | 53 ------------------------------- 3 files changed, 1 insertion(+), 58 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index eb6e6b9ae..daeacfcd7 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -124,8 +124,7 @@ internal static NewReference ToPython(IPythonDerivedType obj) { Runtime._Py_NewReference(self); GCHandle weak = GetGCHandle(self); - // the weak handle's wrapper is gone after a .NET GC, while the object itself still lives - var clrObject = GetManagedObject(self) ?? CLRObject.Wrap(obj); + var clrObject = GetManagedObject(self); GCHandle gc = GCHandle.Alloc(clrObject, GCHandleType.Normal); SetGCHandle(self, gc); weak.Free(); diff --git a/src/runtime/Types/ClrObject.cs b/src/runtime/Types/ClrObject.cs index 8887c75f4..98ceba8f4 100644 --- a/src/runtime/Types/ClrObject.cs +++ b/src/runtime/Types/ClrObject.cs @@ -40,9 +40,6 @@ static NewReference Create(object ob, BorrowedReference tp) this.inst = inst; } - // A wrapper for an object whose Python object already exists - internal static CLRObject Wrap(object inst) => new CLRObject(inst); - internal static NewReference GetReference(object ob, BorrowedReference pyType) => Create(ob, pyType); diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index 63fbabc09..b96745080 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -536,59 +536,6 @@ def test_namespaced_exception_subclass_construction(): ] -_NAMESPACED_ROUND_TRIP_SCRIPT = """ -from System import Exception as ClrException -from System.Collections.Generic import List -from System.Threading.Tasks import Task - -class Plain(Object): - __namespace__ = "Python.Test.RoundTrips" - def __init__(self): - self.tag = "plain" - -class Inner(ExtendedException): - __namespace__ = "Python.Test.RoundTrips" - def __init__(self): - super().__init__("inner") - self.tag = "inner" - -def collect(): - gc.collect() - GC.Collect() - GC.WaitForPendingFinalizers() - -held = List[Object]() -held.Add(Plain()) -held.Add(Inner()) -task = Task.FromException(Inner()) -collect() - -plain, inner = held[0], held[1] -print(type(plain).__name__, plain.tag, held[0] is plain) -print(type(inner).__name__, inner.tag, str(inner), held[1] is inner) -cause = task.Exception.__cause__ -print(type(cause).__name__, cause.tag, str(cause), cause.args) -del plain, inner, cause, task -collect() -print("collected") -""" - - -@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") -def test_namespaced_subclass_round_trip_after_gc(): - """A __namespace__ subclass that Python dropped, and .NET garbage collected around - while still holding it, comes back to Python as its own working Python object, - from a .NET collection and as an exception's __cause__""" - output = _run_namespaced_exception_script(_NAMESPACED_ROUND_TRIP_SCRIPT) - - assert output[-4:] == [ - "Plain plain True", - "Inner inner inner True", - "Inner inner inner ('inner',)", - "collected", - ] - - _NAMESPACED_EXCEPTION_RELEASE_SCRIPT = """ class Probe(Object): __namespace__ = "Python.Test.ReleasedExceptions" From a6afc1c84b7c0fb66664ad3bdac13a26bba25c3a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:13:06 +0000 Subject: [PATCH 14/14] Revert "Reuse a derived exception's Python object as another exception's cause" This reverts commit a47645898e0363410bfe537abd4bf876d14b1dc8. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Exceptions.cs | 9 +-------- tests/test_exceptions.py | 14 ++++++-------- 2 files changed, 7 insertions(+), 16 deletions(-) diff --git a/src/runtime/Exceptions.cs b/src/runtime/Exceptions.cs index 0c1898a59..c3ac889ed 100644 --- a/src/runtime/Exceptions.cs +++ b/src/runtime/Exceptions.cs @@ -102,14 +102,7 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e) if (e.InnerException != null) { // Note: For an AggregateException, InnerException is only the first of the InnerExceptions. - // A Python subclass's exception is its own Python object, whose release .NET handles - using var cause = e.InnerException is IPythonDerivedType derived - ? ClassDerivedObject.ToPython(derived) - : CLRObject.GetReference(e.InnerException); - if (cause.IsNull()) - { - return false; - } + using var cause = CLRObject.GetReference(e.InnerException); Runtime.PyException_SetCause(ob, cause.Steal()); } diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index b96745080..709ac0feb 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -480,7 +480,6 @@ def _run_namespaced_exception_script(script): _NAMESPACED_EXCEPTION_SCRIPT = """ -from System import Exception as ClrException from System.Collections.Generic import List class WithoutInit(ExtendedException): @@ -506,8 +505,7 @@ def check(cls): raise error except ExtendedException as caught: raised = caught is error - outer = ClrException("outer", error) - print(cls.__name__, error.extra, held[0] is error, raised, str(error), error.args, outer.__cause__ is error) + print(cls.__name__, error.extra, held[0] is error, raised, str(error), error.args) check(WithoutInit) check(InitWithoutSuper) @@ -523,15 +521,15 @@ def check(cls): @pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime") def test_namespaced_exception_subclass_construction(): """A Python subclass of a .NET exception declaring __namespace__ runs its base - constructor, keeps its Python object for .NET and its overrides, still reads - as an exception, and is itself the __cause__ of an exception it is the inner one of""" + constructor, keeps its Python object for .NET and its overrides, and still + reads as an exception""" output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_SCRIPT) overflow = "Arithmetic operation resulted in an overflow." assert output[-4:] == [ - f"WithoutInit extra True True {overflow} ('{overflow}',) True", - f"InitWithoutSuper extra True True overridden ('{overflow}',) True", - "InitWithSuper extra True True message ('message',) True", + f"WithoutInit extra True True {overflow} ('{overflow}',)", + f"InitWithoutSuper extra True True overridden ('{overflow}',)", + "InitWithSuper extra True True message ('message',)", "collected", ]