Skip to content

Stop getall() from hiding a live key mid-update on free-threaded builds - #1484

Merged
asvetlov merged 8 commits into
aio-libs:masterfrom
asvetlov:fix-getall-foreign-mark-visibility
Sep 20, 2026
Merged

asvetlov merged 8 commits into
aio-libs:masterfrom
asvetlov:fix-getall-foreign-mark-visibility

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

On the free-threaded build, getall() and the items()/keys()/values()
equality path shared a finder with _md_replace()'s and md_to_dict()'s
internal marking protocol. A concurrent update()/extend()/__setitem__()
call can have its critical section transiently suspended while an entry it
just wrote is still marked as part of its own bookkeeping (a decref
triggering the allocator's own lock, see the existing comment in
_md_replace()), and a reader landing in exactly that window treated the
mark as "not found" instead of "still there, in flight", raising KeyError
for a key that was never deleted.

The shared finder now takes a readonly mode for getall()/md_finder_collect():
it matches identity with a masked hash comparison instead of a raw one, and
never writes to the entry, tracking its own already-returned slots locally
instead. _md_replace(), _md_update() and md_to_dict()'s inner scan keep
the existing raw comparison and marking, since they can restart their own
scan and need to tell an entry they already marked apart from a fresh
duplicate.

Are there changes in behavior for the user?

No visible behavior change on the happy path. On the free-threaded build,
getall() (and equality checks that materialize items()/keys()/values())
no longer spuriously raises KeyError for a live key racing a concurrent
update to that same key.

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

No. The change is contained to multidict/_multilib/hashtable.h and only
affects the free-threaded build's read-only finder path.

Related issue number

While investigating this, testing under a much wider (artificially delayed)
version of the race window surfaced a second, more serious, pre-existing bug:
two threads calling update() on the same key concurrently can lose the
key entirely rather than just transiently hide it from a reader. That is a
writer-side data race in _md_replace()/_md_update(), independent of this
fix (confirmed against the unmodified master baseline), and needs separate
design work. Filed as #1483; not fixed here.

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)

The existing regression test (test_getall_update_vs_lock_free_reads_thread_safety)
already covers the reported failure mode under natural timing; a
deterministic repro isn't included here since it needs a temporary,
non-shippable delay injected into the C extension to force the exact
interleaving (removed before this commit).

Tests: pytest tests/ -q -k "not test_leak" -- 1757 passed on
MULTIDICT_DEBUG_BUILD=1 free-threaded 3.14.7t, 1756 passed on the default
(GIL) build. MULTIDICT_NO_EXTENSIONS=1 pure-Python path is untouched by
this diff (only multidict/_multilib/hashtable.h changed); the failing
test is marked c_extension-only, and pure Python's threading.RLock-based
locking has no equivalent to the critical-section suspension this exploits.

Lint: pre-commit run --files multidict/_multilib/hashtable.h CHANGES/1484.bugfix.rst docs/spelling_wordlist.txt -- clean (clang-format reformatted once, re-verified after).

Drafted with Claude Code (Sonnet 5); reviewed by asvetlov.

getall() and the items()/keys()/values() equality path shared a finder
with _md_replace()'s and md_to_dict()'s marking protocol. A concurrent
update()/extend()/__setitem__() call can have its critical section
transiently suspended while an entry it just wrote is still marked, and
a reader landing in that window treated the mark as "not found" instead
of "still there, in flight", raising KeyError for a key that was never
deleted.

Give the shared finder a readonly mode for getall()/md_finder_collect():
match identity with a masked hash comparison instead of a raw one, and
never write to the entry, tracking each already-returned slot locally
in the finder itself. _md_replace(), _md_update() and md_to_dict()'s
inner scan keep the existing raw comparison and marking, since they can
restart their own scan and need to recognize an entry they already
marked earlier.

A concurrent update()-vs-update() data race on the same key remains;
filed as aio-libs#1483, out of scope here.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 20, 2026
@codspeed

codspeed Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 266 untouched benchmarks


Comparing asvetlov:fix-getall-foreign-mark-visibility (98d424f) with master (eaca953)

Open in CodSpeed

asvetlov and others added 5 commits September 20, 2026 11:23
CodSpeed flagged a 14-21% regression on getall()-heavy and items()
equality benchmarks from the previous commit here. Folding the fix into
the shared md_finder_t/md_find_next() bloated that struct for every
caller (including _md_replace() and md_to_dict(), which need none of
the new bookkeeping) and added a branch on every entry either kind of
scan visits, hit or miss.

Split it instead: md_finder_t/md_find_next()/md_finder_cleanup() go back
to their original, unmodified form, used only by _md_replace() and
md_to_dict()'s inner scan as before. getall() and md_finder_collect()
get a new, dedicated md_readonly_finder_t/md_readonly_find_next()/
md_readonly_finder_cleanup(), matching identity with a masked hash
comparison and tracking its own already-returned slots in a small
buffer that lives inline in the struct for up to 8 duplicate values (an
actual duplicate count observed in this project's own getall()
benchmark), only spilling to the heap past that.
md_readonly_find_next() returns without advancing past a match, so the
very next call re-examines that same slot and depends on the
already-returned check to move past it -- meaning that check is almost
always looking for the most recently appended slot. Scanning from index
0 made it an O(visited_count) walk to find what is normally the last
element; walking from the end instead makes the common case O(1),
turning what had been O(n^2) across a whole duplicate-heavy getall()
into O(n).
Matches HT_COLD's existing use in htkeys.h for the same reason: a
getall() with more than MD_FINDER_INLINE_VISITED duplicates for one key
is rare, and folding the growth logic into md_readonly_find_next()'s
loop body kept that code inline with the common, never-grows path.
_md_readonly_finder_grow_visited() is its own HT_COLD function now, and
the compiler puts it in a separate .cold section rather than mixing it
into multidict_getall's hot body (confirmed via nm -S on a release
build).

This alone isn't the full story for the regression CodSpeed reported:
md_get_all()/md_readonly_find_next() were already being inlined into
multidict_getall() before this change too (no separate symbols either
way), and the compiled size of multidict_getall barely moved. Whatever
else is driving the remaining gap needs the actual instruction-level
profile to pin down further.
CodSpeed's flame graph for the previous commit (checked via the
CodSpeed MCP tools once authorized) showed multidict_getall's own
self-time growing by cache-miss cost, not instructions, pointing away
from the earlier de-inlining theory. md_readonly_finder_t is 160 bytes
(vs md_finder_t's 72), mostly the 8-slot visited_inline array, and both
call sites zeroed the whole struct with `= {0}` even though
md_readonly_finder_init() already sets every field it needs; the extra
64 bytes of memset on every call, hit or miss, is pure waste.

md_get_all() keeps a single `finder.visited = NULL;` before the struct
is otherwise live, since md_calc_identity() can fail before init() runs
and jump straight to cleanup, which frees `visited` if it isn't still
visited_inline; NULL takes that branch and PyMem_Free(NULL) is a no-op.
md_finder_collect() drops the zero-init entirely, since its only path
to cleanup is after init() has already run.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
nm -S on a release build showed _str_cmp still existed as its own
symbol: the compiler inlined it at some of its ~14 call sites (it is
the identity comparison used by get, contains, getall, replace, and
update) and kept a real call at others, so where its cost was
attributed depended on which caller reached it rather than being
consistent hot-path behavior.

Adds HT_ALWAYS_INLINE next to the existing HT_COLD/HT_UNLIKELY
cross-compiler macros in htkeys.h and applies it to _str_cmp. Verified
_str_cmp no longer appears as a standalone symbol in nm -S output
after this change, on either backend's identity comparison path.

Builds clean under -Werror at both -O3 (default) and -O0
(MULTIDICT_DEBUG_BUILD=1), on the free-threaded and default-GIL
interpreters; full suite passes on both (2060 passed / 9 skipped free-
threaded, 2059 passed / 10 skipped default-GIL). Whether this actually
moves CodSpeed's numbers still needs a same-hardware before/after
comparison; the last one was confounded by a CI runner swap.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@asvetlov
asvetlov marked this pull request as ready for review September 20, 2026 10:49
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 20, 2026 10:49
@greptile-apps

greptile-apps Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

Not safe to merge until the stale-entry access is fixed and the required regression coverage is added.

Reviews (1) · Last reviewed commit: "Trim verbose comments from the readonly ..."

Comment thread multidict/_multilib/hashtable.h Resolved
Comment thread multidict/_multilib/hashtable.h Resolved
@greptile-apps

greptile-apps Bot commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

These findings sit on lines the diff does not cover, so they could not be posted inline. Each one leaves this list once its file changes.

  • P1 Readonly finder can dereference a reclaimed entry after visited-buffer allocation ▶

    • Bug
      • With more than eight matches, md_readonly_find_next() computes an entry_t * from the current keys table, then invokes _md_readonly_finder_grow_visited(). If its PyMem_Malloc or PyMem_Realloc blocks, the active self critical section may be suspended. A concurrent mutation can resize the MultiDict, retire the original table, and drain it because this finder has not entered the per-table reader protocol. After resumption, the old entry is used by _md_ensure_key() and/or Py_NewRef(entry->value), producing a use-after-free.
    • Cause
      • The code retains a table-derived pointer across a potentially suspending allocation and does not validate/restart after the allocation. Critical-section resumption reacquires the object lock but does not restore the lifetime of pointers captured before suspension. The retirement protection only applies to callers using _md_reader_enter() / _md_reader_exit(); this locked finder does not.
    • Fix
      • Do not retain entries/entry across _md_readonly_finder_grow_visited(). After a successful grow, revalidate that finder->md->keys and version are unchanged and recompute/restart the probe, or move the allocation before deriving any table pointer. A restart must re-check the iterator/table/version invariants before dereferencing an entry.

@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

@asvetlov
asvetlov merged commit f56ac58 into aio-libs:master Sep 20, 2026
107 of 109 checks passed
@asvetlov
asvetlov deleted the fix-getall-foreign-mark-visibility branch September 20, 2026 11:25
asvetlov added a commit that referenced this pull request Sep 20, 2026
)

