Skip to content

fix: reset gil_safe_call_once_and_store cache on interpreter finalize - #6162

Open
henryiii wants to merge 9 commits into
pybind:masterfrom
henryiii:fix/gil-safe-call-once-restart
Open

henryiii wants to merge 9 commits into
pybind:masterfrom
henryiii:fix/gil-safe-call-once-restart

Conversation

@henryiii

@henryiii henryiii commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

🤖 AI text below 🤖

Description

When subinterpreter support is enabled, gil_safe_call_once_and_store keeps the stored value in the
state dict of the interpreter, and caches a pointer to it in the helper. Nothing cleared that cache
when the interpreter was finalized. After finalize_interpreter(); initialize_interpreter(); the
fast path gave freed memory back to the caller. py::register_exception uses this class, thus
re-importing an embedded module which registers an exception used the freed exception object.

The per-interpreter storage now knows its owner and clears the cached pointer from its destructor,
with a compare-and-swap so that it only removes its own pointer. The interpreter destroys the
storage during finalization, thus the helper must stay loaded until then.

Also, get_stored() now fails with an error if the current interpreter has no stored value.
Before, it returned a reference to memory with no constructed object.

This PR does not change builds without subinterpreter support (Python 3.9 to 3.11, or
PYBIND11_HAS_SUBINTERPRETER_SUPPORT=0). There the value is process-global and a restart still
uses the old value.

New Catch2 tests in tests/test_with_catch/test_interpreter.cpp restart the interpreter and then
use the stored value. Before the fix, the callable was not called again for the new interpreter, and
the re-imported exception module had no exception attribute.

Suggested changelog entry:

  • Fixed a use-after-free in py::gil_safe_call_once_and_store (and therefore in
    py::register_exception) when an embedded interpreter is finalized and then initialized again,
    in builds with subinterpreter support. The helper must stay loaded until the interpreter is
    finalized.

📚 Documentation preview 📚: https://pybind11--6162.org.readthedocs.build/

@henryiii
henryiii force-pushed the fix/gil-safe-call-once-restart branch from 67b0007 to 695f1a1 Compare November 12, 2026 19:40
@rwgk

rwgk commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Avoid writes to owner from concurrent get_stored() calls. Once a subinterpreter has existed, two threads in the same interpreter can both enter the slow path and write the same non-atomic value->owner. On free-threaded CPython 3.15.2, ThreadSanitizer reported conflicting writes in three of three runs at this head and zero of three on the original code. call_once_and_store_result() already assigns the owner in the std::call_once initializer. Keeping the assignment there would avoid the race. Slow path and owner assignment

Generated by Codex. Ralf has yet to review these findings.

@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

Writes to owner from concurrent get_stored() calls: confirmed and fixed in 2563686.

  • I added a Catch test (gil_safe_call_once_and_store concurrent get_stored after subinterpreter): four threads call get_stored() after a subinterpreter existed.
  • With free-threaded CPython 3.14 and ThreadSanitizer, the test reported the conflicting writes at the value->owner = this line in get_stored() before the fix. After the fix, three of three runs are clean, and the full test_with_catch run has no ThreadSanitizer reports.
  • The fix removes the assignment from get_stored(). The std::call_once initializer in call_once_and_store_result() sets owner for each storage that holds a value, so the second assignment was not necessary.

CI does not use ThreadSanitizer, so the new test only detects this race in a local sanitizer build.

@henryiii
henryiii force-pushed the fix/gil-safe-call-once-restart branch from 2563686 to 05aad66 Compare November 22, 2026 14:54
@rwgk

rwgk commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

