Skip to content

Make pure-Python MultiDict safe under free-threading - #1447

Merged
asvetlov merged 7 commits into
aio-libs:masterfrom
asvetlov:pure-python-free-threading
Sep 13, 2026
Merged

asvetlov merged 7 commits into
aio-libs:masterfrom
asvetlov:pure-python-free-threading

Conversation

@asvetlov

Copy link
Copy Markdown
Member

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

  • 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)

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.

Drafted with Claude Code; reviewed by asvetlov.

Add per-instance locking (an RLock created in __new__, reused across
re-init) to the pure-Python fallback so it matches the C extension's
free-threaded-build safety guarantees. Two-object operations lock both
objects in a fixed id() order to avoid deadlock, view iterators take
the lock per step rather than for the whole iteration, and the shared
version counter gets its own lock. On a GIL-enabled interpreter every
locked method is the exact same function object as before; the change
adds no overhead there.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 13, 2026
…threading

# Conflicts:
#	multidict/_multidict_py.py
Comment thread tests/test_multidict.py Dismissed
Comment thread tests/test_multidict.py Dismissed
Comment thread tests/test_multidict.py Dismissed
Comment thread tests/test_multidict.py Dismissed
@codspeed

codspeed Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 12.17%

⚠️ 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

⚡ 3 improved benchmarks
✅ 245 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_getall_str_hit[cs-c] 38 ms 33.3 ms +13.95%
⚡ test_cimultidict_getall_istr_hit[c] 36.8 ms 32.8 ms +12.2%
⚡ test_multidict_getall_str_hit[ci-c] 38.8 ms 35.1 ms +10.39%

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:pure-python-free-threading (45cbb9a) with master (80632eb)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 13, 2026 20:52
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 13, 2026 20:52
CI showed these tests are not reliable on a plain GIL-enabled
interpreter: pure Python bytecode isn't atomic even under the GIL, and
several multidict operations have a pre-existing, unlocked race that
predates this branch and is out of scope for it (GIL builds
intentionally get no locking here). CI's shared runners hit it far
more easily than local testing did. Skip every test that drives
several real threads through shared pure-Python multidict state
unless free-threading is actually active, where the locking this
branch adds is what's being verified.
@greptile-apps

greptile-apps Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

Safe to merge; no blocking issues remain.

Both previous deadlock reports were resolved without explanatory replies. greptile-apps[bot] manually resolved the order-view lock thread without explanation. greptile-apps[bot] manually resolved the view-iterator locking thread without explanation. The current code recognizes _Iter operands and applies the same stable pair-lock ordering.

Reviews (4): Last reviewed commit: "Recognize a bare view iterator in _other..." | Re-trigger Greptile

Comment thread multidict/_multidict_py.py Resolved
@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 (80632eb) to head (45cbb9a).

Additional details and impacted files
@@            Coverage Diff             @@
##            master     #1447    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           31        31            
  Lines         4471      4784   +313     
  Branches       341       382    +41     
==========================================
+ Hits          4471      4784   +313     
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

Copy link
Copy Markdown
Member Author

@codspeedbot fix this regression

_locked_md only held the calling multidict's own lock, but a view's
set-algebra methods (&, |, -, ^, isdisjoint) can iterate an `other`
argument that is itself a view over a *different* multidict, and each
step of that iteration takes the other multidict's lock too. Two
threads doing the reciprocal operation (a.items() & b.items() racing
b.items() & a.items()) could each hold one lock while blocked waiting
for the other: a classic AB-BA deadlock.

Extend _other_lock to also resolve the multidict backing one of our
own views, and add _locked_md_pair (mirroring _locked_pair) so these
methods pair both locks up front, in the same fixed order _PairLock
already uses elsewhere. This also fixes the same exposure in
update()/extend()/merge()/__init__() when their argument is a view
over another multidict rather than the multidict itself.

Found by review (Greptile). Reproduced the deadlock against the prior
code and confirmed the fix resolves it before adding the regression
test.
@asvetlov

Copy link
Copy Markdown
Member Author

Addressed the reciprocal-view deadlock: _locked_md only held the calling multidict's own lock, but a view's set-algebra methods can iterate an other argument that is itself a view over a different multidict, and each iteration step takes that multidict's lock too. a.items() & b.items() racing b.items() & a.items() could hold one lock while blocked on the other. Fixed in 56b8a94..da6c743 by extending _other_lock() to resolve a view's backing multidict and pairing both locks up front, in the same fixed order _PairLock already uses for update()/extend()/merge()/__eq__()/copy construction (this also covers the same exposure there, e.g. d1.update(d2.items())). Reproduced the deadlock against the prior code, confirmed the fix resolves it, and added test_pure_python_reciprocal_view_ops_no_deadlock as a regression test.

