Skip to content

Commit 4efed34

Browse files
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 <noreply@anthropic.com>
1 parent 0e25193 commit 4efed34

5 files changed

Lines changed: 225 additions & 9 deletions

File tree

‎src/runtime/Interop.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,9 @@ internal static ThunkInfo GetThunk(Delegate @delegate)
188188
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
189189
public delegate void N_V(NewReference ob);
190190

191+
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
192+
public delegate void B_V(BorrowedReference ob);
193+
191194
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
192195
public delegate int BPP_I32(BorrowedReference ob, IntPtr a1, IntPtr a2);
193196
}

‎src/runtime/Native/ITypeOffsets.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ interface ITypeOffsets
5252
int tp_descr_set { get; }
5353
int tp_dict { get; }
5454
int tp_dictoffset { get; }
55+
int tp_finalize { get; }
5556
int tp_flags { get; }
5657
int tp_free { get; }
5758
int tp_getattro { get; }

‎src/runtime/Native/TypeOffset.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ static partial class TypeOffset
5959
internal static int tp_descr_set { get; private set; }
6060
internal static int tp_dict { get; private set; }
6161
internal static int tp_dictoffset { get; private set; }
62+
internal static int tp_finalize { get; private set; }
6263
internal static int tp_flags { get; private set; }
6364
internal static int tp_free { get; private set; }
6465
internal static int tp_getattro { get; private set; }

‎src/runtime/Types/ClassDerived.cs‎

Lines changed: 98 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System.Linq;
66
using System.Reflection;
77
using System.Reflection.Emit;
8+
using System.Runtime.CompilerServices;
89
using System.Runtime.InteropServices;
910

1011
using Python.Runtime.Native;
@@ -34,6 +35,21 @@ internal class ClassDerivedObject : ClassObject
3435
private static Dictionary<string, AssemblyBuilder> assemblyBuilders;
3536
private static Dictionary<Tuple<string, string>, ModuleBuilder> moduleBuilders;
3637

