Skip to content

Merge the deferred-decref accumulator into reflist_t - #1530

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/merge-freelist-deferred-list-4651d6
Sep 23, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/merge-freelist-deferred-list-4651d6

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

The C extension carried two collectors of strong references that differ
only in how they are drained: reflist_t turned them into a list,
deferred_decref_t decref'd them. Both exist for the same reason,
that neither job can run while a critical section is held, and both
were filled by an almost identical push. They are now one type in
_multilib/reflist.h, built on the deferred accumulator's chain of
blocks, and deferred_decref.h is gone.

The inline array that starts the chain is small, 15 slots: it sits in
the caller's stack frame, and a bigger one costs md_get_all() its
inlining into the calling method. Everything past it is a 127 slot heap
block, and every path that touches a block is kept out of line, so a
call that never overflows compiles to roughly what the old plain array
did while a call that does overflow stops copying its refs to ever
bigger buffers. getall() and popall() on keys with many values come
out a few percent ahead; see the numbers below.

Pure Python is untouched: reflist_t is a C-side implementation
detail with no counterpart in _multidict_py.py.

Are there changes in behavior for the user?

No. The collected references are still handed back in push order, and
both drains keep the ownership rules they had.

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

No, it is one header and one push path fewer to keep in sync.

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

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

Agent run details (optional, for reviewers)

Tests, C extension, CPython 3.14.7t (free-threaded):
python -m pytest tests -q -> 2293 passed, 118 skipped.

Tests, pure Python:
MULTIDICT_NO_EXTENSIONS=1 python -m pytest tests -q --no-c-extensions
-> 1115 passed, 9 skipped, plus one failure that is not from this
branch: test_circular_imports.py::test_no_warnings[multidict._testcapi]
fails whenever a multidict/_testcapi built earlier is still in the
tree, since importing it with the C extension disabled raises
AttributeError: module 'multidict' has no attribute '_multidict'.
Those files are byte identical to master here.

ASan + UBSan, MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1,
CPython 3.14.2, PYTHONMALLOC=malloc, -k "not test_leak":
2293 passed, 98 skipped, no sanitizer reports.

make doc-spelling: build succeeded.

Performance, callgrind instruction counts (PYTHONHASHSEED=0, GIL
CPython 3.14.2, branch vs master, workloads copied from
tests/test_multidict_benchmarks.py):

workload master branch
getall, 8 values per key 22,741,337 22,662,966 -0.3%
getall, 64 values per key 13,135,259 12,810,027 -2.5%
popall, 64 values per key 11,311,190 10,990,294 -2.8%
__setitem__ over existing keys 9,703,191 9,622,571 -0.8%
update(), no duplicates 3,700,973 3,713,138 +0.3%
update(), with duplicates 5,339,618 5,372,143 +0.6%

The two update() rows are the trade: replacing many entries in one
call now spills into a heap block where the old 511 slot inline buffer
covered it. Making blocks bigger to win that back cost more elsewhere
than it saved (255 slot blocks: popall +2.7%, update() with
duplicates +2.2%), so the smaller block stayed.

Inline array sizes were picked the same way. Anything above 28 slots
pushes md_get_all()'s frame over the 256 byte limit that GCC's
large-stack-frame heuristic applies, which stops it being inlined
into multidict_getall() and costs about 2% on every getall() call,
overflow or not.

The C extension had two near-identical collectors of strong references,
both filled under a critical section and drained once it ends:
reflist_t, a growing array whose refs become a list, and
deferred_decref_t, a chain of fixed blocks whose refs are decref'd.
Neither can do its work inside the critical section, since PyList_New()
can run a GC and a decref can run a __del__.

They are now one type in reflist.h, keeping the block chain: an inline
array in the caller's frame, spilling into heap blocks that every path
but the push itself handles out of line. The inline array is small
enough to leave the callers' frames inlinable, so getall() on a key with
many values is a little faster than the old doubling array as well.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 23, 2026 10:55
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 10:55
@greptile-apps

greptile-apps Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (1) · Last reviewed commit: "Merge the deferred-decref accumulator in..."

@codspeed

codspeed Bot commented Sep 23, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 9.46%

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

⚡ 3 improved benchmarks
✅ 307 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_getall_str_hit_many_values[ci-c] 2.2 ms 2 ms +9.67%
⚡ test_multidict_getall_str_hit_many_values[cs-c] 2.2 ms 2 ms +9.6%
⚡ test_cimultidict_getall_istr_hit_many_values[c] 2.2 ms 2 ms +9.11%

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/merge-freelist-deferred-list-4651d6 (954621b) with master (e50bed4)

Open in CodSpeed

@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 (690e43c) to head (954621b).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1530   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        40           
  Lines         6761      6820   +59     
  Branches       594       596    +2     
=========================================
+ Hits          6761      6820   +59     
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 merged commit d4171b9 into aio-libs:master Sep 23, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/merge-freelist-deferred-list-4651d6 branch September 23, 2026 11:11
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 23, 2026
aio-libs#1530 folded the deferred decref accumulator into `reflist_t` and
reworked the same region of `hashtable.h` that this branch moves out, so
both conflicting hunks resolve the same way: the block leaves
`hashtable.h`, and `bulk_update.h` is rebuilt from master's text rather
than the branch's older copy. `deferred_decref.h` is gone from the new
header's includes, replaced by `reflist.h`.

`tools/codegen_diff.py` arrived on master with aio-libs#1529 and now runs from
the tree: 0 of 191 functions differ on CPython 3.13.2 and 0 of 196 on
3.14.7t, against master.
asvetlov added a commit that referenced this pull request Sep 23, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`hashtable.h` was 2735 lines covering three separate things: the table
itself, the single-key operations, and the multi-item `extend()`,
`update()` and `merge()` engine behind the constructors and the bulk
methods. The last of those was a contiguous block nothing else in the
file called into, whose only consumer is `_multidict.c`.

It moves verbatim into `multidict/_multilib/bulk_update.h`, along with
the `UpdateOp` enum: `_md_update()`, `_md_merge()`, the
`_md_post_update_*` family, `md_post_update()`, `md_update_from_ht()`,
`md_extend_self()`, `md_update_from_dict()`, `md_update_from_kwnames()`,
`md_update_from_seq()` and the sequence-parsing helpers beside it. The
new header includes `hashtable.h`, so `views.h`, `iter.h` and
`capsule.h` keep reaching only the hash table. This continues the split
started by #1510, #1513 and #1522.

Two things worth flagging for the reviewer.

`_list_getitem_ref()` and `_list_item_gone()` stay behind. `views.h`
uses them too, and it includes `hashtable.h` but not the new header, so
moving them would have left `views.h` compiling only by accident of the
include order in `_multidict.c`. They now have no user left in
`hashtable.h` itself, which deserves a proper home shared with the
open-coded two-element unpacking in `views.h`; that is its own change,
not this one.

The order the compiler sees does change, since the block now expands
after the rest of `hashtable.h` rather than in the middle of it.
`tools/codegen_diff.py` reports no difference at all, so nothing fell in
or out of line.

## Are there changes in behavior for the user?

No. The move is verbatim, and the pure Python implementation has no
header structure to mirror.

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

No, it shrinks `hashtable.h` by around 710 lines and keeps the bulk
paths separate from the table and its single-key API.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist: N/A, code move only; the moved
  functions are already covered through the constructors, `extend()`,
  `update()` and `merge()`
- [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>

Rebased onto master after #1529 and #1530 landed; #1530 reworked the
same region, so `bulk_update.h` was rebuilt from master's text rather
than carried over from the earlier push, and its includes now name
`reflist.h` instead of the removed `deferred_decref.h`.

Verbatim-move check: the moved text, with the retained
`_list_getitem_ref` block spliced back at its original offset,
reconstructs master's `hashtable.h` lines 1693-2416 exactly.

Codegen (`tools/codegen_diff.py --ref upstream/master`):
- CPython 3.13.2: 0 of 191 functions differ
- CPython 3.14.7t: 0 of 196 functions differ

Tests, `python -m pytest tests -q -k "not test_leak"`, each in its own
venv:
- 3.13.2 release build: 2326 passed, 107 skipped
- 3.13.2 debug build (`MULTIDICT_DEBUG_BUILD=1`, asserts on): 2326
  passed, 107 skipped
- 3.14.7t debug build: 2315 passed, 118 skipped
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`): 1124
  passed, 17 skipped

Lint: `pre-commit run --all-files` passed; `make doc-spelling` passed.
</details>

Drafted with Claude Code (Opus 5); reviewed by @asvetlov.
asvetlov added a commit that referenced this pull request Sep 26, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Prepares the news fragments for 7.0.0.

The public C API (#1480) and the watchers API (#1551) are new in this
release, so the fragments describing later changes to them describe
states that never shipped. They are folded into the entries that added
the APIs: the visitor's identity and hash (#1552, #1561) into `1478`,
and the 32-watcher limit, the watcher registration race fix and the
failing-callback report (#1574, #1583, #1585) into `1551`. The
`MultiDict_SetDefault(NULL)` half of `1553` is dropped for the same
reason.

Intermediate header names that never shipped are removed as well: `1510`
no longer mentions `deferred_decref.h`, which #1530 merged into
`reflist.h`, and `1513` names `debug.h` directly, so `1576` goes.
`1572`, a fix to a tool added this cycle, is folded into `1529`. `1560`
and the last sentence of `1556` go too, since the release refresh of the
benchmark tables supersedes those intermediate ones.

Finally, the fragments that did not lead with a past-tense verb or
described the change as "now ..." are rewritten per `AGENTS.md`.

The benchmark table refresh from `RELEASE.md` step 2 is still to be
added to this branch before it leaves draft.

## 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
- [ ] Unit tests for the changes exist (N/A, changelog only)
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` (N/A)
- [ ] Add a new news fragment into the `CHANGES/` folder (N/A, edits
existing fragments; the benchmark refresh will add a `doc` fragment)
- [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>

`python -Im towncrier build --draft --version 7.0.0` renders cleanly.
The symlinked pairs `1512` -> `1492` and `1562` -> `1555`, and both
`1535` fragments, are intentional and left alone.
</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>
@asvetlov asvetlov mentioned this pull request Oct 7, 2026
3 of 6 tasks
asvetlov added a commit that referenced this pull request Oct 7, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Dropped `ALWAYS_INLINE static inline` from `md_get_all()`, making it a
plain `static` function. GCC keeps one out-of-line copy shared by
`multidict_getall` and `multidict_proxy_getall`, so the #1530 rule in
`tools/check_inlining.py` no longer holds and was removed.

Cost (callgrind, Ir per op, CPython 3.14.7): `getall` +20 to +24 Ir,
i.e. +2.4% GIL and +2.7 to +2.9% FT for both `MultiDict` and
`CIMultiDict`. On FT, `setdefault_new` moved -1.5% and `MultiDict`
`contains_hit` -1.4%; nothing else moved more than 0.3%.

## 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
- [ ] Unit tests for the changes exist (N/A, no behaviour change;
existing suite covers getall)
- [ ] 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`

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

| Build | Operation | Before | After | Change |
|---|---|---|---|---|
| GIL | `MultiDict.getall` | 820.0 | 840.0 | +2.44% |
| GIL | `CIMultiDict.getall` | 866.3 | 888.3 | +2.54% |
| FT | `MultiDict.getall` | 836.4 | 860.4 | +2.87% |
| FT | `CIMultiDict.getall` | 880.8 | 904.8 | +2.72% |

Measured with `benchmarks/callgrind_driver.py --include-multidict-only`
against 1a94ccd.

Tests: `pytest -q` passed with the C extension on 3.14, 3.14t and 3.10,
and with `MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions` on 3.14.
Inlining: `tools/check_inlining.py` ok on 3.14.7 and 3.14.7t.
Docs: `make doc-spelling` passed.
</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