Skip to content

Keep the insert-path resize out of line - #1601

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:md-resize-for-insert-noinline
Sep 26, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:md-resize-for-insert-noinline

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Marks _md_resize_for_insert() as NOINLINE. On GIL builds GCC inlined _md_shrink() through it into md_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):

operation before after delta
ctor_items 46705 44704 -4.28%
ctor_small 4411 4229 -4.13%
setitem_insert 412 403 -2.11%
add 503 494 -1.73%
setdefault_new 521 512 -1.67%
add_istr 840 831 -1.05%
update 39230 39625 +1.01%

On 3.14.7t no row moved by 0.3% or more. update pays about 1% because md_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

  • I think the code is well written
  • Unit tests for the changes exist (N/A, no behaviour change; the existing suite covers the insert and resize paths)
  • Documentation reflects the changes (N/A)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A, already listed)
  • 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.5); reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Tests: pytest -q passed 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-extensions on 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_refs prologue went from 6 pushes to 2 (objdump -d, GCC 15.2, -O3).
Wall clock (pyperf): not measured yet.

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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 26, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 26, 2026 15:05
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 26, 2026 15:05
@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Compiler optimization hint in the hash table implementation.

No merge-blocking issue was found.

What we checked:

  • We built the parent and PR C extensions separately and ran the deletion-and-reinsertion script against each; both runs produced identical ordered-item hashes and the selected multidict tests passed (1,474 passed and 6 skipped per build). T-Rex
  • We built the C extension and C API consumer separately from the parent and PR commits and ran the growth probe against both builds; both runs exited successfully and reported that all Python and C capsule growth paths passed. T-Rex
  • The before-and-after runs produced identical ordered-item hashes, and the script asserted that 35 deletions leave zero usable slots before the next insertion compacts the reference table. T-Rex
  • We ran a comparative growth test across two compiled extensions built from different commits; the probes reported exit code 0 and that all growth paths passed. T-Rex

Reviews (1) · Last reviewed commit: "Keep the insert-path resize out of line"

@codspeed

codspeed Bot commented Sep 26, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:md-resize-for-insert-noinline (3b423cb) with master (602dedc)

Open in CodSpeed

@asvetlov
asvetlov merged commit 8708f36 into aio-libs:master Sep 26, 2026
62 checks passed
@asvetlov
asvetlov deleted the md-resize-for-insert-noinline branch September 26, 2026 16:09
@asvetlov asvetlov mentioned this pull request Sep 26, 2026
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>
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.
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