Skip to content

Lock pure-Python MultiDict mutators against concurrent corruption - #1449

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:fix-pure-python-mutator-race
Sep 14, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:fix-pure-python-mutator-race

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 13, 2026 •

Copy link
Copy Markdown
Member

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

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A, this repo has no CONTRIBUTORS.txt)
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt
Agent run details (optional, for reviewers)

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.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 13, 2026
@codspeed

codspeed Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 25.6%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 20 (👁 20) regressed benchmarks
✅ 228 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
👁 test_create_empty_multidict[cs-py] 147.2 µs 201.2 µs -26.84%
👁 test_multidict_insert_str[ci-py] 2.5 ms 3.1 ms -19.36%
👁 test_multidict_add_str[ci-py] 217.2 ms 286 ms -24.07%
👁 test_multidict_popitem_str[ci-py] 1.4 ms 2 ms -30.23%
👁 test_multidict_pop_str[ci-py] 2 ms 2.6 ms -25.18%
👁 test_multidict_clear_str[ci-py] 71 µs 89.3 µs -20.46%
👁 test_multidict_delitem_str[ci-py] 2.1 ms 2.8 ms -24.84%
👁 test_create_empty_multidict[ci-py] 151 µs 207.2 µs -27.12%
👁 test_multidict_add_str[cs-py] 205.6 ms 272.3 ms -24.5%
👁 test_multidict_insert_str[cs-py] 2.3 ms 2.9 ms -21.54%
👁 test_multidict_pop_str[cs-py] 1.8 ms 2.5 ms -26.5%
👁 test_multidict_clear_str[cs-py] 74.2 µs 92.2 µs -19.48%
👁 test_multidict_popitem_str[cs-py] 1.2 ms 1.8 ms -33.42%
👁 test_multidict_delitem_str[cs-py] 2 ms 2.6 ms -25.11%
👁 test_cimultidict_delitem_istr[py] 2 ms 2.7 ms -25.5%
👁 test_create_from_existing_cimultidict[py] 104.7 µs 154 µs -32.01%
👁 test_cimultidict_add_istr[py] 209.9 ms 277.9 ms -24.47%
👁 test_cimultidict_insert_istr[py] 2.4 ms 3 ms -21.25%
👁 test_cimultidict_pop_istr[py] 1.9 ms 2.6 ms -26.35%
👁 test_copy_from_existing_cimultidict[py] 107.8 µs 157.6 µs -31.57%

Comparing asvetlov:fix-pure-python-mutator-race (a8724d5) with master (144171b)

Open in CodSpeed

@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (144171b) to head (a8724d5).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1449   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           32        32           
  Lines         4956      4994   +38     
  Branches       408       411    +3     
=========================================
+ Hits          4956      4994   +38     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@asvetlov
asvetlov marked this pull request as ready for review September 14, 2026 02:58
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 14, 2026 02:58
@greptile-apps

greptile-apps Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge.

No outstanding blocking issues were identified.

Reviews (5): Last reviewed commit: "Merge branch 'master' into fix-pure-pyth..." | Re-trigger Greptile

update()/extend()/merge()/clear()/popitem() in the pure-Python
fallback ran without any synchronization on a GIL-enabled build.
Pure-Python bytecode is not atomic even under the GIL, so enough
concurrent contention lets two threads interleave mid hash-table
insert or deletion and corrupt the shared index table, hanging in an
infinite probe loop or raising AttributeError. Confirmed on unmodified
master with a repro that hangs threads inside iter_hash()'s probe
loop.

This race is independent of free-threading and predates the locking
aio-libs#1447 added for that: aio-libs#1447 correctly scoped its own fix to
free-threaded builds and left this one as a known follow-up (see the
`_gil_build_race_skip` marker it added to tests/test_multidict.py).
This is that follow-up. Rather than adding a separate locking scheme,
this reuses aio-libs#1447's per-instance RLock, _PairLock and _other_lock:
_locked_always/_locked_pair_always are unconditional counterparts to
_locked/_locked_pair that skip the free-threading gate, applied to the
five affected methods. __new__ now always constructs the lock (not
just under free-threading), since these methods need it on every
build; __new__ (not __init__) is unaffected by a later re-init, so the
lock identity stays stable across `d.__init__(other)`.

