Skip to content

Share one __init__ body between MultiDict and CIMultiDict - #1591

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fold-tp-init
Sep 25, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:fold-tp-init

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

multidict_tp_init() and cimultidict_tp_init() were about 80 lines each and differed only in the is_ci flag and the type name used in error messages. They now share one ALWAYS_INLINE body, and the two slots are one-line wrappers. Forcing the inline matters: as a plain out-of-line helper taking is_ci at run time, CIMultiDict subclass construction measured 7 to 8 percent slower; inlined, each slot gets its own constant-folded copy again, the same size as before.

Are there changes in behavior for the user?

No.

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

No, it removes a copy that had to be kept in sync by hand.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (no behavior change; the existing suite covers these paths)
  • Documentation reflects the changes (N/A, internal only)
  • 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.5); pending review by @asvetlov before leaving draft.

Agent run details (optional, for reviewers)

Tests: pytest -q on 3.14.7 (C, 2756 passed), 3.10.17 (C, 2756 passed), 3.14.7t with MULTIDICT_DEBUG_BUILD=1 (2732 passed); pure Python leg with MULTIDICT_NO_EXTENSIONS=1 ... --no-c-extensions (1296 passed).
Lint: pre-commit (clang-format, ruff, mypy) and make doc-spelling pass.
Wall clock: interleaved pyperf A/B, 6 alternating rounds x 2 processes, GIL on cpu 1 and free-threaded on cpu 3. An A/A control of base against itself showed single rows moving up to 7% (GIL) and 4% (free-threaded) with geometric mean within 1%, so only the geometric mean and callgrind are meaningful here.

Symbols (GIL): base cimultidict_tp_init 0x484 and multidict_tp_init 0x474 bytes; this branch 0x47e each.
Callgrind, subclass construction (SubMD(pairs), SubMD(dict), SubCIMD(pairs), SubCIMD(CIMultiDict)), Ir per op: identical to base within 1 Ir on both builds. Registry rows: GIL 0 of 52 moved; free-threaded only setdefault_new +10 Ir (layout, the path is untouched).
pyperf geometric mean: GIL 1.00x, free-threaded 1.01x slower (within noise).

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 25, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 25, 2026 19:27
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 25, 2026 19:27
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Refactors initialization logic for two dictionary types.

No issue was found that would block merging.

What we checked:

  • The base C extension and the PR C extension were built separately, and the same constructor script was run against both. T-Rex
  • All 57 checked cases matched across re-initialization, watcher events, and yarl query flows, and the focused multidict and C API tests passed: 1,540 passed and 153 skipped. T-Rex
  • Both runs exited with status 0, and the focused PR test run completed 1,540 tests with 153 skipped due to the optional Cython extension not being built, while no tracked files were changed. T-Rex

Reviews (1) · Last reviewed commit: "Share one __init__ body between MultiDic..."

@codspeed

codspeed Bot commented Sep 25, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:fold-tp-init (11f8ac0) with master (1706f5c)

Open in CodSpeed

@asvetlov
asvetlov merged commit 5ce1730 into aio-libs:master Sep 25, 2026
59 checks passed
@asvetlov
asvetlov deleted the fold-tp-init branch September 25, 2026 19:50
@codecov

codecov Bot commented Sep 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9d2a676) to head (11f8ac0).
⚠️ Report is 6 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1591   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7797      7856   +59     
  Branches       650       652    +2     
=========================================
+ Hits          7797      7856   +59     
Flag Coverage Δ
CI-GHA 100.00% <ø> (ø)
pytest 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 added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds `tools/check_inlining.py` and an `Inlining` CI job on 3.14 and
3.14t. The script compiles `_multidict.c` with the interpreter's flags
plus the release flags from `setup.py`, disassembles it, and fails when
an entry point a rule names (a slot, method or `MultiDict_*` C API
function) reaches the rule's helper through any chain of out-of-line
calls; the report shows the chain. The first rules come from the
regressions in #1527, #1530, #1541, #1542, #1554, #1591 and #1604, each
of which slowed a benchmark on code the change never touched. AGENTS.md
now asks agents to run it, to add a rule whenever they fix an inlining
regression or pin a helper, and never to weaken a rule without a
measurement.

CI builds with GCC 13.3. The two rules it failed on master at first
(`md_calc_identity` out of line in `getall()` and `popall()` on
free-threaded builds) were fixed by #1614; master now passes every rule
with GCC 13 and GCC 15 on both builds.

## Are there changes in behavior for the user?

No.

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

