Skip to content

PyObject finalizer #692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
8083f3b
Finalizer for PyObject
amos402 Jun 23, 2018
af33e74
Avoid test interdependency
amos402 Jun 24, 2018
6d9f897
Add source to .csproj
amos402 Jun 24, 2018
7140fd0
Make sure recover the environment
amos402 Jun 24, 2018
f66697d
Add StackTrace of C# exception
amos402 Jun 24, 2018
799d37e
Clean up the test and interface
amos402 Jun 24, 2018
cb55163
Update CHANGELOG.md
amos402 Jun 24, 2018
bfc0392
Mono doesn't have GC.WaitForFullGCComplete
amos402 Jun 24, 2018
59b614d
Fixed PythonException leak
amos402 Jun 25, 2018
569cd94
Merge branch 'master' into pyobject-finalizer
den-run-ai Jul 5, 2018
f4f5032
Fixed nPython.exe crash on Shutdown
amos402 Jul 10, 2018
0967a12
Merge branch 'master' into pyobject-finalizer
filmor Jul 17, 2018
f071c55
Add error handler
amos402 Aug 4, 2018
cfda491
Merge branch 'master' into pyobject-finalizer
amos402 Aug 4, 2018
f6c6e42
Merge branch 'master' into pyobject-finalizer
filmor Aug 30, 2018
0d96641
Make collect callback without JIT
amos402 Sep 6, 2018
34713f7
Merge branch 'master' into pyobject-finalizer
filmor Oct 16, 2018
b4e30ac
Merge branch 'master' into pyobject-finalizer
filmor Oct 17, 2018
f836ffa
Merge remote-tracking branch 'remotes/upstream/master' into pyobject-…
amos402 Oct 20, 2018
a4bb82d
Add pending marker
amos402 Oct 23, 2018
21da86d
Merge branch 'master' into pyobject-finalizer
amos402 Oct 24, 2018
5254c65
Remove PYTHONMALLOC setting
amos402 Oct 25, 2018
916e85e
Merge remote-tracking branch 'remotes/upstream/master' into pyobject-…
amos402 Nov 22, 2018
eee3683
Fix ref count error
amos402 Nov 22, 2018
cee8e17
Add ref count check for helping discover the bugs of decref too much
amos402 Nov 22, 2018
247e2d9
Fix ref count error
amos402 Nov 25, 2018
90c67ca
typo error
amos402 Nov 26, 2018
6d68d70
Merge branch 'master' into pyobject-finalizer
filmor Mar 6, 2019
4eff81e
Merge branch 'master' into pyobject-finalizer
filmor Mar 29, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,12 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
- Catches exceptions thrown in C# iterators (yield returns) and rethrows them in python ([#475][i475])([#693][p693])
- Implemented GetDynamicMemberNames() for PyObject to allow dynamic object members to be visible in the debugger ([#443][i443])([#690][p690])
- Incorporated reference-style links to issues and pull requests in the CHANGELOG ([#608][i608])
- Added PyObject finalizer support, Python objects referred by C# can be auto collect now ([#692][p692]).
- Added detailed comments about aproaches and dangers to handle multi-app-domains ([#625][p625])
- Python 3.7 support, builds and testing added. Defaults changed from Python 3.6 to 3.7 ([#698][p698])

### Changed
- PythonException included C# call stack

- Reattach python exception traceback information (#545)
- PythonEngine.Intialize will now call `Py_InitializeEx` with a default value of 0, so signals will not be configured by default on embedding. This is different from the previous behaviour, where `Py_Initialize` was called instead, which sets initSigs to 1. ([#449][i449])
Expand Down
1 change: 1 addition & 0 deletions src/embed_tests/Python.EmbeddingTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@
<Compile Include="TestCustomMarshal.cs" />
<Compile Include="TestDomainReload.cs" />
<Compile Include="TestExample.cs" />
<Compile Include="TestFinalizer.cs" />
<Compile Include="TestPyAnsiString.cs" />
<Compile Include="TestPyFloat.cs" />
<Compile Include="TestPyInt.cs" />
Expand Down
239 changes: 239 additions & 0 deletions src/embed_tests/TestFinalizer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
using NUnit.Framework;
using Python.Runtime;
using System;
using System.Linq;
using System.Threading;

namespace Python.EmbeddingTest
{
public class TestFinalizer
{
private int _oldThreshold;

[SetUp]
public void SetUp()
{
_oldThreshold = Finalizer.Instance.Threshold;
PythonEngine.Initialize();
Exceptions.Clear();
}

[TearDown]
public void TearDown()
{
Finalizer.Instance.Threshold = _oldThreshold;
PythonEngine.Shutdown();
}

private static void FullGCCollect()
{
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
}

[Test]
public void CollectBasicObject()
{
Assert.IsTrue(Finalizer.Instance.Enable);

int thId = Thread.CurrentThread.ManagedThreadId;
Finalizer.Instance.Threshold = 1;
bool called = false;
EventHandler<Finalizer.CollectArgs> handler = (s, e) =>
{
Assert.AreEqual(thId, Thread.CurrentThread.ManagedThreadId);
Assert.GreaterOrEqual(e.ObjectCount, 1);
called = true;
};

WeakReference shortWeak;
WeakReference longWeak;
{
MakeAGarbage(out shortWeak, out longWeak);
}
FullGCCollect();
// The object has been resurrected
Assert.IsFalse(shortWeak.IsAlive);
Assert.IsTrue(longWeak.IsAlive);

{
var garbage = Finalizer.Instance.GetCollectedObjects();
Assert.NotZero(garbage.Count);
Assert.IsTrue(garbage.Any(T => ReferenceEquals(T.Target, longWeak.Target)));
}

Assert.IsFalse(called);
Finalizer.Instance.CollectOnce += handler;
try
{
Finalizer.Instance.CallPendingFinalizers();
}
finally
{
Finalizer.Instance.CollectOnce -= handler;
}
Assert.IsTrue(called);
}

private static void MakeAGarbage(out WeakReference shortWeak, out WeakReference longWeak)
{
PyLong obj = new PyLong(1024);
shortWeak = new WeakReference(obj);
longWeak = new WeakReference(obj, true);
obj = null;
}

private static long CompareWithFinalizerOn(PyObject pyCollect, bool enbale)
{
// Must larger than 512 bytes make sure Python use
string str = new string('1', 1024);
Finalizer.Instance.Enable = true;
FullGCCollect();
FullGCCollect();
pyCollect.Invoke();
Finalizer.Instance.Collect();
Finalizer.Instance.Enable = enbale;

// Estimate unmanaged memory size
long before = Environment.WorkingSet - GC.GetTotalMemory(true);
for (int i = 0; i < 10000; i++)
{
// Memory will leak when disable Finalizer
new PyString(str);
}
FullGCCollect();
FullGCCollect();
pyCollect.Invoke();
if (enbale)
{
Finalizer.Instance.Collect();
}

FullGCCollect();
FullGCCollect();
long after = Environment.WorkingSet - GC.GetTotalMemory(true);
return after - before;

}

/// <summary>
/// Because of two vms both have their memory manager,
/// this test only prove the finalizer has take effect.
/// </summary>
[Test]
[Ignore("Too many uncertainties, only manual on when debugging")]
public void SimpleTestMemory()
{
bool oldState = Finalizer.Instance.Enable;
try
{
using (PyObject gcModule = PythonEngine.ImportModule("gc"))
using (PyObject pyCollect = gcModule.GetAttr("collect"))
{
long span1 = CompareWithFinalizerOn(pyCollect, false);
long span2 = CompareWithFinalizerOn(pyCollect, true);
Assert.Less(span2, span1);
}
}
finally
{
Finalizer.Instance.Enable = oldState;
}
}

class MyPyObject : PyObject
{
public MyPyObject(IntPtr op) : base(op)
{
}

protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
GC.SuppressFinalize(this);
throw new Exception("MyPyObject");
}
internal static void CreateMyPyObject(IntPtr op)
{
Runtime.Runtime.XIncref(op);
new MyPyObject(op);
}
}

[Test]
public void ErrorHandling()
{
bool called = false;
EventHandler<Finalizer.ErrorArgs> handleFunc = (sender, args) =>
{
called = true;
Assert.AreEqual(args.Error.Message, "MyPyObject");
};
Finalizer.Instance.Threshold = 1;
Finalizer.Instance.ErrorHandler += handleFunc;
try
{
WeakReference shortWeak;
WeakReference longWeak;
{
MakeAGarbage(out shortWeak, out longWeak);
var obj = (PyLong)longWeak.Target;
IntPtr handle = obj.Handle;
shortWeak = null;
longWeak = null;
MyPyObject.CreateMyPyObject(handle);
obj.Dispose();
obj = null;
}
FullGCCollect();
Finalizer.Instance.Collect();
Assert.IsTrue(called);
}
finally
{
Finalizer.Instance.ErrorHandler -= handleFunc;
}
}

[Test]
public void ValidateRefCount()
{
if (!Finalizer.Instance.RefCountValidationEnabled)
{
Assert.Pass("Only run with FINALIZER_CHECK");
}
IntPtr ptr = IntPtr.Zero;
bool called = false;
Finalizer.IncorrectRefCntHandler handler = (s, e) =>
{
called = true;
Assert.AreEqual(ptr, e.Handle);
Assert.AreEqual(2, e.ImpactedObjects.Count);
// Fix for this test, don't do this on general environment
Runtime.Runtime.XIncref(e.Handle);
return false;
};
Finalizer.Instance.IncorrectRefCntResolver += handler;
try
{
ptr = CreateStringGarbage();
FullGCCollect();
Assert.Throws<Finalizer.IncorrectRefCountException>(() => Finalizer.Instance.Collect());
Assert.IsTrue(called);
}
finally
{
Finalizer.Instance.IncorrectRefCntResolver -= handler;
}
}

private static IntPtr CreateStringGarbage()
{
PyString s1 = new PyString("test_string");
// s2 steal a reference from s1
PyString s2 = new PyString(s1.Handle);
return s1.Handle;
}

}
}
1 change: 1 addition & 0 deletions src/embed_tests/TestPyAnsiString.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public void TestCtorPtr()
const string expected = "foo";

var t = new PyAnsiString(expected);
Runtime.Runtime.XIncref(t.Handle);
var actual = new PyAnsiString(t.Handle);

Assert.AreEqual(expected, actual.ToString());
Expand Down
1 change: 1 addition & 0 deletions src/embed_tests/TestPyFloat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public void Dispose()
public void IntPtrCtor()
{
var i = new PyFloat(1);
Runtime.Runtime.XIncref(i.Handle);
var ii = new PyFloat(i.Handle);
Assert.AreEqual(i.Handle, ii.Handle);
}
Expand Down
2 changes: 2 additions & 0 deletions src/embed_tests/TestPyInt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ public void TestCtorSByte()
public void TestCtorPtr()
{
var i = new PyInt(5);
Runtime.Runtime.XIncref(i.Handle);
var a = new PyInt(i.Handle);
Assert.AreEqual(5, a.ToInt32());
}
Expand All @@ -94,6 +95,7 @@ public void TestCtorPtr()
public void TestCtorPyObject()
{
var i = new PyInt(5);
Runtime.Runtime.XIncref(i.Handle);
var a = new PyInt(i);
Assert.AreEqual(5, a.ToInt32());
}
Expand Down
2 changes: 2 additions & 0 deletions src/embed_tests/TestPyLong.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ public void TestCtorDouble()
public void TestCtorPtr()
{
var i = new PyLong(5);
Runtime.Runtime.XIncref(i.Handle);
var a = new PyLong(i.Handle);
Assert.AreEqual(5, a.ToInt32());
}
Expand All @@ -110,6 +111,7 @@ public void TestCtorPtr()
public void TestCtorPyObject()
{
var i = new PyLong(5);
Runtime.Runtime.XIncref(i.Handle);
var a = new PyLong(i);
Assert.AreEqual(5, a.ToInt32());
}
Expand Down
Loading