Repository navigation
Keep the insert-path resize out of line - #1601
Merged
Merged
Conversation
GCC inlined _md_shrink() through _md_resize_for_insert() into md_add_with_hash_steal_refs(), growing its prologue from two to six callee-saved pushes that every insert paid for a branch it almost never takes.
asvetlov
marked this pull request as ready for review
September 26, 2026 15:05
Contributor
|
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 26, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? `_multidict.c` and every `_multilib` header form one translation unit, and GCC caps how much the whole unit may grow through inlining (`inline-unit-growth`, 40%). `-fopt-info-inline` shows the cap refusing 98 call sites on the GIL build and 662 on the free-threaded one, so unrelated edits keep moving these decisions (#1601 fixed one such case on the insert path). This marks `NOINLINE` the operations that sit behind Python slots (`md_replace()`, `md_del()`, `md_repr()`) and the bulk update loops (`md_update_from_dict/ht/seq()`, `md_extend_self()`). Otherwise they compete with the hot paths for the budget, and freed budget goes to inlining them into a slot such as `mp_ass_subscript`, where `delitem` then pays `md_replace()`'s register saves. The bulk loops are refused today anyway, so for them the attribute only pins the current layout. It uses only the existing `NOINLINE` macro, which also works on MSVC, with no build flags. The pure-Python implementation has nothing equivalent. Instructions per operation on 3.14.7t against master 8708f36 (Callgrind, `benchmarks/callgrind_driver.py`), rows that moved at least 1%. On 3.14.7 no row moved 1% or more. | operation | `MultiDict` | `CIMultiDict` | |---|---:|---:| | `getitem_hit` | 246 -> 234 (-4.9%) | 296 -> 286 (-3.4%) | | `get_miss` | 380 -> 371 (-2.4%) | 419 -> 412 (-1.7%) | | `contains_hit` | 195 -> 195 | 250 -> 247 (-1.2%) | | `setitem_replace` | 511 -> 505 (-1.2%) | 562 -> 556 (-1.1%) | | `pop` | 549 -> 538 (-2.0%) | 600 -> 586 (-2.3%) | | `popitem` | 677 -> 665 (-1.8%) | 1,728 -> 1,716 (-0.7%) | | `ctor_empty` | 893 -> 878 (-1.7%) | 981 -> 966 (-1.5%) | | `ctor_items` | 70,308 -> 69,893 (-0.6%) | 81,336 -> 80,321 (-1.2%) | ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No, these are annotations. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [x] Unit tests for the changes exist (no behavior change; the existing suite covers these paths) - [x] Documentation reflects the changes (N/A, internal only) - [ ] 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` Drafted with Claude Code (Claude Opus 5.5); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> Tests, merged with master 8708f36: - C extension, 3.14.7: 2790 passed, 170 skipped - C extension, 3.14.7t: 2777 passed, 183 skipped - C extension, 3.10.17: 2790 passed, 170 skipped - Pure Python, 3.14.7 (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`): 1320 passed, 17 skipped Lint: pre-commit hooks pass. `make doc-spelling` passes. Most of the free-threaded refusals are `Py_DECREF()` and `Py_NewRef()`, whose free-threaded bodies are large, so hot loops call a local out-of-line copy for each reference (about 40 instructions per `del d[key]`). A first revision forced them inline by redeclaring them `always_inline`, which gained another 3 to 10% there, but that does not work on Windows and macOS and was dropped. `--param=inline-unit-growth=400` removes every refusal but is a GCC-only flag and grows the code by 36 to 54%. Adding `NOINLINE` to slot-only functions themselves does nothing: 83 of the 98 slot and method functions have no direct caller. Wall clock: not re-measured for this revision. The pyperf A/B run was for the first revision, which included the dropped redeclaration. Not tested: musl, macOS, Windows and Android builds. </details>
5 of 6 tasks
asvetlov
added a commit
that referenced
this pull request
Sep 28, 2026
<!-- Thank you for your contribution! --> ## What do these changes do? `popitem()` built its result while it still pointed at the popped entry, and read the entry's value afterwards. Building the result can run Python code that mutates the multidict: a `str` subclass key's `__str__()` when a `CIMultiDict` makes its `istr`, and on Python 3.10 and 3.11 a garbage collection the tuple allocation triggers, whose finalizers run there. If that code replaced the table, the value came from freed memory (a wrong value, or a crash). The C implementation now takes its own references, removes the pair, and only then builds the result, the order the pure-Python implementation already used. The pure-Python `popitem()` decremented its size after building the key, so it miscounted `len()` in the same case, and kept the old entry list alive in a local until it returned; both are fixed. ## Are there changes in behavior for the user? Yes: the use-after-free is gone. If building the key raises, the pair is removed before the exception propagates, as the pure-Python implementation always did; the C one used to leave it in place. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number Found by the finalizer audit in #1631; same class as #1619. ## 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 tests: `test_popitem_key_str_mutates` (fails on both backends against master: C returns the value `'1'` read from the freed table, pure Python miscounts `len`), `test_popitem_key_str_raises`, and `test_popitem_collection_mutates`, which arms a collection at each of 12 allocation offsets; on 3.10 against master it fails 6 C cases with wrong values. Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2951 passed), FT 3.14.7t (2939), 3.10.17 (2951), `MULTIDICT_DEBUG_BUILD=1` GIL (2951) and FT (2939), pure Python with `MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions` (1384), and ASan+UBSan on a debug GIL build with `PYTHONMALLOC=malloc` (2939, `test_leaks` deselected) and again with `MULTIDICT_NO_FREELIST=1` (2939). 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: rows that moved by 0.5% or more: | row | GIL MultiDict | GIL CIMultiDict | FT MultiDict | FT CIMultiDict | |---|---|---|---|---| | popitem | 502.6 -> 489.4 (-2.6%) | 1507.1 -> 1495.9 (-0.7%) | 646.6 -> 564.4 (-12.7%) | 1698.0 -> 1613.8 (-5.0%) | | delitem | 237.5 -> 234.5 (-1.3%) | 290.2 -> 287.2 (-1.0%) | 392.2 -> 396.2 (+1.0%) | 443.9 -> 447.9 (+0.9%) | | setitem_replace | 327.5 -> 321.5 (-1.8%) | | | | | setitem_insert | 402.5 -> 395.7 (-1.7%) | | | | | iter_items | 129.7 -> 127.7 (-1.5%) | 133.7 -> 131.7 (-1.5%) | 188.7 -> 186.7 (-1.1%) | 189.7 -> 187.7 (-1.1%) | | iter_keys | 60.1 -> 59.1 (-1.7%) | 64.1 -> 63.1 (-1.6%) | | | | getall | 812.9 -> 807.9 (-0.6%) | | | | `popitem()` takes over the entry's references (`_md_unlink_at()`, split out of `_md_del_at()`) instead of adding its own; a first cut that did `Py_NewRef()` three times cost +6.3% on GIL `popitem`. `md_next()` is `ALWAYS_INLINE` here too (the same hunk as #1628): after the rebase onto 9802f1b, GCC 15 pushed it out of the FT items iterator, and `tools/check_inlining.py` failed its #1601 rule; pinned, all 8 rules pass on GIL and FT with GCC 13 and 15. Lint: pre-commit clean; `make doc-spelling` passes (adds `finalizers`). </details> Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What do these changes do?
Marks
_md_resize_for_insert()asNOINLINE. On GIL builds GCC inlined_md_shrink()through it intomd_add_with_hash_steal_refs(), so the insert helper's prologue saved six callee-saved registers instead of two on every insert, for a branch taken only when the table is full. Free-threaded builds were not inlining it and are unchanged.Instruction counts from
benchmarks/callgrind_driver.py(3.14.7,multidict_c, rows that moved by 0.3% or more):ctor_itemsctor_smallsetitem_insertaddsetdefault_newadd_istrupdateOn 3.14.7t no row moved by 0.3% or more.
updatepays about 1% becausemd_update_from_dict()lays its loop out differently once the budget shifts.Are there changes in behavior for the user?
No, only performance.
Is it a substantial burden for the maintainers to support this?
No, it is a single attribute.
Related issue number
N/A
Checklist
CONTRIBUTORS.txt(N/A, already listed)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Tests:
pytest -qpassed on 3.14.7 (2790 passed) and 3.14.7t (2777 passed);pytest -q -m "not leaks and not hypothesis and not capi"on 3.10.17 (2641 passed);MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensionson 3.14.7 (1320 passed).Callgrind:
PYTHONHASHSEED=0 callgrind_driver.py --include-multidict-only --impl multidict_c, base 602dedc, the same patch measured in isolation.Codegen:
md_add_with_hash_steal_refsprologue went from 6 pushes to 2 (objdump -d, GCC 15.2,-O3).Wall clock (pyperf): not measured yet.