Also fixes the write ordering in _add_with_hash()/
_add_with_hash_for_upd() and popitem() so an index is only published
once its entry is reachable, and an entry's index is cleared before
it's dropped from the entries list.

The C extension already serializes these operations with a critical
section and is unaffected.
@asvetlov
asvetlov force-pushed the fix-pure-python-mutator-race branch from 6f4a112 to 40f7332 Compare September 14, 2026 03:16
An automated review (Greptile) on the previous commit found two real
gaps in scoping the fix to only update()/extend()/merge()/clear()/
popitem():

- extend() held a non-reentrant lock while parsing its argument, so a
  callback that re-entered the same multidict (e.g. a SupportsKeys
  argument's keys() calling add()) would deadlock. Moot after the
  rebase onto aio-libs#1447's RLock, but worth a regression test since it was
  reported against the pre-rebase Lock-based version.
- add()/__setitem__()/__delitem__()/setdefault()/popone()/popall()
  still ran unlocked. A concurrent add() during a locked extend()'s
  resize can write into the table being replaced and have that write
  silently disappear once the resize publishes the new one: the
  now-locked methods are safe against each other, but not against
  these.

Every method that mutates self._keys/self._used now uses
_locked_always/_locked_pair_always, matching the C extension's
critical-section coverage of the same set of methods. __init__ is
included, since a re-init on a shared instance touches the same state.
Read-only methods (getall, getone, __contains__, __eq__, __repr__,
to_dict, iteration, view operations) are unaffected and stay
free-threading-gated, matching aio-libs#1447's original scope; this PR is
about lost/corrupted writes, not read tearing.

Adds a regression test for the reentrancy scenario Greptile described,
and updates test_pure_python_locking_is_free_threaded_only to check
still-free-threading-only methods instead of the now-always-locked
add()/__setitem__().

Re-verified: full suite on the C-extension build, the pure-Python
GIL build, and a pure-Python free-threaded build (3.13.7t), plus the
stress repro and consistency check from the first commit, all clean.

@Vizonex Vizonex left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The Use of a wrapper seems to be the correct approach here. I Approve this pull request since it will help strengthen against concurrent edits in free-threaded mode.

@asvetlov

Copy link
Copy Markdown
Member Author

Locks are slow, but without locks the code is literally not thread-safe.
I expect that people usually install C Extension anyway; which in GIL mode provides multithreading capability without extra overhead.

@asvetlov
asvetlov merged commit a445660 into aio-libs:master Sep 14, 2026
58 of 59 checks passed
@asvetlov
asvetlov deleted the fix-pure-python-mutator-race branch September 14, 2026 15:48
provos added a commit to provos/multidict that referenced this pull request Nov 24, 2026
The lock-pairing wrapper around the pure-Python constructors, extend(),
update() and merge() did not make its first parameter positional-only,
so MultiDict(arg=1) bound arg instead of adding a key named arg, and
raised TypeError. The C extension adds the key. This regressed in 6.9.0
with aio-libs#1449.
asvetlov added a commit that referenced this pull request Dec 2, 2026
…uments (#1842)

* Stop the pure-Python MultiDict taking a false argument for no argument

The pure-Python implementation defaulted the positional argument of the
constructors, extend(), update() and merge() to None and tested it by
truth value, so None, 0, False and other false non-iterables were
silently treated as if no argument had been passed. The C extension, like
dict, raises TypeError for them. The truth test also rejected iterables
whose __bool__() raises. This regressed in 6.2.0 with #1046.

Use the existing sentinel as the default and test identity against it,
and drop None from MDArg, which only existed to type the old default.

* Pass an arg keyword through to kwargs in the pure-Python MultiDict

The lock-pairing wrapper around the pure-Python constructors, extend(),
update() and merge() did not make its first parameter positional-only,
so MultiDict(arg=1) bound arg instead of adding a key named arg, and
raised TypeError. The C extension adds the key. This regressed in 6.9.0
with #1449.

* Update tests/test_update.py

---------

Co-authored-by: Andrew Svetlov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants