Skip to content

Fix del, popall() and getall() walking a table a finalizer changed - #1512

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:fix-1492-del-popall-restart
Sep 22, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:fix-1492-del-popall-restart

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

md_del() (del md[key]) and md_pop_all() (popall()) cached the entries pointer before the loop and kept walking the table after each _md_del_at(). That call decrefs the deleted value, and a __del__ there can suspend the critical section (or release the GIL), letting another thread resize the multidict and free the old table. Both functions now re-check md->keys and md->version after each deletion and rescan from the current table when either changed, the same approach _md_replace() already uses.

md_pop_all() and md_get_all() also used to create the result list inside the critical section. PyList_New() can run a GC (synchronously before 3.12), and a finalizer there could resize the multidict mid-walk: popall() then deleted through a stale entry pointer and getall() raised a spurious RuntimeError. Both functions now take the critical section themselves, collect strong refs into a small PyMem-backed reflist_t while locked, and build the list after unlocking.

This also removes the free-threaded skip from test_del_pop_vs_update_same_key_thread_safety, which was waiting on this issue. The pure-Python implementation is unaffected.

Are there changes in behavior for the user?

No, apart from the crash and the spurious RuntimeError being gone.

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

No.

Related issue number

Fixes #1492

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 N/A
  • 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

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

Agent run details (optional, for reviewers)

Repro from #1492 on the current master: 8/8 segfaults on 3.14.7t (traceback in del d["k"]), 0/15 on 3.13.12. With this change: 0/10 on both.

Tests: python -m pytest tests -q passes on 3.13.12 (2160 passed) and 3.14.7t (2149 passed); the suite is parametrised over the C and pure-Python backends.

An alternative that pushed the decrefs to deferred_decref_t also fixed the crash, but slowed del md[k] by about 20 to 27% on the GIL build. The restart check is within noise (about 4%) of master on every case measured (delitem, popall, pop, setitem, 200 keys, best of 3 pinned runs).

test_getall_popall_gc_finalizer_mutates segfaults the first commit's build on 3.11 and passes with the second; on 3.12+ the GC is deferred, so it passes either way.

getall/popall timings, first commit vs second (best of 3, 200 keys): multi-value getall is 17 to 53% faster, multi-value popall 12 to 26% faster, single-value getall/popall and misses within noise.

ASan+UBSan (3.11, PYTHONMALLOC=malloc): 2157 passed. Full suite also passes on 3.11.13, 3.13.12, and 3.14.7t (release and MULTIDICT_DEBUG_BUILD=1).

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 22, 2026
@asvetlov asvetlov changed the title Restart del and popall() scans when a decref changes the table Fix del, popall() and getall() walking a table a finalizer changed Sep 22, 2026
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 13.11%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 12 improved benchmarks
✅ 286 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_getall_str_hit[cs-c] 3.6 ms 3.1 ms +17.37%
⚡ test_cimultidict_getall_istr_hit[c] 3.8 ms 3.2 ms +16.09%
⚡ test_cimultidict_getall_istr_hit_nonascii[c] 3.9 ms 3.4 ms +15.49%
⚡ test_multidict_getall_str_hit_nonascii[cs-c] 3.7 ms 3.2 ms +15.34%
⚡ test_multidict_getall_str_hit_large_table_many_values[cs-c] 1.3 ms 1.1 ms +13.33%
⚡ test_multidict_getall_str_hit_large_table[cs-c] 681.6 µs 602.6 µs +13.1%
⚡ test_multidict_getall_str_hit[ci-c] 4.6 ms 4.1 ms +12.65%
⚡ test_multidict_getall_str_hit_many_values[cs-c] 3 ms 2.7 ms +12.28%
⚡ test_multidict_getall_str_hit_nonascii[ci-c] 5.3 ms 4.7 ms +12.16%
⚡ test_multidict_getall_str_hit_large_table_many_values[ci-c] 1.4 ms 1.3 ms +10.87%
⚡ test_cimultidict_getall_istr_hit_many_values[c] 3 ms 2.7 ms +9.71%
⚡ test_multidict_getall_str_hit_large_table[ci-c] 810.6 µs 742 µs +9.24%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:fix-1492-del-popall-restart (b6e5cf6) with master (e2c568d)

Open in CodSpeed

Comment thread tests/test_multidict.py Dismissed
@asvetlov
asvetlov marked this pull request as ready for review September 22, 2026 07:51
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 22, 2026 07:51
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (3) · Last reviewed commit: "Skip the GC finalizer test on PyPy"

