Skip to content

Add free-threading race tests for the C extension - #1317

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
rodrigobnogueira:fix-free-threaded-race-condition
Sep 14, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
rodrigobnogueira:fix-free-threaded-race-condition

Conversation

@rodrigobnogueira

@rodrigobnogueira rodrigobnogueira commented Apr 12, 2026 •

Copy link
Copy Markdown
Member

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

  • I think the code is well written
  • 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
  • Add a new news fragment into the CHANGES/ folder

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Apr 12, 2026
Comment thread tests/test_free_threading.py Fixed
Comment thread tests/test_free_threading.py Fixed
@codspeed

codspeed Bot commented Apr 12, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing rodrigobnogueira:fix-free-threaded-race-condition (d813b3e) with master (cc8c06a)

Open in CodSpeed

@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from ff45477 to 0b04769 Compare April 12, 2026 05:29
@rodrigobnogueira
rodrigobnogueira marked this pull request as draft April 12, 2026 05:33
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from 0af9e6a to e1cbca0 Compare April 12, 2026 15:10
@rodrigobnogueira

This comment was marked as outdated.

@codecov

codecov Bot commented Apr 12, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1317   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        30    +1     
  Lines         4259      4329   +70     
  Branches       324       338   +14     
=========================================
+ Hits          4259      4329   +70     
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.

@rodrigobnogueira rodrigobnogueira changed the title Fix memory safety race condition in CPython 3.13 free-threaded mode Fix use-after-free race condition in C extension for free-threaded CPython (3.13t+) Apr 12, 2026
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from 62dce51 to 8121e70 Compare April 13, 2026 03:27
@rodrigobnogueira
rodrigobnogueira marked this pull request as ready for review April 13, 2026 03:49

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

Looks good surprised this wasn't seen with the sniffer from #1306. Be sure you update your branches if you haven't since #1314 Got merged which I wrote to help with broken coverage but other than that I have no suggestions.

@Vizonex

Vizonex commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

@rodrigobnogueira it's been 2 weeks so I'll see if we can get someone else in here to merge since I don't have that authorization to do so yet. for now I recommend staying updated with the main branch.

Comment thread CHANGES/1317.bugfix.rst Resolved
Comment thread tests/test_free_threading.py Resolved
@Vizonex Vizonex added the free-threading FT-related discussion, issue or PR label May 1, 2026
Comment thread tests/test_free_threading.py Fixed
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch 3 times, most recently from 1d70349 to 469dda9 Compare May 2, 2026 02:36
@rodrigobnogueira

Copy link
Copy Markdown
Member Author

While fixing the C extension race condition, our test suite (now running the any_multidict_class fixture against both implementations) uncovered a related but separate thread-safety bug in _multidict_py.py on free-threaded CPython (3.13t).

Root cause: __setitem__ temporarily sets e.hash = -1 as a sentinel marker while traversing entries, relying on restore_hash() to clean up afterwards. Under free-threaded CPython, a concurrent thread can enter _add_with_hash → _resize → build_indices(update=False) in that window, where it hits:

assert hash_ != -1  # line 543

...and raises AssertionError because it observed the in-progress -1 sentinel from the other thread.

The fix for the C extension in this PR uses Py_BEGIN_CRITICAL_SECTION, but the pure-Python implementation has no equivalent synchronization. Fixing it properly would require adding a threading.Lock to MultiDict.

I've skipped the test for the pure-Python variant for now to unblock this PR.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

Error showed up in CI (traceback from Thread B):

  File "_multidict_py.py", line 881, in __setitem__
    self._add_with_hash(_Entry(hash_, identity, key, value))
       ↓ (usable <= 0, triggers resize)
  File "_multidict_py.py", line 1088, in _add_with_hash
    self._resize((self._used * 3 | _HtKeys.MINSIZE - 1).bit_length(), False)
       ↓
  File "_multidict_py.py", line 1083, in _resize
    newkeys.build_indices(update)
       ↓
  File "_multidict_py.py", line 543, in build_indices
    assert hash_ != -1
AssertionError

Two concurrent __setitem__ calls race:

  • Thread A is updating an existing key — it sets e.hash = -1 (line 874) as a sentinel while iterating, and has not yet called restore_hash().
  • Thread B is inserting a new key — it enters the not found branch (line 880–881), calls _add_with_hash → _resize → build_indices(update=False), which iterates the same shared entries and hits Thread A's -1 sentinel → AssertionError.

@rodrigobnogueira
rodrigobnogueira requested a review from webknjaz May 2, 2026 03:28
@Vizonex

Vizonex commented May 2, 2026

Copy link
Copy Markdown
Member

See #1327

@Dreamsorcerer

Copy link
Copy Markdown
Member

I'm unclear how much we should be concerned with such issues. The entire point of aio-libs is to provide asyncio libraries, so threading issues shouldn't be relevant. I'd rather not start introducing threading locks into our libraries..

@Vizonex

Vizonex commented May 2, 2026 •

Copy link
Copy Markdown
Member

I'm unclear how much we should be concerned with such issues. The entire point of aio-libs is to provide asyncio libraries, so threading issues shouldn't be relevant. I'd rather not start introducing threading locks into our libraries..

@Dreamsorcerer You have to remember to that multidict is used in other libraries or projects besides our own. An example that I have is litestar however I'm with you on questioning weather or not thread locks should be considered acceptable or unacceptable however.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

I'm unclear how much we should be concerned with such issues. The entire point of aio-libs is to provide asyncio libraries, so threading issues shouldn't be relevant. I'd rather not start introducing threading locks into our libraries..

Adding threading.Lock to the pure-Python fallback would add overhead for all users to solve a problem that is probably an edge case. Would it be acceptable to emit a RuntimeWarning at import time only when both conditions are true: running on free-threaded CPython (GIL disabled) AND the C extension is not available?

@Dreamsorcerer

Copy link
Copy Markdown
Member

Adding threading.Lock to the pure-Python fallback would add overhead for all users to solve a problem that is probably an edge case. Would it be acceptable to emit a RuntimeWarning at import time only when both conditions are true: running on free-threaded CPython (GIL disabled) AND the C extension is not available?

We're talking about just iterating and modifying the same multidict, right? Can just mention that this shouldn't be done in a threaded situation. Maybe issue a warning.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

pre-commit surfaced the new PLC0415 rule, fixed in 4079a3e.

@rodrigobnogueira

Copy link
Copy Markdown
Member Author

Are we still planning to move forward with these free-threaded PRs at all or will these be closed?

IMO this solves the issue, and the main cost is how many functions it has to touch: every entry point that reads md->keys needs the critical section, the same way CPython's dict does it. The sections are no-ops on regular builds, so only free-threaded builds pay.

I think it deserves fixing: this is memory unsafety, not a logical race. A pure-Python user on 3.13t can segfault the process, where CPython's dict raises RuntimeError. The lighter alternative is documenting it as unsupported and keeping only the RuntimeWarning, but that leaves a crash reachable from Python code.

@devdanzin

Copy link
Copy Markdown
Contributor

This is the right approach — mirroring CPython dict's per-object critical sections at every entry point, no-op on the default build. Two follow-ups:

1. The cross-object paths lock only self. multidict_tp_richcompare correctly uses Py_BEGIN_CRITICAL_SECTION2(self, other_md), but multidict_extend / update / merge-from-another-multidict are wrapped Py_BEGIN_CRITICAL_SECTION(self) only — and md_update_from_ht / md_clone_from_ht read the source other->keys. A thread mutating other while another does a.update(other) still races the read. These want CRITICAL_SECTION2(self, other) too. (multidict_copy is fine — there self is the source.)

2. A few of the crashes are reachable single-threaded, so they survive the critical sections. A critical section is a no-op on the default (GIL) build and doesn't guard same-thread reentrancy, so these need the function bodies fixed regardless of locking — they're borrowed-pointer-across-callback bugs, not pure data races:

  • md_update_from_ht caches htkeys_entries(other->keys) and holds borrowed entry->key/value across a resize / key.lower(). Reproduces on a plain debug and ASan build, no threads:

    from multidict import MultiDict
    d = MultiDict([(f"k{i}", i) for i in range(64)])
    d.extend(d)   # self-alias: growing d resizes/frees d->keys mid-copy -> SIGSEGV
  • md_update_from_seq caches the list size once, then a CI key's .lower() can shrink the list → PyList_GET_ITEM past the end (OOB). Also reproduces single-threaded.

  • md_eq holds lft_entries/rht_entries across PyObject_RichCompareBool; a value's __eq__ that mutates a dict dangles the cached base (reentrant even under the GIL).