38+
/// <summary>
39+
/// Python objects whose .NET object holds one reference to them, taken in <see cref="tp_finalize"/>
40+
/// </summary>
41+
internal static readonly HashSet<IntPtr> KeptByManagedObject = new();
42+
/// <summary>
43+
/// Python objects whose .NET object was finalized while it held a reference to them:
44+
/// <see cref="tp_dealloc"/> frees them
45+
/// </summary>
46+
internal static readonly HashSet<IntPtr> ReleasedByManagedObject = new();
47+
/// <summary>
48+
/// Nothing else references the wrapper of a .NET object its Python object holds weakly:
49+
/// this keeps it alive as long as the .NET object
50+
/// </summary>
51+
private static readonly ConditionalWeakTable<object, CLRObject> WeaklyHeldWrappers = new();
52+
3753
static ClassDerivedObject()
3854
{
3955
assemblyBuilders = new Dictionary<string, AssemblyBuilder>();
@@ -44,6 +60,9 @@ public static void Reset()
4460
{
4561
assemblyBuilders = new Dictionary<string, AssemblyBuilder>();
4662
moduleBuilders = new Dictionary<Tuple<string, string>, ModuleBuilder>();
63+
KeptByManagedObject.Clear();
64+
ReleasedByManagedObject.Clear();
65+
WeaklyHeldWrappers.Clear();
4766
}
4867

4968
internal ClassDerivedObject(Type tp) : base(tp)
@@ -76,20 +95,79 @@ protected override void SetTypeNewSlot(BorrowedReference pyType, SlotsHolder slo
7695
// don't let the python GC destroy this object
7796
Runtime.PyObject_GC_UnTrack(ob.Borrow());
7897

98+
if (ReleasedByManagedObject.Remove(ob.DangerousGetAddress()))
99+
{
100+
PythonDerivedType.Finalize(ob.DangerousMoveToPointer());
101+
return;
102+
}
103+
79104
// self may be null after Shutdown begun
80105
if (self is not null)
81106
{
82107
// The python should now have a ref count of 0, but we don't actually want to
83108
// deallocate the object until the C# object that references it is destroyed.
84109
// So we don't call PyObject_GC_Del here and instead we set the python
85110
// reference to a weak reference so that the C# object can be collected.
86-
GCHandle oldHandle = GetGCHandle(ob.Borrow());
87-
GCHandle gc = GCHandle.Alloc(self, GCHandleType.Weak);
88-
SetGCHandle(ob.Borrow(), gc);
89-
oldHandle.Free();
111+
ReplaceGCHandle(ob.Borrow(), self, GCHandleType.Weak);
90112
}
91113
}
92114

115+
/// <summary>
116+
/// Called by the Python cyclic GC on an object it found unreachable from Python, before it clears
117+
/// the cycle. .NET may still reference the object, which Python can't see, so instead of letting
118+
/// the cycle be cleared, the .NET object keeps one reference to the Python object, and the Python
119+
/// object stops keeping the .NET object alive, as <see cref="tp_dealloc"/> does. Python gets that
120+
/// reference back in <see cref="ToPython"/>, and the .NET object releases it when it's finalized.
121+
/// </summary>
122+
public static void tp_finalize(BorrowedReference ob)
123+
{
124+
// The GC marks an object finalized before it calls tp_finalize and doesn't call it again
125+
// once marked. Otherwise, it's a direct __del__ call from Python, which still references the object.
126+
if ((GCPrev(ob) & FinalizedFlag) == 0)
127+
{
128+
return;
129+
}
130+
131+
var self = (CLRObject?)GetManagedObject(ob);
132+
// null once the .NET object is gone: the GC frees the cycle
133+
if (self is null)
134+
{
135+
return;
136+
}
137+
138+
// the next time Python lets go of the object in a cycle, the GC has to call tp_finalize again
139+
GCPrev(ob) &= ~FinalizedFlag;
140+
Runtime.XIncref(ob);
141+
KeptByManagedObject.Add(ob.DangerousGetAddress());
142+
ReplaceGCHandle(ob, self, GCHandleType.Weak);
143+
}
144+
145+
/// <summary>
146+
/// _PyGC_PREV_MASK_FINALIZED: the GC's finalized flag in _gc_prev
147+
/// </summary>
148+
private const nint FinalizedFlag = 1;
149+
150+
/// <summary>
151+
/// _gc_prev, the last field of the GC header that precedes the object
152+
/// </summary>
153+
private static unsafe ref nint GCPrev(BorrowedReference ob)
154+
=> ref *((nint*)ob.DangerousGetAddress() - 1);
155+
156+
private static void ReplaceGCHandle(BorrowedReference ob, CLRObject self, GCHandleType type)
157+
{
158+
if (type == GCHandleType.Weak)
159+
{
160+
WeaklyHeldWrappers.AddOrUpdate(self.inst, self);
161+
}
162+
else
163+
{
164+
WeaklyHeldWrappers.Remove(self.inst);
165+
}
166+
GCHandle oldHandle = GetGCHandle(ob);
167+
SetGCHandle(ob, GCHandle.Alloc(self, type));
168+
oldHandle.Free();
169+
}
170+
93171
/// <summary>
94172
/// No-op clear. Real cleanup happens in <seealso cref="Finalize(IntPtr)"/>
95173
/// </summary>
@@ -113,6 +191,13 @@ internal static NewReference ToPython(IPythonDerivedType obj)
113191
return default;
114192
}
115193

194+
if (KeptByManagedObject.Remove(self.DangerousGetAddress()))
195+
{
196+
// Python takes over the reference the .NET object kept in tp_finalize
197+
ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal);
198+
return NewReference.DangerousFromPointer(self.DangerousGetAddress());
199+
}
200+
116201
var result = new NewReference(self);
117202