codex GPT-6.2-Sol ultra (I'll add a commit to fix the finding):

I’d hold #6162 for one more fix. The earlier owner race is resolved. ThreadSanitizer reported it in all three runs on the preceding commit and in zero of three on the current head. I found a separate race in how the cache is cleared.

The mental model is that each interpreter owns its stored value, such as the Python exception class created by py::register_exception. The static C++ helper outlives the interpreter and keeps a shortcut to that value. On shutdown, the interpreter destroys the value, so the helper must forget the shortcut. The next interpreter can then run the initializer again. Storage and initialization

The remaining bug is that teardown can erase another interpreter’s cache entry. A subinterpreter checks that the cached pointer belongs to it. Before it finishes clearing the cache, the main interpreter can publish its own pointer and mark the cache valid. The subinterpreter then clears the pointer, leaving a null pointer marked valid. After a restart, the helper skips initialization. I reproduced this with test-only timing hooks on both GIL-enabled and free-threaded CPython. The usual chained .call_once_and_store_result(...).get_stored() form can hit it too. Invalidation code

I’d use one atomic pointer for the cache, with null meaning empty, and clear it using compare-and-exchange so teardown can only remove its own entry. A scratch version passed the same forced ordering on both builds. Separately, AddressSanitizer confirmed that the new back-pointer can access freed memory if the helper itself is destroyed before the interpreter. If static lifetime is part of the API contract, I’d state that explicitly where callers see it.

GitHub CI passed. The local Catch2 suite passed all 35 cases on both CPython 3.15.2 builds, and the three new cases also passed with the GIL forced off. Local compilation needed a CPython-header warning workaround, and the free-threaded suite passed after extending the harness’s three-second timeout. CI

@rwgk rwgk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving based on a codex GPT-6.2-Sol ultra review, after adding commit 4b1fa3e.

I'm leaving the final review and merging to @henryiii.

@henryiii henryiii self-assigned this Nov 23, 2026
@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

A review of this branch found five items. Commit 6d9f055 addresses them.

  1. Restart stayed broken without subinterpreter support (Python 3.9 to 3.11, or PYBIND11_HAS_SUBINTERPRETER_SUPPORT=0). That variant keeps the result process-global, and nothing reset it on finalize_interpreter(). After a restart, call_once_and_store_result skipped fn, and get_stored() returned an object that the old interpreter owned.
    Fix: the global variant now registers a small object in the interpreter state dict. When the interpreter is finalized, that object resets is_initialized_ and once_flag_. The old result is leaked, not destroyed, so the behavior at process exit does not change. The two restart tests now run in all builds. On Python 3.11 they failed before the fix and pass after it.

  2. get_stored() could return storage that holds no constructed T. The slow path did not check is_initialized. This occurs if the capsule is already destroyed during Py_Finalize, or if a subinterpreter never ran call_once_and_store_result.
    Fix: the slow path now calls pybind11_fail. A new test covers this.

  3. The reordered load in get_cached_storage() is a race fix by inspection, but its comment did not have the required sentence.
    Fix: the comment now explains what another thread can observe, references this PR, and has No targeted race test yet.

  4. The fast-path cache can stay empty if a subinterpreter replaces the pointer, clears it at teardown, and has_seen_non_main_interpreter() then goes back to false while the main interpreter is alive. Only unsafe_reset_internals_for_single_interpreter() in the tests does this. Results stay correct, only slower.
    Fix: documented as accepted in a comment. A republish would add a new race path without a test.

  5. The storage destructor now writes through owner during interpreter teardown. This is safe only if the helper is still loaded at that time.
    Fix: the comments now state this as a requirement: do not unload the shared library that contains the helper before the interpreter is finalized.

The Catch tests pass locally on Python 3.11 (no subinterpreter support) and on 3.15t.

The PR description still says the bug applies "when subinterpreter support is enabled". That is now too narrow, and the changelog entry should mention the requirement from item 5.

@rwgk

rwgk commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

I’d hold #6162 at 6d9f055.

The new commit fixes ordinary restarts on builds without subinterpreter support. I verified both the initializer and exception-registration fixes on CPython 3.9, 3.11, and free-threaded 3.15 with subinterpreter support disabled. The new get_stored() check also correctly throws when only a different interpreter initialized the helper. The other three items clarify cache ordering, the slow-path fallback, and the library lifetime requirement.

A late cleanup callback can still defeat the restart fix. After one helper’s capsule is destroyed, a later finalizer can call call_once_and_store_result() on that helper again. CPython has already detached the state dictionary, so the call creates a new dictionary and publishes a value whose cleanup never runs. The next interpreter gets the old value. I reproduced this on 3.11 and 3.15, including a 3.15 case using only the documented finalize_fn callback. The default 3.15 path already had this hole after our compare-and-exchange fix. The new commit extends it to builds without subinterpreter support. See attached 6162-late-finalization-repro.zip below.

The new reset introduces two regressions on 3.11. A plain get_stored() from a later cleanup callback now hits a debug assertion even though the helper was initialized in that interpreter. Each restart also overwrites the stored C++ value without destroying it. A probe with a resource-owning T retained three resources after three interpreter lifetimes, versus one on the previous head. See attached 6162-resource-lifetime-repro.zip below.

I’d share the interpreter-owned storage path across CPython builds and prevent teardown callbacks from republishing the fast cache. I’d handle PyPy separately. Its state-dict fallback uses the calling frame’s builtins, and I reproduced a new SystemError on first use from a frame whose __builtins__ entry had been removed. See attached 6162-pypy-builtins-repro.zip below.

All 36 local Catch2 cases passed on both CPython 3.15.2 builds. The four targeted cases also passed with the GIL forced off. See attached 6162-local-validation.zip below. Full CI was queued at the time of review.

6162-local-validation.zip
6162-pypy-builtins-repro.zip
6162-resource-lifetime-repro.zip
6162-late-finalization-repro.zip

@rwgk

rwgk commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

@henryiii I'm a bit surprised that we're getting into more agent-back-and-forth here. The combinations of Python versions and subinterpreter support on/off appear to generate multiple tricky edge cases. I left the codex findings and evidence in the previous comment, but I'm holding off adding more commits until I get your feedback.

henryiii and others added 8 commits November 23, 2026 09:52
The old reference was released into the new interpreter's allocator, which
crashed on Python 3.12. This was also the cause of the enum test skip.
Threads of one interpreter can run the slow path of get_stored() at the
same time when a subinterpreter has existed. The write to the non-atomic
owner was a data race under free-threading. The owner is already set in
the std::call_once initializer.

Assisted-by: ClaudeCode:claude-fable-5-2
Use the cached pointer as the validity marker. Compare and clear the pointer in one operation so a subinterpreter cannot erase another interpreter's cache publication during teardown.
Without subinterpreter support, the stored result is process-global and
was not reset when the interpreter was finalized. A restarted interpreter
then used an object that the old interpreter owned.

Also:
- get_stored() fails if the interpreter has no stored value.
- Add the race comment for the load order in get_cached_storage().
- Document that the fast-path cache is not published again.
- Document that the helper must stay loaded until finalization.

Assisted-by: ClaudeCode:claude-fable-5-2
Remove the reset on finalize for the process-global variant, and put
the restart tests back inside PYBIND11_HAS_SUBINTERPRETER_SUPPORT. The
other changes of 6d9f055 stay.

Assisted-by: ClaudeCode:claude-fable-5-2
A callback can call the helper during finalization, after the
interpreter destroyed the stored value. The interpreter does not destroy
the storage which that call creates, so its pointer stayed in the
fast-path cache and the next interpreter used the old value.

Publish the cache only from the main interpreter, and only when Python
is not finalizing.

Assisted-by: ClaudeCode:claude-fable-5-2
Store a pointer to the cache atomic in the storage instead of the helper,
removing the forward declaration, friend, and invalidate_cache().

Assisted-by: ClaudeCode:claude-opus-5-5
@henryiii
henryiii force-pushed the fix/gil-safe-call-once-restart branch from 24a65e5 to c178690 Compare November 23, 2026 14:57
@henryiii

Copy link
Copy Markdown
Collaborator Author

I ran this on high effort level instead of medium, and fixing the discovered sidetrack was too tempting. :) I've switched back to medium, reverted that part, now this is sub interpreter only again. I've also applied a fix for half of point 1, which wasn't dependent on the main interpreter restart change. I ran an Opus simplification run too, as it's quite good at writing clean comments.

Assisted-by: ClaudeCode:claude-opus-5-5

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants