Repository navigation
Protect MultiDict update()/extend()/merge()/clear() with a critical section - #1433
Conversation
_multidict_extend() mutated self across several separate calls into the hash table code, releasing self's lock between them. On the free-threaded build this let another thread observe self with soft-deleted entries (identity set, key/value NULL) not yet cleaned up by md_post_update(), crashing with a NULL-pointer Py_INCREF in _md_add_with_hash() when that other thread read self as the source of its own update()/extend()/merge() call. Fix it by locking the whole operation: extract the goto-heavy mutation logic into _multidict_extend_locked() and call it from _multidict_extend() under a single Py_BEGIN_CRITICAL_SECTION(self), or Py_BEGIN_CRITICAL_SECTION2(self, other) when the argument is a multidict or multidict proxy instance distinct from self. The md_reserve() calls in extend()/update()/merge() get their own, separate critical section, since resizing self's table is already a self-contained, atomic step. Reproduced the crash against master and confirmed the fix under a genuine free-threaded build (CPython 3.13.7t via pyenv), including a gdb backtrace pinpointing the NULL key/value read. CI does not cover the free-threaded build (dropped in aio-libs#1326), so the new regression test is gated on the C extension and kept to a small thread/iteration count to stay fast under pytest-cov's line tracer.
extend()/update()/merge() locked md_reserve() and _multidict_extend() separately, so a resize from md_reserve() was itself atomic but the gap between the two critical sections still let another thread observe self between the resize and the update it was reserving space for. Fold both into one critical section per call so the whole operation is atomic, matching the constructors and the Py_BEGIN_CRITICAL_SECTION2 case. _multidict_extend() goes back to assuming the caller already holds the necessary lock(s), same as before it grew its own locking; _multidict_resolve_other() factors out the "is arg a multidict or proxy" check needed to select the critical section, since every caller (three methods and two constructors) now has to make that choice for itself. Kept Py_BEGIN_CRITICAL_SECTION2(self, other) rather than nesting two single-object critical sections: per Include/cpython/critical_section.h, "you CANNOT use nested critical sections to lock more than one object at once, because the inner critical section may suspend the outer critical sections" -- nesting would silently drop self's lock while other's is held, reopening the same race.
The branch was opened as PR aio-libs#1433, not the guessed aio-libs#1432.
md_clear() walks self's entries, clearing each one, then frees self->keys, without holding self's lock. On the free-threaded build a concurrent extend() on the same multidict could run partway through that walk, crashing: reproduced a SIGSEGV in about 40% of runs against the pre-fix code under a genuine free-threaded CPython 3.13.7t build. Wrap the call in multidict_clear() with Py_BEGIN_CRITICAL_SECTION(self), same as the other mutating methods on this branch; clear() only ever touches self, so it doesn't need the two-object form. Confirmed fixed with 20+ stress runs under the same free-threaded build with no crashes, and added a C-extension-only regression test mirroring test_update_extend_merge_thread_safety().
CI caught this on Windows: asserting len(d) == 200 assumed clear() and extend() from different threads would always leave exactly 200 entries behind, but nothing orders one thread's clear() against another's extend() from a different clear()/extend() pair, so the count left behind depends on scheduling, not just correctness. Assert internal consistency (len() matches the actual item count) instead of a specific size.
Confidence Score: 3/5Direct reads need the same lifetime protection as One memory-safety failure remains: lookup and containment can dereference storage released by a concurrent clear operation. Files Needing Attention: multidict/_multilib/hashtable.h, multidict/_multidict.c
|
One function per shape of the extend()/update()/merge() argument: _multidict_extend_from_arg() for a dict/list/tuple/mapping/sequence, _multidict_extend_self() for other-is-self, and _multidict_extend_from_other() for a distinct multidict/proxy. Each caller already has to compute `other` up front to pick the critical section macro, so it can pick the matching function at the same time instead of re-deriving "which case is this" inside one combined function. _multidict_extend_from_other() now asserts other != self, since that case has its own function.
CI caught this on a genuine free-threaded debug build (Test ubuntu 3.14t ext debug, PR aio-libs#1433): extend()/update()/merge()/clear() each called ASSERT_CONSISTENT(self, false) again after their Py_END_CRITICAL_SECTION[2](), on top of the identical check the locked helper (or md_clear()) already runs at the end of its own locked scope. That second, unlocked call could read self while a different thread's update()/merge() was mid-operation on the same self, with some entries' hash temporarily negative (the soft-delete mark md_post_update() hasn't cleaned up yet), tripping the debug build's `entry->hash >= 0` assertion and aborting the process. In a release build ASSERT_CONSISTENT is a no-op, which is why this did not show up in any of the release-build stress testing on this branch. Reproduced locally by building the C extension in debug mode (MULTIDICT_DEBUG_BUILD=1) against the free-threaded CPython 3.13.7t build and running test_update_extend_merge_thread_safety under gdb: Assertion failed: "entry->hash >= 0", multidict/_multilib/hashtable.h, in _md_check_consistency(), called from multidict_update() at _multidict.c:954 (outside the critical section). Removed the four redundant, unlocked calls; the locked ones already cover the same check. Confirmed fixed with 45 stress runs (15 targeted + 30 more) and the full suite, all under the same debug free-threaded build, no aborts. The MultiDict/CIMultiDict constructors keep their trailing ASSERT_CONSISTENT: self there is a brand-new object under construction, not yet reachable from another thread, so the same race does not apply. Noted but not fixed here (out of scope for this PR): the constructor fast-clone path and MultiDict.copy() read `other`/`self` via md_clone_from_ht() without any locking at all.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1433 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 3942 4022 +80
Branches 283 293 +10
=========================================
+ Hits 3942 4022 +80
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:
|
future.result() re-raises a worker's exception directly, so there is no need for a manually-collected errors list, a try/except around the worker body, or the pragma: no cover on an except clause that should never fire.
map() is shorter and does the same thing here: iterate the returned generator to run every worker and propagate the first exception.
_multidict_clone_fast() (the MultiDict(other)/CIMultiDict(other) constructor fast path) and multidict_copy() (.copy()) both called md_clone_from_ht(target, source) with no locking on `source` at all, even though it can be a pre-existing, concurrently-mutated multidict. Reproduced a crash reliably (20/20 stress runs under a free-threaded CPython 3.14.7t debug build) by racing .copy()/MultiDict(other) against concurrent update()/merge() on the same source, then fixed it the same way as the rest of this branch: Py_BEGIN_CRITICAL_SECTION2 on both objects, or Py_BEGIN_CRITICAL_SECTION(self) alone for the other == self case in the fast-clone path (an explicit re-init, `d.__init__(d)`, can reach that). Also drops the redundant, unlocked trailing ASSERT_CONSISTENT(new_md, false) in multidict_copy(): like the ones removed earlier on this branch, it duplicates the check md_clone_from_ht() already does under lock. Also applies two review comments: kwds validation moves out of the three _multidict_extend_* specializations and into their five callers (it doesn't depend on `self`'s state, so there's no reason to duplicate it inside the locked helpers), and _multidict_extend_from_arg() gets an assert documenting that it's never called with a multidict/ proxy arg, matching the existing assert(other != self) on _multidict_extend_from_other(). Known residual issue, not fixed here: racing update()/merge() against .copy() (or even just against other update()/merge() calls) can still very rarely (roughly 1 in 20-40 runs under the same debug build) trip the same entry->hash >= 0 assertion, despite every call being properly locked at the API level. It doesn't reproduce under any amount of sequential (single-threaded) stress, which points to CPython's critical-section suspend-around-a-blocking-call behavior interacting with md_clone_from_ht()/_md_resize() caching a size or pointer read before a PyMem_Malloc() call and using it after -- a correctness gap inside the hashtable resize/clone internals themselves, not something another critical section placement at the API layer can fix. Tracked separately.
md_init() (which calls md_clear(), freeing self's old hash table and replacing it) ran before any critical section began in multidict_tp_init()/cimultidict_tp_init(). For the normal case (self still private to the constructor call) that's harmless, but __init__ can also run explicitly on an already-published, potentially shared multidict (d.__init__(other)), at which point a concurrent caller of any other locked method could observe self mid-reset. Reorder to resolve `other` first, then fold md_init() into the same critical section as the extend/clone call that follows it -- same pattern already used for md_reserve() in extend()/update()/merge(). Also drops the trailing, unlocked ASSERT_CONSISTENT(self, false) at the end of both constructors: like the other trailing checks removed earlier on this branch, it's redundant with the one the locked helper (or the fast-clone path) already runs, and it raced the same way. Verified with a new regression test racing __init__() against other locked methods (20/20 clean runs, plus the full suite) under the free-threaded CPython 3.14.7t debug build that CI uses. While verifying this, found a separate, pre-existing, and much larger issue while stress-testing with a concurrent reader that also iterates (list(d.items())) rather than just calling plain methods: the C extension's iterators (items()/keys()/values()/__iter__) hold no lock at all across their lifetime. md_next()'s version check is a best-effort heuristic, not synchronization -- it can pass the check and then read out of bounds against a table another thread replaced a moment later, which reproduces reliably (SIGSEGV/SIGABRT within a handful of stress runs) whenever a full-reset operation like clear() or __init__() races a live external iterator. That is not new to this commit (it is pre-existing for every method that fully replaces the keys table, not specific to __init__), well beyond "add critical sections to public API methods", and not fixed here. The regression test added in this commit deliberately avoids the iteration pattern so it verifies the __init__ atomicity fix without tripping over the separate, unfixed iterator problem.
_multidict_extend_from_arg(), _multidict_extend_self(), and _multidict_extend_from_other() are only ever called from inside a Py_BEGIN_CRITICAL_SECTION[2] block; their doc comments already said so, but the names themselves didn't signal it. Rename them to _multidict_extend_from_arg_locked(), _multidict_extend_self_locked(), and _multidict_extend_from_other_locked(), matching the convention (a _locked suffix meaning "caller must already hold the lock") used in other C codebases for this exact contract. Pure rename, no behaviour change.
_multidict_extend_from_arg_locked() iterated a plain dict `arg` via md_update_from_dict() (PyDict_Next()) while holding only self's lock, not arg's. PyDict_Next() isn't safe against concurrent mutation of the dict it's iterating, so a shared dict passed as the argument to update()/extend()/merge() could be read mid-mutation by another thread, even though that thread's own writes to the dict went through dict's own, individually-locked methods. Split the dict case out into its own _multidict_extend_from_dict_locked(), which requires `arg` locked in addition to `self`; the remaining list/tuple/generic-mapping cases stay in _multidict_extend_from_arg_locked(), renamed to _multidict_extend_from_seq_locked() to match what it actually handles now (the generic-mapping fallback materializes a fresh, unshared sequence via arg.items(), so it doesn't have the same problem). Updated all five call sites (three methods, two constructors) to pick Py_BEGIN_CRITICAL_SECTION2(self, arg) when arg is a plain dict. Also, per review: multidict_copy() locks only `self`, not the freshly-allocated `new_md` -- unlike _multidict_clone_fast() (used from __init__, where self can be an existing, shared object via explicit re-init), copy()'s target is never reachable from another thread until the call returns, so locking it serves no purpose. Verified with a new regression test racing update() from a shared dict against concurrent mutation of that dict (20/20 clean runs, plus the full suite) under the free-threaded CPython 3.14.7t debug build. While doing so, noticed the already-tracked residual entry->hash assertion (see the earlier commit fixing extend()/update()/merge()) fires noticeably more often now in a mixed update()+merge()+copy() stress test -- merge() with a plain dict literal argument now goes through the two-object critical section instead of the simpler one-object form, which appears to widen exposure to that same pre-existing, separately-tracked bug. Not something this commit's own locking can fix; raises the priority of the existing follow-up rather than changing what needs to happen there.
Each of the four _multidict_extend_*_locked() specializations duplicated the same "if (op != Extend) md_post_update(self);" in both its success and fail path. op is a compile-time constant at every call site (multidict_extend()/the constructors always pass Extend; multidict_update()/multidict_merge() always pass Update or Merge), so the caller already knows whether it's needed without a runtime check. Move it there: multidict_update()/multidict_merge() now call md_post_update() unconditionally after the extend attempt, still inside the same critical section; the constructors and multidict_extend() never call it at all. The specializations' own ASSERT_CONSISTENT(self, false) has to become ASSERT_CONSISTENT(self, op != Extend): md_post_update() no longer runs before it for Update/Merge, so entries can still be soft-deleted or hash-marked at that point, which is expected mid-operation, not a bug. md_post_update() already does its own strict ASSERT_CONSISTENT(md, false) at the end, so the overall guarantee -- a strict check by the time the whole call returns -- is unchanged. Verified with the full suite on both backends and the free-threaded CPython 3.14.7t debug build (where a wrong locking or assert choice here would have shown up immediately as a false-positive entry->hash/soft-delete assertion).
Move md_update_from_dict(kwds) and ASSERT_CONSISTENT out of the _locked specializations to the caller, then drop the specializations entirely in favor of calling md_update_from_ht/md_update_from_dict/ md_update_from_seq/md_extend_self directly from each of the five call sites. Also fold _multidict_extend_from_seq_locked's PyMapping_Items fallback into md_update_from_seq itself, so mapping and plain-iterable arguments are both handled in one place.
…finding) md_clear() used to release each entry's identity/key/value while the old table was still the published one. Releasing a value can run arbitrary Python code (a __del__), which can suspend the held critical section; a concurrent, properly-locked caller could then observe the multidict mid-clear, a state nothing else in the codebase expects. Swap md->keys to the empty table before releasing any entry's references, so a suspended thread only ever exposes the fully populated table or the fully empty one.
…l section (#1438) <!-- Thank you for your contribution! --> ## 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`/`keysview` `and`/`or`/`sub`/ `contains`/`isdisjoint`) use the same `_lock_held`-style split CPython's own `dictobject.c` uses: the existing body is extracted into a `_impl` function, and a thin wrapper acquires the critical section around it, since several of these have multiple `goto`/return exits that can't be wrapped with `Py_BEGIN_CRITICAL_SECTION`/`Py_END_CRITICAL_SECTION` in place. This also fixes a compile error in the in-progress atomic-reads branch this stacks on: `htkeys.h` referenced `atomic_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 way CPython's `Include/cpython/pyatomic.h` does: GCC/Clang builtins by default, C11 `stdatomic.h` next, and MSVC intrinsics only as the last resort for `cl.exe`, which supports neither. `len()` stays lock-free (a relaxed atomic read of `md->used`), matching CPython's own `dict_length()`, which is also unlocked even though the rest of `dictobject.c` is 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 a retry-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_SECTION` compiles to a no-op there). On the free-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 - [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 (1833 passed), on a free-threaded `3.13.7t` release build (1828 passed, 5 skipped), and on a `MULTIDICT_DEBUG_BUILD=1` free-threaded build (1828 passed, 5 skipped). Re-verified on the GIL and free-threaded release builds again after the `atomic_helpers.h` rework. 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_safety` reliably crashed the free-threaded interpreter (within 3 runs) before this fix, and passes 10/10 after. `test_view_set_ops_thread_safety` passes reliably after the 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 bare `try`/`except: pass` for the racing-with-concurrent-mutation exceptions they intentionally tolerate. `make doc-spelling` currently fails on a pre-existing misspelling ("fallbacks") in an already-released `CHANGES.rst` entry, unrelated to this PR's fragment; `towncrier build --draft` renders this PR's `CHANGES/1438.bugfix.rst` fragment cleanly on its own. Drafted with Claude Code (Sonnet 5); reviewed by [email protected]. </details>
## 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>
## What do these changes do? Bulk updates from a list and `[key, value] in md.items()` borrowed items from a list the caller still owns and increfed them in a separate step. On a free-threaded build another thread can drop the item in between, or shrink the list between its length check and the reads, and the C extension reads freed memory. Each item is now taken as a new reference with `PyList_GetItemRef` on free-threaded builds, which fetches atomically and locks the list only if its lock-free attempt fails; GIL builds keep the `PyList_GET_ITEM` macro, so their hot paths are unchanged. Follows #1379, which fixed the stale length in the same loop. A critical section on the list, as #1433 takes on a dict argument, would not do: it covers neither a `[key, value]` item inside the list nor the probe handed to `in`, and it is released whenever the thread detaches, which a key's `__hash__` or `__eq__` can cause mid-loop. A strong reference per fetch is what actually holds. ## Are there changes in behavior for the user? On free-threaded builds only: a call that finds a list item gone after the list's length was checked now raises `RuntimeError("list changed size during iteration")`, from `update()`, a `[key, value]` item and `[key, value] in md.items()` alike. A list that is simply shorter by the next iteration of `update()` still ends the update there, as before (#1379) and as in a plain `for` loop. ## Is it a substantial burden for the maintainers to support this? No. One helper in `hashtable.h`, used at three sites. ## Related issue number None. ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist - [ ] Documentation reflects the changes -- N/A, no API change - [ ] If you provide code modification, please add yourself to `CONTRIBUTORS.txt` -- N/A, no such file - [x] Add a new news fragment into the `CHANGES/` folder --------- Co-authored-by: Junhyung Lee <[email protected]>
What do these changes do?
Protects
MultiDict.update(),.extend(),.merge(),.clear(),.copy(),and the
MultiDict/CIMultiDictconstructors (including the fast-clonepath and, for an explicit re-init on an already-published multidict, the
reset step) in the C extension with a critical section, so each operation
is atomic from the point of view of other threads. When update()/extend()/
merge() take a plain dict argument, that dict is locked too (in addition
to self), since PyDict_Next() is not thread-safe against a foreign thread
concurrently mutating the dict being iterated.
Are there changes in behavior for the user?
No behavioral change for single-threaded code. On the free-threaded
build of CPython, this fixes a real segmentation fault and/or data corruption.
Is it a substantial burden for the maintainers to support this?
No, it only touches the extend/update/merge/copy/clone/init implementation
in the C extension and uses the critical section macros already vendored via
pythoncapi_compat.h.Related issue number
Part of #1432
Checklist
CONTRIBUTORS.txtCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Reproduced the crash against
masterwith a threaded stress script and agdbbacktrace pinpointing a NULL key/value read in_md_add_with_hash(), using a genuine free-threaded CPython 3.13.7tbuild (via pyenv), not just compiling the macros. Confirmed the fix
under the same build: 25+ stress runs and 3
gdb-driven runs with nocrashes, plus the project's own
pytestsuite passing there (1798passed, 5 skipped for the pre-existing free-threaded
getrefcountincompatibility).
CI's "Test ubuntu 3.14t ext debug" job (free-threaded,
-UNDEBUG) thencaught a second bug the release-build stress testing above couldn't see:
extend()/update()/merge()/clear()each calledASSERT_CONSISTENTa second time after already releasing the lock, racing a concurrent
operation on the same object. Fixed by removing the redundant, unlocked
calls (the locked helper already performs the identical check). Verified
against the exact CI interpreter (
pyenv install 3.14.7t,MULTIDICT_DEBUG_BUILD=1): 45+ stress runs, full suite (1805 passed),several
gdb-driven runs, all clean..copy()and the constructor fast-clone path (MultiDict(other)) had thesame missing-lock problem on the read side: reproduced 20/20 crashes
under the same debug build by racing them against concurrent
update()/merge(), then fixed with the same critical-section pattern.
.copy()locks onlyself(the source being read), not the freshlyallocated target -- unlike the constructor fast-clone path, where
selfcan itself be an existing, shared object via an explicit re-init,
.copy()'starget is never reachable from another thread until the call returns.
Review also flagged that
__init__()'s reset (md_init(), which freesself's old hash table) ran before any critical section began. Harmless
for the usual case where self is still private to the constructor call,
but reachable via an explicit re-init on an already-published multidict
(
d.__init__(other)). Fixed by foldingmd_init()into the samecritical section as the extend/clone call that follows it, and confirmed
with a new regression test (20/20 clean runs) under the debug build.
Review also flagged that the dict-argument path iterated a plain dict
argviaPyDict_Next()(insidemd_update_from_dict()) while holdingonly self's lock, not arg's -- unsafe against a shared dict being
concurrently mutated by another thread through its own, individually-locked
methods. Split into its own
_multidict_extend_from_dict_locked()specialization that requires
arglocked too(
Py_BEGIN_CRITICAL_SECTION2(self, arg)), confirmed with a newregression test (20/20 clean runs) racing
update()from a shared dictagainst concurrent mutation of that dict.
Known residual issues, not fixed in this PR:
calls against each other (or against
.copy()) can still trip the sameentry->hash >= 0assertion. It never reproduces under any amount ofsequential stress, which points to CPython's critical-section "suspend
around a potentially-blocking call" behavior interacting with a cached
size/pointer read that spans a
PyMem_Malloc()call inside_md_resize()/md_clone_from_ht()(multidict/_multilib/hashtable.h).Initially measured at ~1 in 20-40 runs; after the dict-argument fix above
(which moved more call sites onto
Py_BEGIN_CRITICAL_SECTION2, e.g. adict-literal
merge()argument), a mixed update()+merge()+.copy()stress test now trips it in the large majority of runs. That's useful
signal for whoever picks up the follow-up:
Py_BEGIN_CRITICAL_SECTION2'sacquisition path specifically looks implicated, not critical sections
in general.
(
items()/keys()/values()/__iter__) hold no lock at all acrosstheir lifetime.
md_next()'s version-number check is a best-effortheuristic, not synchronization; a live iterator racing any operation
that fully replaces the table (
clear(),__init__(), ...) can readout of bounds and crash. This is pre-existing, not introduced by this
PR, and well beyond "add critical sections to public API methods."
Both are correctness gaps deeper than a critical-section placement at the
API layer can fix, so they're being tracked as separate follow-ups
rather than guessed at here.
A related, separate bug was found during this work: the pure-Python
implementation (
_multidict_py.py) has no locking at all around itsupdate()/extend()/merge(), so it can raiseAttributeErrorunderconcurrent access on a free-threaded build. That is out of scope for
this PR (which only touches the C extension) and is tracked as a
follow-up.
Tests:
pytest -qandMULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensionsboth pass on the current branch tip.
Lint:
make lint(ruff, clang-format, mypy, yamllint, etc.) all passedSpelling:
make doc-spellingpasses for the new fragment; onepre-existing, unrelated failure in already-released
CHANGES.rst("fallbacks" not in the wordlist) predates this branch and was left
untouched
Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.