118203
// when the C# constructor creates the python object it starts as a weak
@@ -123,11 +208,7 @@ internal static NewReference ToPython(IPythonDerivedType obj)
123208
if (Runtime.Refcount(self) == 1)
124209
{
125210
Runtime._Py_NewReference(self);
126-
GCHandle weak = GetGCHandle(self);
127-
var clrObject = GetManagedObject(self);
128-
GCHandle gc = GCHandle.Alloc(clrObject, GCHandleType.Normal);
129-
SetGCHandle(self, gc);
130-
weak.Free();
211+
ReplaceGCHandle(self, (CLRObject)GetManagedObject(self)!, GCHandleType.Normal);
131212

132213
// now the object has a python reference it's safe for the python GC to track it
133214
Runtime.PyObject_GC_Track(self);
@@ -933,6 +1014,14 @@ public static void PyFinalize(IPythonDerivedType obj)
9331014

9341015
internal static void Finalize(IntPtr derived)
9351016
{
1017+
if (ClassDerivedObject.KeptByManagedObject.Remove(derived))
1018+
{
1019+
// the Python object may still be part of a cycle: Python frees it once nothing references it
1020+
ClassDerivedObject.ReleasedByManagedObject.Add(derived);
1021+
Runtime.XDecref(StolenReference.DangerousFromPointer(derived));
1022+
return;
1023+
}
1024+
9361025
var @ref = NewReference.DangerousFromPointer(derived);
9371026

9381027
ClassBase.tp_clear(@ref.Borrow());

‎tests/test_subclass.py‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,3 +305,125 @@ class Derived(BaseClass):
305305

306306
import gc
307307
gc.collect()
308+
309+
310+
def _release_python_and_net_objects():
311+
"""Collect Python cycles and .NET objects, then free the Python objects whose .NET object was finalized"""
312+
import gc
313+
from System import GC
314+
315+
for _ in range(3):
316+
gc.collect()
317+
GC.Collect()
318+
GC.WaitForPendingFinalizers()
319+
# every 200th Python object passed to .NET frees the queued ones
320+
List[System.Object]([object() for _ in range(300)])
321+
gc.collect()
322+
323+
324+
def test_namespaced_subclass_held_by_net_keeps_its_cycle():
325+
from System import String
326+
327+
class CycleHolder(System.Object):
328+
__namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_cycle"
329+
330+
def __init__(self, code):
331+
self.code = code
332+
self.me = self
333+
self.items = [self]
334+
self.items.append(self.items)
335+
336+
def ToString(self):
337+
return "holder {}".format(self.code)
338+
339+
class PythonSubclass(CycleHolder):
340+
pass
341+
342+
# each instance references its class, until it's freed
343+
refcounts = sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass)
344+
held = List[System.Object]()
345+
held.Add(CycleHolder(7))
346+
held.Add(PythonSubclass(8))
347+
348+
for _ in range(2):
349+
_release_python_and_net_objects()
350+
# .NET calls the Python override while only .NET holds the object
351+
assert String.Join[System.Object](",", held) == "holder 7,holder 8"
352+
353+
holder = held[0]
354+
assert holder.code == 7
355+
assert holder.me is holder
356+
assert holder.items[0] is holder
357+
assert held[1].code == 8
358+
del holder
359+
360+
held.Clear()
361+
_release_python_and_net_objects()
362+
assert (sys.getrefcount(CycleHolder), sys.getrefcount(PythonSubclass)) == refcounts
363+
364+
365+
def test_namespaced_subclass_cycle_is_collected():
366+
class CycleMember(System.Object):
367+
__namespace__ = "test_namespaced_subclass_cycle_is_collected"
368+
369+
def __init__(self):
370+
self.me = self
371+
372+
refcount = sys.getrefcount(CycleMember)
373+
for _ in range(100):
374+
CycleMember()
375+
first, second = CycleMember(), CycleMember()
376+
first.other, second.other = second, first
377+
del first, second
378+
379+
held = List[System.Object]()
380+
first, second = CycleMember(), CycleMember()
381+
first.other, second.other = second, first
382+
first.code = 1
383+
held.Add(second)
384+
del first, second
385+
386+
_release_python_and_net_objects()
387+
assert held[0].other.code == 1
388+
assert held[0].other.other is held[0]
389+
assert sys.getrefcount(CycleMember) == refcount + 2
390+
391+
held.Clear()
392+
_release_python_and_net_objects()
393+
assert sys.getrefcount(CycleMember) == refcount
394+
395+
396+
def test_namespaced_subclass_direct_del_call_keeps_net_object():
397+
class DirectDelCall(System.Object):
398+
__namespace__ = "test_namespaced_subclass_direct_del_call_keeps_net_object"
399+
400+
def __init__(self):
401+
self.me = self
402+
403+
instance = DirectDelCall()
404+
instance.__del__()
405+
_release_python_and_net_objects()
406+
instance.GetHashCode()
407+
assert instance.me is instance
408+
409+
410+
@pytest.mark.parametrize("in_cycle", [False, True])
411+
def test_namespaced_subclass_held_by_net_keeps_its_wrapper(in_cycle):
412+
class HeldByNet(System.Object):
413+
__namespace__ = "test_namespaced_subclass_held_by_net_keeps_its_wrapper_{}".format(in_cycle)
414+
415+
def __init__(self, code):
416+
self.code = code
417+
if in_cycle:
418+
self.me = self
419+
420+
held = List[System.Object]()
421+
held.Add(HeldByNet(7))
422+
for _ in range(2):
423+
_release_python_and_net_objects()
424+
425+
instance = held[0]
426+
assert instance.code == 7
427+
assert held.Contains(instance)
428+
assert instance.GetType().Name == "HeldByNet"
429+
del instance

0 commit comments

Comments
 (0)