Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions src/runtime/Exceptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,24 @@ internal static void Shutdown()
/// __getattr__ implementation, and thus dereferencing a NULL
/// pointer.
/// </summary>
internal static bool SetArgsAndCause(BorrowedReference ob, Exception e)
/// <param name="message">the message read by the refresh of an exception created from .NET,
/// which reports a message Python can't hold by returning false</param>
internal static bool SetArgsAndCause(BorrowedReference ob, Exception e, string? message = null)
{
NewReference args;
if (!string.IsNullOrEmpty(e.Message))
if (!string.IsNullOrEmpty(message ?? e.Message))
{
using var msg = Runtime.PyString_FromString(message ?? e.Message);
if (msg.IsNull())
{
if (message != null)
{
return false;
}
throw PythonException.ThrowLastAsClrException();
}
args = Runtime.PyTuple_New(1);
using var msg = Runtime.PyString_FromString(e.Message);
Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow());
Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.Steal());
}
else
{
Expand All @@ -102,7 +112,16 @@ internal static bool SetArgsAndCause(BorrowedReference ob, Exception e)
if (e.InnerException != null)
{
// Note: For an AggregateException, InnerException is only the first of the InnerExceptions.
using var cause = CLRObject.GetReference(e.InnerException);
// a generated inner exception keeps its Python object, when it has one in this runtime
// whose CLR wrapper is still alive: .NET may have collected the weak wrapper meanwhile
var peer = e.InnerException is IPythonDerivedType derived ? PythonDerivedType.GetPyObj(derived) : default;
var wrapper = peer.Ref != null && peer.Run == Runtime.GetRun()
? ManagedType.GetManagedObject(peer.CheckRun())
: null;
using var cause = wrapper != null
? ClassDerivedObject.ToPython((IPythonDerivedType)e.InnerException)
: CLRObject.GetReference(e.InnerException);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Known limit, not blocking: ordinary .NET GC can collect a generated inner exception's weak CLR wrapper before Activator.CreateInstance constructs the outer exception. The fallback makes the cause readable, but the replacement isn't the peer that the CLR finalizer frees. After dropping the outers and draining finalizers, 20,000 constructions retained about 4.15 MB here versus effectively zero on master, which left the cause unset. Python-created outers using the same fallback retained the same amount on both. Please record the .NET-construction case under Known limits; no wrapper lifecycle change requested.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorded under Known limits, per the maintainer decision on exotic cases, with no code change.

GC.KeepAlive(wrapper);
Runtime.PyException_SetCause(ob, cause.Steal());
}

Expand Down
47 changes: 45 additions & 2 deletions src/runtime/Types/ClassDerived.cs
Original file line number Diff line number Diff line change
Expand Up @@ -904,8 +904,8 @@ public static void InvokeSetProperty<T>(IPythonDerivedType obj, string propertyN

public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, object[] args)
{
var selfRef = GetPyObj(obj);
if (selfRef.Ref == null)
var createdFromDotNet = GetPyObj(obj).Ref == null;
if (createdFromDotNet)
{
// this might happen when the object is created from .NET
using var _ = Py.GIL();
Expand All @@ -922,6 +922,49 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec
null,
obj,
args);

// the Python object of an exception created from .NET got its args and __cause__
// before the base constructor set its Message and InnerException
if (!createdFromDotNet || obj is not Exception exception)
{
return;
}
using var gil = Py.GIL();
// a strong reference while it's refreshed: the Python object starts with a weak one
using var pySelf = ClassDerivedObject.ToPython(obj);
// .NET construction doesn't run the Python __init__, which Python overrides of Message may rely on:
// read it without them, as when the Python object was created
var pyObj = GetPyObj(obj);
SetPyObj(obj, BorrowedReference.Null);
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
string message;
try
{
// a .NET Message may wait on another thread that runs Python code
using var threads = Py.AllowThreads();
message = exception.Message ?? string.Empty;
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
}
catch (Exception)
{
// the exception keeps the args it was created with
return;
}
finally
{
SetPyObj(obj, pyObj.CheckRun());
}

try
{
if (!Exceptions.SetArgsAndCause(pySelf.Borrow(), exception, message))
{
Exceptions.Clear();
}
}
catch (Exception)
{
// such as an inner exception whose Message throws: construction succeeds as when
// the exception was created, without a cause
}
}

public static void PyFinalize(IPythonDerivedType obj)
Expand Down
5 changes: 3 additions & 2 deletions src/runtime/Types/ClrObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ internal sealed class CLRObject : ManagedType
static NewReference Create(object ob, BorrowedReference tp)
{
Debug.Assert(tp != null);
var py = Runtime.PyType_GenericAlloc(tp, 0);
// freed when reading or converting an exception's Message throws
using var py = Runtime.PyType_GenericAlloc(tp, 0);

var self = new CLRObject(ob);

Expand All @@ -32,7 +33,7 @@ static NewReference Create(object ob, BorrowedReference tp)
// slot if wrapping a CLR exception
if (ob is Exception e) Exceptions.SetArgsAndCause(py.Borrow(), e);

return py;
return py.Move();
}

CLRObject(object inst)
Expand Down
77 changes: 77 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -711,3 +711,80 @@ def test_namespaced_exception_subclass_override_errors():
"inherited str outer KeyError 'inner'",
"two-level inherited str outer KeyError 'inner'",
]


