Repository navigation
Add free-threading race tests for the C extension - #1317
Conversation
ff45477 to
0b04769
Compare
0af9e6a to
e1cbca0
Compare
This comment was marked as outdated.
This comment was marked as outdated.
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
62dce51 to
8121e70
Compare
|
@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. |
1d70349 to
469dda9
Compare
|
While fixing the C extension race condition, our test suite (now running the Root cause: 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. |
|
Error showed up in CI (traceback from Thread B): Two concurrent
|
|
See #1327 |
|
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. |
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. |
|
pre-commit surfaced the new PLC0415 rule, fixed in 4079a3e. |
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. |
|
This is the right approach — mirroring CPython 1. The cross-object paths lock only 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:
The fix for these is in the bodies: re-fetch the entries base after any call that can mutate/resize (the |
|
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.
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 Measured on 3.14.0rc1t with all three PRs applied — 8 threads running The last control is the one that places it: with matching Not reporting this as a separate finding — it is the race already documented, not a new one. Reproducer available if useful. |
Confidence Score: 4/5Not 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
What T-Rex did
Comments Outside Diff (2)
Reviews (8): Last reviewed commit: "[pre-commit.ci] auto fixes from pre-comm..." | Re-trigger Greptile |
1d03cf0 to
b14a239
Compare
|
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 |
33d3400 to
5233b0f
Compare
5233b0f to
ce72000
Compare
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.
ce72000 to
8c309a8
Compare
|
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. |
|
Thanks for tests, @rodrigobnogueira ! |
<!-- 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>
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
contribfragment; the tests arec_extension-marked and take about a quarter of a second.Related issue number
Follows #1431, #1433, #1438, #1441, #1445, #1446.
Checklist
CONTRIBUTORS.txt-- N/ACHANGES/folder