Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Implement PEP 788 #133110

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

Draft
wants to merge 65 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
1828b9a
Implement interpreter state reference counting.
ZeroIntensity Apr 24, 2025
d0895f9
Add a test for interpreter reference counts.
ZeroIntensity Apr 24, 2025
5c3ee8d
Add thread state daemon-ness that doesn't work yet.
ZeroIntensity Apr 25, 2025
7b9ac59
Add untested implementation of non-daemon native threads.
ZeroIntensity Apr 25, 2025
0868c15
Add a test for PyThreadState_SetDaemon().
ZeroIntensity Apr 25, 2025
e9ea644
Add untested implementation of Ensure()/Release() that probably doesn…
ZeroIntensity Apr 25, 2025
0ebdca4
Change some comments.
ZeroIntensity Apr 25, 2025
40989de
Add a test that I'm sure doesn't work.
ZeroIntensity Apr 25, 2025
d501f35
Use the interpreter's reference count and native thread countdown as …
ZeroIntensity Apr 25, 2025
c5ec89c
Fix the countdown decrement.
ZeroIntensity Apr 26, 2025
4e1f599
Remove unused variable.
ZeroIntensity Apr 26, 2025
3127a3f
Test for PyGILState_Ensure()
ZeroIntensity Apr 26, 2025
82b5b9f
Fix the test for the new reference counting.
ZeroIntensity Apr 26, 2025
fda9886
Add PyInterpreterState_Lookup()
ZeroIntensity Apr 26, 2025
f7723c0
Fix a few bugs and add a test.
ZeroIntensity Apr 26, 2025
62e9549
Add a test for PyThreadState_Ensure() across interpreters.
ZeroIntensity Apr 27, 2025
bc60630
Remove an artifact from old approach.
ZeroIntensity Apr 28, 2025
9d8d526
Fix test from earlier semantics.
ZeroIntensity Apr 28, 2025
54b0ce0
Remove 'daemonness' as a property of a thread.
ZeroIntensity May 22, 2025
5955de6
Add strong interpreter reference functions.
ZeroIntensity May 22, 2025
92cf906
Implement weak references.
ZeroIntensity May 22, 2025
b0d0673
Fix some thread safety issues regarding interpreter deletion.
ZeroIntensity May 22, 2025
0a15beb
Merge from main branch.
ZeroIntensity May 22, 2025
16d79de
Implement new version of PyThreadState_Ensure() and PyThreadState_Rel…
ZeroIntensity May 22, 2025
c2bffcd
Use the new APIs in the tests.
ZeroIntensity May 22, 2025
911c6b5
Fix _testcapi.
ZeroIntensity May 22, 2025
b84fa90
Fix the ensure counter.
ZeroIntensity May 22, 2025
9ccf6bd
Add the test to test_embed.
ZeroIntensity May 22, 2025
481caf5
Allow the wait to be interrupted by CTRL+C.
ZeroIntensity May 22, 2025
71e1aec
Print the error before bailing out.
ZeroIntensity May 22, 2025
d661578
Updates for the new proposal.
ZeroIntensity May 28, 2025
4249c5d
Bikeshedding.
ZeroIntensity May 28, 2025
71f2fd7
Apply suggestions from code review
ZeroIntensity May 28, 2025
03ccb38
Fix failing build.
ZeroIntensity May 29, 2025
bca65fb
Rename parameter.
ZeroIntensity May 29, 2025
510ade1
Fix formatting.
ZeroIntensity May 29, 2025
3971408
Add tstate check.
ZeroIntensity May 29, 2025
6c4c52b
Move to pycore_pystate.h
ZeroIntensity May 29, 2025
64920a8
Revert "Move to pycore_pystate.h"
ZeroIntensity May 29, 2025
05436f3
Use an exponential wait time for the event.
ZeroIntensity May 29, 2025
02bc2d7
Mark function as static.
ZeroIntensity May 29, 2025
03fa2af
Update fatal error message.
ZeroIntensity May 29, 2025
b955d85
Remove incorrect assertion.
ZeroIntensity May 29, 2025
5236700
Add a comment regarding PyMem_RawMalloc()
ZeroIntensity May 29, 2025
a277130
Add a comment.
ZeroIntensity Jun 1, 2025
dac0c1a
Update Include/cpython/pystate.h
ZeroIntensity Jun 1, 2025
ab9e3b5
Merge branch 'pep-788-impl' of https://github.com/ZeroIntensity/cpyth…
ZeroIntensity Jun 1, 2025
79a1852
Move some tests around to prevent exposure of the private API.
ZeroIntensity Jun 1, 2025
47957b8
Move weakref test to internal C API.
ZeroIntensity Jun 1, 2025
771d7ed
Improve reference counting tests.
ZeroIntensity Jun 1, 2025
0c3c1c7
Remove dead function.
ZeroIntensity Jun 1, 2025
531928e
Add some more tests.
ZeroIntensity Jun 1, 2025
08a8af6
Remove unused variables.
ZeroIntensity Jun 1, 2025
02f93bc
Fix some thread state attachment problems.
ZeroIntensity Jun 1, 2025
d6c82bd
Only delete thread states created by PyThreadState_Ensure()
ZeroIntensity Jun 1, 2025
082fd69
Add a test for crossinterpreter ensures.
ZeroIntensity Jun 1, 2025
61f70ae
Add a test for weak interpreter references.
ZeroIntensity Jun 1, 2025
fa961e9
Fix concurrent shutdown races in PyGILState_Ensure().
ZeroIntensity Jun 1, 2025
ea1da77
Add a test for PyInterpreterRef_Main().
ZeroIntensity Jun 1, 2025
6f19384
Use PyErr_FormatUnraisable to show signals.
ZeroIntensity Jun 1, 2025
b702da2
Fix a re-entrancy deadlock.
ZeroIntensity Jun 1, 2025
40e7e68
Remove stupid IDE imports.
ZeroIntensity Jun 1, 2025
96efc81
Merge branch 'main' of https://github.com/python/cpython into pep-788…
ZeroIntensity Jun 21, 2025
af6f6fd
Merge branch 'pep-788-impl' of https://github.com/ZeroIntensity/cpyth…
ZeroIntensity Jun 21, 2025
2c52cdc
Fix interpreter reference count tests.
ZeroIntensity Jun 21, 2025
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
53 changes: 53 additions & 0 deletions Include/cpython/pystate.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,20 @@ struct _ts {
*/
PyObject *threading_local_sentinel;
_PyRemoteDebuggerSupport remote_debugger_support;

struct {
/* Number of nested PyThreadState_Ensure() calls on this thread state */
Py_ssize_t counter;

/* Thread state that was active before PyThreadState_Ensure() was called. */
PyThreadState *prior_tstate;

/* Should this thread state be deleted upon calling
PyThreadState_Release() (with the counter at 1)?

This is only true for thread states created by PyThreadState_Ensure() */
int delete_on_release;
} ensure;
};

