Skip to content

Pool the multidict and proxy shells - #1542

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/freelist-md-proxy-shells
Sep 24, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/freelist-md-proxy-shells

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

The last of the short-lived allocations: constructing a MultiDict,
CIMultiDict or either proxy went through PyType_GenericAlloc() every
time. Those shells now come from two more module-state pools, one shared
by MultiDict and CIMultiDict, which share a struct and differ only
in md->is_ci, and one by the two proxy types.

Only the exact types. A subclass has its own basicsize, and possibly its
own __dict__ and __weakref__ preheader, so _md_pool_for() returns
NULL for one and it keeps going through tp_alloc, both when allocating
and when being freed. The tp_alloc and tp_free slots are untouched.

Reuse redoes what PyType_GenericAlloc() does, less the allocation: the
body is zeroed and PyObject_Init() sets the header. The preheader
needs nothing, since PyObject_GC_UnTrack() leaves the GC header
untracked and PyObject_ClearWeakRefs() leaves the managed weakref slot
NULL. A proxy reaches the pool through the multidict it proxies, so one
the GC has already cleared is freed rather than pooled.

Are there changes in behavior for the user?

No. Construction is cheaper, nothing observable otherwise. Subclasses
are explicitly unaffected, and there is a test for that.

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

No, though it is the sharpest of the four pools, since it is the one
that has to get the exact-type gate right at both ends. The tests cover
subclasses, weakrefs, proxies, the shared MultiDict/CIMultiDict pool
not leaking a case-insensitive flag, and shells the collector clears.

Related issue number

None.

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, no such file in this repo
  • 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

Fourth of five, stacked on #1539, #1540 and #1541 and including their
commits until they land. GitHub cannot base a cross-repo pull request on
a fork branch.

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

Agent run details (optional, for reviewers)

Tests: pytest -q on 3.13.2 and 3.14.7t, release and
MULTIDICT_DEBUG_BUILD=1, plus MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions and pytest -q -m leaks. All pass.

Perf: callgrind with PYTHONHASHSEED=0, GC collected and disabled around
the loop, a matching empty-body run subtracted.

@asvetlov
asvetlov force-pushed the claude/freelist-md-proxy-shells branch from 84b917b to 37f7c2b Compare September 23, 2026 18:50
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 9.1%

⚠️ 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

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_empty_multidict[cs-c] 25.9 µs 23.7 µs +9.1%

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:claude/freelist-md-proxy-shells (6f95739) with master (cd92a6c)

Open in CodSpeed

@asvetlov
asvetlov force-pushed the claude/freelist-md-proxy-shells branch 3 times, most recently from eca5218 to f3f8d28 Compare September 23, 2026 19:54
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`bitmap_t` carried a 4 KB inline word buffer. It sits in the caller's
frame, twice over inside `update_marks_t`, and `md_walk()` is always
inlined, so that frame lands in every `getall()`, `popall()`,
`__delitem__()`, `__contains__()` and `to_dict()`. Past about 1 KB it
costs those callers more in the inlining it crowds out than it saves in
allocations.

Nothing else changes. `_bitmap_start()` already falls back to the heap
past the inline capacity, so only the crossover moves, and a table of up
to 8192 entries still gets its bitmap for free.

Instructions per operation on a GIL build, swept at 4096, 2048, 1024 and
512 bytes:

| case | 4096 | 2048 | 1024 | 512 |
| --- | --- | --- | --- | --- |
| `getall()` that hits | 1055 | 1054 | 1026 | 1026 |
| `getall()`, 16384-entry table | 270685 | 270429 | 266973 | 266973 |

Everything else is flat to within 0.1%, and `popall()` over the same
table exactly so. The cliff is between 2048 and 1024. 1024 keeps twice
the inline capacity of 512 for the same result, and 512 is the floor
anyway: below it `BITMAP_INLINE_SUMMARY` rounds down to zero entries and
the struct does not compile.

## Are there changes in behavior for the user?

No. A walk over a table between 8192 and 32768 entries now allocates a
bitmap where it did not before, but only once it has more matches than
the short list holds, and the numbers above cover that case.

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

