Skip to content
Closed
Prev Previous commit
Update Doc/c-api/init.rst
Co-authored-by: Eric Snow <ericsnowcurrently@gmail.com>
  • Loading branch information
jbms and ericsnowcurrently authored Jun 2, 2023
commit bdebcf832d13e4e79204e67d852b790fc950f98b
23 changes: 14 additions & 9 deletions Doc/c-api/init.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1588,19 +1588,24 @@ All of the following functions must be called after :c:func:`Py_Initialize`.

.. c:function:: int PyThread_AcquireFinalizeBlock()
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

AFAICT, this API is interpreter-specific, rather than tied to a thread or the global runtime. So Py_AcquireFinalizeBlock() might be more consistent with similar existing API (e.g. Py_NewInterpreterFromConfig(), Py_EndInterpreter()).

That said, the proposed function relies on knowing the interpreter associated with the current thread (e.g. PyInterpreterState_Get()). I'd say we're trending away from that approach generally, and, ideally, we would not introduce new C-API that relies on that implicit knowledge. Instead, it may make more sense to add a variant instead: PyInterpreterState_AcquireFinalizeBlock().

The caller would explicitly provide the interpreter that should be blocked:

    PyInterpreterState *interp = PyInterpreterState_Get();
    if (!PyInterpreterState_AcquireFinalizeBlock(interp)) {
        end_early_because_we_are_finalizing_unexpectedly();
        return;
    }
    do_the_normal_work();
    PyInterpreterState_ReleaseFinalizeBlock(interp);
    return;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Given what I've said about "finalize block", consider alternate names:

  • PyInterpreterState_PreventFini() (and PyInterpreterState_AllowFini())
    • similarly, Py_PreventInterpreterFini() (and Py_AllowInterpreterFini())
  • PyInterpreterState_BlockFini() (and PyInterpreterState_ReleaseFini())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

While it is fairly straightforward to make these finalize blocks interpreter-specific, it is not clear to me, with my limited understanding of sub-interpreters, whether that is actually useful.

  • It isn't clear to me how PyFinalize_Ex interacts with multiple interpreters. It only seems to finalize the current interpreter.

  • The documentation for Py_EndInterpreter states that the interpreter must "have no other threads". In fact it only does this check after calling the AtExit functions for the interpreter, so it seems it would be sufficient to ensure that all other thread states are destroyed before the AtExit functions finish. But there is also the question of what happens if we try to create a thread state while Py_EndInterpreter is still in progress. Py_EndInterpreter doesn't seem to check for other thread states while holding the HEAD_LOCK, but that is not an issue as long as the check does not fail.

  • In general, given the "no other threads" constraint for Py_EndInterpreter it seems that if other non-Python-created or daermon threads hold references to the PyInterpreterState, then some external synchronization mechanism will be needed to ensure that they don't attempt to access the PyInterpreterState once the "no other threads" check completes.

As an example, suppose we have a C extension that provides a Python API that allows Python callbacks to be passed in, and then later calls those Python functions on its own non-Python-created thread pool. If this extension is to support sub-interpreters, then either during multi-phase module initialization, or when it receives the Python callback, it must record the PyInterpreterState associated with the callback. Then, in order to invoke the callback on a thread from its thread pool, it must obtain a PyThreadState for the (thread, interpreter) combination, creating one if one does not already exist. To ensure the PyInterpreterState pointers that it holds remain valid, it would need to register an AtExit function for the interpreter that ensures the PyInterpreterState won't be used. This AtExit function would likely need to essentially implement its own version of the "finalize block" mechanism introduced here.

Given the need for external synchronization of threads when calling Py_EndInterpreter, it seems to me that the finalize block mechanism defined by this PR is only useful for the main interpreter.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Before I dig in to responding: one key point to consider is that Python users (especially extension authors, via the C-API) only interact directly with the global runtime via a few API functions. In nearly every case they are instead interacting with the Python thread (state) or interpreter associated with the current OS thread.

Another key point is that, as of 3.12, each interpreter has its own GIL.

Finally, it is certainly possible that I've misunderstood either the problem you're trying to solve or the way you're trying to solve it or both. I'm completely willing to learn and adjust. Then again, I might be completely right too!

(Sorry for the length of this post. I genuinely want to understand and to be sure we're taking the right approach. I appreciate the work you've done and your willingness to converse.)


Now, on to responses:

  • It isn't clear to me how PyFinalize_Ex interacts with multiple interpreters. It only seems to finalize the current interpreter.

PyFinalize_Ex() finalizes the main interpreter and the global runtime. At the point it is called, no other interpreters should exist.

Py_EndInterpreter() finalizes any other interpreter, almost entirely in the same way we finalize the main interpreter.

  • The documentation for Py_EndInterpreter states that the interpreter must "have no other threads".