/* other API */
Expand Down Expand Up @@ -261,3 +275,42 @@ PyAPI_FUNC(_PyFrameEvalFunction) _PyInterpreterState_GetEvalFrameFunc(
PyAPI_FUNC(void) _PyInterpreterState_SetEvalFrameFunc(
PyInterpreterState *interp,
_PyFrameEvalFunction eval_frame);

/* Strong interpreter references */

typedef uintptr_t PyInterpreterRef;

PyAPI_FUNC(int) PyInterpreterRef_Get(PyInterpreterRef *ref);
PyAPI_FUNC(PyInterpreterRef) PyInterpreterRef_Dup(PyInterpreterRef ref);
PyAPI_FUNC(int) PyInterpreterRef_Main(PyInterpreterRef *ref);
PyAPI_FUNC(void) PyInterpreterRef_Close(PyInterpreterRef ref);
PyAPI_FUNC(PyInterpreterState *) PyInterpreterRef_AsInterpreter(PyInterpreterRef ref);

#define PyInterpreterRef_Close(ref) do { \
PyInterpreterRef_Close(ref); \
ref = 0; \
} while (0)

/* Weak interpreter references */

typedef struct _PyInterpreterWeakRef {
int64_t id;
Py_ssize_t refcount;
} _PyInterpreterWeakRef;

typedef _PyInterpreterWeakRef *PyInterpreterWeakRef;

