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

When detaching, check if STW is requested. If so, switch to SUSPENDED state and then decrement the STW countdown. Also, park_detached_threads() now sets the please-stop bit on threads in the DETACHED_WAITING state, telling them to stop immediately. Otherwise they can start executing Python code again when waking.

Note: this change cannot be backported as is since it changes the interp structure (requested member goes from bool to int). Also, note that an LLM assisted in writing and benchmarking this PR.

Benchmarks

Stop-the-world latency

The reproducer from the issue calls _testinternalcapi.stop_the_world() 1000 times while worker threads run in different modes. Free-threaded debug build, Linux x86-64, us per stop-the-world:

Mode Workers main this PR
none no other threads 0.3 1.3
spin pure Python loop 131 3.1
sleep time.sleep(0) loop 39 0.3
lock 2 threads contending on a threading.Lock 677 3.6

The first change fixes the sleep mode. The second change fixes spin and lock: there the straggler was a thread that had been DETACHED_WAITING when the pause started, and gdb showed it running Python code while the requester waited in PyEvent_WaitTimed(). The none column is within noise; it does not touch the changed code.

Detach overhead

The new check adds two loads and two branches to every _PyThreadState_Detach(). On x86-64 the seq_cst loads are plain movs; HEAD_LOCK and the CAS are only reached while a stop is pending.

Measured with a ctypes call to libc abs(): ctypes.CDLL calls detach and re-attach around the C call, ctypes.PyDLL calls do not, and the difference is the detach/attach cost. Release free-threaded build, pinned to one CPU, best of 15 runs of 200,000 calls, 4 alternating runs per build:

CDLL call PyDLL call detach/attach overhead
main 128.4 - 129.0 ns 117.2 - 119.1 ns 9.3 - 11.8 ns (avg 10.4)
this PR 128.5 - 130.4 ns 117.3 - 118.3 ns 11.2 - 12.2 ns (avg 11.9)

That is about 1.5 ns per detach/attach pair, roughly 1% of the cheapest detaching call measured, and close to the noise. requested is only written when a pause starts or ends, so between pauses its cache line stays shared and there is no contention between threads.

Benchmark script
import ctypes, time
f = ctypes.CDLL(None).abs   # detaches around the call
g = ctypes.PyDLL(None).abs  # same call, no detach
N = 200_000
def bench(fn):
    best = 1e9
    for _ in range(15):
        t0 = time.perf_counter_ns()
        for _ in range(N):
            fn(1)
        best = min(best, (time.perf_counter_ns() - t0) / N)
    return best
d = bench(f); c = bench(g)
print(f"detach call {d:6.1f} ns  no-detach {c:6.1f} ns  delta {d-c:5.1f} ns")

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.

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.

2 participants