Deleting an entry drops its references immediately, and the value's
__del__ can suspend the critical section (or release the GIL), letting
another thread resize the multidict. md_del() and md_pop_all() then kept
walking the old table. Re-check md->keys and md->version after each
deletion and rescan from the new table when either changed, the same
way _md_replace() already does.

Fixes aio-libs#1492
Creating the result list inside the critical section can run a GC
(synchronously before 3.12), and a finalizer there could resize the
multidict mid-walk: popall() then deleted through a stale entry pointer
and getall() raised a spurious RuntimeError. md_get_all() and
md_pop_all() now take the critical section themselves, collect strong
refs into a PyMem-backed reflist_t while locked, and create the list
only after unlocking.
@asvetlov
asvetlov force-pushed the fix-1492-del-popall-restart branch from 65c150b to b6e5cf6 Compare September 22, 2026 08:17
@codecov

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1512   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           38        38           
  Lines         6325      6347   +22     
  Branches       573       574    +1     
=========================================
+ Hits          6325      6347   +22     
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 merged commit a4479a6 into aio-libs:master Sep 22, 2026
60 of 61 checks passed
@asvetlov
asvetlov deleted the fix-1492-del-popall-restart branch September 22, 2026 08:50
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`del md[key]` and `popall()` decref'd each match as soon as they
unlinked it. A finalizer of a removed key or value could add the key
back mid-scan; the scan then restarted (the restart #1512 added for
concurrent resizes) and removed that new pair too, and `popall()`
returned its value. The removed pairs are now held until every match is
gone: the first in place, which covers the usual single match, any more
in a `reflist_t`. With nothing in the loops able to run Python, the
restart is gone.

The pure-Python `__delitem__()`, `popall()` and `__setitem__()` freed
each match mid-scan as well, and with a finalizer that replaced the
table they raised `IndexError` or miscounted `len()`; they now keep the
removed entries alive until the scan ends. The C `__setitem__()` already
deferred its decrefs.

## Are there changes in behavior for the user?

Yes: pairs a finalizer adds during `del md[key]` or `popall()` stay in
the multidict.

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

No.

## Related issue number

Found by the finalizer audit in #1631.

## 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` (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>

New `test_remove_all_keeps_what_a_finalizer_adds` (delitem, popall,
setitem x key/value side x both classes x both backends): against master
6 C and 6 pure-Python delitem/popall cases fail, and the 4 pure-Python
setitem ones.

Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2923
passed), FT 3.14.7t (2911), 3.10.17 (2923), `MULTIDICT_DEBUG_BUILD=1`
GIL (2923) and FT (2911), pure Python with `MULTIDICT_NO_EXTENSIONS=1
--no-c-extensions` (1370), and ASan+UBSan on a debug GIL build with
`PYTHONMALLOC=malloc` (2911, `test_leaks` deselected) and again with
`MULTIDICT_NO_FREELIST=1` (2911). The Cython harness was not built, so
its cases skipped.

Callgrind, `PYTHONHASHSEED=0`, `benchmarks/callgrind_driver.py
--include-multidict-only`, base master 9802f1b, Ir per op: GIL `delitem`
237.5 -> 251.5 (`MultiDict`, +5.9%) and 290.2 -> 307.2 (`CIMultiDict`,
+5.9%); FT `delitem` 392.2 -> 387.2 (-1.3%) and 443.9 -> 437.9 (-1.4%).
The `md_next()` pin below takes GIL `iter_items`/`iter_keys` down 1.5%
and `setitem_*` 1.7%; nothing else moved by 0.5% or more. A first cut
that pushed all three refs of every match into a `reflist_t` cost +61 Ir
on GIL `delitem`; holding the first pair in place brought that down.

`tools/check_inlining.py` first failed `multidict_items_iter_tp_iternext
-> md_next` on FT with GCC 15 (FT `iter_items` +19%);
`removed_pairs_release()` is `NOINLINE` for that; after the rebase onto
9802f1b it failed again, so `md_next()` is `ALWAYS_INLINE` as well (the
same hunk as #1628), and all 8 rules pass on GIL and FT with GCC 13 and
15. Lint: pre-commit clean; `make doc-spelling` passes.
</details>

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
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.

Concurrent __delitem__()/pop()/popall() can still segfault racing update()/merge() on the same key

2 participants