PyAPI_FUNC(int) PyInterpreterWeakRef_Get(PyInterpreterWeakRef *ptr);
PyAPI_FUNC(PyInterpreterWeakRef) PyInterpreterWeakRef_Dup(PyInterpreterWeakRef wref);
PyAPI_FUNC(int) PyInterpreterWeakRef_AsStrong(PyInterpreterWeakRef wref, PyInterpreterRef *strong_ptr);
PyAPI_FUNC(void) PyInterpreterWeakRef_Close(PyInterpreterWeakRef wref);

#define PyInterpreterWeakRef_Close(ref) do { \
PyInterpreterWeakRef_Close(ref); \
ref = 0; \
} while (0)


PyAPI_FUNC(int) PyThreadState_Ensure(PyInterpreterRef interp_ref);

PyAPI_FUNC(void) PyThreadState_Release(void);
7 changes: 7 additions & 0 deletions Include/internal/pycore_interp_structs.h
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,13 @@ struct _is {
or the size specified by the THREAD_STACK_SIZE macro. */
/* Used in Python/thread.c. */
size_t stacksize;

struct _Py_finalizing_threads {
Py_ssize_t countdown;
PyEvent finished;
PyMutex mutex;
int shutting_down;
} finalizing;
} threads;

/* Reference to the _PyRuntime global variable. This field exists
Expand Down
4 changes: 4 additions & 0 deletions Include/internal/pycore_pystate.h
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,10 @@ _Py_RecursionLimit_GetMargin(PyThreadState *tstate)
return Py_ARITHMETIC_RIGHT_SHIFT(intptr_t, here_addr - (intptr_t)_tstate->c_stack_soft_limit, PYOS_STACK_MARGIN_SHIFT);
}

// Exports for '_testinternalcapi' shared extension
PyAPI_FUNC(Py_ssize_t) _PyInterpreterState_Refcount(PyInterpreterState *interp);
PyAPI_FUNC(int) _PyInterpreterState_Incref(PyInterpreterState *interp);

#ifdef __cplusplus
}
#endif
Expand Down
7 changes: 6 additions & 1 deletion Lib/test/test_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -1914,10 +1914,15 @@ def test_audit_run_stdin(self):
def test_get_incomplete_frame(self):
self.run_embedded_interpreter("test_get_incomplete_frame")


def test_gilstate_after_finalization(self):
self.run_embedded_interpreter("test_gilstate_after_finalization")

def test_thread_state_ensure(self):
self.run_embedded_interpreter("test_thread_state_ensure")

def test_main_interpreter_ref(self):
self.run_embedded_interpreter("test_main_interpreter_ref")


class MiscTests(EmbeddingTestsMixin, unittest.TestCase):
def test_unicode_id_init(self):
Expand Down
192 changes: 192 additions & 0 deletions Modules/_testcapimodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -2546,6 +2546,194 @@ toggle_reftrace_printer(PyObject *ob, PyObject *arg)
Py_RETURN_NONE;
}

static PyInterpreterRef
get_strong_ref(void)
{
PyInterpreterRef ref;
if (PyInterpreterRef_Get(&ref) < 0) {
Py_FatalError("strong reference should not have failed");
}
return ref;
}

static void
test_interp_ref_common(void)
{
PyInterpreterState *interp = PyInterpreterState_Get();
PyInterpreterRef ref = get_strong_ref();
assert(PyInterpreterRef_AsInterpreter(ref) == interp);

PyInterpreterRef ref_2 = PyInterpreterRef_Dup(ref);
assert(PyInterpreterRef_AsInterpreter(ref_2) == interp);

// We can close the references in any order
PyInterpreterRef_Close(ref);
PyInterpreterRef_Close(ref_2);
}

static PyObject *
test_interpreter_refs(PyObject *self, PyObject *unused)
{
// Test the main interpreter
test_interp_ref_common();

// Test a (legacy) subinterpreter
PyThreadState *save_tstate = PyThreadState_Swap(NULL);
PyThreadState *interp_tstate = Py_NewInterpreter();
test_interp_ref_common();
Py_EndInterpreter(interp_tstate);

// Test an isolated subinterpreter
PyInterpreterConfig config = {
.gil = PyInterpreterConfig_OWN_GIL,
.check_multi_interp_extensions = 1
};

PyThreadState *isolated_interp_tstate;
PyStatus status = Py_NewInterpreterFromConfig(&isolated_interp_tstate, &config);
if (PyStatus_Exception(status)) {
PyErr_SetString(PyExc_RuntimeError, "interpreter creation failed");
return NULL;
}

test_interp_ref_common();
Py_EndInterpreter(isolated_interp_tstate);
PyThreadState_Swap(save_tstate);
Py_RETURN_NONE;
}

static PyObject *
test_thread_state_ensure_nested(PyObject *self, PyObject *unused)
{
PyInterpreterRef ref = get_strong_ref();
PyThreadState *save_tstate = PyThreadState_Swap(NULL);
assert(PyGILState_GetThisThreadState() == save_tstate);

for (int i = 0; i < 10; ++i) {
// Test reactivation of the detached tstate.
if (PyThreadState_Ensure(ref) < 0) {
PyInterpreterRef_Close(ref);
return PyErr_NoMemory();
}

// No new thread state should've been created.
assert(PyThreadState_Get() == save_tstate);
PyThreadState_Release();
}

assert(PyThreadState_GetUnchecked() == NULL);

// Similarly, test ensuring with deep nesting and *then* releasing.
// If the (detached) gilstate matches the interpreter, then it shouldn't
// create a new thread state.
for (int i = 0; i < 10; ++i) {
if (PyThreadState_Ensure(ref) < 0) {
// This will technically leak other thread states, but it doesn't
// matter because this is a test.
PyInterpreterRef_Close(ref);
return PyErr_NoMemory();
}

assert(PyThreadState_Get() == save_tstate);
}

for (int i = 0; i < 10; ++i) {
assert(PyThreadState_Get() == save_tstate);
PyThreadState_Release();
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose that PyThreadState_GetUnchecked() should be NULL at this point? Maybe add a check for that?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I redid this test.


assert(PyThreadState_GetUnchecked() == NULL);
PyInterpreterRef_Close(ref);
PyThreadState_Swap(save_tstate);
Py_RETURN_NONE;
}

static PyObject *
test_thread_state_ensure_crossinterp(PyObject *self, PyObject *unused)
{
PyInterpreterRef ref = get_strong_ref();
PyThreadState *save_tstate = PyThreadState_Swap(NULL);
PyThreadState *interp_tstate = Py_NewInterpreter();
if (interp_tstate == NULL) {
PyInterpreterRef_Close(ref);
return PyErr_NoMemory();
}

/* This should create a new thread state for the calling interpreter, *not*
reactivate the old one. In a real-world scenario, this would arise in
something like this:

def some_func():
import something
# This re-enters the main interpreter, but we
# shouldn't have access to prior thread-locals.
something.call_something()

interp = interpreters.create()
interp.exec(some_func)
*/
if (PyThreadState_Ensure(ref) < 0) {
PyInterpreterRef_Close(ref);
return PyErr_NoMemory();
}

