Repository navigation
Make __contains__ lock-free with reader-counted table retirement - #1441
Conversation
First slice of the lock-free read work aio-libs#1438 deferred: instead of critical-section-protected reads, entries a lock-free reader might still be walking are kept alive until it's safe to free them. Adds a two-counter reclamation scheme to hashtable.h, 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 has already been observed closed -- not itself load-bearing for safety, since an embedded refcount can't safely announce "about to use this" without a bootstrap hazard (the increment itself dereferences memory that might already be freed). - 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 is deferred to a per-object retired list and 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; needs atomic stores at every entry-mutation site plus PyUnstable_TryIncRef on read, 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 pre-existing, unrelated double-decref in md_contains: identity was decref'd once on a match, then decref'd again via goto fail if _md_ensure_key() failed afterward. getall() and the view set-algebra methods stay under the critical section for now: 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.
md_reader_enter(), md_reader_exit(), md_retire(), md_drain_retired(), md_calc_key(), md_finder_slot(), and md_finder_index() have no callers outside hashtable.h (only doc-comment cross-references from dict.h/atomic_helpers.h/htkeys.h, updated to match), unlike the rest of the md_* names in this file, which are the module's actual internal API surface used from _multidict.c/views.h/iter.h. Renamed with the _md_ prefix the file already uses for this distinction, matching _md_resize/_md_shrink/_md_replace/etc.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1441 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 4139 4214 +75
Branches 306 318 +12
=========================================
+ Hits 4139 4214 +75
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:
|
Revert their _md_ prefix from the previous commit: despite having no callers outside hashtable.h, they belong to the same naming family as md_finder_t/md_init_finder/md_find_next/md_finder_cleanup, and breaking two members out of that group for a naming rule that doesn't apply to the rest of it hurts more than it helps.
…rees Extends the reader-counted table retirement from __contains__ to md_get_one(), gated on PyUnstable_TryIncRef()/PyUnstable_EnableTryIncRef() (CPython 3.14+ only; 3.13 keeps taking the critical section, same as before). entry->identity and entry->value now go through atomic, TryIncRef-safe accessors on the free-threaded build, and insertion publishes identity last so a lock-free reader never sees a partially-populated slot. Stress-testing get() under a debug build surfaced three unrelated, pre-existing races, all fixed here since get()'s own correctness depends on them: _md_resize()/md_clone_from_ht() cached a keys-table pointer or size across a PyMem_Malloc() call whose contended allocator lock can transiently suspend the critical section, letting a concurrent operation invalidate it; _md_del_at() could leave self in an inconsistent state across a similarly-suspending decref; and multidict_get() ran ASSERT_CONSISTENT() over the whole table with no lock at all, racing any concurrent mutation on a debug build. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Confidence Score: 5/5Merge-safe; the one outstanding concern is non-blocking. The outstanding previous concern remains: retired hash tables are only drained during a later clear or resize, so an idle mapping can retain a previously cleared or resized allocation until another retirement-triggering operation occurs. The previous atomic key-publication finding was resolved by greptile-apps[bot] without explanation. The previous marked-hash lookup finding was resolved by greptile-apps[bot] without explanation. Reviews (6): Last reviewed commit: "Fix data race on md->used and clean up s..." | Re-trigger Greptile |
…lace path Extends the same fix pattern applied earlier to _md_resize()/_md_del_at() to _md_replace() and _md_update(): a decref inside these functions can transiently suspend the critical section (same allocator-lock mechanism as PyMem_Malloc()), letting a concurrent resize run against a half-finished replace. Both now defer dropping the old key/value reference until the entry is already in its final form, and detect (pointer and version, to rule out an ABA false negative from a freed table getting reallocated at the same address) whether the table changed underneath them, retrying the scan from scratch if so. _md_del_at_for_upd() and md_post_update() get the analogous fix for the same reason. Two more bugs surfaced while stress-testing this with an artificially widened suspension window: htkeys_build_indices() indexed a temporarily marked entry by its marked (and thus wrong) hash unless the caller's own update flag happened to be set, misplacing it wherever a different, concurrently-suspended _md_replace()/_md_update() call had marked something with a colliding bucket; and md_finder_cleanup() restored any marked entry it walked past to its own target hash, regardless of whether that entry was the one it had actually marked, corrupting an unrelated key's hash on a bucket collision. _md_check_consistency()'s strict-mode checks are also relaxed on the free-threaded build, since a concurrently-suspended operation on an unrelated key can legitimately leave an entry marked or half-deleted regardless of the caller's own update flag. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…asked hash comparison md->keys was published via plain, non-atomic stores at several sites while lock-free readers load it with atomic_load_ptr, which is undefined behaviour under C11 and could let the retirement protocol's ordering guarantee be broken by compiler or hardware reordering. All writers now go through a new _md_store_keys() helper on free-threaded builds. _md_contains_lockfree() and _md_get_one_lockfree() also compared a possibly MD_HASH_MARK-ed hash directly against the target hash, which could spuriously report a key absent while it was mid-_md_replace()/ _md_update() on another thread. Both now mask the mark bit off before comparing. Also renames active_readers/readers to num_active_readers/num_readers for clarity. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e read path md->used was written with plain, non-atomic compound ops at every mutation site while md_len() reads it lock-free via a relaxed atomic load, the same mismatch already fixed for md->keys. Every write now goes through _md_store_used()/_md_add_used() on free-threaded builds. Also drops a comment in _md_check_consistency() that claimed atomic loads were used for keys->usable/keys->nentries when the reads below it are plain (harmless since only the writer itself, under its own critical section, ever reads them), and fixes a stale reference to a _md_retire_resized() function that does not exist in _md_free_retired()'s comment. 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>
PyMem_Malloc never suspends an acquired critical section. The code for this guard was added by oversight by #1441; it is never executed.
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 areader-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 isin 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 asa 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 longerfrees the outgoing table immediately, only once
active_readersreads0 at a point synchronized (
seq_cston both themd->keysswap andthe
active_readersops -- 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 underPy_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 thecurrent 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: itmemcpys another livetable's header wholesale, which was copying that table's in-flight
reader count and retirement link along with everything else.
md_contains()withpret == NULL(__contains__'s actual callshape) is the first lock-free consumer:
entry->identity/hasharewrite-once-at-insertion and never mutated again outside
getall()'salready-critical-section-only
MD_HASH_MARKtoggling, so this walkneeds nothing beyond the table's own lifetime protection -- no atomic
entry-field stores or
TryIncRefmachinery required, unlikeget()'svalue read (out of scope here; deferred as its own follow-up). The
critical sections around
multidict_sq_containsandmultidict_keysview_containsare removed accordingly; viewset-algebra callers of
md_contains(pret != NULL)keep their existingcritical sections untouched.
Also fixes a small, pre-existing, unrelated bug noticed while
rewriting
md_contains():identitywas decref'd once on a match,then decref'd again via
goto failif_md_ensure_key()failedafterward.
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 thefile 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 criticalsection:
md_find_next()/md_finder_cleanup()mark visited entriesby mutating
entry->hashin place (MD_HASH_MARK), which races anyconcurrent access to those entries the same way
_md_shrink()'sin-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 everyentry-mutation site plus
PyUnstable_TryIncRefon 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 criticalsection.
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.hand gated entirely behindPy_GIL_DISABLED; no behavior change on the GIL build and no newpublic API.
Related issue number
N/A, no linked issue.
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 (1834 passed) and on afree-threaded
3.13.7tbuild, both release andMULTIDICT_DEBUG_BUILD=1(1829 passed, 5 skipped each), re-verifiedafter each structural change (retirement scheme,
_md_shrinkrewrite,
md_containsconversion, the rename) and again afterrebasing onto master's #1440.
Added
test_contains_lock_free_thread_safety, driving heavyconcurrent
add()/pop()churn against concurrentinchecksspecifically to exercise the retire/drain path, not just the
(always-safe) case where
active_readershappens to already be 0 atretirement time.
Same honest caveat as on #1438's second regression test: I could not
force a crash on a deliberately-unprotected version of
md_containsby 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-spellingpasses 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].