Repository navigation
Fix del, popall() and getall() walking a table a finalizer changed - #1512
Conversation
Merging this PR will improve performance by 13.11%
|
| 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)
|
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.
65c150b to
b6e5cf6
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
<!-- 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.
What do these changes do?
md_del()(del md[key]) andmd_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-checkmd->keysandmd->versionafter each deletion and rescan from the current table when either changed, the same approach_md_replace()already uses.md_pop_all()andmd_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 andgetall()raised a spuriousRuntimeError. Both functions now take the critical section themselves, collect strong refs into a smallPyMem-backedreflist_twhile 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
RuntimeErrorbeing gone.Is it a substantial burden for the maintainers to support this?
No.
Related issue number
Fixes #1492
Checklist
CONTRIBUTORS.txtN/ACHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted 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 -qpasses 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_talso fixed the crash, but sloweddel 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_mutatessegfaults 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
getallis 17 to 53% faster, multi-valuepopall12 to 26% faster, single-valuegetall/popalland 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 andMULTIDICT_DEBUG_BUILD=1).