PyThreadState *ensured_tstate = PyThreadState_Get();
assert(ensured_tstate != save_tstate);
assert(PyInterpreterState_Get() == PyInterpreterRef_AsInterpreter(ref));
assert(PyGILState_GetThisThreadState() == ensured_tstate);

// Now though, we should reactivate the thread state
if (PyThreadState_Ensure(ref) < 0) {
PyInterpreterRef_Close(ref);
return PyErr_NoMemory();
}

assert(PyThreadState_Get() == ensured_tstate);
PyThreadState_Release();

// Ensure that we're restoring the prior thread state
PyThreadState_Release();
assert(PyThreadState_Get() == interp_tstate);
assert(PyGILState_GetThisThreadState() == interp_tstate);

PyThreadState_Swap(interp_tstate);
Py_EndInterpreter(interp_tstate);

PyInterpreterRef_Close(ref);
PyThreadState_Swap(save_tstate);
Py_RETURN_NONE;
}

static PyObject *
test_weak_interpreter_ref_after_shutdown(PyObject *self, PyObject *unused)
{
PyThreadState *save_tstate = PyThreadState_Swap(NULL);
PyInterpreterWeakRef wref;
PyThreadState *interp_tstate = Py_NewInterpreter();
if (interp_tstate == NULL) {
return PyErr_NoMemory();
}

int res = PyInterpreterWeakRef_Get(&wref);
(void)res;
assert(res == 0);

// As a sanity check, ensure that the weakref actually works
PyInterpreterRef ref;
res = PyInterpreterWeakRef_AsStrong(wref, &ref);
assert(res == 0);
PyInterpreterRef_Close(ref);

// Now, destroy the interpreter and try to acquire a weak reference.
// It should fail.
Py_EndInterpreter(interp_tstate);
res = PyInterpreterWeakRef_AsStrong(wref, &ref);
assert(res == -1);

PyThreadState_Swap(save_tstate);
Py_RETURN_NONE;
}

