Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

gh-162764: Avoid 1 ms STW delay when a thread detaches - #162771

Open
nascheme wants to merge 3 commits into
python:mainfrom
nascheme:gh-162764-stw-detach-notify
Open

nascheme wants to merge 3 commits into
python:mainfrom
nascheme:gh-162764-stw-detach-notify

Conversation

@nascheme

@nascheme nascheme commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

In the free-threaded build, a stop-the-world (STW) request can wait for the 1 ms fallback rescan even though the thread it is waiting for has already detached. This happens when a thread detaches to block on a lock or around a C call without first handling the stop request at an eval-breaker check.

Implementation

  • After publishing DETACHED, _PyThreadState_Detach() checks the thread’s own _PY_EVAL_PLEASE_STOP_BIT. If it is set, the slow path takes HEAD_LOCK, checks for an active STW request, and decrements the countdown only if it successfully transitions the thread from DETACHED to SUSPENDED. The common path does not read shared STW flags or take HEAD_LOCK.
  • The requester first tries to park the thread. If it observes ATTACHED or DETACHED_WAITING, it sets the please-stop bit and makes one more attempt to park it. That second attempt covers the race where the thread detached and checked the bit before the requester set it. DETACHED_WAITING threads are still allowed to finish attaching so consecutive pauses cannot starve them; the bit asks them to stop at their next eval-breaker check (or when they detach again).

The 1 ms rescan remains as a fallback. The current patch does not change the runtime or interpreter structure layout, so the original backport caveat no longer applies.

Benchmarks

Updated measurements use a free-threaded release build on Linux x86-64 (Clang 20.1.8, -O3, no PGO, i7-14700K).

Five interleaved runs of test_opcache.test_binary_subscr_getitem and test_opcache.test_load_attr_getattribute_overridden. A pause counts here only if it triggers at least one 1 ms fallback rescan, not simply if it lasts longer than 1 ms.

Variant Median wall time Pauses hitting fallback
main 18.43 s 82,956 / 112,725 (73.59%)
This PR 0.123 s 3 / 112,725 (0.0027%)

In C loops pinned to one P-core, the median paired overhead versus main was +0.23 ns (+1.4%) for a bare PyEval_SaveThread() / PyEval_RestoreThread() pair and +0.12 ns (+0.8%) for a Py_BEGIN_ALLOW_THREADS block around a trivial C call. CI measurements also show that the patch resolves the Windows free-threaded debug timeouts in test_unregister_lingering_tasks_of_exited_thread.

An LLM assisted in writing and benchmarking this PR.

Original approach (for context on earlier review comments)

The first revision atomically read the shared runtime and interpreter stoptheworld.requested flags after detaching. The requester set its flag before scanning threads, so a thread that detached during the scan could see the request even if it had not yet been signalled. That approach changed requested from bool to int and added shared loads to every detach. Earlier comments about a please-stop-bit check missing the race refer to a version without the requester’s second parking attempt. The current version uses that retry instead of reading the shared flags on the fast path.

When detaching, check if STW is requested.  If so, move from DETACHED to
SUSPENDED and decrement countdown.  Also, threads waiting to re-attach
after a previous pause are asked to stop.
@nascheme

Copy link
Copy Markdown
Member Author

CC @colesbury

Comment thread Python/pystate.c Outdated
_PyRuntimeState *runtime = &_PyRuntime;
PyInterpreterState *interp = tstate->interp;

