Repository navigation
Protect MultiDict single-item ops and view set-algebra with a critical section - #1438
Conversation
…l section add(), __setitem__/__delitem__, get()/getone()/__getitem__, __contains__, getall(), setdefault(), pop()/popone()/popall()/popitem(), __eq__, iteration, and the &/|/-/^/in/isdisjoint() operations on .keys() and .items() views in the C extension used to run without holding self's lock at all, unlike update()/extend()/merge()/clear()/repr() (already protected in aio-libs#1431/aio-libs#1433). A resize triggered by one thread's mutation could free the hash table a concurrent reader on another thread was still walking. Also fixes a compile error in the in-progress atomic-reads work (htkeys.h referenced an undefined atomic_load_ssize_relaxed helper; helpers.h is now included where the helper is used). The .keys()/.items() view set operations use the CPython _lock_held split (body extracted to a _impl function, a thin wrapper acquires the lock) since several have multiple goto/return exits that can't be wrapped in place. Lock-free reads (get/contains/iteration) are intentionally out of scope here; that follow-up will introduce a separate, validated threadsafe lookup path the way CPython's dict does.
Merging this PR will improve performance by 9.54%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_multidict_insert_str[cs-c] |
103.8 µs | 94.7 µs | +9.54% |
Tip
Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.
Comparing asvetlov:atomic (e1e5cfc) with master (286a6f8)
Renamed helpers.h to atomic_helpers.h, and replaced the C11 stdatomic.h/C++ std::atomic split with the same three-way dispatch CPython's Include/cpython/pyatomic.h uses: GCC/Clang builtins as the default, C11 stdatomic.h as the next choice, and MSVC intrinsics only as the last resort for cl.exe (which supports neither). This drops the C++-specific std::atomic branch, since the GCC-builtin and MSVC paths already work under both C and C++ compilation. Also replaced the do-nothing try/except blocks in the two new thread-safety tests with contextlib.suppress().
Py_END_CRITICAL_SECTION() expands to a bare closing brace, so a done: label placed immediately before it (with no statement between them) is a label at the end of a compound statement -- valid only under C23. GCC accepted it silently as an extension, which is why this built cleanly everywhere tested locally, but clang (macOS CI) and MSVC (Windows CI) both reject it under -std=c11: clang's -Wc23-extensions and MSVC's C5299. done:; (an empty statement after the label) fixes it under C11 on all three toolchains. Reproduced locally with clang and confirmed the fix; ran the full suite (gcc and clang, default GIL build and a free-threaded 3.13.7t build): 1833 / 1828+5 skipped, all passing.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1438 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 4065 4139 +74
Branches 293 306 +13
=========================================
+ Hits 4065 4139 +74
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Confidence Score: 5/5Safe to merge. The previously reported coverage gap is fully addressed: the concurrent worker now exercises getall(), popone(), popall(), and equality against both a MultiDict and a plain dict. The prior thread was resolved by greptile-apps[bot] without explanation. Reviews (3): Last reviewed commit: "Close test-coverage gap flagged by revie..." | Re-trigger Greptile |
…all/eq test_single_item_ops_thread_safety's docstring claimed coverage for getall(), popone(), popall(), getone(), __getitem__, and __eq__, but the worker loop never called any of them -- popone()/popall() are separate C wrappers from pop()/popitem() (same underlying md_pop_one/ md_pop_all, but each independently locked), so exercising only pop() proved nothing about popone()'s own lock. Adds a second concurrently-mutated MultiDict so __eq__ is exercised against both another multidict (the CRITICAL_SECTION2 path) and a plain dict (the single-object, generic-mapping path).
<!-- Thank you for your contribution! --> ## What do these changes do? First slice of the lock-free read path deferred out of #1438: instead of a critical section, `__contains__` now protects itself with a reader-counted table retirement scheme, and the hash table a lock-free reader might still be walking is kept alive until it's safe to free. Two counters, gated entirely behind `Py_GIL_DISABLED`: - `MultiDictObject.active_readers`: a coarse "some lock-free reader is in flight on this object" gate, bumped before a reader ever dereferences a keys table and dropped once it's done (`_md_reader_enter()`/`_md_reader_exit()`). - `htkeys_t.readers`: a per-table count, advisory only, used purely as a defensive assertion once the coarse gate is already known closed. It is not itself load-bearing for safety: an embedded refcount can't safely announce "about to use this" without a bootstrap hazard, since the increment itself would dereference memory that might already be freed by the time it runs. `_md_retire()`/`_md_drain_retired()`: a resize/shrink/clear no longer frees the outgoing table immediately, only once `active_readers` reads 0 at a point synchronized (`seq_cst` on both the `md->keys` swap and the `active_readers` ops -- anything weaker leaves a real, architecture-dependent race, the same shape as Dekker's algorithm). A table that can't be freed yet moves to a per-object retired list and is freed opportunistically the next time the object resizes. `_md_shrink()` gets a second implementation under `Py_GIL_DISABLED`: the existing one compacts the currently-published table in place, which races a lock-free reader walking the very memory being rewritten. The free-threaded version reuses `_md_resize()` at the current size instead (build a new table, swap, retire the old one), which already has the right shape; the GIL build keeps the original in-place version unchanged. `md_clone_from_ht()` gets a matching fix: it `memcpy`s another live table's header wholesale, which was copying that table's in-flight reader count and retirement link along with everything else. `md_contains()` with `pret == NULL` (`__contains__`'s actual call shape) is the first lock-free consumer: `entry->identity`/`hash` are write-once-at-insertion and never mutated again outside `getall()`'s already-critical-section-only `MD_HASH_MARK` toggling, so this walk needs nothing beyond the table's own lifetime protection -- no atomic entry-field stores or `TryIncRef` machinery required, unlike `get()`'s value read (out of scope here; deferred as its own follow-up). The critical sections around `multidict_sq_contains` and `multidict_keysview_contains` are removed accordingly; view set-algebra callers of `md_contains(pret != NULL)` keep their existing critical sections untouched. Also fixes a small, pre-existing, unrelated bug noticed while rewriting `md_contains()`: `identity` was decref'd once on a match, then decref'd again via `goto fail` if `_md_ensure_key()` failed afterward. Renamed seven helpers in `hashtable.h` (`_md_reader_enter`, `_md_reader_exit`, `_md_retire`, `_md_drain_retired`, `_md_calc_key`, `_md_finder_slot`, `_md_finder_index`) to use the `_md_` prefix the file already uses for internal-only helpers, since none of them have callers outside the file. `getall()` and the view set-algebra methods stay under the critical section: `md_find_next()`/`md_finder_cleanup()` mark visited entries by mutating `entry->hash` in place (`MD_HASH_MARK`), which races any concurrent access to those entries the same way `_md_shrink()`'s in-place compaction did. Fixing that needs moving the visited-tracking to a call-local structure instead of shared entry state -- a self-contained follow-up, not attempted here. `get()`/`getone()`/ `__getitem__` likewise stay locked, needing atomic stores at every entry-mutation site plus `PyUnstable_TryIncRef` on read. ## Are there changes in behavior for the user? No behavior change for single-threaded code or the default GIL build. On the free-threaded build, `__contains__` no longer takes a critical section. ## Is it a substantial burden for the maintainers to support this? Some: this introduces the reclamation scheme the rest of the lock-free read work will build on, so it's more surface than a typical PR, but it's confined to `hashtable.h` and gated entirely behind `Py_GIL_DISABLED`; no behavior change on the GIL build and no new public API. ## Related issue number N/A, no linked issue. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` <details> <summary>Agent run details (optional, for reviewers)</summary> Tests: `pytest -q` on the default GIL build (1834 passed) and on a free-threaded `3.13.7t` build, both release and `MULTIDICT_DEBUG_BUILD=1` (1829 passed, 5 skipped each), re-verified after each structural change (retirement scheme, `_md_shrink` rewrite, `md_contains` conversion, the rename) and again after rebasing onto master's #1440. Added `test_contains_lock_free_thread_safety`, driving heavy concurrent `add()`/`pop()` churn against concurrent `in` checks specifically to exercise the retire/drain path, not just the (always-safe) case where `active_readers` happens to already be 0 at retirement time. Same honest caveat as on #1438's second regression test: I could not force a crash on a deliberately-unprotected version of `md_contains` by stress-testing it (release build, debug build, a heavier standalone script) -- this allocator doesn't poison freed memory, so a stale read tends to return coherent-looking bytes rather than crash. The race is real by construction (verified by manually disabling the protection and reviewing the resulting code path), just not reliably reproducible empirically in this environment. `make doc-spelling` passes clean (the pre-existing "fallbacks" wordlist gap from #1438 was fixed by #1439, already on master). Drafted with Claude Code (Sonnet 5); reviewed by [email protected]. </details> --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
<!-- Thank you for your contribution! --> ## What do these changes do? Adds per-instance locking to the pure-Python `MultiDict`/`CIMultiDict` fallback (`multidict/_multidict_py.py`) so it gives the same crash-free, corruption-free guarantee as the C extension under a free-threaded (no-GIL) build. Every method that touches an instance's hash table takes that instance's own `RLock` (created once in `__new__`, reused across a later re-init); two-object operations (`update()`, `extend()`, `merge()`, `__eq__()`, copy construction) lock both objects together in a fixed, deadlock-safe order; view iterators take the lock per step rather than for the whole iteration, so a concurrent mutation between steps surfaces as the same "changed during iteration" `RuntimeError` a single-threaded caller already gets today instead of a deadlock; and the version counter shared by every instance gets its own lock. On a regular GIL-enabled interpreter the locked methods are the exact same function objects as before this change -- no wrapper, no lock, no measurable overhead. ## Are there changes in behavior for the user? Yes, but only on a free-threaded build: concurrent use of a pure-Python `MultiDict`/`CIMultiDict` from multiple threads is now safe against crashes and data corruption, matching the C extension. On a regular (GIL-enabled) build there is no behavior or performance change. ## Is it a substantial burden for the maintainers to support this? No. The change is self-contained to `_multidict_py.py`, gated entirely behind a runtime free-threading check computed once at import, and mirrors the locking approach already reviewed and merged for the C extension (#1438, #1441, #1445, #1446). The C extension itself is unaffected; this only touches the pure-Python fallback. ## Related issue number N/A -- no linked issue. Continues the free-threading hardening already done for the C extension. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` (N/A, this repo has no `CONTRIBUTORS.txt`) - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` <details> <summary>Agent run details (optional, for reviewers)</summary> Tests: `pytest -q` passes on both backends; the pure-Python leg was additionally run under a free-threaded interpreter (CPython 3.13.7t, `PYTHON_GIL=0`) multiple times with coverage active, plus a standalone stress script driving 16 threads through thousands of concurrent mutations, with no crashes or corruption. Lint: `ruff check`, `ruff format --check`, and `mypy` (3.11 and 3.13, via `pre-commit`) all pass on the changed files. Docs: `make doc-spelling` passes. Note: while calibrating test load, a pre-existing, unrelated race in `update()`/`extend()`/`merge()`/`clear()` was found -- reachable even on a plain GIL-enabled interpreter under heavy concurrent use (pure Python bytecode isn't atomic even under the GIL). Confirmed present on unmodified `master` too, so it predates and is out of scope for this PR; a follow-up is planned separately. Two of the new tests that would otherwise be flaky against it are skipped on non-free-threaded builds, with the reason stated inline. </details> Drafted with Claude Code; reviewed by asvetlov.
## What do these changes do? Adds two race tests for the C extension on free-threaded builds: one iterates a multidict while other threads mutate it, the other extends from a source that other threads are resizing. #1431 through #1446 made these paths safe. Against the tree before that series both tests segfault on every run; against current master they pass. There is no other threaded test in the suite, so this is what would turn a regression into a red free-threaded CI leg instead of silence. The C changes this PR originally carried are superseded by that series and have been dropped. ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No. One test file and a `contrib` fragment; the tests are `c_extension`-marked and take about a quarter of a second. ## Related issue number Follows #1431, #1433, #1438, #1441, #1445, #1446. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [ ] Documentation reflects the changes -- N/A - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` -- N/A - [x] Add a new news fragment into the `CHANGES/` folder --------- Co-authored-by: Andrew Svetlov <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
) <!-- Thank you for your contribution! --> ## What do these changes do? Every method in the pure-Python `MultiDict`/`CIMultiDict` fallback (`multidict/_multidict_py.py`) that mutates `self._keys`/`self._used` (`add()`, `__setitem__`/`__delitem__`, `setdefault()`, `pop()`/`popone()`/`popall()`, `popitem()`, `update()`, `extend()`, `merge()`, `clear()`, and re-`__init__`) ran without any synchronization on a GIL-enabled build. Pure-Python bytecode is not atomic even under the GIL, so two threads calling these concurrently on the same instance (or reading one as the argument to another thread's `update()`/`extend()`/`merge()`) can interleave mid hash-table insert or deletion and corrupt the shared index table (hanging in an infinite probe loop or raising `AttributeError`), or silently drop a completed write (e.g. a concurrent `add()` writing into a table an in-progress `extend()`'s resize is about to replace). This is reproducible on a regular, GIL-enabled interpreter given enough contention; the coverage tracing this test suite already runs under is enough to hit it reliably, no free-threaded build required. Every `MultiDict`/`CIMultiDict` instance now gets its own `RLock`, held for the duration of these operations. Two-object operations (`__init__`/`update()`/`extend()`/`merge()` reading another `MultiDict` as their argument) lock both instances in a fixed order to avoid deadlock. `_add_with_hash()`/`_add_with_hash_for_upd()` and `popitem()` also had their write ordering fixed so an index is only published once its entry is reachable, and an entry's index is cleared before the entry is dropped from the entries list. Read-only methods (`getall()`, `getone()`, `__contains__()`, `__eq__()`, `__repr__()`, `to_dict()`, iteration, view operations) are unaffected and stay locked only on a free-threaded build, matching the scope of #1447: this PR is about lost or corrupted writes between mutators, not about a reader observing a torn read. This builds directly on #1447's locking infrastructure (`RLock`, `_PairLock`, `_other_lock`) rather than adding a separate scheme: `_locked_always`/`_locked_pair_always` are unconditional counterparts to `_locked`/`_locked_pair` that skip the free-threading gate, applied to every mutating method. `__new__` now always constructs the lock (not just under free-threading), since these methods need it on every build. The C extension already serializes all of these operations with a critical section (see #1438, #1441) and is unaffected by this change. ## Are there changes in behavior for the user? No observable API change. Concurrent use of a pure-Python `MultiDict`/ `CIMultiDict` from multiple threads no longer risks corruption, a hang, or a silently lost write; single-threaded use is unaffected apart from a small added lock overhead (see benchmark note below). ## Is it a substantial burden for the maintainers to support this? No. The change is self-contained to `_multidict_py.py`'s mutating methods and mirrors the locking approach already used by the C extension's critical sections, and reuses #1447's infrastructure rather than adding a parallel one. ## Related issue number N/A -- no linked issue. This race predates and is unrelated to the free-threading work in #1447; that PR's own testing flagged this exact race as reachable on a plain GIL build and out of scope for it (see the `_gil_build_race_skip` marker it added to `tests/test_multidict.py`, with a comment noting a follow-up was planned separately). This is that follow-up. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [x] Documentation reflects the changes - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` (N/A, this repo has no `CONTRIBUTORS.txt`) - [x] Add a new news fragment into the `CHANGES/` folder - [x] `make doc-spelling` passes and any new technical words are added to `docs/spelling_wordlist.txt` <details> <summary>Agent run details (optional, for reviewers)</summary> Repro: confirmed the race on unmodified master with a repro script running `update()`/`merge()`/`extend()` from 8 threads; it hung with multiple threads stuck in `iter_hash()`'s probe loop (`faulthandler` stack dump captured during the session). The same script passes cleanly after this fix, run 10+ times, plus an extended variant that also exercises `popitem()`/`clear()` and asserts internal consistency (every live entry reachable via its own hash bucket) after the run, run 8+ times. This branch was rebased onto master after #1447 merged (it touched the same file, adding the free-threading-only locking this PR now also reuses); an automated review (Greptile) on the pre-rebase commit correctly flagged two real gaps, both addressed in the second commit: a reentrancy deadlock (moot after picking up #1447's `RLock`, now covered by a regression test) and `add()`/`__setitem__()`/etc. still running unlocked, which this PR's second commit closes by locking every mutator, not just the original five methods. Tests: `pytest -q` (1908 passed) against the default C-extension build, `MULTIDICT_NO_EXTENSIONS=1` + `pytest -q --no-c-extensions` (963 passed, 6 skipped) against the pure-Python GIL build, and the same pure-Python command under a free-threaded interpreter (CPython 3.13.7t, 969 passed), all in isolated venvs built from this worktree. Coverage stayed at 99% on `_multidict_py.py` on every leg, with the free-threading-only branches covered by the free-threaded leg and vice versa (the same split #1447's own decorators already have). Performance: locking every mutator (not just the original five) adds roughly 150-200ns of uncontended lock overhead per call on the pure-Python backend. For O(n) bulk operations (`update()`/`extend()`/ `merge()`) this is a few percent at a realistic size (~20 items, e.g. typical HTTP headers) and within measurement noise; for O(1) single-item operations (`add()`/`popone()`/etc.) it's a fixed cost that doesn't shrink with size, roughly 15-20% by `timeit` best-of-7 samples. The C extension is unaffected either way. Flagging per the trade-off note in `AGENTS.md` rather than trying to eliminate it, since correctness under a GIL build (data loss, not just a crash) was the point; the `@contextmanager`-based approach tried initially added roughly 5x more overhead than this and was dropped in favor of `with self._lock:` directly and, for the two-object case, plain `acquire()`/`release()` calls. Lint: `pre-commit run` (ruff, mypy for 3.11 and 3.13) passed on the changed files. Docs: `make doc-spelling` passed after adding `bytecode` to `docs/spelling_wordlist.txt`. Drafted with Claude Sonnet 5; reviewed by asvetlov. </details>
What do these changes do?
Extends the free-threaded-build locking from #1431/#1433 to the operations
that were still running without holding
self's lock at all:add(),__setitem__/__delitem__,get()/getone()/__getitem__,__contains__,getall(),setdefault(),pop()/popone()/popall()/popitem(),__eq__, iteration (keys()/items()/values()), and the&/|/-/^/in/isdisjoint()operations on.keys()and.items()views. A resize triggered by one thread's mutation could free the hash
table while a concurrent, unprotected reader on another thread was still
walking it.
The view set-algebra methods (
itemsview/keysviewand/or/sub/contains/isdisjoint) use the same_lock_held-style split CPython'sown
dictobject.cuses: the existing body is extracted into a_implfunction, and a thin wrapper acquires the critical section around it,
since several of these have multiple
goto/return exits that can't bewrapped with
Py_BEGIN_CRITICAL_SECTION/Py_END_CRITICAL_SECTIONinplace.
This also fixes a compile error in the in-progress atomic-reads branch
this stacks on:
htkeys.hreferencedatomic_load_ssize_relaxed()without including the header where it's defined. That header (renamed
atomic_helpers.h) now selects its atomic-load backend the same wayCPython's
Include/cpython/pyatomic.hdoes: GCC/Clang builtins bydefault, C11
stdatomic.hnext, and MSVC intrinsics only as the lastresort for
cl.exe, which supports neither.len()stays lock-free (a relaxed atomic read ofmd->used), matchingCPython's own
dict_length(), which is also unlocked even though therest of
dictobject.cis fully critical-section-protected.Lock-free reads are intentionally out of scope here. CPython's dict
gets its
get()/__contains__/iteration speed back with a separate,validated
_Py_dict_lookup_threadsafe()path (optimistic lookup with aretry-on-concurrent-mutation check); that's a distinct follow-up, not
this PR.
Are there changes in behavior for the user?
No behavior change for single-threaded code or the default GIL build
(
Py_BEGIN_CRITICAL_SECTIONcompiles to a no-op there). On thefree-threaded build, these operations no longer race a concurrent
resize.
Is it a substantial burden for the maintainers to support this?
No. The change only adds locking around existing logic and reworks an
internal-only header; no new public API, and no behavior change on the
GIL build.
Related issue number
#1432
Checklist
CONTRIBUTORS.txtCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Tests:
pytest -qon the default GIL build (1833 passed), on afree-threaded
3.13.7trelease build (1828 passed, 5 skipped), and ona
MULTIDICT_DEBUG_BUILD=1free-threaded build (1828 passed, 5skipped). Re-verified on the GIL and free-threaded release builds
again after the
atomic_helpers.hrework.Two new regression tests were added
(
test_single_item_ops_thread_safety,test_view_set_ops_thread_safety)and verified against the unpatched code:
test_single_item_ops_thread_safetyreliably crashed thefree-threaded interpreter (within 3 runs) before this fix, and passes
10/10 after.
test_view_set_ops_thread_safetypasses reliably afterthe fix, but I could not reproduce a crash on the unpatched code in 40
pytest runs, a dedicated 32k-operation stress script, or under the
debug build -- likely because this pyenv build's allocator doesn't
poison freed memory, so the use-after-free (same unlocked-dereference
shape as the fixed single-item path) often reads stale-but-coherent
bytes rather than crashing. Flagging this so the weaker empirical
signal on that one test is not overstated. Both tests use
contextlib.suppress()rather than a baretry/except: passforthe racing-with-concurrent-mutation exceptions they intentionally
tolerate.
make doc-spellingcurrently fails on a pre-existing misspelling("fallbacks") in an already-released
CHANGES.rstentry, unrelated tothis PR's fragment;
towncrier build --draftrenders this PR'sCHANGES/1438.bugfix.rstfragment cleanly on its own.Drafted with Claude Code (Sonnet 5); reviewed by [email protected].