No, it is one constant.

## Related issue number

None.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist — N/A,
`tests/test_update_marks.py` already crosses the inline/heap boundary
and passes at every value swept
- [x] Documentation reflects the changes
- [x] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A, no such file in this repo
- [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`

---

Fifth of five and independent of the other four, which are #1539, #1540,
#1541 and #1542. It came out of the same investigation.

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

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

Tests: `pytest -q` on 3.13.2 and 3.14.7t, release and
`MULTIDICT_DEBUG_BUILD=1`, plus `MULTIDICT_NO_EXTENSIONS=1 pytest -q
--no-c-extensions` and `pytest -q -m leaks`. All pass.

Perf: callgrind with `PYTHONHASHSEED=0`, GC collected and disabled
around
the loop, a matching empty-body run subtracted.

</details>
@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (51c75e4) to head (6f95739).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1542   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7001      7066   +65     
  Branches       610       615    +5     
=========================================
+ Hits          7001      7066   +65     
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 force-pushed the claude/freelist-md-proxy-shells branch from f3f8d28 to d619c40 Compare September 23, 2026 20:35
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`htkeys_new()` and `htkeys_free()` carried a standing TODO to do what
CPython does for `PyDictKeysObject`. They now check a bounded
per-size-class pool held in the module state, which every multidict
reaches through its cached `state` pointer. A miss allocates and a full
pool frees, so the ordinary path is unchanged.

Size classes `log2_size` 3 to 8, at depths 32, 32, 32, 16, 8 and 4:
about 109 KB per interpreter with every pool full. The ladder stops
where a 100-item constructor pre-sizes to, since past that the
allocation is a small part of filling the table.

Nothing is pooled on a free-threaded build, and that was the measurement
that decided the design. A shared pool needs an atomic exchange to pop
and another to push; on x86 an exchange is a locked operation whatever
memory order it asks for, which came to a flat ~41 cycles per round trip
against mimalloc's 30-52, so it lost below a 1456-byte block. mimalloc
already gives every thread its own freelist. On a GIL build the same
pool is ~10 cycles against pymalloc's 26-55 and libc `malloc`'s 117-158.
Instruction counts said the opposite, 22 against 108-312, which is the
blind spot: callgrind cannot see what a locked exchange costs.

The pools live in the module state rather than at file scope because
under a per-interpreter GIL a block has to be freed by the interpreter
that allocated it. They hold no reference, so `module_traverse()` needs
no change; `module_clear()` drains them.

`MULTIDICT_NO_FREELIST=1` builds without them. A pooled block never
reaches `free()`, so AddressSanitizer can neither poison it nor report a
use-after-free on it, and an ASan run now wants a second pass with that
set. AGENTS.md says so.

## Are there changes in behavior for the user?

No. Faster construction and teardown, nothing observable otherwise.

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

No. The pool is one small header, and it degrades to the present
behaviour: an empty pool allocates, a full one frees, and a pool that
was never given a capacity misses every time.

## Related issue number

None. This is the TODO that stood in `htkeys.h` at `htkeys_new()` and
`htkeys_free()`.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [x] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A, no such file in this repo
- [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`

---

First of five. #1540, #1541 and #1542 stack on this
one and include its commits until it lands; #1543 is independent.
GitHub cannot base a cross-repo pull request on a fork branch, so all
five are opened against `master`.

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

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

Tests: `pytest -q` on 3.13.2 and 3.14.7t, release and
`MULTIDICT_DEBUG_BUILD=1`, plus `MULTIDICT_NO_EXTENSIONS=1 pytest -q
--no-c-extensions`, `pytest -q -m hypothesis` on both builds, and
`pytest -q -m leaks`. All pass.

ASan: `MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1`, run twice, once
as built and once with `MULTIDICT_NO_FREELIST=1`. No reports either way.

Perf: callgrind with `PYTHONHASHSEED=0`, GC collected and disabled
around
the loop, a matching empty-body run subtracted. The cycle figures quoted
above are `perf stat -e cycles:u` pinned to one P-core, min of 9 runs of
20M iterations, from a standalone probe module built with the
extension's
own flags. Cycles rather than instructions because that is the only way
to see what the free-threaded pool's locked exchange costs.

Not pooled, having been measured and rejected: reflist blocks
(`_reflist_grow` is 0.20% inclusive of a workload built to hammer it,
2000 popalls of 200 values under one key), resume slots, and the bitmap
heap block.

</details>
@asvetlov
asvetlov force-pushed the claude/freelist-md-proxy-shells branch 3 times, most recently from 204b3ad to d9e211f Compare September 24, 2026 07:01
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 07:47
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 07:47
The last of the short-lived allocations: constructing a MultiDict,
CIMultiDict or either proxy went through PyType_GenericAlloc() every
time. Those shells now come from two more module-state pools, one shared
by MultiDict and CIMultiDict, which share a struct and differ only in
md->is_ci, and one by the two proxy types.

Only the exact types. A subclass has its own basicsize, and possibly its
own __dict__ and __weakref__ preheader, so _md_pool_for() returns NULL
for one and it keeps going through tp_alloc, both when allocating and
when being freed. The tp_alloc and tp_free slots are untouched.

Reuse redoes what PyType_GenericAlloc() does, less the allocation: the
body is zeroed and PyObject_Init() sets the header. The preheader needs
nothing, since PyObject_GC_UnTrack() leaves the GC header untracked and
PyObject_ClearWeakRefs() leaves the managed weakref slot NULL. A proxy
reaches the pool through the multidict it proxies, so one the GC has
already cleared is freed rather than pooled.

Instructions per operation on a GIL build: MultiDict() -23.5%,
CIMultiDictProxy(md) -15.6%, copying a 5-item CIMultiDict -12.4%,
constructing a 20-header CIMultiDict -4.2%. getall() and iteration are
unchanged.
@asvetlov
asvetlov force-pushed the claude/freelist-md-proxy-shells branch from d9e211f to 6f95739 Compare September 24, 2026 07:51
@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

The benchmark-table requirement must be satisfied before merging.

Reviews (1) · Last reviewed commit: "Pool the multidict and proxy shells"

Comment thread multidict/_multilib/dict.h Resolved
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

The registry measured every operation on a 200-item mapping. The
allocation an operation makes is a fixed cost, so at that size it was
divided across 200 entries and all but disappeared: `d.items()`
measured 1.7% faster under #1541 where it is in fact 46% faster, and
the shell pools looked marginal when they are not.

Six operations are added for the shapes where the allocation is most of
the work: `cls()`, `cls(items)` and `d.copy()` at 20 items, `d.items()`
and `iter(d)` taken without being consumed, and `Proxy(d)`. The last
needs a proxy type per implementation, so `Impl` gains `load_proxy` and
`Operation` a `proxy` flag, mirroring how `istr` already works.

The generated tables in `docs/benchmark.rst` are regenerated, so their
numbers also move to current `master`.

## Are there changes in behavior for the user?

No. Nothing outside `benchmarks/` and `docs/` changes.

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

No. The new cases reuse the existing `Case` shape and the existing
runners; `callgrind_driver.py --self-check` covers them.

## Related issue number

None.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist — N/A, `benchmarks/` has no
suite; `--self-check` runs every cell
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A, already listed
- [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>

What the new cases say about the two shell-pool PRs, instructions per
operation, GIL build:

#1541 against its parent `130bd92`:

| operation | `MultiDict` | `CIMultiDict` |
| --- | ---: | ---: |
| `d.items()` | -46.3% | -34.3% |
| `iter(d)` | -41.0% | -41.0% |
| `for k in d`, 200 keys | -1.7% | -1.7% |

#1542 against `51c75e4`:

| operation | `MultiDict` | `CIMultiDict` |
| --- | ---: | ---: |
| `cls()` | -28.8% | -23.3% |
| `Proxy(d)` | -28.6% | -22.9% |
| `d.copy()`, 20 items | -9.7% | -8.1% |
| `cls(items)`, 20 items | -4.9% | -3.3% |
| `cls(items)`, 200 items | -0.5% | -0.3% |

`callgrind_driver.py --self-check` passes at 124 cells. Tables collected
on CPython 3.14.7 GIL and 3.14.7t, `PYTHONHASHSEED=0`, client-request
bracketing, matching the environment the previous tables recorded.

</details>

Drafted with Claude Opus 5; reviewed by @asvetlov.
@asvetlov
asvetlov merged commit ed928af into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/freelist-md-proxy-shells branch September 24, 2026 08:47
@asvetlov asvetlov mentioned this pull request Sep 24, 2026
5 of 6 tasks
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

The published numbers had gone stale for the operations the object-shell
pools made cheaper. AGENTS.md asks for the tables to be refreshed in the
same PR as the change that moves them; #1542 landed without it, so this
catches them up. Collected again on the environment the tables record.

Rows that moved by more than 2%, GIL build:

| row | `MultiDict` | `CIMultiDict` |
| --- | ---: | ---: |
| `cls()` | -24.7% | -20.7% |
| `d.copy()`, 20 items | -9.4% | -7.7% |
| `cls(items)`, 20 items | -4.5% | -3.1% |
| `d.setdefault(key, v)`, new key | -3.7% | -2.2% |
| `d[key] = v`, existing key | -3.1% | - |
| `d[key] = v`, new key | -2.7% | - |

The first three are the multidict and proxy shell pools from #1542; the
`setdefault()` and `d[key] = v` rows are #1553 keeping the implicit
default in the module state. No `dict` row moved, which is the control.

## Are there changes in behavior for the user?

No. Documentation only; the measurements themselves are unchanged code.

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

No.

## Related issue number

Follows up #1542.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist — N/A, documentation only
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A, already listed
- [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>

Collected with `benchmarks/callgrind_driver.py` on CPython 3.14.7 and
3.14.7t, `PYTHONHASHSEED=0`, client-request bracketing, one virtualenv
per build. The GIL virtualenv needs `pytest-codspeed` installed, or the
driver counts the whole process and `render_tables.py` refuses the
result rather than publishing numbers that undercount every destructive
operation.

</details>

Drafted with Claude Opus 5; reviewed by @asvetlov.
asvetlov added a commit that referenced this pull request Sep 24, 2026
…#1562)

<!-- Thank you for your contribution! -->

## What do these changes do?

On the free-threaded build, `md_clear()` returned early once `md->keys`
was
`&empty_htkeys`, so nothing on that path drained `md->retired`. The
drain
leaves a table on that list whenever it finds a lock-free reader in
flight,
for the next drain to free, and the only drain sites are reader exits
and
retirements; a multidict dropped right after a `clear()` that left its
table
there gets neither, so the table, and the references its entries still
owned,
were never freed. Draining in that early return makes the object's own
teardown the last drain, and that drain does free the table: a lock-free
reader reaches a multidict through a live reference, so its count is
zero by
the time the refcount is.

Getting a table onto that list and leaving it there needs the coarse
active-readers gate to flip between the two times
`_md_drain_retired_slow()`
reads it. The first read sees zero and takes the list, a reader then
enters,
the second read sees it, so the table goes to the push-back at the end
of the
function, and that reader's own exit drain runs before the push-back
lands and
finds the list empty. Nothing is left to drain, and since #1542 the
shell the
object is recycled into is memset, so the next owner cannot pick the
table up
either. Forcing that ordering takes an artificially widened window; the
recipe
and the resulting trace are in the footer.

## Are there changes in behavior for the user?

No, beyond the leak going away. The fix is C-extension only, and only
the
free-threaded build has a retirement scheme; builds with the GIL enabled
emit
byte-identical code.

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

No. It is one load on a path that is not hot, and no benchmarked
operation
moves.

## Related issue number

Fixes #1555

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes N/A, no user-facing API changed
- [x] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` N/A, this repo has no such file
- [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 Opus 5 in Claude Code; to be reviewed by @asvetlov
before
it leaves draft.

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

Proof of the bug. Three sleeps compiled in behind
`-DMULTIDICT_WIDEN_DRAIN`:
300ms at the end of `_md_reader_enter()`, 100ms in
`_md_drain_retired_slow()` between the exchange and the `readers_active`
read, and 300ms before the push-back CAS. The driver builds a multidict
holding one weakref'd value, starts a thread that waits 50ms and then
does a
single `d.get()`, calls `clear()`, joins, drops the multidict and
collects.

Base (`f28b2c0`), leaked 3/3 attempts:

```
[w] drain: took head=0x4ec8a2f1200
[w] reader enter keys=<&empty_htkeys>
[w] drain: readers_active=1
[w] reader exit prev_active=1
[w] drain: pushing back 0x4ec8a2f1200
```

With this branch, leaked 0/3; the second `took head` is the teardown
drain:

```
[w] drain: took head=0x4d2a42f1200
[w] reader enter keys=<&empty_htkeys>
[w] drain: readers_active=1
[w] reader exit prev_active=1
[w] drain: pushing back 0x4d2a42f1200
[w] drain: took head=0x4d2a42f1200
[w] free_retired 0x4d2a42f1200
```

The committed test cannot force that ordering, so it runs the shape (a
`clear()` racing reader traffic, then teardown with nothing left to
drain)
50 times over and asserts nothing the cleared table held survives. What
it
does cover deterministically is that the added drain runs against a
table a
reader may still be walking, rather than only against an empty list.

Tests, all on CPython 3.14.7 unless noted, one venv and one tree per
leg:

```
free-threaded, MULTIDICT_DEBUG_BUILD=1   2614 passed, 125 skipped
GIL                                      2626 passed, 113 skipped
GIL, CPython 3.10.17                     2626 passed, 113 skipped
MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions
                                         1266 passed, 17 skipped
MULTIDICT_TSAN_BUILD=1, TSan CPython 3.14.7t, -k "thread_safety or
drain or retired or clear"                 153 passed, 13 skipped
```

That TSan run reports 57 warnings and exits 66. Every one of them is
CPython's own `faulthandler` racing the threads whose stacks it is
dumping
(`dump_traceback`, `dump_frame`, `_PyFrame_SafeGetCode`,
`_PyFrame_SafeGetLasti`), after `pytest-timeout` fires on
`test_pure_python_view_set_ops_thread_safety`, which takes 444s under
TSan.
No multidict frame appears in any racing access; multidict only shows up
inside the dumped Python tracebacks. Run on their own, the three
retirement tests report zero warnings.

Two things this PR does not fix, both pre-existing and worth their own
issues:

* The push-back at the end of `_md_drain_retired_slow()` does not
re-read
the active-readers count afterwards, so a table can sit on the list
until
  the object's next operation even while no reader is left. Harmless in
  itself now that teardown drains, but it is the window this leak was
  reached through.
* `md_traverse()` visits `md->keys` only, so the references a retired
table
  holds are invisible to the GC. That under-reports, which is the safe
  direction, but a reference cycle running through a value stranded on
  `md->retired` cannot be collected.

Lint: `pre-commit run --from-ref f28b2c0 --to-ref HEAD`, all hooks
passed.
Docs: `make doc-spelling`, build succeeded.

Performance, `benchmarks/callgrind_driver.py --impl multidict_c
--include-multidict-only`, free-threaded, base and branch built in the
same
tree and venv so only the source differs: every one of the 26 cells
within
0.10%, `ctor_empty` and `clear` exactly flat. `docs/benchmark.rst`
therefore
needs no refresh. `tools/codegen_diff.py --ref f28b2c0` reports 0 of 203
functions changed on the GIL build. It reports 52 of 206 on the
free-threaded build, from `md_clear()` no longer being split into a
`.part.0`; the call targets and instruction counts of the hot paths are
unchanged and the measurements above cover them. Both numbers need a
fresh
worktree: run from a tree with a populated `build/`, the tool's own
in-place build is stale and its report is meaningless (a control with
identical source reported the same 52).

An alternative that keeps `md_clear()` byte-identical, putting the drain
at
the `multidict_tp_dealloc()` call site instead, measured 3 Ir worse on
`ctor_empty`, `ctor_small` and `copy_small` and perturbed 74 functions
rather than 52, so it is not what landed.

</details>
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>
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