No. A PR that moves an inlining decision on purpose edits the matching
rule.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A, a CI-only tool; verified by
reintroducing past regressions, see below)
- [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`

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

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

Master passes on 3.14.7 and 3.14.7t with GCC 14 and GCC 15.

Each past regression reintroduced by hand was caught:
- dropping `ALWAYS_INLINE` from `htkeysiter_init`: out-of-line copy
reported, plus `md_contains` out of `isdisjoint`
- dropping `NOINLINE` from the view, iterator and shell pool helpers
(#1541/#1542): `md_contains` out of `isdisjoint`
- dropping `NOINLINE` from `_ci_str_to_identity` (#1527): failures
across getitem, getall, replace and `isdisjoint` on both builds

GCC 13.5 (`gcc:13` Docker image): the two failures listed above.
Lint: `pre-commit run` clean; `make doc-spelling` clean.
</details>
asvetlov added a commit that referenced this pull request Oct 4, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`__init__()`, `extend()`, `update()` and `merge()` in `_multidict.c`
were four copies of the same structure: parse the arguments, pick one of
three locking arms by the type of the source, run the batch, flush the
watchers. They now share `_multidict_bulk()` and
`_multidict_bulk_locked()`, which removes about 140 lines from
`_multidict.c`.

Both helpers are `ALWAYS_INLINE` and take the operation as a constant,
so every entry point still compiles its own copy, as the
`check_inlining.py` rule from #1591 requires; the rule now names
`_multidict_bulk`.

`md_post_update()` moves out of line. Left to GCC it was inlined into
one arm of `update()`, and on free-threaded builds that took
`Py_NewRef()` out of the items iterator (+5 instructions per step) and
`list_getitem_ref()` out of the constructor loop. There is no way to
express a `NOINLINE` pin as a rule in `check_inlining.py`, so the
comment on the function carries the reason.

No behaviour change. The pure-Python implementation is not affected.

Measured with callgrind, before and after, on 3.14.7 and 3.14.7t, both
classes:

- `benchmarks/callgrind_driver.py --include-multidict-only`: every row
within 0.06%.
- The four entry points themselves, with a list, a dict, a multidict of
the same class, one of the other class, and keyword arguments only as
the source: all 80 cells between -0.12% and +0.29%. `merge()` is the
consistent mover, about +0.1% to +0.2% (roughly 20 to 30 instructions
per call) for the call to `md_post_update()`.

## Are there changes in behavior for the user?

No.

## 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
- [x] Unit tests for the changes exist (the existing suite; no behaviour
change)
- [x] 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`

Drafted with Claude Code (Claude Fable 5.1); not yet reviewed by a
human.

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

All numbers are from the branch rebased onto cfcf7f3.

- `tools/codegen_diff.py` is not empty for this change (30 functions on
3.14.7 and 184 on 3.14.7t before the rebase), which is why it was
measured instead.
- Out-of-line call targets of `multidict_items_iter_tp_iternext`,
`_md_update_from_seq_extend_ci/cs`, `md_del_ci/cs` on 3.14.7t are the
same as on the base; without `NOINLINE` on `md_post_update()` they
differ.
- `tools/check_inlining.py` on 3.14.7 and 3.14.7t: ok
- C extension: 3.14.7 4077 passed, 3.14.7t 4062 passed, 3.10.17 4081
passed
- Pure Python, 3.14.7, clean tree, `--no-c-extensions`: 1604 passed
- `MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1`, 3.14.7,
`PYTHONMALLOC=malloc`, `-k "not test_leak"`: 4065 passed
- `make doc-spelling` and pre-commit: pass

Not run: the `MULTIDICT_NO_FREELIST=1` ASan pass, TSan, wall-clock
benchmarks.
</details>
asvetlov added a commit that referenced this pull request Oct 6, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Drops `ALWAYS_INLINE static inline` from `_multidict_bulk()` and
`_multidict_bulk_locked()`, so `__init__()`, `extend()`, `update()` and
`merge()` share one out-of-line copy instead of each compiling its own.
`_md_to_dict_scan()` is folded into `md_to_dict()`, which now picks the
entry kind at runtime instead of specializing a copy per kind.
`_multidict_clone_fast()` was already plain `static`.

The `_multidict_bulk` rule in `tools/check_inlining.py` (#1591, "one
shared copy made subclass init 7-8% slower") is removed: the bulk paths
changed a lot since then, and the cost measured now is far smaller.

Callgrind, 3.14.7, instructions per operation, base vs this branch:

| Operation | GIL | FT |
|---|---|---|
| `reinit_items_small` | +1.1% to +1.5% | +0.9% to +1.1% |
| `to_dict()`, 200 entries, 150 keys | -0.7% to +0.9% | -0.7% to +0.9% |
| every other row, `ctor_*` included | under 0.5% | under 0.5%
(`iter_items` +2 Ir) |

`reinit_items_small` is `d.__init__(items)` on an existing instance;
construction itself goes through vectorcall and is unaffected.

## Are there changes in behavior for the user?

No.

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

No, it removes code.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A, no behaviour change;
covered by the existing suite)
- [ ] 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`

Drafted with Claude Code (Claude Opus 5.5); to be reviewed by @asvetlov.

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

Tests: `pytest -q` passed on the C extension under 3.14.7 GIL (4089
passed), 3.14.7t FT (4074 passed) and 3.10 (4093 passed), and on the
pure-Python build with `--no-c-extensions` (1610 passed).
Inlining: `tools/check_inlining.py` ok on 3.14.7 and 3.14.7t.
Measurement: `benchmarks/callgrind_driver.py --include-multidict-only`,
base and branch trees in separate copies; `to_dict()` measured with a
bracketed callgrind script (PYTHONHASHSEED=0, two loop counts
differenced).
</details>
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