if (!_Py_atomic_load_int(&runtime->stoptheworld.requested) &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we just check the _PY_EVAL_PLEASE_STOP_BIT. on this threads eval-breaker?

Would this work:

void
_PyThreadState_Detach(PyThreadState *tstate)
{
    if (_Py_eval_breaker_bit_is_set(tstate, _PY_EVAL_PLEASE_STOP_BIT) {
        _PyThreadState_Suspend(tstate);
    }
    else {
        detach_thread(tstate, _Py_THREAD_DETACHED);
    }
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

That helps but doesn't always avoid the 1 ms delay. The requester can see the thread as ATTACHED, then the thread can check the bit and detach before the requester sets it. Checking the bit after detaching doesn’t fix this either: the requester can still set it after that check, based on its earlier ATTACHED read. The requested flag works because the requester sets it before scanning thread states. If the scan sees ATTACHED, the request is already visible to the detaching thread’s post-detach check.

Benchmarking: the please-stop bit check still hit the retry about once every 360 pauses, in exchange for saving about 0.2 ns per detach/reattach pair on this machine.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think we're always going to have a race here, right?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think it's important that detach and attach remain as inexpensive as possible. There are a lot of Py_BEGIN_ALLOW_THREADS type things around really simple around really simple functions, especially in things like PyTorch. I'm not sure ctypes captures that well because you have all the overhead of ctypes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Using Hugo's bug with test_opcache slowdown (test_binary_subscr_getitem + test_load_attr_getattribute_overridden, 22,545 pauses):

variant wall retried pauses
base 18.18 s 73.6%
please-stop (bit) 0.89 s (0.74–0.94) 1.5–2.2%
requested (flag) 0.21 s 0.01%

I measured detach/attach cost directly in C, with no ctypes in the loop. For a PyTorch type pattern, checking requested costs +0.13 ns per detach/attach pair (+0.8%), or +0.14 ns on a 14.85 ns detaching call. The trade is about 0.13 ns per detach vs 1 ms per missed pause. So I lean to the requested check as the fix.

However, checking please-stop is simpler and does help. So, if you prefer that, I'll revise the PR.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I figured out how to use the please-stop bit, getting the low % of "retried pauses". It's a more code change vs your suggestion but it avoids extra cost for detach/attach and also avoids the 1 ms pause nearly always.

Comment thread Python/pystate.c Resolved
Replace the check of the `requested` flags in _PyThreadState_Detach()
with a check of the thread's own _PY_EVAL_PLEASE_STOP_BIT.  This avoids
reading the shared runtime and interpreter stop-the-world state on every
detach.
@nascheme

nascheme commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Re-done benchmarks, for e49b99c version. Done with free-threaded release build (--disable-gil, Clang 20.1.8, -O3, no PGO), Linux x86-64, i7-14700K. bit is the current bounded-CAS patch; flags is the earlier shared-flag implementation.

1 ms STW fallback

Five interleaved runs of the two test_opcache race tests: test_binary_subscr_getitem and test_load_attr_getattribute_overridden. A pause counts as retried if it triggers at least one 1 ms fallback rescan, not simply if it lasts longer than 1 ms.

Variant Median wall time Pauses hitting fallback % of pauses
main 18.43 s 82,956 / 112,725 73.59%
flags 0.137 s 0 / 112,725 0%
bit 0.123 s 3 / 112,725 0.0027%

Detach/attach cost

C loops pinned to one P-core, eight interleaved runs per variant. Times are ns per detach/attach pair. no-check is the current patch with only the detach check removed.

Benchmark main no-check flags bit
Bare PyEval_SaveThread / PyEval_RestoreThread 16.80 16.80 16.97 17.03
Marginal Py_BEGIN_ALLOW_THREADS around a trivial call 16.12 16.12 16.24 16.25
Bare pair with continuous runtime flag cache-line writes (synthetic) 16.80 16.79 54.01 17.03

The median paired bit − main deltas were +0.23 ns (+1.4%) for the bare pair and +0.12 ns (+0.8%) around the trivial call.

@hugovk

hugovk commented Nov 30, 2026

Copy link
Copy Markdown
Member

This also fixes the test_unregister_lingering_tasks_of_exited_thread timeouts on the Windows free-threading debug jobs:

Job main This PR
Windows arm64 6 to 9.5 min, often the 10 min timeout 54 s
Windows x64 4.5 to 10 min, sometimes the timeout 3 min 41 s
macOS 1 to 3 min under 30 s

Note: this change cannot be backported as is since it changes the interp structure (requested member goes from bool to int).

Is this still the case? Only pystate.c is now changed.

test_unregister_lingering_tasks_of_exited_thread was slow since added in #159483 (cc @jblespiau @kumaraditya303), and was also backported to 3.14 and so causes timeouts and up to 10 minutes to the CI's bottleneck job.

If this can't be backported, can we do something for those branches? Maybe cut the number of iterations in the test, like @cmaloney suggested in #162364?

@nascheme

Copy link
Copy Markdown
Member Author

Is this still the case? Only pystate.c is now changed.

No, that statement is no longer true (should be easy backport now). On Sunday I got Claude to build a TLA+ version of the new STW logic, to give me more confidence this doesn't introduce deadlocks or starvation issues. That checks out.

@cmaloney

Copy link
Copy Markdown
Contributor

re: test_unregister_lingering_tasks_of_exited_thread still think we can make that more reliably trigger the states it is looking for via test structure change; have a prototype patch which helps but getting to deployable was taking too long at the moment. Do plan to pick back up when don't have quite so many things in flight.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants