Add soft shutdown by amos402 · Pull Request #958 · pythonnet/pythonnet
Repository navigation
Add soft shutdown - #958
Merged
lostmsu merged 163 commits into pythonnet:master from amos402:soft-shutdown Oct 8, 2020
Merged
Add soft shutdown #958 lostmsu merged 163 commits into pythonnet:master from amos402:soft-shutdown
Conversation
amos402 commented Sep 17, 2019 · edited Loading
Copy link Copy Markdown
Member
What does this implement/fix? Explain your changes.
An upgraded version for #754
An implementation for #957
Also included some minor fixes.
Still simple and roughly, reset all GC objects by a save state, the old domain objects will be leaking and unaccessible.
Here's my next plan, I think I can replace all the clr objects slots to solid callbacks, that may help the memory leaking.
How to use: use PythonEngine.Initialize(softShutdown: true) for startup.
Updated Details:
- Changes from above: objects in GC chains will not remove by default, it can be setting by
RuntimeState.ShouldRestoreObjects, and modules which not insys.modulesafter just call initial CPython will be remove fromsys.moduleson soft shutdown mode. - Multiple fixes about memory leaks and reference count errors.
- The heap types which represent managed types will degenerate to normal type objects by set their slot callbacks to some function that builtin CPython regardless of normal mode or soft shutdown mode. Before their degenerations, through using
tp_traveseandtp_clearto release their sub objects, then useSlotsHolder.ReleaseTypeSlotsreset their slots.
Points can be optimize for the above mechanism:tp_traveseandtp_clearare not necessary for all time, they will become overhead for CPython's GC, maybe we can just use C# methods instead.- Maybe name of
SlotsHolderis not suitable because it also handle the memory release.
tp_is_gcand some other slots are no need to be override at start, they can inherit fromPyType_Typeby default.Interopdo not holding the delegate objects by callingGetThunkanymore, theSlotsHolderwill take care of them.__import__will restore at shutdown.
Does this close any currently open issues?
Any other comments?
Checklist
Check all those that are applicable and complete.
- Make sure to include one or more tests for your change
- If an enhancement PR, please create docs and at best an example
- Add yourself to
AUTHORS - Updated the
CHANGELOG
Drop LoadLibrary dependency
d1928dc
Explain for getting _PyObject_NextNotImplemented
f000e08
Update changelog and authors
f882400
Merge branch 'master' into drop-dlopen
b7715ee
Merge remote-tracking branch 'remotes/upstream/master' into drop-dlopen
41ac665
Merge branch 'master' into drop-dlopen
c6dae9e
Add soft shutdown
4e19a4f
lostmsu commented Sep 17, 2019
Copy link Copy Markdown
Member
|
Can you explain how does soft shutdown work in more details? |
amos402 commented Sep 17, 2019
Copy link Copy Markdown
Member
Author
|
The base concept is, after |
benoithudson commented Sep 17, 2019
Copy link Copy Markdown
Contributor
|
I'm unsure how this relates to #957 . Seems to be more about improving the GC handling? The prototype that @BadSingleton did was, in implementation, fairly simple (took us a while to figure it out of course):
|
amos402 commented Sep 18, 2019
Copy link Copy Markdown
Member
Author
|
Well, Python crash is connect with GC handling, after domain unload, when the GC collect occurred, it will traverse all GC objects, but the memory from old domain has been invalid, any access will result to crash. |
* Fix refcnt error
657452e
* Keep delegate of Thunk in tp_dict * Remove useless code
Fixed leaking of tp_name
91f64b9
* Reset type slots
b07b844
* Fix ref error at PythoneEngine.With
Clear ExtensionType
7db724e
Del SlotsHolder from tp_dict when shutting down
2a88be4
Fix refcnt error of qualname
2940973
Since ClassBase not override tp_init for BaseException, repr(Exceptio...
d108913
...nObject) will not care 'u' on Python2.
* Use environment variable PYTHONNET_SOFT_SHUTDOWN to enable soft s...
cc9e7e5
...hutdown forcedly * Disable restore objects on default
Fixed deadlock on finalizer after shutdown
1cb8e8c
lostmsu
reviewed
Oct 23, 2019
View reviewed changes
Comment thread src/runtime/classmanager.cs
Outdated
| cache = new Dictionary<Type, ClassBase>(128); | ||
| } | ||
|
|
||
| public static IList<ClassBase> GetManagedTypes() |
Outdated
| IntPtr py = Runtime.PyType_GenericAlloc(tp, 0); | ||
|
|
||
| GCHandle gc = GCHandle.Alloc(this ); | ||
| GCHandle gc = AllocGCHandle(true ); |
Outdated
Comment on lines +267 to +275
| private static IntPtr GetObjectDict(IntPtr ob) | ||
| { | ||
| return Marshal.ReadIntPtr(ob, ObjectOffset.DictOffset(ob)); | ||
| } | ||
|
|
||
| private static void SetObjectDict(IntPtr ob, IntPtr value) | ||
| { | ||
| Marshal.WriteIntPtr(ob, ObjectOffset.DictOffset(ob), value); | ||
| } |
Outdated
| var gc = PyImport_ImportModule("gc"); | ||
| var get_objects = PyObject_GetAttrString(gc, "get_objects"); | ||
| var objs = PyObject_CallObject(get_objects, IntPtr.Zero); | ||
| var length = PyList_Size(objs); |
benoithudson commented Nov 7, 2019 · edited Loading
Copy link Copy Markdown
Contributor
|
I've summarized my understanding in this document: https://docs.google.com/document/d/1a9OLsdKHXJ6MxHjo0WlVRcfjAiaP5hONNKUKKH6Tr-o I see two PRs that would be easy to pull out of amos' code and check in right now:
I don't yet understand what the gc chains thing is trying to address. I also don't understand how amos handles the modules. I suspect they're related. It seems like amos is turning off python gc for the proxy objects. If that works, we should just turn it all off and then we can eliminate the native code page. But that's yet another PR. There seems to be some refcount fixes as well. If we can get those fixes in separate PRs that makes it easier to review. |
View reviewed changes
amos402 mentioned this pull request Nov 30, 2019 Transfer the ownership of method's thunk to caller(split from #958) #1003 Merged 4 tasks amos402 added 2 commits December 1, 2019 21:32
Merge branch 'master' into drop-dlopen
653a263
* Load PyModuleType without LibraryLoader
b3e889b
* Drop C module dependency when getting _PyObject_NextNotImplemented * Exception details for SetNoSiteFlagfilmor pushed a commit that referenced this pull request Dec 2, 2019
Fix refcnt errors (split from #958) (#1001)
5f56ebc
* Add exception helper * Fixed refcnt error in ExtensionType.FinalizeObject * Fixed typename leaking * Fix refcnt error by using `using`amos402 added 2 commits December 15, 2019 02:26
Merge remote-tracking branch 'remotes/upstream/master' into drop-dlop...
04d6dfb
...en-2
Prevent exception override
5150e61
amos402
added 3 commits
September 10, 2020 15:23
Revert local changes
fa89b48
Remove unused code
80a7644
Merge pull request #3 from Unity-Technologies/soft-shutdown-review-co...
12c0206
...mments-2 Soft shutdown review comments 2lostmsu reviewed Sep 13, 2020
View reviewed changes
Comment thread src/runtime/BorrowedReference.cs
Outdated
| /// <summary>Gets a raw pointer to the Python object</summary> | ||
| public IntPtr DangerousGetAddress() | ||
| => this.IsNull ? throw new NullReferenceException() : this.pointer; | ||
| public IntPtr DangerousGetAddress() => this.pointer; |
| if (_isInitialized) | ||
| { | ||
| return; | ||
| } | ||
| _isInitialized = true; |
Outdated
|
|
||
| // Initialize modules that depend on the runtime class. | ||
| AssemblyManager.Initialize(); | ||
| #if !NETSTANDARD |
Outdated
| Marshal.WriteIntPtr(mem, (IntPtr)ms.Length); | ||
| Marshal.Copy(data, 0, mem + IntPtr.Size, (int)ms.Length); | ||
|
|
||
| IntPtr capsule = PySys_GetObject("clr_data").DangerousGetAddress(); |
Adds an unchecked version to get a BorrowedReference pointer
6a3cfc8
And other code review changes
Remove compile-time check on NETSTANDARD
98da1fa
Even if netstandard lacks (for now) the necessary APIs for domain (un)loading, it is still possible to (un)load domains via the Mono C runtime.
fixup! Remove compile-time check on NETSTANDARD
d7d44e8
Factor out the clearing of clr_data
6aa75c5
In Runtime_data.cs
Partially Revert "Adds an unchecked version to get a BorrowedReferenc...
2343f89
...e pointer" We Don't support python 2 anymore, but the CI machines may still be using it to build.
More changes to use BorrowedReference and NewReference
cc6b8e4
Also adds implicit IntPtr conversion operators to simplify their use.
fixup! More changes to use BorrowedReference and NewReference
d5fcfa4
fixup! fixup! More changes to use BorrowedReference and NewReference
fa47957
Remove unused method
ff956e4
Merge pull request #4 from Unity-Technologies/soft-shutdown-review-co...
c7b134c
...mments-3 * Remove compile-time check on NETSTANDARD * Extract method `ClearCLRData`
lostmsu commented Sep 29, 2020
Copy link Copy Markdown
Member
|
@BadSingleton / @amos402 can you please merge from master? |
Merge branch 'master' into soft-shutdown
97e61a5
Wait for full GC Complete
0b9d2c1
Release atexit manually
178cbc8
* Remove fromPython
3a17f36
* Fix dead lock occur by calling PyEval_RestoreThread without check * Ignore `CollectOnShutdown` temporarily
Merge branch 'master' into soft-shutdown
3203457
Merge branch 'master' into soft-shutdown
8d00e4c
codecov-io commented Oct 8, 2020 · edited Loading
Copy link Copy Markdown
Codecov Report
@@ Coverage Diff @@ ## master #958 +/- ## ======================================= Coverage 86.25% 86.25% ======================================= Files 1 1 Lines 291 291 ======================================= Hits 251 251 Misses 40 40
Flags with carried forward coverage won't be shown. Click here to find out more. Continue to review full report at Codecov .
|
View reviewed changes
Comment thread src/embed_tests/TestFinalizer.cs Comment on lines +112 to +121
| if (!FullGCCollect()) | ||
| { | ||
| Assert.IsTrue(WaitForCollected(op, hash, 10000)); | ||
| } | ||
| Assert.IsFalse(shortWeak.IsAlive); | ||
| garbage = Finalizer.Instance.GetCollectedObjects(); | ||
| Assert.IsNotEmpty(garbage, "The garbage object should be collected"); | ||
| Assert.IsTrue(garbage.Any(r => ReferenceEquals(r.Target, longWeak.Target)), | ||
| "Garbage should contains the collected object"); | ||
|
|
View reviewed changes
lostmsu merged commit
2972f49
into
pythonnet : master
Oct 8, 2020
amos402
mentioned this pull request
Oct 9, 2020
Drop LoadLibrary
#880
Closed
2 of 4 tasks
danabr
mentioned this pull request
Oct 12, 2020
Exception in finalizer of custom encoder
#1256
Open
lostmsu
mentioned this pull request
Nov 12, 2020
Cannot run twice; Unity crashes after running more than once
#701
Closed
akaimody123
mentioned this pull request
May 1, 2021
unity3d crashes on the second run
henon/pythonnet_netstandard#18
Closed
Zulex
mentioned this pull request
Mar 4, 2022
C# jagged arrays and lists make Unity crash the second time
#1713
Open
Sign up for free
to join this conversation on GitHub .
Already have an account?
Sign in to comment