The fix for these is in the bodies: re-fetch the entries base after any call that can mutate/resize (the md_next/md_find_next re-fetch pattern already used elsewhere), snapshot the size, and for the self-alias case detect other == self. I have runnable reproducers for each and am glad to open them as separate issues (they overlap the C-extension report #1306). None of this blocks the concurrency fix here — just flagging that the critical sections alone won't close these particular crashes.

@devdanzin devdanzin mentioned this pull request Jul 22, 2026
3 tasks done
@espressolee

Copy link
Copy Markdown
Contributor

Doing a free-threading pass over multidict I built a tree with this PR, #1327 and #1379 all merged, and one path this PR does not reach turned up. Flagging it here rather than opening an issue, since it belongs to the work you are already doing.

_multidict_extend (_multidict.c:81) calls md_update_from_ht(self, other, op) with no critical section. md_update_from_ht then takes a raw pointer into the other multidict's table and walks it:

entry_t *entries = htkeys_entries(other->keys);
Py_ssize_t nentries = other->keys->nentries;

for (pos = 0; pos < nentries; pos++) {
    entry_t *entry = entries + pos;

The four Py_BEGIN_CRITICAL_SECTION2 uses this PR adds are all in multidict_tp_richcompare, so on the extend path other is never locked. A concurrent insert into other can resize and free the array entries points at.

Measured on 3.14.0rc1t with all three PRs applied — 8 threads running MultiDict().extend(other), 3 mutating other:

original                                    SIGSEGV 12/12
control: no mutator                         clean 12/12
control: mutator touches a decoy multidict  clean 12/12
control: md->is_ci == other->is_ci          SIGSEGV 11, SIGTRAP 1
GIL build, identical script                 clean 12/12

The last control is the one that places it: with matching is_ci, recalc_identity is false and no Python runs inside the loop, and it still crashes. So this is not a borrow-across-Python problem — it is the _md_resize race from devdanzin's #1321 cluster 3, reachable through a path this PR leaves unprotected. Py_BEGIN_CRITICAL_SECTION2(self, other) around the md_update_from_ht calls looks like it would close it, but you know the locking design here better than I do.

Not reporting this as a separate finding — it is the race already documented, not a new one. Reproducer available if useful.

@greptile-apps

greptile-apps Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5

Not merge-safe until item-view equality callbacks can no longer observe transiently incomplete mapping contents.

One confirmed correctness failure remains in the item-view intersection implementation: reentrant equality callbacks can read an incomplete MultiDict.

Files Needing Attention: multidict/_multilib/views.h

T-Rex T-Rex Logs

What T-Rex did

  • Produced a finding-comment-proof for a posted P1 finding and attached the final focused reentrancy validation script along with the normal, reentrant, and critical-section outputs.
  • Issued a second finding-comment-proof for the same P1 finding, with no additional artifacts.
  • Validated the contract-level behavior: the final focused script ran against multidict._multidict on CPython 3.11.6; the normal path exited code 0 with the expected before/after values, the reentrant path also exited 0 and confirmed the snapshot contained only the second value while the mapping was restored after intersection.

View all artifacts

T-Rex Ran code and verified through T-Rex

Comments Outside Diff (2)

  1. multidict/_multilib/views.h, line 285 (link)

    P1 VERIFIED. The final focused script ran against multidict.multidict on CPython 3.11.6.

    • Bug
      • VERIFIED. The final focused script ran against multidict.multidict on CPython 3.11.6. Its normal form exited 0 with normalbefore='first', probe and normalafter='first', probe. Its guarded reentrant form also exited 0, printed REENTRANTEQ other='first' getall=probe, and asserted the snapshot contained only the second value while the mapping was restored after intersection. This exercises views.h:284-285, where the equality callback follows mdfindnext, and hashtable.h:1338-1350, where the matching entry is marked before it is returned. hashtable.h:1364-1380 restores marks only in cleanup. The runtime check confirmed Python 3.11 selects the no-op compatibility definition for PyBEGINCRITICALSECTION in pythoncapicompat.h:1373-1378; it did not prevent the observed reentrant result.
    • Cause
      • T-Rex reproduced this while running the changed behavior, but it did not return a separate root-cause sentence.
    • Fix
      • Update the changed code so this failing path is handled, then rerun the same T-Rex check to confirm it passes.
    Artifacts

    Final focused reentrancy validation script

    • One-shot guarded `Needle.__eq__` performs the exact items-view intersection and records the mapping contents observed during reentry, with the takeaway that the current entry can be hidden.

    Normal intersection observed output

    • Executed normal intersection against `multidict._multidict` exits successfully and keeps both `first` and the probe visible before and after, with the takeaway that non-reentrant contents are complete.

    Reentrant intersection observed output

    • Executed guarded reentrant equality against `multidict._multidict` exits successfully and logs `REENTRANT_EQ ... getall=[probe]`, with the takeaway that the finder-marked current entry is absent during callback reentry.

    Critical-section runtime check

    • Executed runtime inspection confirms CPython 3.11.6 loads the built extension and selects the pre-3.13 no-op critical-section compatibility path, with the takeaway that critical sections do not prevent this observation in this environment.

    View artifacts

    T-Rex Ran code and verified through T-Rex

  2. multidict/_multilib/views.h, line 285 (link)

    P1 Finder-marked entry is hidden during equality callback

    • Bug
      • Finder-marked entry is hidden during equality callback

        multidict_itemsview_and1_impl obtains a matching item through md_find_next() and then calls PyObject_RichCompareBool(value, value2, Py_EQ). md_find_next() has already marked that entry absent, so a user-defined __eq__ can re-enter the same mapping and observe incomplete contents from getall('k'). The completed C-extension reproduction observed [probe] inside the callback even though normal contents before and after are ['first', probe].

    • Cause
      • md_find_next() sets entry->hash to finder->hash | MD_HASH_MARK before returning the value, and cleanup that restores the hash happens only after comparison completes.
    • Fix
      • Do not expose the finder’s temporary visitation state to reentrant Python code; restore or avoid the temporary absence before invoking user-defined equality, or use traversal state that does not alter membership visibility.

    T-Rex Ran code and verified through T-Rex

Reviews (8): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile

Comment thread tests/test_free_threading.py Resolved
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from 1d03cf0 to b14a239 Compare September 5, 2026 19:45
@bdraco

bdraco commented Sep 5, 2026

Copy link
Copy Markdown
Member

Mobile so I can’t check if it’s the same one but there is a zero performance impact to the non free threaded version of this in a GHSA report

@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch 3 times, most recently from 33d3400 to 5233b0f Compare September 12, 2026 17:32
Comment thread multidict/_multilib/views.h Resolved
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from 5233b0f to ce72000 Compare September 12, 2026 17:41
@rodrigobnogueira rodrigobnogueira changed the title Fix use-after-free race condition in C extension for free-threaded CPython (3.13t+) Add free-threading race tests for the C extension Sep 12, 2026
aio-libs#1431 through aio-libs#1446 made the C extension safe to use from several threads
on a free-threaded build, and shipped without a test that exercises it
that way. These two do: one iterates a multidict while other threads
mutate it, the other extends from a source that other threads are
resizing. Both segfault on every run against the tree before that series
and pass on it now, so a regression shows up as a crash on the
free-threaded CI legs rather than as nothing.
@rodrigobnogueira
rodrigobnogueira force-pushed the fix-free-threaded-race-condition branch from ce72000 to 8c309a8 Compare September 12, 2026 17:42
@rodrigobnogueira

Copy link
Copy Markdown
Member Author

Reworked this to tests only. #1431 through #1446 covered everything the C side here was doing, so I dropped it and kept the two race tests: iterate while other threads mutate, and extend while other threads resize the source. Against the tree before that series both segfault on every run; against current master they pass 10/10.

Comment thread tests/test_free_threading.py Resolved
@asvetlov
asvetlov enabled auto-merge (squash) September 13, 2026 18:50
@asvetlov

Copy link
Copy Markdown
Member

Thanks for tests, @rodrigobnogueira !

@asvetlov
asvetlov disabled auto-merge September 14, 2026 02:45
@asvetlov
asvetlov merged commit 0a7b354 into aio-libs:master Sep 14, 2026
56 of 57 checks passed
asvetlov added a commit that referenced this pull request Sep 14, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`items()` set algebra (`&`, `|`, `-`, `in`, `isdisjoint()`) walks a
key's
hash chain while temporarily marking visited entries, then compares
stored
values against a caller-supplied one before unmarking. That comparison
can
run arbitrary user code through a custom `__eq__`, and code that calls
back
into the same `MultiDict` from there (`getall()`, for example) while the
chain is still marked observes some matching entries as missing.
Depending
on the operation this returns wrong data, raises a bogus `KeyError`, or,
in
the C extension, hangs the process outright (see
[#1317
(review)](#1317 (review))
for the report and a reproduction).

The fix materializes the matching `(key, value)` pairs into a plain list
after the hash chain has been fully walked and restored, and only then
runs
the value comparisons against that snapshot. This covers the C
extension's
`and1`/`and2`/`or1`/`sub2`/`contains`/`isdisjoint` paths via a new
`md_finder_collect()` helper, and the pure-Python `__and__()`, the only
pure-Python method using the same mark-then-compare pattern (the other
pure-Python methods don't mark and were never affected).

## Are there changes in behavior for the user?

No, other than the crash/corruption going away. Ordinary comparisons (an
`__eq__` that doesn't touch the multidict) behave exactly as before.

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

No. The fix is a mechanical materialize-then-compare change with no new
public API, plus regression tests.

## Related issue number

Follows up on the review comment at

#1317 (review).
No separate issue is filed.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes -- N/A
- [ ] 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` passed (1927 passed, 12 skipped) under both the C
extension and `MULTIDICT_NO_EXTENSIONS=1` pure-Python builds, plus a
debug
build (`MULTIDICT_DEBUG_BUILD=1`, asserts on, `-O0`).
Lint: `pre-commit run` (ruff, ruff-format, clang-format, mypy for 3.11
and
3.13) passed on all changed files.
Docs: `make doc-spelling` passed with no wordlist additions needed.
Confirmed pre-fix: the new tests hang (C extension) or fail with wrong
results/`KeyError` (pure Python) against the unmodified code.

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.
</details>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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 free-threading FT-related discussion, issue or PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants