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/7] 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/7] 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/7] 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): From 288df02caf13c7dda2bb77f465d81d92a697a29a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:38:45 +0000 Subject: [PATCH 4/7] Run a __namespace__ subclass's base finalizer while the finalizer is disabled, and drop Python 3.7 code While Finalizer.Instance.Enable is false, the deferred finalization isn't queued, so nothing would finalize the object again: run the base type's finalizer then, as master does. Python 3.7 isn't supported, so the finalized flag is always bit 0 of _gc_prev, and CLR types no longer set Py_TPFLAGS_HAVE_FINALIZE. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Finalizer.cs | 6 ++-- src/runtime/Interop.cs | 2 -- src/runtime/Types/ClassDerived.cs | 41 +++------------------------ src/runtime/Types/ReflectedClrType.cs | 4 --- tests/test_subclass.py | 36 +++++++++++++++++++++++ 5 files changed, 44 insertions(+), 45 deletions(-) diff --git a/src/runtime/Finalizer.cs b/src/runtime/Finalizer.cs index e78120dd1..9791bee72 100644 --- a/src/runtime/Finalizer.cs +++ b/src/runtime/Finalizer.cs @@ -154,14 +154,15 @@ internal void AddFinalizedObject(ref IntPtr obj, int run obj = IntPtr.Zero; } - internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false) + /// Whether the object was queued, which it isn't while is false + internal bool AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false) { if (derived == IntPtr.Zero) throw new ArgumentNullException(nameof(derived)); if (!Enable) { - return; + return false; } var pending = new PendingFinalization @@ -170,6 +171,7 @@ internal void AddDerivedFinalizedObject(ref IntPtr derived, int run, object? def }; derived = IntPtr.Zero; _derivedQueue.Enqueue(pending); + return true; } internal void AddFinalizedBuffer(ref Py_buffer buffer) diff --git a/src/runtime/Interop.cs b/src/runtime/Interop.cs index 74ba31123..8b4a250c2 100644 --- a/src/runtime/Interop.cs +++ b/src/runtime/Interop.cs @@ -63,8 +63,6 @@ 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 7047a38f9..bd97eb1ee 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -79,7 +79,6 @@ public static void Reset() ReturnedToPython.Clear(); } WeaklyHeldWrappers.Clear(); - finalizedFlagOffset = GetFinalizedFlagOffset(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -205,40 +204,12 @@ internal static void ReturnToPython(BorrowedReference ob, object managed) } /// - /// The GC's finalized flag: bit 0 of _gc_prev since Python 3.8, of gc_refs before + /// The GC's finalized flag, bit 0 of _gc_prev, the last word of the GC header that precedes the object /// private const nint FinalizedFlag = 1; - /// - /// Offset from the object to the GC header word that holds - /// - 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; - } + => ref *((nint*)ob.DangerousGetAddress() - 1); private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type) { @@ -1118,12 +1089,8 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec public static bool PyDeferFinalization(IPythonDerivedType obj) { var self = GetPyObj(obj); - if (!ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference)) - { - return false; - } - Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); - return true; + return ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference) + && Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); } public static void PyFinalize(IPythonDerivedType obj) diff --git a/src/runtime/Types/ReflectedClrType.cs b/src/runtime/Types/ReflectedClrType.cs index 680232283..d5b06522c 100644 --- a/src/runtime/Types/ReflectedClrType.cs +++ b/src/runtime/Types/ReflectedClrType.cs @@ -168,10 +168,6 @@ 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 4deea4d54..9d3c93141 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -698,6 +698,42 @@ def __init__(self): assert FinalizedConstructorTest.Finalized - before == 1 +def test_namespaced_subclass_runs_base_finalizer_while_finalizer_disabled(): + import gc + from System import GC + from Python.Runtime import Finalizer + from Python.Test import FinalizedConstructorTest + + class Finalized(FinalizedConstructorTest): + __namespace__ = "test_namespaced_subclass_runs_base_finalizer_while_finalizer_disabled" + + def __init__(self): + self.me = self + + before = FinalizedConstructorTest.Finalized + held = List[System.Object]() + held.Add(Finalized()) + gc.collect() + instance = held[0] + instance.me = None + del instance + # while disabled, a finalized PyObject releases its Python object without the GIL + for _ in range(2): + gc.collect() + GC.Collect() + GC.WaitForPendingFinalizers() + + Finalizer.Instance.Enable = False + try: + held.Clear() + for _ in range(3): + GC.Collect() + GC.WaitForPendingFinalizers() + assert FinalizedConstructorTest.Finalized - before == 1 + finally: + Finalizer.Instance.Enable = True + + @pytest.mark.parametrize("in_cycle", [False, True]) def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle): class HeldByNet(System.Object): From 35c457ddef0f4a9e983634e0a26765e655c34e3a Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:31:47 +0000 Subject: [PATCH 5/7] Release a __namespace__ subclass's cycle when .NET collects it unfinalized, and keep its state across .NET owners A closed stream's .NET finalizer is suppressed, so the reference its .NET object kept in tp_finalize was never released: a finalizable object tied to the .NET object now releases it once .NET collects that object, and gives the .NET object back to Python if Python still references it. Passing the object to .NET again keeps its cycle from being cleared, and __del__ can be assigned after the class is defined again. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Converter.cs | 4 ++ src/runtime/Types/ClassDerived.cs | 89 ++++++++++++++++++++++++++--- src/runtime/Types/MetaType.cs | 4 +- tests/test_subclass.py | 94 +++++++++++++++++++++++++++++++ 4 files changed, 181 insertions(+), 10 deletions(-) diff --git a/src/runtime/Converter.cs b/src/runtime/Converter.cs index 47e592d16..31975ff16 100644 --- a/src/runtime/Converter.cs +++ b/src/runtime/Converter.cs @@ -552,6 +552,10 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType, if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type)) { + if (tmp is IPythonDerivedType) + { + ClassDerivedObject.PassedToManaged(value); + } result = tmp; return true; } diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index bd97eb1ee..87e965ed0 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -7,6 +7,7 @@ using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Threading; using Python.Runtime.Native; @@ -36,9 +37,12 @@ internal class ClassDerivedObject : ClassObject private static Dictionary, ModuleBuilder> moduleBuilders; /// - /// Python objects whose .NET object holds one reference to them, taken in + /// Python objects whose .NET object holds one reference to them, taken in , + /// with the id of the that releases it if .NET collects that object + /// without finalizing it /// - private static readonly HashSet KeptByManagedObject = new(); + private static readonly Dictionary KeptByManagedObject = new(); + private static long lastKeptReferenceId; /// /// Python objects that took back the reference their .NET object kept, in , /// while .NET may already be finalizing that .NET object @@ -61,6 +65,54 @@ internal class ClassDerivedObject : ClassObject /// this keeps it alive as long as the .NET object /// private static readonly ConditionalWeakTable WeaklyHeldWrappers = new(); + /// + /// Keeps the of a .NET object alive as long as that object + /// + private static readonly ConditionalWeakTable KeptReferences = new(); + + /// + /// Releases the reference a .NET object kept in once .NET collected + /// that object without finalizing it, such as after . + /// Holding the .NET object, this gives it back to Python if Python still references it. + /// + private sealed class KeptReference + { + private readonly IntPtr ob; + private readonly object inst; + private readonly int run = Runtime.GetRun(); + public readonly long Id = Interlocked.Increment(ref lastKeptReferenceId); + private bool waited; + + public KeptReference(IntPtr ob, object inst) + { + this.ob = ob; + this.inst = inst; + } + + ~KeptReference() + { + // .NET may finalize this along with the .NET object, whose finalizer takes the reference: + // until that finalizer ran, the .NET object keeps this alive through the next collection + if (!waited) + { + waited = true; + GC.ReRegisterForFinalize(this); + return; + } + lock (KeptLock) + { + // otherwise, Python or the .NET object's finalizer took the reference + if (!KeptByManagedObject.TryGetValue(ob, out long id) || id != Id) + { + return; + } + KeptByManagedObject.Remove(ob); + ReturnedToPython.Add(ob); + } + IntPtr pyObj = ob; + Finalizer.Instance.AddDerivedFinalizedObject(ref pyObj, run, inst, keptReference: true); + } + } static ClassDerivedObject() { @@ -79,6 +131,7 @@ public static void Reset() ReturnedToPython.Clear(); } WeaklyHeldWrappers.Clear(); + KeptReferences.Clear(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -131,7 +184,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo /// 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. + /// reference back in , and the .NET object releases it when it's finalized or collected. /// public static void tp_finalize(BorrowedReference ob) { @@ -161,10 +214,12 @@ 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); + var kept = new KeptReference(ob.DangerousGetAddress(), self.inst); lock (KeptLock) { - KeptByManagedObject.Add(ob.DangerousGetAddress()); + KeptByManagedObject[ob.DangerousGetAddress()] = kept.Id; } + KeptReferences.AddOrUpdate(self.inst, kept); // 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, bool) takes // the .NET object back after its finalizer ran. @@ -190,6 +245,17 @@ internal static bool DeferFinalization(IntPtr ob, out bool keptReference) } } + /// + /// Called when Python passes the Python object to .NET, which may keep it from then on + /// + internal static void PassedToManaged(BorrowedReference ob) + { + lock (KeptLock) + { + ReturnedToPython.Remove(ob.DangerousGetAddress()); + } + } + /// /// 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 @@ -1089,8 +1155,14 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec public static bool PyDeferFinalization(IPythonDerivedType obj) { var self = GetPyObj(obj); - return ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference) - && Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); + if (!ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference) + || !Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference)) + { + return false; + } + // finalized again once nothing references it, which runs the base type's finalizer + GC.ReRegisterForFinalize(obj); + return true; } public static void PyFinalize(IPythonDerivedType obj) @@ -1110,7 +1182,8 @@ public static void PyFinalize(IPythonDerivedType obj) /// The Python object /// - /// The .NET object, when deferred its finalization + /// The .NET object, when deferred its finalization, + /// or .NET collected it without finalizing it /// /// /// The .NET object holds a reference to the Python object, taken in tp_finalize @@ -1130,8 +1203,6 @@ internal static void Finalize(IntPtr derived, object? deferred = null, bool kept { ClassDerivedObject.ReturnToPython(ob, deferred); } - // finalized once nothing references it, which runs the base type's finalizer - GC.ReRegisterForFinalize(deferred); return; } diff --git a/src/runtime/Types/MetaType.cs b/src/runtime/Types/MetaType.cs index 34a070c3b..8a2f20445 100644 --- a/src/runtime/Types/MetaType.cs +++ b/src/runtime/Types/MetaType.cs @@ -259,7 +259,9 @@ public static int tp_setattro(BorrowedReference tp, BorrowedReference name, Borr { BorrowedReference dt = Runtime.PyObject_TYPE(descr); - if (dt == Runtime.PyWrapperDescriptorType + // __del__ wraps the tp_finalize of a __namespace__ subclass: Python code may replace it, + // as it can define one on any class + if ((dt == Runtime.PyWrapperDescriptorType && Runtime.GetManagedString(name) != "__del__") || dt == Runtime.PyMethodType || typeof(ExtensionType).IsInstanceOfType(GetManagedObject(descr)) ) diff --git a/tests/test_subclass.py b/tests/test_subclass.py index 9d3c93141..e02dd1dc5 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -670,6 +670,100 @@ def __init__(self): assert sys.getrefcount(TakenBack) == refcount +def test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another(): + class Node(System.Object): + __namespace__ = "test_namespaced_subclass_cycle_passed_from_one_net_owner_to_another" + + refcount = sys.getrefcount(Node) + parents = List[System.Object]() + children = List[System.Object]() + parent, child = Node(), Node() + parent.child, child.parent = child, parent + child.code = 41 + parents.Add(parent) + del parent, child + _release_python_and_net_objects() + + # the child isn't read back from .NET before Python lets go of the cycle again + children.Add(parents[0].child) + parents.Clear() + _release_python_and_net_objects() + assert children[0].code == 41 + assert children[0].parent.child is children[0] + + children.Clear() + _release_python_and_net_objects() + assert sys.getrefcount(Node) == refcount + + +def test_namespaced_subclass_cycle_with_suppressed_finalizer_is_collected(): + import gc + from System.IO import MemoryStream + + class ClosedStream(MemoryStream): + __namespace__ = "test_namespaced_subclass_cycle_with_suppressed_finalizer_is_collected" + + class Payload: + pass + + def payloads(): + return sum(1 for o in gc.get_objects() if type(o) is Payload) + + held = List[System.Object]() + for hold in (False, True): + stream = ClosedStream() + stream.me = stream + stream.payload = Payload() + # suppresses the .NET finalizer + stream.Close() + if hold: + held.Add(stream) + del stream + + _release_python_and_net_objects() + assert payloads() == 1 + assert type(held[0].payload) is Payload + assert held[0].me is held[0] + + held.Clear() + _release_python_and_net_objects() + assert payloads() == 0 + + +def test_namespaced_subclass_with_suppressed_finalizer_resurrected_by_python_keeps_net_object(): + from System.IO import MemoryStream + + class Resurrected(MemoryStream): + __namespace__ = "test_namespaced_subclass_with_suppressed_finalizer_resurrected_by_python_keeps_net_object" + + def __init__(self): + self.code = 7 + # suppresses the .NET finalizer + self.Close() + + survivors = [] + _resurrect_through_python(Resurrected, survivors) + + _release_python_and_net_objects() + assert survivors[0].GetType().Name == "Resurrected" + assert survivors[0].code == 7 + assert not survivors[0].CanRead + + +def test_namespaced_subclass_del_can_be_assigned(): + class AssignedDel(System.Object): + __namespace__ = "test_namespaced_subclass_del_can_be_assigned" + + class PlainSubclass(AssignedDel): + pass + + calls = [] + for cls in (AssignedDel, PlainSubclass): + cls.__del__ = lambda self, cls=cls: calls.append(cls) + cls().__del__() + assert calls == [AssignedDel, PlainSubclass] + + @pytest.mark.parametrize("cycle", ["none", "self", "resurrected"]) def test_namespaced_subclass_runs_base_finalizer_once(cycle): from Python.Test import FinalizedConstructorTest From fe5f8095a3ed72db1d5727da9ca2165f7df462ab Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:42:51 +0000 Subject: [PATCH 6/7] Keep only the __del__ assignment and .NET owner handoff fixes As decided on the pull request, the closed stream case is left for #186: this removes the finalizable object that released a .NET object's Python reference when .NET collected it unfinalized, and the deferred finalizer's re-registration goes back to the queued cleanup. Assigning __del__ is allowed only over the wrapper a __namespace__ class declares, since its tp_finalize adds it. Co-Authored-By: Claude Opus 5.5 --- src/runtime/Types/ClassDerived.cs | 78 ++++--------------------------- src/runtime/Types/MetaType.cs | 23 +++++++-- tests/test_subclass.py | 54 --------------------- 3 files changed, 29 insertions(+), 126 deletions(-) diff --git a/src/runtime/Types/ClassDerived.cs b/src/runtime/Types/ClassDerived.cs index 87e965ed0..f11a179da 100644 --- a/src/runtime/Types/ClassDerived.cs +++ b/src/runtime/Types/ClassDerived.cs @@ -7,7 +7,6 @@ using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Threading; using Python.Runtime.Native; @@ -37,12 +36,9 @@ internal class ClassDerivedObject : ClassObject private static Dictionary, ModuleBuilder> moduleBuilders; /// - /// Python objects whose .NET object holds one reference to them, taken in , - /// with the id of the that releases it if .NET collects that object - /// without finalizing it + /// Python objects whose .NET object holds one reference to them, taken in /// - private static readonly Dictionary KeptByManagedObject = new(); - private static long lastKeptReferenceId; + private static readonly HashSet KeptByManagedObject = new(); /// /// Python objects that took back the reference their .NET object kept, in , /// while .NET may already be finalizing that .NET object @@ -65,54 +61,6 @@ internal class ClassDerivedObject : ClassObject /// this keeps it alive as long as the .NET object /// private static readonly ConditionalWeakTable WeaklyHeldWrappers = new(); - /// - /// Keeps the of a .NET object alive as long as that object - /// - private static readonly ConditionalWeakTable KeptReferences = new(); - - /// - /// Releases the reference a .NET object kept in once .NET collected - /// that object without finalizing it, such as after . - /// Holding the .NET object, this gives it back to Python if Python still references it. - /// - private sealed class KeptReference - { - private readonly IntPtr ob; - private readonly object inst; - private readonly int run = Runtime.GetRun(); - public readonly long Id = Interlocked.Increment(ref lastKeptReferenceId); - private bool waited; - - public KeptReference(IntPtr ob, object inst) - { - this.ob = ob; - this.inst = inst; - } - - ~KeptReference() - { - // .NET may finalize this along with the .NET object, whose finalizer takes the reference: - // until that finalizer ran, the .NET object keeps this alive through the next collection - if (!waited) - { - waited = true; - GC.ReRegisterForFinalize(this); - return; - } - lock (KeptLock) - { - // otherwise, Python or the .NET object's finalizer took the reference - if (!KeptByManagedObject.TryGetValue(ob, out long id) || id != Id) - { - return; - } - KeptByManagedObject.Remove(ob); - ReturnedToPython.Add(ob); - } - IntPtr pyObj = ob; - Finalizer.Instance.AddDerivedFinalizedObject(ref pyObj, run, inst, keptReference: true); - } - } static ClassDerivedObject() { @@ -131,7 +79,6 @@ public static void Reset() ReturnedToPython.Clear(); } WeaklyHeldWrappers.Clear(); - KeptReferences.Clear(); } internal ClassDerivedObject(Type tp) : base(tp) @@ -184,7 +131,7 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo /// 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 or collected. + /// reference back in , and the .NET object releases it when it's finalized. /// public static void tp_finalize(BorrowedReference ob) { @@ -214,12 +161,10 @@ 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); - var kept = new KeptReference(ob.DangerousGetAddress(), self.inst); lock (KeptLock) { - KeptByManagedObject[ob.DangerousGetAddress()] = kept.Id; + KeptByManagedObject.Add(ob.DangerousGetAddress()); } - KeptReferences.AddOrUpdate(self.inst, kept); // 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, bool) takes // the .NET object back after its finalizer ran. @@ -1155,14 +1100,8 @@ public static void InvokeCtor(IPythonDerivedType obj, string origCtorName, objec public static bool PyDeferFinalization(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; - } - // finalized again once nothing references it, which runs the base type's finalizer - GC.ReRegisterForFinalize(obj); - return true; + return ClassDerivedObject.DeferFinalization(self.RawObj, out bool keptReference) + && Finalizer.Instance.AddDerivedFinalizedObject(ref self.RawObj, self.Run, obj, keptReference); } public static void PyFinalize(IPythonDerivedType obj) @@ -1182,8 +1121,7 @@ public static void PyFinalize(IPythonDerivedType obj) /// The Python object /// - /// The .NET object, when deferred its finalization, - /// or .NET collected it without finalizing it + /// The .NET object, when deferred its finalization /// /// /// The .NET object holds a reference to the Python object, taken in tp_finalize @@ -1203,6 +1141,8 @@ internal static void Finalize(IntPtr derived, object? deferred = null, bool kept { ClassDerivedObject.ReturnToPython(ob, deferred); } + // finalized once nothing references it, which runs the base type's finalizer + GC.ReRegisterForFinalize(deferred); return; } diff --git a/src/runtime/Types/MetaType.cs b/src/runtime/Types/MetaType.cs index 8a2f20445..0c9977eb5 100644 --- a/src/runtime/Types/MetaType.cs +++ b/src/runtime/Types/MetaType.cs @@ -244,6 +244,25 @@ public static NewReference tp_call(BorrowedReference tp, BorrowedReference args, : default; } + /// + /// The __del__ that wraps the tp_finalize of a __namespace__ subclass. Python code may replace it, + /// as it can define one on any class. + /// + private static bool IsDerivedClassFinalizer(BorrowedReference descr, BorrowedReference name) + { + if (Runtime.GetManagedString(name) != "__del__") + { + return false; + } + using var declaringType = Runtime.PyObject_GetAttrString(descr, "__objclass__"); + if (declaringType.IsNull()) + { + Exceptions.Clear(); + return false; + } + return GetManagedObject(declaringType.Borrow()) is ClassDerivedObject; + } + /// /// Type __setattr__ implementation for reflected types. Note that this /// is slightly different than the standard setattr implementation for @@ -259,9 +278,7 @@ public static int tp_setattro(BorrowedReference tp, BorrowedReference name, Borr { BorrowedReference dt = Runtime.PyObject_TYPE(descr); - // __del__ wraps the tp_finalize of a __namespace__ subclass: Python code may replace it, - // as it can define one on any class - if ((dt == Runtime.PyWrapperDescriptorType && Runtime.GetManagedString(name) != "__del__") + if ((dt == Runtime.PyWrapperDescriptorType && !IsDerivedClassFinalizer(descr, name)) || dt == Runtime.PyMethodType || typeof(ExtensionType).IsInstanceOfType(GetManagedObject(descr)) ) diff --git a/tests/test_subclass.py b/tests/test_subclass.py index e02dd1dc5..ef1cb4833 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -696,60 +696,6 @@ class Node(System.Object): assert sys.getrefcount(Node) == refcount -def test_namespaced_subclass_cycle_with_suppressed_finalizer_is_collected(): - import gc - from System.IO import MemoryStream - - class ClosedStream(MemoryStream): - __namespace__ = "test_namespaced_subclass_cycle_with_suppressed_finalizer_is_collected" - - class Payload: - pass - - def payloads(): - return sum(1 for o in gc.get_objects() if type(o) is Payload) - - held = List[System.Object]() - for hold in (False, True): - stream = ClosedStream() - stream.me = stream - stream.payload = Payload() - # suppresses the .NET finalizer - stream.Close() - if hold: - held.Add(stream) - del stream - - _release_python_and_net_objects() - assert payloads() == 1 - assert type(held[0].payload) is Payload - assert held[0].me is held[0] - - held.Clear() - _release_python_and_net_objects() - assert payloads() == 0 - - -def test_namespaced_subclass_with_suppressed_finalizer_resurrected_by_python_keeps_net_object(): - from System.IO import MemoryStream - - class Resurrected(MemoryStream): - __namespace__ = "test_namespaced_subclass_with_suppressed_finalizer_resurrected_by_python_keeps_net_object" - - def __init__(self): - self.code = 7 - # suppresses the .NET finalizer - self.Close() - - survivors = [] - _resurrect_through_python(Resurrected, survivors) - - _release_python_and_net_objects() - assert survivors[0].GetType().Name == "Resurrected" - assert survivors[0].code == 7 - assert not survivors[0].CanRead - - def test_namespaced_subclass_del_can_be_assigned(): class AssignedDel(System.Object): __namespace__ = "test_namespaced_subclass_del_can_be_assigned" From 5ab558b90e2c44789f0146158eb0e26d22974d6d Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:22:07 +0000 Subject: [PATCH 7/7] Assign the subclass's __del__ first in the __del__ assignment test Co-Authored-By: Claude Opus 5.5 --- tests/test_subclass.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_subclass.py b/tests/test_subclass.py index ef1cb4833..c85575d9a 100644 --- a/tests/test_subclass.py +++ b/tests/test_subclass.py @@ -703,11 +703,12 @@ class AssignedDel(System.Object): class PlainSubclass(AssignedDel): pass + # the subclass first, so its assignment replaces the inherited __del__ rather than one assigned in Python calls = [] - for cls in (AssignedDel, PlainSubclass): + for cls in (PlainSubclass, AssignedDel): cls.__del__ = lambda self, cls=cls: calls.append(cls) cls().__del__() - assert calls == [AssignedDel, PlainSubclass] + assert calls == [PlainSubclass, AssignedDel] @pytest.mark.parametrize("cycle", ["none", "self", "resurrected"])