<!-- Thank you for your contribution! -->

## What do these changes do?

An automated review of #1484 flagged `md_readonly_find_next()`'s
allocation
as a potential use-after-free, reasoning that a blocking
`PyMem_Malloc()`
call could transiently suspend the held critical section. That mechanism
does not exist: per #1469, `PyMem_Malloc()` never suspends an acquired
critical section on the free-threaded build, so the finding was a false
positive there.

Chasing the same claim through the rest of `hashtable.h` turned up two
real issues. `md_clone_from_ht()` still carried the exact
retry-on-staleness loop #1469 already proved dead in `_md_resize()`,
just
never cleaned up here; this drops it the same way. `_md_del_at()`,
`_md_del_at_for_upd()` and `_md_replace()` have a real suspension risk
(a decref of the old key/value can run a finalizer or weakref callback),
but their comments wrongly attributed it to "the same allocator lock as
`PyMem_Malloc()`", pointing at a comment that no longer exists anywhere
in
the file after #1469; reworded those to name the actual mechanism.

## Are there changes in behavior for the user?

No.

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

No; this only touches internal comments and removes unreachable code in
one free-threaded-only helper.

## Related issue number

Related to #1484 and #1469, not closing either.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist -- N/A, no behavior change; the
      touched paths are already exercised by the existing suite on both
      backends
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` -- N/A, no such file in this repo
- [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`

Drafted with Claude Code (Claude Sonnet 5); reviewed by
:user:`asvetlov`.

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Tests (isolated venvs, this branch rebased onto current upstream
master):

- C extension, default build: `pytest tests -q` -- 2059 passed
- Free-threaded debug build (`MULTIDICT_DEBUG_BUILD=1`): `pytest tests
-q -k "not test_leak" --no-cov` -- 2049 passed
- Free-threaded debug build under ASan+UBSan (`MULTIDICT_ASAN_BUILD=1`):
same command under `LD_PRELOAD=libasan.so ASAN_OPTIONS=detect_leaks=0`
-- 2049 passed, no sanitizer reports
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `pytest --no-c-extensions
--no-cov`): 1037 passed

Lint: `make doc-spelling` passes; pre-commit hooks (clang-format,
changelog filename/role checks) passed on commit.

</details>

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
asvetlov added a commit that referenced this pull request Sep 21, 2026
)

<!-- Thank you for your contribution! -->

## What do these changes do?

Moves the CodSpeed benchmark job to Python 3.14, and makes the `repr()`
and view inequality benchmarks repeat their operation 100 times, the way
the other benchmarks already loop. The benchmark job timeout goes from
10 to 15 minutes, since the job takes about 9.5 minutes.

The high "variability" figures on the CodSpeed dashboard (up to about
140%) come from benchmark redefinitions in #1494 and from the real
`add()` and `getall()` performance changes in #1466 and #1484, not from
run-to-run noise. A same-commit rerun on master (242e5bd) reported 266
of 266 benchmarks unchanged. The dashboard window will age out by
itself.

## Are there changes in behavior for the user?

No, only benchmarks and CI change. The reshaped benchmarks, and the move
to 3.14, will cause a one-time jump in their CodSpeed history.

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

No.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist: N/A, this only changes
benchmarks and CI
- [ ] 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
- [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>

Measurement: valgrind is not available locally, so a small pytest plugin
emulated pytest-codspeed's simulation mode, including the
`gc.collect()`/`gc.disable()` and `random.seed(0)` that
`plugin._measure` does, followed by one warmup call and one measured
call. It recorded user-space retired instructions with
`perf_event_open`, pinned to P-cores. Each run allocated a different
number of dummy objects first, to mimic unrelated heap changes between
commits. The suite ran on CPython 3.15.0rc2 with `PYTHONHASHSEED=0`, 40
runs per variant, using the same seeds for both.

- master benchmarks: every benchmark within 3.6% max/min spread; the
worst was `test_items_view_not_equals[ci-py]`, followed by
`test_values_view_repr[ci-c]` at 2.4%.
- this branch: every benchmark within 3.3% spread; the looped benchmarks
all dropped below 2%.

An earlier revision also added a `gc_disabled` fixture, based on a
harness that did not replicate pytest-codspeed's own GC handling. It was
redundant and has been removed.

Tests (3.14.2): `pytest` passed (2059 passed, 21 skipped); `pytest
--no-c-extensions` passed (1037 passed); `pytest --codspeed
--codspeed-mode simulation` passed (269 benchmarks). 3.15 was tried
first but dropped: setup-python has no prebuilt 3.15 yet, so the job
compiled CPython and ran even longer.

Lint: `pre-commit run` on the changed files passed; `make doc-spelling`
passed.

</details>

Drafted with Claude Code (Opus 5); reviewed by asvetlov.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant