From 4efed344c79a7d7f7ee249f0477d327ca5303ecd Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:19:55 +0000 Subject: [PATCH 1/3] Keep a __namespace__ subclass's Python state while .NET holds it in a cycle The cyclic GC can't see .NET's reference to a __namespace__ subclass instance, so it cleared the instance's cycle, its __dict__ included, while .NET still held the object. The type's tp_finalize now hands the object to its .NET object instead: the .NET object keeps one reference to it, and the Python object holds the .NET object weakly. Python takes that reference back when the object returns to Python, and the .NET object releases it when it's finalized, after which Python frees the cycle. The wrapper a Python object holds weakly is now kept alive as long as its .NET object, so the object still converts back to .NET after a .NET GC. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Interop.cs | 3 + src/runtime/Native/ITypeOffsets.cs | 1 + src/runtime/Native/TypeOffset.cs | 1 + src/runtime/Types/ClassDerived.cs | 107 ++++++++++++++++++++++--- tests/test_subclass.py | 122 +++++++++++++++++++++++++++++ 5 files changed, 225 insertions(+), 9 deletions(-) diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index bcf99bede..8b4a250c2 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -188,6 +188,9 @@ internal static ThunkInfo GetThunk(Delegate @delegate) [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void N_V(NewReference ob); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + public delegate void B_V(BorrowedReference ob); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int BPP_I32(BorrowedReference ob, IntPtr a1, IntPtr a2); } diff --git a/src/runtime/Native/ITypeOffsets.cs b/src/runtime/Native/ITypeOffsets.cs index bae8636c5..3d19cb71e 100644 --- a/src/runtime/Native/ITypeOffsets.cs +++ b/src/runtime/Native/ITypeOffsets.cs @@ -52,6 +52,7 @@ interface ITypeOffsets int tp_descr_set { get; } int tp_dict { get; } int tp_dictoffset { get; } + int tp_finalize { get; } int tp_flags { get; } int tp_free { get; } int tp_getattro { get; } diff --git a/src/runtime/Native/TypeOffset.cs b/src/runtime/Native/TypeOffset.cs index 76196bcad..314f3c8f4 100644 --- a/src/runtime/Native/TypeOffset.cs +++ b/src/runtime/Native/TypeOffset.cs @@ -59,6 +59,7 @@ static partial class TypeOffset internal static int tp_descr_set { get; private set; } internal static int tp_dict { get; private set; } internal static int tp_dictoffset { get; private set; } + internal static int tp_finalize { get; private set; } internal static int tp_flags { get; private set; } internal static int tp_free { get; private set; } internal static int tp_getattro { get; private set; } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 6c2c81b13..742ae229b 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Reflection; using System.Reflection.Emit; +using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Python.Runtime.Native; @@ -34,6 +35,21 @@ internal class ClassDerivedObject : ClassObject private static Dictionary assemblyBuilders; private static Dictionary, ModuleBuilder> moduleBuilders; + /// + /// Python objects whose .NET object holds one reference to them, taken in + /// + internal static readonly HashSet KeptByManagedObject = new(); + /// + /// Python objects whose .NET object was finalized while it held a reference to them: + /// frees them + /// + internal static readonly HashSet ReleasedByManagedObject = new(); + /// + /// Nothing else references the wrapper of a .NET object its Python object holds weakly: + /// this keeps it alive as long as the .NET object + /// + private static readonly ConditionalWeakTable WeaklyHeldWrappers = new(); + static ClassDerivedObject() { assemblyBuilders = new Dictionary(); @@ -44,6 +60,9 @@ public static void Reset() { assemblyBuilders = new Dictionary(); moduleBuilders = new Dictionary, ModuleBuilder>(); + KeptByManagedObject.Clear(); + ReleasedByManagedObject.Clear(); + WeaklyHeldWrappers.Clear(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -76,6 +95,12 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); + if (ReleasedByManagedObject.Remove(ob.DangerousGetAddress())) + { + PythonDerivedType.Finalize(ob.DangerousMoveToPointer()); + return; + } + // self may be null after Shutdown begun if (self is not null) { @@ -83,13 +108,66 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // deallocate the object until the C# object that references it is destroyed. // So we don't call PyObject_GC_Del here and instead we set the python // reference to a weak reference so that the C# object can be collected. - GCHandle oldHandle = GetGCHandle(ob.Borrow()); - GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak); - SetGCHandle(ob.Borrow(), gc); - oldHandle.Free(); + ReplaceGCHandle(ob.Borrow(), self, GCHandleType.Weak); } } + /// + /// Called by the Python cyclic GC on an object it found unreachable from Python, before it clears + /// the cycle. .NET may still reference the object, which Python can't see, so instead of letting + /// the cycle be cleared, the .NET object keeps one reference to the Python object, and the Python + /// object stops keeping the .NET object alive, as does. Python gets that + /// reference back in , and the .NET object releases it when it's finalized. + /// + public static void tp_finalize(BorrowedReference ob) + { + // The GC marks an object finalized before it calls tp_finalize and doesn't call it again + // once marked. Otherwise, it's a direct __del__ call from Python, which still references the object. + if ((GCPrev(ob) & FinalizedFlag) == 0) + { + return; + } + + var self = (CLRObject?)GetManagedObject(ob); + // null once the .NET object is gone: the GC frees the cycle + if (self is null) + { + return; + } + + // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again + GCPrev(ob) &= ~FinalizedFlag; + Runtime.XIncref(ob); + KeptByManagedObject.Add(ob.DangerousGetAddress()); + ReplaceGCHandle(ob, self, GCHandleType.Weak); + } + + /// + /// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev + /// + private const nint FinalizedFlag = 1; + + /// + /// _gc_prev, the last field of the GC header that precedes the object + /// + private static unsafe ref nint GCPrev(BorrowedReference ob) + => ref *((nint*)ob.DangerousGetAddress() - 1); + + private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type) + { + if (type == GCHandleType.Weak) + { + WeaklyHeldWrappers.AddOrUpdate(self.inst, self); + } + else + { + WeaklyHeldWrappers.Remove(self.inst); + } + GCHandle oldHandle = GetGCHandle(ob); + SetGCHandle(ob, GCHandle.Alloc(self, type)); + oldHandle.Free(); + } + /// /// No-op clear. Real cleanup happens in /// @@ -113,6 +191,13 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } + if (KeptByManagedObject.Remove(self.DangerousGetAddress())) + { + // Python takes over the reference the .NET object kept in tp_finalize + ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal); + return NewReference.DangerousFromPointer(self.DangerousGetAddress()); + } + var result = new NewReference(self); // when the C# constructor creates the python object it starts as a weak @@ -123,11 +208,7 @@ internal static NewReference ToPython(IPythonDerivedType obj) if (Runtime.Refcount(self) == 1) { Runtime._Py_NewReference(self); - GCHandle weak = GetGCHandle(self); - var clrObject = GetManagedObject(self); - GCHandle gc = GCHandle.Alloc(clrObject, GCHandleType.Normal); - SetGCHandle(self, gc); - weak.Free(); + ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal); // now the object has a python reference it's safe for the python GC to track it Runtime.PyObject_GC_Track(self); @@ -933,6 +1014,14 @@ public static void PyFinalize(IPythonDerivedType obj) internal static void Finalize(IntPtr derived) { + if (ClassDerivedObject.KeptByManagedObject.Remove(derived)) + { + // the Python object may still be part of a cycle: Python frees it once nothing references it + ClassDerivedObject.ReleasedByManagedObject.Add(derived); + Runtime.XDecref(StolenReference.DangerousFromPointer(derived)); + return; + } + var @ref = NewReference.DangerousFromPointer(derived); ClassBase.tp_clear(@ref.Borrow()); diff --git a/tests/test_subclass.py b/tests/test_subclass.py index 85c50d21a..79e678596 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -305,3 +305,125 @@ class Derived(BaseClass): import gc gc.collect() + + +def _release_python_and_net_objects(): + """Collect Python cycles and .NET objects, then free the Python objects whose .NET object was finalized""" + import gc + from System import GC + + for _ in range(3): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + # every 200th Python object passed to .NET frees the queued ones + List[System.Object]([object() for _ in range(300)]) + gc.collect() + + +def test_namespaced_subclass_held_by_net_keeps_its_cycle(): + from System import String + + class CycleHolder(System.Object): + __namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_cycle" + + def __init__(self, code): + self.code = code + self.me = self + self.items = [self] + self.items.append(self.items) + + def ToString(self): + return "holder {}".format(self.code) + + class PythonSubclass(CycleHolder): + pass + + # each instance references its class, until it's freed + refcounts = sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass) + held = List[System.Object]() + held.Add(CycleHolder(7)) + held.Add(PythonSubclass(8)) + + for _ in range(2): + _release_python_and_net_objects() + # .NET calls the Python override while only .NET holds the object + assert String.Join[System.Object](",", held) == "holder 7,holder 8" + + holder = held[0] + assert holder.code == 7 + assert holder.me is holder + assert holder.items[0] is holder + assert held[1].code == 8 + del holder + + held.Clear() + _release_python_and_net_objects() + assert (sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass)) == refcounts + + +def test_namespaced_subclass_cycle_is_collected(): + class CycleMember(System.Object): + __namespace__ = "test_namespaced_subclass_cycle_is_collected" + + def __init__(self): + self.me = self + + refcount = sys.getrefcount(CycleMember) + for _ in range(100): + CycleMember() + first, second = CycleMember(), CycleMember() + first.other, second.other = second, first + del first, second + + held = List[System.Object]() + first, second = CycleMember(), CycleMember() + first.other, second.other = second, first + first.code = 1 + held.Add(second) + del first, second + + _release_python_and_net_objects() + assert held[0].other.code == 1 + assert held[0].other.other is held[0] + assert sys.getrefcount(CycleMember) == refcount + 2 + + held.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(CycleMember) == refcount + + +def test_namespaced_subclass_direct_del_call_keeps_net_object(): + class DirectDelCall(System.Object): + __namespace__ = "test_namespaced_subclass_direct_del_call_keeps_net_object" + + def __init__(self): + self.me = self + + instance = DirectDelCall() + instance.__del__() + _release_python_and_net_objects() + instance.GetHashCode() + assert instance.me is instance + + +@pytest.mark.parametrize("in_cycle", [False, True]) +def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle): + class HeldByNet(System.Object): + __namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_wrapper_{}".format(in_cycle) + + def __init__(self, code): + self.code = code + if in_cycle: + self.me = self + + held = List[System.Object]() + held.Add(HeldByNet(7)) + for _ in range(2): + _release_python_and_net_objects() + + instance = held[0] + assert instance.code == 7 + assert held.Contains(instance) + assert instance.GetType().Name == "HeldByNet" + del instance From 8482a4d07ca7017126d53cb7215b1fab6d35b29a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:37:05 +0000 Subject: [PATCH 2/3] Keep the .NET object of a __namespace__ subclass that Python resurrects, and support Python 3.7 When another object's __del__ gave Python back an instance the cycle GC had handed to .NET, its .NET object could be collected while Python still used it. The finalized .NET object now stays reachable until the queued finalization runs, which gives the Python object a strong handle to it again when Python still references it. On Python 3.7, the GC's finalized flag is in gc_refs, and tp_finalize only runs for types with Py_TPFLAGS_HAVE_FINALIZE. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Finalizer.cs | 10 +++- src/runtime/Interop.cs | 2 + src/runtime/Types/ClassDerived.cs | 84 +++++++++++++++++++++++---- src/runtime/Types/ReflectedClrType.cs | 4 ++ tests/test_subclass.py | 58 ++++++++++++++++++ 5 files changed, 144 insertions(+), 14 deletions(-) diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index 05c498443..d3b33b9e1 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -154,7 +154,7 @@ internal void AddFinalizedObject(ref IntPtr obj, int run obj = IntPtr.Zero; } - internal void AddDerivedFinalizedObject(ref IntPtr derived, int run) + internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object managed) { if (derived == IntPtr.Zero) throw new ArgumentNullException(nameof(derived)); @@ -164,7 +164,7 @@ internal void AddDerivedFinalizedObject(ref IntPtr derived, int run) return; } - var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run }; + var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run, Managed = managed }; derived = IntPtr.Zero; _derivedQueue.Enqueue(pending); } @@ -254,7 +254,7 @@ internal nint DisposeAll() } #pragma warning disable CS0618 // Type or member is obsolete. OK for internal use - PythonDerivedType.Finalize(derived.PyObj); + PythonDerivedType.Finalize(derived.PyObj, derived.Managed); #pragma warning restore CS0618 // Type or member is obsolete collected++; @@ -367,6 +367,10 @@ struct PendingFinalization public IntPtr PyObj; public BorrowedReference Ref => new(PyObj); public int RuntimeRun; + /// + /// The finalized .NET object of a Python derived type, kept alive until it's handled + /// + public object? Managed; #if TRACE_ALLOC public string StackTrace; #endif diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index 8b4a250c2..74ba31123 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -63,6 +63,8 @@ public ModulePropertyAttribute() [Flags] public enum TypeFlags: long { + /// Python 3.7 calls tp_finalize only when set + HaveFinalize = (1 << 0), HeapType = (1 << 9), BaseType = (1 << 10), Ready = (1 << 12), diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 742ae229b..26c094ee6 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -45,6 +45,10 @@ internal class ClassDerivedObject : ClassObject /// internal static readonly HashSet ReleasedByManagedObject = new(); /// + /// Python objects .NET let go of while Python still referenced them, see + /// + private static readonly HashSet ReturnedToPython = new(); + /// /// Nothing else references the wrapper of a .NET object its Python object holds weakly: /// this keeps it alive as long as the .NET object /// @@ -62,7 +66,9 @@ public static void Reset() moduleBuilders = new Dictionary, ModuleBuilder>(); KeptByManagedObject.Clear(); ReleasedByManagedObject.Clear(); + ReturnedToPython.Clear(); WeaklyHeldWrappers.Clear(); + finalizedFlagOffset = GetFinalizedFlagOffset(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -94,6 +100,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); + ReturnedToPython.Remove(ob.DangerousGetAddress()); if (ReleasedByManagedObject.Remove(ob.DangerousGetAddress())) { @@ -123,7 +130,13 @@ public static void tp_finalize(BorrowedReference ob) { // The GC marks an object finalized before it calls tp_finalize and doesn't call it again // once marked. Otherwise, it's a direct __del__ call from Python, which still references the object. - if ((GCPrev(ob) & FinalizedFlag) == 0) + if ((FinalizedFlagWord(ob) & FinalizedFlag) == 0) + { + return; + } + + // .NET already let go of the object while Python still referenced it: the GC frees the cycle + if (ReturnedToPython.Remove(ob.DangerousGetAddress())) { return; } @@ -136,26 +149,70 @@ public static void tp_finalize(BorrowedReference ob) } // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again - GCPrev(ob) &= ~FinalizedFlag; + FinalizedFlagWord(ob) &= ~FinalizedFlag; Runtime.XIncref(ob); KeptByManagedObject.Add(ob.DangerousGetAddress()); - ReplaceGCHandle(ob, self, GCHandleType.Weak); + // Another object's __del__ may give Python the object back before the cycle is cleared. + // Tracking resurrection keeps the handle valid until Finalize(IntPtr, object) takes the + // .NET object back after its finalizer ran. + ReplaceGCHandle(ob, self, GCHandleType.WeakTrackResurrection); + } + + /// + /// Called when the .NET object kept the Python object since and was + /// finalized while Python still references the Python object: through the cycle, or because Python + /// got the object back without .NET. The Python object keeps the .NET object alive again, as for + /// any object Python holds, and the next time the GC finds the cycle unreachable, it frees it. + /// + internal static void ReturnToPython(BorrowedReference ob, object managed) + { + if (WeaklyHeldWrappers.TryGetValue(managed, out var self)) + { + ReplaceGCHandle(ob, self, GCHandleType.Normal); + GC.ReRegisterForFinalize(managed); + ReturnedToPython.Add(ob.DangerousGetAddress()); + } } /// - /// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev + /// The GC's finalized flag: bit 0 of _gc_prev since Python 3.8, of gc_refs before /// private const nint FinalizedFlag = 1; /// - /// _gc_prev, the last field of the GC header that precedes the object + /// Offset from the object to the GC header word that holds /// - private static unsafe ref nint GCPrev(BorrowedReference ob) - => ref *((nint*)ob.DangerousGetAddress() - 1); + private static nint finalizedFlagOffset; + + private static unsafe ref nint FinalizedFlagWord(BorrowedReference ob) + => ref *(nint*)((byte*)ob.DangerousGetAddress() + finalizedFlagOffset); + + private static nint GetFinalizedFlagOffset() + { + if (Runtime.PyVersion >= new Version(3, 8)) + { + // _gc_prev, the last word of the GC header that precedes the object + return -IntPtr.Size; + } + + // Python 3.7: gc_refs, the third word of a GC header padded to the platform's + // long double alignment. sys.getsizeof adds that header to __sizeof__. + using var list = Runtime.PyList_New(0); + using var sizeOf = Runtime.PyObject_GetAttrString(list.Borrow(), "__sizeof__"); + using var noArgs = Runtime.PyTuple_New(0); + using var size = Runtime.PyObject_CallObject(sizeOf.BorrowOrThrow(), noArgs.Borrow()); + using var getSizeOfArgs = Runtime.PyTuple_New(1); + Runtime.PyTuple_SetItem(getSizeOfArgs.Borrow(), 0, list.Borrow()); + using var sizeWithGCHeader = Runtime.PyObject_CallObject( + Runtime.PySys_GetObject("getsizeof"), getSizeOfArgs.Borrow()); + nint gcHeaderSize = Runtime.PyLong_AsSignedSize_t(sizeWithGCHeader.BorrowOrThrow()) + - Runtime.PyLong_AsSignedSize_t(size.BorrowOrThrow()); + return -gcHeaderSize + 2 * IntPtr.Size; + } private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type) { - if (type == GCHandleType.Weak) + if (type != GCHandleType.Normal) { WeaklyHeldWrappers.AddOrUpdate(self.inst, self); } @@ -191,6 +248,7 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } + ReturnedToPython.Remove(self.DangerousGetAddress()); if (KeptByManagedObject.Remove(self.DangerousGetAddress())) { // Python takes over the reference the .NET object kept in tp_finalize @@ -1009,16 +1067,20 @@ 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); - Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run); + Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj); } - internal static void Finalize(IntPtr derived) + internal static void Finalize(IntPtr derived, object? managed = null) { if (ClassDerivedObject.KeptByManagedObject.Remove(derived)) { - // the Python object may still be part of a cycle: Python frees it once nothing references it + // tp_dealloc frees the Python object if this was its last reference ClassDerivedObject.ReleasedByManagedObject.Add(derived); Runtime.XDecref(StolenReference.DangerousFromPointer(derived)); + if (ClassDerivedObject.ReleasedByManagedObject.Remove(derived) && managed is not null) + { + ClassDerivedObject.ReturnToPython(new BorrowedReference(derived), managed); + } return; } diff --git a/src/runtime/Types/ReflectedClrType.cs b/src/runtime/Types/ReflectedClrType.cs index 15ea5c2b2..eab7df316 100644 --- a/src/runtime/Types/ReflectedClrType.cs +++ b/src/runtime/Types/ReflectedClrType.cs @@ -112,6 +112,10 @@ static ReflectedClrType AllocateClass(Type clrType) | TypeFlags.HeapType | TypeFlags.BaseType | TypeFlags.HaveGC; + if (Runtime.PyVersion < new Version(3, 8)) + { + type.Flags |= TypeFlags.HaveFinalize; + } return new ReflectedClrType(type.Steal()); } diff --git a/tests/test_subclass.py b/tests/test_subclass.py index 79e678596..0604d42b8 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -407,6 +407,64 @@ def __init__(self): assert instance.me is instance +def _resurrect_through_python(cls, survivors): + """Drop an instance in a cycle whose other member's __del__ gives Python the instance back""" + import gc + from System import GC + + class Resurrector: + def __init__(self, owner): + self.owner = owner + + def __del__(self): + survivors.append(self.owner) + + owner = cls() + owner.other = Resurrector(owner) + del owner + + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + + +def test_namespaced_subclass_resurrected_by_python_keeps_net_object(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_keeps_net_object" + + def __init__(self): + self.code = 7 + + survivors = [] + _resurrect_through_python(Resurrected, survivors) + # before the finalized .NET object is handled + survivors[0].GetHashCode() + + _release_python_and_net_objects() + assert survivors[0].GetType().Name == "Resurrected" + assert survivors[0].code == 7 + + +def test_namespaced_subclass_resurrected_by_python_is_collected(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_is_collected" + + def __init__(self): + self.code = 7 + + refcount = sys.getrefcount(Resurrected) + survivors = [] + _resurrect_through_python(Resurrected, survivors) + + _release_python_and_net_objects() + assert survivors[0].code == 7 + assert survivors[0].other.owner is survivors[0] + + survivors.clear() + _release_python_and_net_objects() + assert sys.getrefcount(Resurrected) == refcount + + @pytest.mark.parametrize("in_cycle", [False, True]) def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle): class HeldByNet(System.Object): From 598f456e3accd5c8783a0a8fcda42207feafee0e Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:14:24 +0000 Subject: [PATCH 3/3] Run a __namespace__ subclass's base finalizer once, and keep it when .NET gets it back Deferring the .NET finalization of an object Python may still reference, instead of re-registering an already finalized object, runs the base type's finalizer once. The finalizer decides atomically whether the cleanup is deferred, so .NET getting the object back before the queued cleanup runs no longer frees a live object. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Finalizer.cs | 17 ++-- src/runtime/Types/ClassDerived.cs | 144 ++++++++++++++++++++++-------- tests/test_subclass.py | 90 +++++++++++++++++++ 3 files changed, 209 insertions(+), 42 deletions(-) diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index d3b33b9e1..e78120dd1 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -154,7 +154,7 @@ internal void AddFinalizedObject(ref IntPtr obj, int run obj = IntPtr.Zero; } - internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object managed) + internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false) { if (derived == IntPtr.Zero) throw new ArgumentNullException(nameof(derived)); @@ -164,7 +164,10 @@ internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object mana return; } - var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run, Managed = managed }; + var pending = new PendingFinalization + { + PyObj = derived, RuntimeRun = run, Deferred = deferred, KeptReference = keptReference, + }; derived = IntPtr.Zero; _derivedQueue.Enqueue(pending); } @@ -254,7 +257,7 @@ internal nint DisposeAll() } #pragma warning disable CS0618 // Type or member is obsolete. OK for internal use - PythonDerivedType.Finalize(derived.PyObj, derived.Managed); + PythonDerivedType.Finalize(derived.PyObj, derived.Deferred, derived.KeptReference); #pragma warning restore CS0618 // Type or member is obsolete collected++; @@ -368,9 +371,13 @@ struct PendingFinalization public BorrowedReference Ref => new(PyObj); public int RuntimeRun; /// - /// The finalized .NET object of a Python derived type, kept alive until it's handled + /// The .NET object of a Python derived type whose finalization waits until this is handled + /// + public object? Deferred; + /// + /// holds a reference to /// - public object? Managed; + public bool KeptReference; #if TRACE_ALLOC public string StackTrace; #endif diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 26c094ee6..8c3d2070f 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -38,17 +38,25 @@ internal class ClassDerivedObject : ClassObject /// /// Python objects whose .NET object holds one reference to them, taken in /// - internal static readonly HashSet KeptByManagedObject = new(); + private static readonly HashSet KeptByManagedObject = new(); /// - /// Python objects whose .NET object was finalized while it held a reference to them: - /// frees them + /// Python objects that took back the reference their .NET object kept, in , + /// while .NET may already be finalizing that .NET object /// - internal static readonly HashSet ReleasedByManagedObject = new(); + private static readonly HashSet TakenBackByPython = new(); /// - /// Python objects .NET let go of while Python still referenced them, see + /// Python objects whose .NET object was finalized while it held the reference taken in + /// , and that weren't passed to .NET since: the next time the GC finds + /// such an object unreachable, nothing else references it and the GC frees the cycle /// private static readonly HashSet ReturnedToPython = new(); /// + /// Guards , and + /// , which the .NET finalizer thread updates in + /// + /// + private static readonly object KeptLock = new(); + /// /// Nothing else references the wrapper of a .NET object its Python object holds weakly: /// this keeps it alive as long as the .NET object /// @@ -64,9 +72,12 @@ public static void Reset() { assemblyBuilders = new Dictionary(); moduleBuilders = new Dictionary, ModuleBuilder>(); - KeptByManagedObject.Clear(); - ReleasedByManagedObject.Clear(); - ReturnedToPython.Clear(); + lock (KeptLock) + { + KeptByManagedObject.Clear(); + TakenBackByPython.Clear(); + ReturnedToPython.Clear(); + } WeaklyHeldWrappers.Clear(); finalizedFlagOffset = GetFinalizedFlagOffset(); } @@ -100,12 +111,9 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo // don't let the python GC destroy this object Runtime.PyObject_GC_UnTrack(ob.Borrow()); - ReturnedToPython.Remove(ob.DangerousGetAddress()); - - if (ReleasedByManagedObject.Remove(ob.DangerousGetAddress())) + lock (KeptLock) { - PythonDerivedType.Finalize(ob.DangerousMoveToPointer()); - return; + ReturnedToPython.Remove(ob.DangerousGetAddress()); } // self may be null after Shutdown begun @@ -136,9 +144,12 @@ public static void tp_finalize(BorrowedReference ob) } // .NET already let go of the object while Python still referenced it: the GC frees the cycle - if (ReturnedToPython.Remove(ob.DangerousGetAddress())) + lock (KeptLock) { - return; + if (ReturnedToPython.Remove(ob.DangerousGetAddress())) + { + return; + } } var self = (CLRObject?)GetManagedObject(ob); @@ -151,26 +162,45 @@ public static void tp_finalize(BorrowedReference ob) // the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again FinalizedFlagWord(ob) &= ~FinalizedFlag; Runtime.XIncref(ob); - KeptByManagedObject.Add(ob.DangerousGetAddress()); + lock (KeptLock) + { + KeptByManagedObject.Add(ob.DangerousGetAddress()); + } // Another object's __del__ may give Python the object back before the cycle is cleared. - // Tracking resurrection keeps the handle valid until Finalize(IntPtr, object) takes the - // .NET object back after its finalizer ran. + // Tracking resurrection keeps the handle valid until Finalize(IntPtr, object, bool) takes + // the .NET object back after its finalizer ran. ReplaceGCHandle(ob, self, GCHandleType.WeakTrackResurrection); } /// - /// Called when the .NET object kept the Python object since and was - /// finalized while Python still references the Python object: through the cycle, or because Python - /// got the object back without .NET. The Python object keeps the .NET object alive again, as for - /// any object Python holds, and the next time the GC finds the cycle unreachable, it frees it. + /// Called by the .NET finalizer of a Python derived type. Returns true when the .NET object + /// held the Python object since , or Python took it back while .NET + /// may have been finalizing it: Python may still reference the object, so its .NET finalization + /// waits until handles it. + /// + internal static bool DeferFinalization(IntPtr ob, out bool keptReference) + { + lock (KeptLock) + { + keptReference = KeptByManagedObject.Remove(ob); + if (keptReference) + { + ReturnedToPython.Add(ob); + } + return TakenBackByPython.Remove(ob) || keptReference; + } + } + + /// + /// Called when .NET finalized the .NET object of a Python object Python still references: + /// through the cycle, or because Python got the object back without .NET. The Python object + /// keeps the .NET object alive again, as for any object Python holds. /// internal static void ReturnToPython(BorrowedReference ob, object managed) { if (WeaklyHeldWrappers.TryGetValue(managed, out var self)) { ReplaceGCHandle(ob, self, GCHandleType.Normal); - GC.ReRegisterForFinalize(managed); - ReturnedToPython.Add(ob.DangerousGetAddress()); } } @@ -248,8 +278,17 @@ internal static NewReference ToPython(IPythonDerivedType obj) return default; } - ReturnedToPython.Remove(self.DangerousGetAddress()); - if (KeptByManagedObject.Remove(self.DangerousGetAddress())) + bool kept; + lock (KeptLock) + { + ReturnedToPython.Remove(self.DangerousGetAddress()); + kept = KeptByManagedObject.Remove(self.DangerousGetAddress()); + if (kept) + { + TakenBackByPython.Add(self.DangerousGetAddress()); + } + } + if (kept) { // Python takes over the reference the .NET object kept in tp_finalize ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal); @@ -408,7 +447,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, + // then runs the base type's finalizer, unless PyFinalize defers it MethodBuilder methodBuilder = typeBuilder.DefineMethod("Finalize", MethodAttributes.Family | MethodAttributes.Virtual | @@ -417,12 +457,15 @@ internal static Type CreateDerivedType(string name, typeof(void), Type.EmptyTypes); ILGenerator il = methodBuilder.GetILGenerator(); + Label deferred = il.DefineLabel(); 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.Brfalse_S, deferred); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseClass.GetMethod("Finalize", BindingFlags.NonPublic | BindingFlags.Instance)); + il.MarkLabel(deferred); il.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); @@ -1062,25 +1105,52 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec args); } - public static void PyFinalize(IPythonDerivedType obj) + /// + /// Called by the .NET finalizer of a Python derived type + /// + /// + /// Whether the base type's finalizer runs now. When Python may still reference the Python object, + /// .NET finalizes the object again once handled it. + /// + public static bool PyFinalize(IPythonDerivedType obj) { + var self = GetPyObj(obj); + if (ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference)) + { + Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); + return false; + } + // the C# object is being destroyed which must mean there are no more // references to the Python object as well - var self = GetPyObj(obj); - Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj); + Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run); + return true; } - internal static void Finalize(IntPtr derived, object? managed = null) + /// The Python object + /// + /// The .NET object, when deferred its finalization + /// + /// + /// The .NET object holds a reference to the Python object, taken in tp_finalize + /// + internal static void Finalize(IntPtr derived, object? deferred = null, bool keptReference = false) { - if (ClassDerivedObject.KeptByManagedObject.Remove(derived)) + if (deferred is not null) { - // tp_dealloc frees the Python object if this was its last reference - ClassDerivedObject.ReleasedByManagedObject.Add(derived); - Runtime.XDecref(StolenReference.DangerousFromPointer(derived)); - if (ClassDerivedObject.ReleasedByManagedObject.Remove(derived) && managed is not null) + var ob = new BorrowedReference(derived); + bool referencedByPython = Runtime.Refcount(ob) > (keptReference ? 1 : 0); + if (keptReference) + { + // when it's the last reference, tp_dealloc waits for the .NET object, as for any object + Runtime.XDecref(StolenReference.DangerousFromPointer(derived)); + } + if (referencedByPython) { - ClassDerivedObject.ReturnToPython(new BorrowedReference(derived), managed); + ClassDerivedObject.ReturnToPython(ob, deferred); } + // finalized once nothing references it, which runs the base type's finalizer + GC.ReRegisterForFinalize(deferred); return; } diff --git a/tests/test_subclass.py b/tests/test_subclass.py index 0604d42b8..1b126285d 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -465,6 +465,96 @@ def __init__(self): assert sys.getrefcount(Resurrected) == refcount +def test_namespaced_subclass_resurrected_by_python_and_passed_to_net(): + class Resurrected(System.Object): + __namespace__ = "test_namespaced_subclass_resurrected_by_python_and_passed_to_net" + + def __init__(self): + self.code = 7 + + from Python.Runtime import Finalizer + + refcount = sys.getrefcount(Resurrected) + survivors = [] + held = List[System.Object]() + threshold = Finalizer.Instance.Threshold + # .NET gets the instance back before the finalized .NET object is handled + Finalizer.Instance.Threshold = 1000000 + try: + _resurrect_through_python(Resurrected, survivors) + held.Add(survivors[0]) + alias = held[0] + assert alias is survivors[0] + # the next Python object passed to .NET handles the finalized .NET object + Finalizer.Instance.Threshold = 1 + List[System.Object]([object()]) + finally: + Finalizer.Instance.Threshold = threshold + assert alias.code == 7 + + # Python lets go first, then .NET + survivors.clear() + del alias + _release_python_and_net_objects() + assert held[0].code == 7 + assert held[0].GetType().Name == "Resurrected" + + held.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(Resurrected) == refcount + + +def test_namespaced_subclass_taken_back_by_python_then_released(): + class TakenBack(System.Object): + __namespace__ = "test_namespaced_subclass_taken_back_by_python_then_released" + + def __init__(self): + self.code = 7 + self.me = self + + refcount = sys.getrefcount(TakenBack) + held = List[System.Object]() + held.Add(TakenBack()) + _release_python_and_net_objects() + + instance = held[0] + assert instance.code == 7 + instance.me = None + del instance + held.Clear() + for _ in range(2): + _release_python_and_net_objects() + assert sys.getrefcount(TakenBack) == refcount + + +@pytest.mark.parametrize("cycle", ["none", "self", "resurrected"]) +def test_namespaced_subclass_runs_base_finalizer_once(cycle): + from Python.Test import FinalizedConstructorTest + + class Finalized(FinalizedConstructorTest): + __namespace__ = "test_namespaced_subclass_runs_base_finalizer_once_{}".format(cycle) + + def __init__(self): + self.code = 7 + + before = FinalizedConstructorTest.Finalized + survivors = [] + if cycle == "resurrected": + _resurrect_through_python(Finalized, survivors) + _release_python_and_net_objects() + assert survivors[0].code == 7 + survivors.clear() + else: + instance = Finalized() + if cycle == "self": + instance.me = instance + del instance + + for _ in range(3): + _release_python_and_net_objects() + assert FinalizedConstructorTest.Finalized - before == 1 + + @pytest.mark.parametrize("in_cycle", [False, True]) def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle): class HeldByNet(System.Object):