The _md_restore_all_hashes() finding is accurate but out of scope for this PR: it's a C-extension-only race in to_dict() (added by #1288, merged into this branch from master, not introduced here), the same class of bug #1448 already fixed for the neighboring md_find_next()/md_post_update() paths. The pure-Python to_dict() has no equivalent hash-marking scheme and isn't affected. Filed as a separate follow-up to keep this PR scoped to the pure-Python implementation.

Comment thread multidict/_multidict_py.py Resolved
_other_lock() recognized _ItemsView/_KeysView/_ValuesView but not the
_Iter that iter(view) returns, so a.items() & iter(b.items()) racing
b.items() & iter(a.items()) (and the same for update()/extend()/merge()
given a bare iterator argument) could still hit the same AB-BA
deadlock _locked_md_pair was meant to close. _Iter already carries the
RLock its view resolved at construction time, so recognizing it is a
one-line addition to the same helper.

Found by review (Greptile). Reproduced the deadlock against the prior
code and confirmed the fix resolves it before adding the regression
test.
@asvetlov

Copy link
Copy Markdown
Member Author

Good catch, fixed in da6c743..45cbb9a: `_other_lock()` recognized the view classes but not the `_Iter` that `iter(view)` returns, so `a.items() & iter(b.items())` racing `b.items() & iter(a.items())` (and the equivalent for `update()`/`extend()`/`merge()` given a bare iterator argument) could still deadlock the same way. `_Iter` already carries the RLock its view resolved at construction time, so recognizing it there was a one-line fix. Reproduced the deadlock against the prior code, confirmed the fix resolves it, and added a regression test.

@asvetlov
asvetlov merged commit 1ecdbb0 into aio-libs:master Sep 13, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the pure-python-free-threading branch September 13, 2026 23:05
asvetlov added a commit that referenced this pull request Sep 13, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`to_dict()` (via `md_to_dict()`) marks every entry's hash while it walks
the table to collect keys, then clears all the marks in one pass via
`_md_restore_all_hashes()`, while holding `self`'s critical section.
That
excludes other mutators but not a lock-free reader: `__contains__` and
`get()`/`getone()`/`__getitem__` load the same field with an atomic op
and no lock at all. `_md_restore_all_hashes()`'s clear was a plain,
non-atomic store, racing that atomic load under the free-threaded
build. This routes it through the existing `_md_entry_store_hash()`
helper, matching the pattern already used for the sibling mark/unmark
sites in `md_find_next()`/`md_finder_cleanup()`/`md_post_update()`
fixed by #1448.

This is a C-extension-only fix: the pure-Python `to_dict()` has no
equivalent hash-marking scheme, so there is nothing to change there.

## Are there changes in behavior for the user?

No. This only affects the free-threaded build's internal memory-model
correctness; there is no change to observable behavior.

## Is it a substantial burden for the maintainers to support this?

No, it's a small, self-contained fix mirroring the existing atomic-op
pattern already used elsewhere in `hashtable.h`.

## Related issue number

Found via a Greptile review comment on #1447; not otherwise linked to
an 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` (N/A: no `CONTRIBUTORS.txt` in this repo)
- [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>

Race confirmed with ThreadSanitizer (clang 21, `-fsanitize=thread`,
`LD_PRELOAD`ed into a CPython 3.14.7 free-threaded build): on the
pre-fix code, TSan reports a data race between the plain store in
`_md_restore_all_hashes()` (hashtable.h:1748) and the atomic load in
`_md_entry_load_hash()` reached from both `get()`
(`_md_get_one_lockfree`) and `__contains__` (`_md_contains_lockfree`).
After the fix, that report is gone; only an unrelated, pre-existing
CPython-internal biased-refcounting race remains, present identically
before and after.

New test:
`tests/test_multidict.py::test_to_dict_vs_lock_free_reads_thread_safety`,
marked `c_extension`, races `to_dict()` against lock-free
`contains()`/`get()` on never-deleted keys.

Tests: `pytest -q` against the default C-extension build (1897
passed), a free-threaded debug build (`MULTIDICT_DEBUG_BUILD=1` on
CPython 3.14.7 free-threaded, `--c-extensions`, 1892 passed, 5
skipped), and the pure-Python leg (`MULTIDICT_NO_EXTENSIONS=1`, 1897
passed).

Lint: `pre-commit run` (ruff, clang-format, mypy) passed on the changed
files.

Docs: `make doc-spelling` passed with no wordlist additions needed.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

</details>
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 14, 2026
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 added a commit to asvetlov/multidict that referenced this pull request Sep 14, 2026
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.
asvetlov added a commit that referenced this pull request Sep 14, 2026
)

<!-- 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>
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