Skip to content

Fix memory leaks due to spurious handle increment and add unit tests #704

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 6 commits into from
Jul 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
- Ville M. Vainio ([@vivainio](https://github.com/vivainio))
- Virgil Dupras ([@hsoft](https://github.com/hsoft))
- Wenguang Yang ([@yagweb](https://github.com/yagweb))
- William Sardar ([@williamsardar])(https://github.com/williamsardar)
- Xavier Dupré ([@sdpython](https://github.com/sdpython))
- Zane Purvis ([@zanedp](https://github.com/zanedp))
- ([@bltribble](https://github.com/bltribble))
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
- Fixed `LockRecursionException` when loading assemblies ([#627][i627])
- Fixed errors breaking .NET Remoting on method invoke ([#276][i276])
- Fixed PyObject.GetHashCode ([#676][i676])
- Fix memory leaks due to spurious handle incrementation ([#691][i691])


## [2.3.0][] - 2017-03-11
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Requirements for both Travis and AppVeyor
pytest==3.2.5
coverage
psutil

# Coverage upload
codecov
Expand Down
4 changes: 1 addition & 3 deletions src/runtime/constructorbinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public static IntPtr tp_descr_get(IntPtr op, IntPtr instance, IntPtr owner)
return Exceptions.RaiseTypeError("How in the world could that happen!");
}
}*/
Runtime.XIncref(self.pyHandle); // Decref'd by the interpreter.
Runtime.XIncref(self.pyHandle);
return self.pyHandle;
}

Expand Down Expand Up @@ -105,8 +105,6 @@ public static IntPtr mp_subscript(IntPtr op, IntPtr key)
}
var boundCtor = new BoundContructor(self.type, self.pyTypeHndl, self.ctorBinder, ci);

/* Since nothing is cached, do we need the increment???
Runtime.XIncref(boundCtor.pyHandle); // Decref'd by the interpreter??? */
return boundCtor.pyHandle;
}

Expand Down
2 changes: 0 additions & 2 deletions src/runtime/methodbinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx)
}

var mb = new MethodBinding(self.m, self.target) { info = mi };
Runtime.XIncref(mb.pyHandle);
return mb.pyHandle;
}

Expand Down Expand Up @@ -85,7 +84,6 @@ public static IntPtr tp_getattro(IntPtr ob, IntPtr key)
case "__overloads__":
case "Overloads":
var om = new OverloadMapper(self.m, self.target);
Runtime.XIncref(om.pyHandle);
return om.pyHandle;
default:
return Runtime.PyObject_GenericGetAttr(ob, key);
Expand Down
1 change: 0 additions & 1 deletion src/runtime/overload.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ public static IntPtr mp_subscript(IntPtr tp, IntPtr idx)
}

var mb = new MethodBinding(self.m, self.target) { info = mi };
Runtime.XIncref(mb.pyHandle);
return mb.pyHandle;
}

Expand Down
20 changes: 20 additions & 0 deletions src/testing/methodtest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -666,3 +666,23 @@ public string PublicMethod(string echo)
}
}
}

namespace PlainOldNamespace
{
public class PlainOldClass
{
public PlainOldClass() { }

public PlainOldClass(int param) { }

private readonly byte[] payload = new byte[(int)Math.Pow(2, 20)]; //1 MB

public void NonGenericMethod() { }

public void GenericMethod<T>() { }

public void OverloadedMethod() { }

public void OverloadedMethod(int param) { }
}
}
134 changes: 134 additions & 0 deletions src/tests/test_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,3 +832,137 @@ def test_case_sensitive():

with pytest.raises(AttributeError):
MethodTest.casesensitive()

def test_getting_generic_method_binding_does_not_leak_ref_count():
"""Test that managed object is freed after calling generic method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import sys

refCount = sys.getrefcount(PlainOldClass().GenericMethod[str])
assert refCount == 1

def test_getting_generic_method_binding_does_not_leak_memory():
"""Test that managed object is freed after calling generic method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import psutil, os, gc, clr

process = psutil.Process(os.getpid())
processBytesBeforeCall = process.memory_info().rss
print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall))

iterations = 500
for i in range(iterations):
PlainOldClass().GenericMethod[str]

gc.collect()
clr.System.GC.Collect()

processBytesAfterCall = process.memory_info().rss
print("Memory consumption (bytes) at end of test: " + str(processBytesAfterCall))
processBytesDelta = processBytesAfterCall - processBytesBeforeCall
print("Memory delta: " + str(processBytesDelta))

bytesAllocatedPerIteration = pow(2, 20) # 1MB
bytesLeakedPerIteration = processBytesDelta / iterations

# Allow 50% threshold - this shows the original issue is fixed, which leaks the full allocated bytes per iteration
failThresholdBytesLeakedPerIteration = bytesAllocatedPerIteration / 2

assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration

def test_getting_overloaded_method_binding_does_not_leak_ref_count():
"""Test that managed object is freed after calling overloaded method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import sys

refCount = sys.getrefcount(PlainOldClass().OverloadedMethod.Overloads[int])
assert refCount == 1

def test_getting_overloaded_method_binding_does_not_leak_memory():
"""Test that managed object is freed after calling overloaded method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import psutil, os, gc, clr

process = psutil.Process(os.getpid())
processBytesBeforeCall = process.memory_info().rss
print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall))

iterations = 500
for i in range(iterations):
PlainOldClass().OverloadedMethod.Overloads[int]

gc.collect()
clr.System.GC.Collect()

processBytesAfterCall = process.memory_info().rss
print("Memory consumption (bytes) at end of test: " + str(processBytesAfterCall))
processBytesDelta = processBytesAfterCall - processBytesBeforeCall
print("Memory delta: " + str(processBytesDelta))

bytesAllocatedPerIteration = pow(2, 20) # 1MB
bytesLeakedPerIteration = processBytesDelta / iterations

# Allow 50% threshold - this shows the original issue is fixed, which leaks the full allocated bytes per iteration
failThresholdBytesLeakedPerIteration = bytesAllocatedPerIteration / 2

assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration

def test_getting_method_overloads_binding_does_not_leak_ref_count():
"""Test that managed object is freed after calling overloaded method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import sys

refCount = sys.getrefcount(PlainOldClass().OverloadedMethod.Overloads)
assert refCount == 1

def test_getting_method_overloads_binding_does_not_leak_memory():
"""Test that managed object is freed after calling overloaded method. Issue #691"""

from PlainOldNamespace import PlainOldClass

import psutil, os, gc, clr

process = psutil.Process(os.getpid())
processBytesBeforeCall = process.memory_info().rss
print("\n\nMemory consumption (bytes) at start of test: " + str(processBytesBeforeCall))

iterations = 500
for i in range(iterations):
PlainOldClass().OverloadedMethod.Overloads

gc.collect()
clr.System.GC.Collect()

processBytesAfterCall = process.memory_info().rss
print("Memory consumption (bytes) at end of test: " + str(processBytesAfterCall))
processBytesDelta = processBytesAfterCall - processBytesBeforeCall
print("Memory delta: " + str(processBytesDelta))

bytesAllocatedPerIteration = pow(2, 20) # 1MB
bytesLeakedPerIteration = processBytesDelta / iterations

# Allow 50% threshold - this shows the original issue is fixed, which leaks the full allocated bytes per iteration
failThresholdBytesLeakedPerIteration = bytesAllocatedPerIteration / 2

assert bytesLeakedPerIteration < failThresholdBytesLeakedPerIteration

def test_getting_overloaded_constructor_binding_does_not_leak_ref_count():
"""Test that managed object is freed after calling overloaded constructor, constructorbinding.cs mp_subscript. Issue #691"""

from PlainOldNamespace import PlainOldClass

import sys

# simple test
refCount = sys.getrefcount(PlainOldClass.Overloads[int])
assert refCount == 1