Please clarify. The only thing I see is: "All thread states associated with this interpreter are destroyed."

The behavior should be the same for all interpreters, whether via Py_EndInterpreter() or the main interpreter via Py_FinalizeEx():

  1. check if current thread and holds GIL and not still running (ensures no reentrancy from the eval loop)
  2. internally mark the interpreter as finalizing
  3. wait for all non-daemon threads to finish
  4. call all of the interpreter's atexit callbacks, if any
  5. externally mark the interpreter as finalizing (this causes daemon threads to die, or, now, pause)
  6. finalize imports
  7. clear the interpreter state (including all its remaining thread states)
  8. delete the interpreter state

Caveats:

Py_FinalizeEx() does a few extra things at various places, but that should not relate to interpreter lifecycle.

I do see that it calls _PyThreadState_DeleteExcept() right after step (5), which Py_EndInterpreter() does not do. However, that's unexpected and should probably be resolved.

There are a few things we don't do in either that we probably should, probably before or right after step (5), e.g. disable the import system, disallow new threads (thread states).

Also, step (3) only applies to threads created by the threading module. We might want to extend that to all other threads states (i.e. created via PyThreadState_New() or PyGILState_Ensure()).

In fact it only does this check after calling the AtExit functions for the interpreter,

Looking at Py_EndInterpreter():

  • calls wait_for_thread_shutdown() right before _PyAtExit_Call()
  • publicly marks itself as finalizing right after _PyAtExit_Call()
  • destroys its remaining thread states at the end during finalize_interp_clear()

So I'm not sure what you mean specifically.

FWIW, Py_FinalizeEx() is exactly the same, except currently it does that last part a little earlier with _PyThreadState_DeleteExcept().

so it seems it would be sufficient to ensure that all other thread states are destroyed before the AtExit functions finish.

Only daemon threads (and, for now, threads (states) created via the C-API) would still be running at that point, and only until next step (5) above.

So are we talking about both the following?

  • move step (5) before step (4)
  • apply steps (3) and (5) to thread states that were not created by the threading module

Just to be clear, here are the ways thread states get created:

  • Py_Initialize*()
  • Py_NewInterpreter*()
  • PyThreadState_New()
  • PyGILState_Ensure()
  • _thread.start_new_thread() (via threading.Thread.start())

At the moment, it's mostly only with that last one that we are careful during runtime/interp finalization.

It occurs to me that this PR is mostly about addressing that: dealing with other thread states in the same way we currently do threads created via the threading module. Does that sound right?

But there is also the question of what happens if we try to create a thread state while Py_EndInterpreter is still in progress. Py_EndInterpreter doesn't seem to check for other thread states while holding the HEAD_LOCK, but that is not an issue as long as the check does not fail.

Yeah, we should probably be more deliberate about disallowing that sort of thing during finalization.

  • In general, given the "no other threads" constraint for Py_EndInterpreter it seems that if other non-Python-created or daermon threads hold references to the PyInterpreterState, then some external synchronization mechanism will be needed to ensure that they don't attempt to access the PyInterpreterState once the "no other threads" check completes.

That's what the proposed change in the PR is, AFAICS. The API you're adding must be specific to each interpreter, not to the global runtime. The resources that the proposed change protects are per-interpreter resources, not global ones. So I would not expect there to be any additional API or synchronization mechanism other than what you've already proposed (except applied to each interpreter instead of the main interpreter. Otherwise users of multiple interpreters will still be subject to the problem you're trying to solve.

As an example, suppose we have a C extension that provides a Python API that allows Python callbacks to be passed in, and then later calls those Python functions on its own non-Python-created thread pool. If this extension is to support sub-interpreters, then either during multi-phase module initialization, or when it receives the Python callback, it must record the PyInterpreterState associated with the callback. Then, in order to invoke the callback on a thread from its thread pool, it must obtain a PyThreadState for the (thread, interpreter) combination, creating one if one does not already exist.

That's literally what PyGILState_Ensure() is for and does. 😄

To ensure the PyInterpreterState pointers that it holds remain valid, it would need to register an AtExit function for the interpreter that ensures the PyInterpreterState won't be used. This AtExit function would likely need to essentially implement its own version of the "finalize block" mechanism introduced here.

Why wouldn't we just exclusively use the mechanism you're proposed here? Why would each interpreter have to have an additional duplicate? Again, the resources we're trying to protect here are specific to each interpreter, not to the global runtime, no?

Given the need for external synchronization of threads when calling Py_EndInterpreter, it seems to me that the finalize block mechanism defined by this PR is only useful for the main interpreter.

Hmm, I didn't catch what external synchonization of threads you are talking about. Sorry if I missed it or misunderstood. Please restate what you mean specifically. Thanks!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I don't have any experience with implementing extensions that work with multiple interpreters, but I'm trying to think how that would be done safely.

