Skip to content

Protect MultiDict update()/extend()/merge()/clear() with a critical section - #1433

Merged
asvetlov merged 22 commits into
aio-libs:masterfrom
asvetlov:bulk-critical-sections
Sep 10, 2026
Merged

asvetlov merged 22 commits into
aio-libs:masterfrom
asvetlov:bulk-critical-sections

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Protects MultiDict.update(), .extend(), .merge(), .clear(), .copy(),
and the MultiDict/CIMultiDict constructors (including the fast-clone
path 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

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

Reproduced the crash against master with a threaded stress script and a
gdb backtrace pinpointing a NULL key/value read in
_md_add_with_hash(), using a genuine free-threaded CPython 3.13.7t
build (via pyenv), not just compiling the macros. Confirmed the fix
under the same build: 25+ stress runs and 3 gdb-driven runs with no
crashes, plus the project's own pytest suite passing there (1798
passed, 5 skipped for the pre-existing free-threaded getrefcount
incompatibility).

CI's "Test ubuntu 3.14t ext debug" job (free-threaded, -UNDEBUG) then
caught a second bug the release-build stress testing above couldn't see:
extend()/update()/merge()/clear() each called ASSERT_CONSISTENT
a 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 the
same 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 only self (the source being read), not the freshly
allocated target -- unlike the constructor fast-clone path, where self
can itself be an existing, shared object via an explicit re-init, .copy()'s
target is never reachable from another thread until the call returns.

Review also flagged that __init__()'s reset (md_init(), which frees
self'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 folding md_init() into the same
critical 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
arg via PyDict_Next() (inside md_update_from_dict()) while holding
only 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 arg locked too
(Py_BEGIN_CRITICAL_SECTION2(self, arg)), confirmed with a new
regression test (20/20 clean runs) racing update() from a shared dict
against concurrent mutation of that dict.

Known residual issues, not fixed in this PR:

  • Even with every API call above correctly locked, racing update()/merge()
    calls against each other (or against .copy()) can still trip the same
    entry->hash >= 0 assertion. It never reproduces under any amount of
    sequential 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. a
    dict-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's
    acquisition path specifically looks implicated, not critical sections
    in general.
  • Separately, and more fundamentally: the C extension's iterators
    (items()/keys()/values()/__iter__) hold no lock at all across
    their lifetime. md_next()'s version-number check is a best-effort
    heuristic, not synchronization; a live iterator racing any operation
    that fully replaces the table (clear(), __init__(), ...) can read
    out 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 its
update()/extend()/merge(), so it can raise AttributeError under
concurrent 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 -q and MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions
both pass on the current branch tip.
Lint: make lint (ruff, clang-format, mypy, yamllint, etc.) all passed
Spelling: make doc-spelling passes for the new fragment; one
pre-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.

_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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 9, 2026
Comment thread multidict/_multidict.c Resolved
@codspeed

codspeed Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing asvetlov:bulk-critical-sections (19285b6) with master (e65b0f2)

Open in CodSpeed

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().
Comment thread tests/test_multidict.py Fixed
@asvetlov asvetlov changed the title Protect MultiDict update()/extend()/merge() with a critical section Protect MultiDict update()/extend()/merge()/clear() with a critical section Sep 9, 2026
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.
@asvetlov
asvetlov marked this pull request as ready for review September 10, 2026 08:17
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 10, 2026 08:17
Comment thread tests/test_multidict.py Fixed
@greptile-apps

greptile-apps Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5

Direct reads need the same lifetime protection as clear() before this can safely support concurrent free-threaded access.

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

Security Review

A concurrent clear() can free a hash-table allocation after an unlocked reader has already captured it. This is a memory-safety issue on free-threaded Python and can crash the interpreter or corrupt process memory.

T-Rex T-Rex Logs

What T-Rex did

  • T-Rex produced a proof for a posted P1 finding, including a diff between the parent and current clear implementations and validation of lookup locking under concurrent stress, plus confirmation that the existing clear finalizer regression test passes.
  • A focused finalizer re-entrancy reproducer was built and run against both the parent and current revisions; the parent exited with a segmentation fault during explicit reinitialization and fast cloning, while the current revision completed successfully, and the targeted clear-finalizer and explicit-reinitialization thread-safety tests passed.
  • T-Rex produced a proof for a posted P1 finding; see the corresponding review comment for the finding details.
  • A detailed contract-validation analysis traced md_contains and md_get_one paths, showing reads do not acquire the same locks as clear and explaining how the finalizer locks interact with Python-level Py_CLEAR calls.
  • A before/after HEAD comparison described how the finalizer and md_clear changes avoid freeing old tables, with notes on the locking and potential re-entrancy in CPython.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (1)

  1. General comment

    P1 Free-threaded lookup and containment can dereference old_keys after clear frees it

    • Bug
      • md_clear() publishes the empty singleton table and later calls htkeys_free(old_keys), but __contains__ and __getitem__ enter md_contains()/md_get_one() without Py_BEGIN_CRITICAL_SECTION(self). A reader can load the old table at hashtable.h:880-881 or :930-931, then a concurrent clear() can free that allocation at :2066, leaving the reader's iterator/entries pointer dangling.
    • Cause
      • The clear entry point takes the per-object Python critical section (_multidict.c:671-673), whereas the direct containment and subscript slots (_multidict.c:365-367, :381-383) do not. The current publication ordering only prevents new readers from selecting the old table after line 2055; it does not retain the table for readers that selected it earlier.
    • Fix
      • Wrap all direct read entry points that traverse md->keys, at minimum multidict_mp_subscript() and multidict_sq_contains(), in Py_BEGIN_CRITICAL_SECTION(self) / Py_END_CRITICAL_SECTION(). Audit the remaining direct md_get_*, finder, view, iterator, and traversal callers for equivalent object-lock coverage or a table-lifetime scheme compatible with free-threaded CPython.

    T-Rex Ran code and verified through T-Rex

Reviews (10): Last reviewed commit: "Publish the empty table before releasing..." | Re-trigger Greptile

Comment thread multidict/_multidict.c Resolved
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

codecov Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e65b0f2) to head (19285b6).

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

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.
Comment thread multidict/_multidict.c Resolved
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).
Comment thread multidict/_multidict.c Resolved
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.
Comment thread multidict/_multilib/hashtable.h Resolved
@asvetlov
asvetlov merged commit f3e65eb into aio-libs:master Sep 10, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the bulk-critical-sections branch September 10, 2026 13:13
asvetlov added a commit that referenced this pull request Sep 11, 2026
…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>
asvetlov added a commit that referenced this pull request Sep 14, 2026
## 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>
asvetlov pushed a commit that referenced this pull request Sep 20, 2026
## 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]>
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