Repository navigation
Lock pure-Python MultiDict mutators against concurrent corruption - #1449
Conversation
Merging this PR will degrade performance by 25.6%
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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. 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.
6f4a112 to
40f7332
Compare
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
left a comment
There was a problem hiding this comment.
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.
|
Locks are slow, but without locks the code is literally not thread-safe. |
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.
…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]>
What do these changes do?
Every method in the pure-Python
MultiDict/CIMultiDictfallback(
multidict/_multidict_py.py) that mutatesself._keys/self._used(
add(),__setitem__/__delitem__,setdefault(),pop()/popone()/popall(),popitem(),update(),extend(),merge(),clear(), and re-__init__) ran without anysynchronization 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 midhash-table insert or deletion and corrupt the shared index table
(hanging in an infinite probe loop or raising
AttributeError), orsilently drop a completed write (e.g. a concurrent
add()writinginto 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/CIMultiDictinstance now gets its ownRLock,held for the duration of these operations. Two-object operations
(
__init__/update()/extend()/merge()reading anotherMultiDictas their argument) lock both instances in a fixed order toavoid deadlock.
_add_with_hash()/_add_with_hash_for_upd()andpopitem()also had their write ordering fixed so an index is onlypublished 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) areunaffected 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_alwaysare unconditional counterpartsto
_locked/_locked_pairthat skip the free-threading gate, appliedto 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/CIMultiDictfrom multiple threads no longer risks corruption, ahang, 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 mutatingmethods 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_skipmarker it added totests/test_multidict.py,with a comment noting a follow-up was planned separately). This is
that follow-up.
Checklist
CONTRIBUTORS.txt(N/A, this repo has noCONTRIBUTORS.txt)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent 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 withmultiple threads stuck in
iter_hash()'s probe loop (faulthandlerstack 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, nowcovered by a regression test) and
add()/__setitem__()/etc. stillrunning 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-extensionbuild,
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.pyon every leg, with thefree-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 costthat doesn't shrink with size, roughly 15-20% by
timeitbest-of-7samples. The C extension is unaffected either way. Flagging per the
trade-off note in
AGENTS.mdrather 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 addedroughly 5x more overhead than this and was dropped in favor of
with self._lock:directly and, for the two-object case, plainacquire()/release()calls.Lint:
pre-commit run(ruff, mypy for 3.11 and 3.13) passed on thechanged files.
Docs:
make doc-spellingpassed after addingbytecodetodocs/spelling_wordlist.txt.Drafted with Claude Sonnet 5; reviewed by asvetlov.