Repository navigation
Protect MultiDict repr() with a critical section and fix recursion guards - #1431
Conversation
repr() walked the hash table without holding the object's lock, which is unsafe on the free-threaded build of CPython if another thread mutates the multidict concurrently. Wrap the md_repr() call in Py_BEGIN_CRITICAL_SECTION/Py_END_CRITICAL_SECTION for MultiDict, MultiDictProxy, and the items/keys/values views. The macros compile to no-ops on the GIL build and on Python versions before 3.13, so this only changes behaviour under Py_GIL_DISABLED.
multidict_proxy_repr() and multidict_keysview_repr() called md_repr() directly, unlike multidict_repr(), multidict_itemsview_repr(), and multidict_valuesview_repr(), which already bracket the call with Py_ReprEnter/Py_ReprLeave to print "..." instead of recursing forever on a self-referential container. Add the same guard to the two remaining repr implementations for consistency.
The five multidict_*_repr() functions each duplicated the same Py_ReprEnter/Py_ReprLeave dance and the __name__ lookup around the call to md_repr(). Move both into md_repr() itself, keyed on the actual repr target (obj), so each call site is reduced to acquiring the critical section and delegating. Also unifies the views, which previously looked up "__name__" via a literal string, with the cached interned name already used by MultiDict and MultiDictProxy. No behaviour change; verified with the existing repr test coverage plus manual refcount and recursive-repr checks.
Add tests exercising the recursive-repr guard on MultiDictProxy (both backends) and KeysView (both backends). The new KeysView test caught that _KeysView.__repr__ in _multidict_py.py never got the @reprlib.recursive_repr() decorator that MultiDict, _ItemsView, and _ValuesView already have, so a self-referential key would blow the recursion limit under the pure-Python build. Add the missing decorator to match the C extension's guard added earlier on this branch.
|
The PR doesn't add explicit tests for free-threaded mode because it could be checked only in fuzzy-style. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1431 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 3926 3942 +16
Branches 283 283
=========================================
+ Hits 3926 3942 +16
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Confidence Score: 4/5Not fully merge-safe until concurrent One non-security P2 finding remains, so the required score is 4. Files Needing Attention: tests/test_multidict.py needs a focused concurrent representation-and-mutation regression test; multidict/_multidict.c is the protected native traversal path it should exercise. Reviews (1): Last reviewed commit: "Guard pure-Python KeysView.__repr__ agai..." | Re-trigger Greptile |
…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>
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.
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.
## 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>
What do these changes do?
Protects
repr()ofMultiDict,MultiDictProxy, and their items/keys/valuesviews in the C extension with
Py_BEGIN_CRITICAL_SECTION, avoiding data raceswhen another thread mutates the multidict during iteration on the
free-threaded build of CPython. Also adds the missing
Py_ReprEnter/Py_ReprLeaverecursion guard toMultiDictProxyandKeysViewrepr in theC extension (already present on
MultiDict,ItemsView, andValuesView),consolidates that guard plus the
__name__lookup into the sharedmd_repr()helper, and adds the same missing guard to the pure-Python_KeysView.__repr__, which never had it either.Are there changes in behavior for the user?
Yes: a self-referential
MultiDictProxyorKeysViewnow prints...forthe cyclic reference instead of recursing until
RecursionError, matchingthe existing behavior of
MultiDict,ItemsView, andValuesView, on boththe C extension and the pure-Python implementation.
Is it a substantial burden for the maintainers to support this?
No, it only touches the
repr()implementations and uses the criticalsection macros already vendored via
pythoncapi_compat.h.Related issue number
#1432
Checklist
CONTRIBUTORS.txtCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent run details (optional, for reviewers)
Tests:
pytest -q(1808 passed, C extension + pure-Python legs) andMULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions(917 passed,pure-Python-only leg)
Lint:
make lint(ruff, clang-format, mypy, yamllint, etc.) all passedSpelling:
make doc-spellingpasses for the new fragments; one pre-existing,unrelated failure in already-released
CHANGES.rst("fallbacks" not in thewordlist) predates this branch and was left untouched
Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.