Skip to content

Commit 294da5e

Browse files
Keep a __namespace__ subclass's Python state while .NET holds it in a cycle (#176)
* 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> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * 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 <noreply@anthropic.com> * Assign the subclass's __del__ first in the __del__ assignment test Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: quantconnect-kronos[bot] <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent aa64d2a commit 294da5e

8 files changed

Lines changed: 610 additions & 17 deletions

File tree

‎src/runtime/Converter.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -552,6 +552,10 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
552552

553553
if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type))
554554
{
555+
if (tmp is IPythonDerivedType)
556+
{
557+
ClassDerivedObject.PassedToManaged(value);
558+
}
555559
result = tmp;
556560
return true;
557561
}

‎src/runtime/Finalizer.cs‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,19 +154,24 @@ internal void AddFinalizedObject(ref IntPtr obj, int run
154154
obj = IntPtr.Zero;
155155
}
156156

157-
internal void AddDerivedFinalizedObject(ref IntPtr derived, int run)
157+
/// <returns>Whether the object was queued, which it isn't while <see cref="Enable"/> is false</returns>
158+
internal bool AddDerivedFinalizedObject(ref IntPtr derived, int run, object? deferred = null, bool keptReference = false)
158159
{
159160
if (derived == IntPtr.Zero)
160161
throw new ArgumentNullException(nameof(derived));
161162

162163
if (!Enable)
163164
{
164-
return;
165+
return false;
165166
}
166167

167-
var pending = new PendingFinalization { PyObj = derived, RuntimeRun = run };
168+
var pending = new PendingFinalization
169+
{
170+
PyObj = derived, RuntimeRun = run, Deferred = deferred, KeptReference = keptReference,
171+
};
168172
derived = IntPtr.Zero;
169173
_derivedQueue.Enqueue(pending);
174+
return true;
170175
}
171176

172177
internal void AddFinalizedBuffer(ref Py_buffer buffer)
@@ -254,7 +259,7 @@ internal nint DisposeAll()
254259
}
255260

256261
#pragma warning disable CS0618 // Type or member is obsolete. OK for internal use
257-
PythonDerivedType.Finalize(derived.PyObj);
262+
PythonDerivedType.Finalize(derived.PyObj, derived.Deferred, derived.KeptReference);
258263
#pragma warning restore CS0618 // Type or member is obsolete
259264

260265
collected++;
@@ -367,6 +372,14 @@ struct PendingFinalization
367372
public IntPtr PyObj;
368373
public BorrowedReference Ref => new(PyObj);
369374
public int RuntimeRun;
375+
/// <summary>
376+
/// The .NET object of a Python derived type whose finalization waits until this is handled
377+
/// </summary>
378+
public object? Deferred;
379+
/// <summary>
380+
/// <see cref="Deferred"/> holds a reference to <see cref="PyObj"/>
381+
/// </summary>
382+
public bool KeptReference;
370383
#if TRACE_ALLOC
371384
public string StackTrace;
372385
#endif

‎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; }

0 commit comments

Comments
 (0)