static PyMethodDef TestMethods[] = {
{"set_errno", set_errno, METH_VARARGS},
{"test_config", test_config, METH_NOARGS},
Expand Down Expand Up @@ -2640,6 +2828,10 @@ static PyMethodDef TestMethods[] = {
{"test_atexit", test_atexit, METH_NOARGS},
{"code_offset_to_line", _PyCFunction_CAST(code_offset_to_line), METH_FASTCALL},
{"toggle_reftrace_printer", toggle_reftrace_printer, METH_O},
{"test_interpreter_refs", test_interpreter_refs, METH_NOARGS},
{"test_thread_state_ensure_nested", test_thread_state_ensure_nested, METH_NOARGS},
{"test_thread_state_ensure_crossinterp", test_thread_state_ensure_crossinterp, METH_NOARGS},
{"test_weak_interpreter_ref_after_shutdown", test_weak_interpreter_ref_after_shutdown, METH_NOARGS},
{NULL, NULL} /* sentinel */
};

Expand Down
56 changes: 56 additions & 0 deletions Modules/_testinternalcapi.c
Original file line number Diff line number Diff line change
Expand Up @@ -2345,6 +2345,60 @@ incref_decref_delayed(PyObject *self, PyObject *op)
Py_RETURN_NONE;
}

#define NUM_REFS 100

static PyObject *
test_interp_refcount(PyObject *self, PyObject *unused)
{
PyInterpreterState *interp = PyInterpreterState_Get();
assert(_PyInterpreterState_Refcount(interp) == 0);
PyInterpreterRef refs[NUM_REFS];
for (int i = 0; i < NUM_REFS; ++i) {
int res = PyInterpreterRef_Get(&refs[i]);
(void)res;
assert(res == 0);
assert(_PyInterpreterState_Refcount(interp) == i + 1);
}

for (int i = 0; i < NUM_REFS; ++i) {
PyInterpreterRef_Close(refs[i]);
assert(_PyInterpreterState_Refcount(interp) == (NUM_REFS - i - 1));
}

Py_RETURN_NONE;
}

static PyObject *
test_interp_weakref_incref(PyObject *self, PyObject *unused)
{
PyInterpreterState *interp = PyInterpreterState_Get();
PyInterpreterWeakRef wref;
if (PyInterpreterWeakRef_Get(&wref) < 0) {
return NULL;
}
assert(_PyInterpreterState_Refcount(interp) == 0);

PyInterpreterRef refs[NUM_REFS];

for (int i = 0; i < NUM_REFS; ++i) {
int res = PyInterpreterWeakRef_AsStrong(wref, &refs[i]);
(void)res;
assert(res == 0);
assert(PyInterpreterRef_AsInterpreter(refs[i]) == interp);
assert(_PyInterpreterState_Refcount(interp) == i + 1);
}

for (int i = 0; i < NUM_REFS; ++i) {
PyInterpreterRef_Close(refs[i]);
assert(_PyInterpreterState_Refcount(interp) == (NUM_REFS - i - 1));
}

PyInterpreterWeakRef_Close(wref);
Py_RETURN_NONE;
}

#undef NUM_REFS

static PyMethodDef module_functions[] = {
{"get_configs", get_configs, METH_NOARGS},
{"get_recursion_depth", get_recursion_depth, METH_NOARGS},
Expand Down Expand Up @@ -2447,6 +2501,8 @@ static PyMethodDef module_functions[] = {
{"is_static_immortal", is_static_immortal, METH_O},
{"incref_decref_delayed", incref_decref_delayed, METH_O},
GET_NEXT_DICT_KEYS_VERSION_METHODDEF
{"test_interp_refcount", test_interp_refcount, METH_NOARGS},
{"test_interp_weakref_incref", test_interp_weakref_incref, METH_NOARGS},
{NULL, NULL} /* sentinel */
};

Expand Down
Loading
Loading