Let's say this extension lets the user schedule a Python callback to invoked at a specific time, on a global thread pool not created by Python.

With a single interpreter, the extension may either keep a cached PyThreadState per thread in the pool for the main interpreter, or create it on demand. I haven't checked exactly what happens when trying to create a new PyThreadState while PyFinalize_Ex is running, but I think there is no problem there. The core problem is that the extension could attempt to dispatch a callback just as Py_FinalizeEx is running. Using the existing finalize block mechanism in this PR, the extension can ensure that finalization does not start while a callback is being dispatched, in order to ensure threads in the thread pool won't hang trying to acquire the GIL.

With multiple interpreters, we need a separate PyThreadState per thread in the pool per interpreter, and for each callback that has been scheduled, we also need to store the associated PyInterpreterState*. However, we also need a way to know that the interpreter is exiting, and cancel any scheduled callbacks, so that we don't attempt to use a dangling PyInterpreterState pointer. If PyThreadState objects have been cached for the thread pool threads, we would also need to destroy those PyThreadState objects, to avoid violating the constraint of Py_EndInterpreter. This cancellation mechanism is what I mean by an external synchronization mechanism. Given this external synchronization mechanism, I don't think such an extension would need to use the "finalize block" mechanism. We can't use PyGILState_Ensure because that does not take a PyInterpreterState*, and even if it did, we would need a way to ensure that our PyInterpreterState* is not dangling.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think I get it now. The "finalize block" API, as proposed, relies on the global runtime state, which is guaranteed to exist in the process, whereas a given interpreter state pointer may have already been freed.

That said, do we continually have the guarantees we might need relative to the global runtime state, since at a certain point we will have freed some of the state the proposed API would need, no? I suppose if we can rely on some final flag for already-finalized then we'd be okay.

As to interpreters, even if the target one has been finalized already, we can still know that. Interpreters may be looked up by ID, rather than referenced by pointer. It's an O(n) operation, of course, but I'm not sure that would be a huge obstacle. Likewise the pointer can be checked against the list of alive interpreters to check for validity. Would we need more than that?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think it is safe to assume that there may be numerous race conditions still remaining in the finalization logic. In particular I'd assume that calling Py_Initialize again after Py_FinalizeEx could definitely result in a lot of problems. I had put that in the category of things not to be done in production code. At least for the single interpreter case, single call to Py_Initialize, I think such bugs could likely be fixed without further API changes, though.

I am unclear on how sub-interpreters should be handled. Checking if the PyInterpreterState* is valid by checking if it is in the list of alive interpreters could fail if the interpreter is freed and then another allocated again at the same address, unless something is done to prevent that. In addition, if a given C/C++ extension only finds out afterwards that an interpreter has been destroyed, it is too late for it to free any PyObjects it has, so it would likely end up leaking memory. Therefore an atexit callback would seem to be more appropriate.

For the single-interpreter case we don't care about leaking memory because the program is about to exit anyway.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Since there are some API questions to resolve here, one option may be to split out the change to make threads hang rather than terminate, which can go in right away, and I expect will be sufficient for almost all single-interpreter use cases. The finalize block API, or other API changes to safely support multi-threading without leaks in the presence of interpreters stopping, could then be added later without blocking the fix for the common case.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Agreed @jbms, can you make a PR splitting that part out?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, see #105805


Attempts to acquire a block on Python finalization.
Attempts to prevent finalizing the current interpreter.

While the *finalize block* is held, the Python interpreter will block before
it begins finalization. Holding a finalize block ensures that the
:term:`GIL` can be safely acquired without the risk of hanging the thread.
Refer to :ref:`cautions-regarding-runtime-finalization` for more details.
If the interpreter is already finalizing then this returns 0 and has no
effect. Likewise if the interpreter is about to begin finalization but
is waiting for earlier calls to ``PyThread_AcquireFinalizeBlock()`` to be
resolved. The caller should then proceed knowing that they should
not use this interpreter any more.

If successful, returns 1. If the interpreter is already finalizing, or about
to begin finalization and waiting for all previously-acquired finalize blocks
to be released, returns 0 without acquiring a finalize block.
If the interpreter is not finalizing (nor about to) then it is immediately
prevented from finalizing, though this does not otherwise affect it.
This function returns 1 for this case.

Every successful call must be paired with a call to
:c:func:`PyThread_ReleaseFinalizeBlock`.
:c:func:`PyThread_ReleaseFinalizeBlock`. Until that happens, the
interpreter will be prevented from finalizing. During this period of
time, the caller is guaranteed that the :term:`GIL` can be safely
acquired without the risk of hanging the thread.
Refer to :ref:`cautions-regarding-runtime-finalization` for more details.

This function may be safely called with or without holding the :term:`GIL`.

Expand Down