_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT = """
from System import Activator, Array, Exception as ClrException, String, Type

class CreatedError(ClrException):
__namespace__ = "Python.Test.DotNetCreatedExceptions"
def __init__(self):
pass

class ChildCreatedError(CreatedError):
__namespace__ = "Python.Test.DotNetCreatedExceptions"
def __init__(self):
pass

class DelayedError(ClrException):
__namespace__ = "Python.Test.DotNetCreatedExceptions"
@clr.clrmethod(None, [str])
def __init__(self, text):
self.text = text
def get_Message(self):
return self.text

class CollectingError(ClrException):
__namespace__ = "Python.Test.DotNetCreatedExceptions"
def __init__(self):
pass
def get_Message(self):
GC.Collect()
GC.WaitForPendingFinalizers()
return "collected"

def check(name, error):
cause = error.__cause__
print(name, error.Message, error.args, cause.Message if cause is not None else None,
error.InnerException.Message if error.InnerException is not None else None)

inner = ClrException("inner")
created = clr.GetClrType(CreatedError)
Comment thread
quantconnect-kronos-reviewer-2[bot] marked this conversation as resolved.
Resolved
check("activator", Activator.CreateInstance(created, Array[Object](["custom message", inner])))
check("constructor info", created.GetConstructor(Array[Type]([String])).Invoke(Array[Object](["message only"])))
check("parameterless", Activator.CreateInstance(created))
check("child", Activator.CreateInstance(clr.GetClrType(ChildCreatedError), Array[Object](["child message", inner])))

# .NET construction doesn't run __init__: the caller runs it after the constructor
delayed = Activator.CreateInstance(clr.GetClrType(DelayedError), Array[Object](["base message"]))
delayed.GetType().GetMethod("__init__").Invoke(delayed, Array[Object](["initialized"]))
check("delayed", delayed)

collecting = Activator.CreateInstance(clr.GetClrType(CollectingError), Array[Object](["collecting message"]))
GC.Collect()
GC.WaitForPendingFinalizers()
print("collecting", Object.GetType(collecting).Name, collecting.Message, collecting.args)

generated_inner = Activator.CreateInstance(created, Array[Object](["generated inner"]))
generated_inner.tag = "tagged"
outer = Activator.CreateInstance(created, Array[Object](["outer", generated_inner]))
print("generated cause", outer.__cause__ is generated_inner, outer.__cause__.tag)
"""


@pytest.mark.skipif(os.environ.get("PYTHONNET_RUNTIME") != "netcore", reason="loads the netcore runtime")
def test_namespaced_exception_subclass_created_from_dotnet():
"""The args and __cause__ of a __namespace__ exception subclass constructed from .NET
match the Message and InnerException its base constructor set"""
output = _run_namespaced_exception_script(_NAMESPACED_EXCEPTION_FROM_DOTNET_SCRIPT)

default = "Exception of type 'Python.Test.DotNetCreatedExceptions.CreatedError' was thrown."
assert output[-7:] == [
"activator custom message ('custom message',) inner inner",
"constructor info message only ('message only',) None None",
f"parameterless {default} ({default!r},) None None",
"child child message ('child message',) inner inner",
"delayed initialized ('base message',) None None",
"collecting CollectingError collected ('collecting message',)",
"generated cause True tagged",
]
Loading