Skip to content

Protect MultiDict repr() with a critical section and fix recursion guards - #1431

Merged
asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:reprs
Sep 9, 2026
Merged

asvetlov merged 4 commits into
aio-libs:masterfrom
asvetlov:reprs

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Protects repr() of MultiDict, MultiDictProxy, and their items/keys/values
views in the C extension with Py_BEGIN_CRITICAL_SECTION, avoiding data races
when another thread mutates the multidict during iteration on the
free-threaded build of CPython. Also adds the missing Py_ReprEnter/
Py_ReprLeave recursion guard to MultiDictProxy and KeysView repr in the
C extension (already present on MultiDict, ItemsView, and ValuesView),
consolidates that guard plus the __name__ lookup into the shared
md_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 MultiDictProxy or KeysView now prints ... for
the cyclic reference instead of recursing until RecursionError, matching
the existing behavior of MultiDict, ItemsView, and ValuesView, on both
the 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 critical
section macros already vendored via pythoncapi_compat.h.

Related issue number

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

Tests: pytest -q (1808 passed, C extension + pure-Python legs) and
MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions (917 passed,
pure-Python-only leg)
Lint: make lint (ruff, clang-format, mypy, yamllint, etc.) all passed
Spelling: make doc-spelling passes for the new fragments; 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.

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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 9, 2026
@asvetlov asvetlov mentioned this pull request Sep 9, 2026
3 tasks done
@asvetlov

asvetlov commented Sep 9, 2026

Copy link
Copy Markdown
Member Author

The PR doesn't add explicit tests for free-threaded mode because it could be checked only in fuzzy-style.
Fuzzy tests are not bad at all but they are out of scope for this PR

@codspeed

codspeed Bot commented Sep 9, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 248 untouched benchmarks


Comparing asvetlov:reprs (132b5e6) with master (c46652b)

Open in CodSpeed

@codecov

codecov Bot commented Sep 9, 2026

Copy link
Copy Markdown

Codecov Report

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

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     
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
asvetlov marked this pull request as ready for review September 9, 2026 19:28
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 9, 2026 19:28
@greptile-apps

greptile-apps Bot commented Sep 9, 2026

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5

Not fully merge-safe until concurrent repr() and mutation coverage is added for the new critical-section protection.

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

Comment thread multidict/_multidict.c Resolved
@asvetlov
asvetlov merged commit e65b0f2 into aio-libs:master Sep 9, 2026
56 of 57 checks passed
@asvetlov
asvetlov deleted the reprs branch September 9, 2026 19:54
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>
rodrigobnogueira added a commit to rodrigobnogueira/multidict that referenced this pull request 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 added a commit to rodrigobnogueira/multidict that referenced this pull request 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.
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>
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.

1 participant