Skip to content

Replace the per-key finder with a single callback walk - #1522

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-iteration-refactor-cad55f
Sep 23, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/multidict-iteration-refactor-cad55f

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

finder.h exported a resumable iterator, finder_t plus finder_init(),
find_next() and finder_cleanup(), for walking every entry that matches one
identity. Nothing needed it to be resumable: both drivers, getall() and the
items view set algebra, collect every match into a list and only then run a
user __eq__ against it, because a re-entrant mutation must not happen
mid-walk. What the protocol did cost was a ~4.5 KB struct declared by each
caller, a "not zero-initialized, cleanup only needs nvisited_few" contract
for each to honour, and a finder_cleanup() on every error path;
finder_collect() carried a second failure label for that reason alone.

The header becomes walk.h and exports one function, md_walk_key(), which
owns the probe walk and the visited-entry bitmap and calls a visitor per match.
Its two consumers move next to their own callers: getall() into hashtable.h
beside popall(), and the collect helper into views.h above the six set
operations that use it. The algorithm, the dedup bitmap and the critical
section boundaries are unchanged.

Two small things worth flagging for the reviewer. The version check moves from
the top of find_next() to just after the visitor call, which is the same
check at the same point in the sequence, since the old consumer loop called
find_next() once more even after the last match. And
assert(finder->iter.keys == finder->md->keys) is dropped: it sat directly
above the if that handles exactly that condition, so a debug build aborted
where a release build correctly raised RuntimeError.

md_walk_key() keeps find_next()'s plain field reads and does not include
freethreading.h, per #1518's rule that reads made under md's critical
section stay plain.

This touches the C extension only. The pure-Python backend has no equivalent:
its getall() and items view set algebra dedup by marking entry.hash in the
table and restoring it afterwards, over the iter_hash() generator, with no
finder object and no visited bitmap, so there is nothing to mirror.

Are there changes in behavior for the user?

No behavior change. Keeping the walk's position in registers instead of
reloading it from the finder on every step does make things faster: getall()
on a key with many values by about 30%, CIMultiDict.getall() by about 24%,
and itemsview.isdisjoint() by about 10%. Everything else measured within
noise, nothing regressed.

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

No; it removes a caller-visible contract rather than adding one. A new consumer
writes a visitor and cannot forget to release the bitmap.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (N/A, no behavior change; the existing
    suite is the test)
  • Documentation reflects the changes (N/A, internal C headers only)
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
  • 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
Agent run details (optional, for reviewers)

All runs on this branch, isolated venvs, against 1cdd934.

Tests:

  • C extension, CPython 3.14.2 (GIL): 2198 passed, 12 skipped
  • C extension, CPython 3.14.7t (free-threaded): 2187 passed, 23 skipped
  • Pure Python (MULTIDICT_NO_EXTENSIONS=1): 1098 passed, 6 skipped
  • MULTIDICT_DEBUG_BUILD=1 (-O0 -UNDEBUG, asserts live): 2198 passed
  • MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 under ASan/UBSan
    (LD_PRELOAD, PYTHONMALLOC=malloc, -k "not test_leak"): 2187 passed,
    no sanitizer reports

Lint: pre-commit run --all-files clean (ruff, clang-format, yamllint, mypy
3.11 and 3.13). make doc-spelling passes.

Code generation, -O3 GIL build, before vs after:

  • No _visit symbol survives in the .so; the visitors are inlined into the
    walk and the walk into its two consumers.
  • _multidict_collect_matches has exactly one indirect call, a
    call *0x78(%rax) on PyUnicode_Type, which finder_collect had too. No
    indirect call was introduced.
  • Symbol inventory differs only by the rename: finder_collect,
    finder_collect.cold and _finder_spill out; _multidict_collect_matches,
    _multidict_collect_matches.cold and _md_seen_spill in.
  • .text shrinks from 98144 to 97472 bytes.

Benchmarks, best of 8 runs each, GC disabled per round, CPython 3.14.2:

case before after delta
getall, 100 values, 1k keys 1335.8 ns 860.9 ns -35.6%
getall, 100 values, 20 keys 1206.1 ns 819.9 ns -32.0%
getall, 5000 values 57.3 us 41.1 us -28.2%
CIMultiDict.getall, 100 values 2217.7 ns 1687.8 ns -23.9%
itemsview.isdisjoint 1044.5 ns 939.0 ns -10.1%
getall hit, single value 106.3 ns 104.0 ns -2.2%
getall miss 69.2 ns 65.9 ns -4.8%
(k, v) in itemsview, duplicates 1133.3 ns 1119.2 ns -1.2%
itemsview & set 133.5 us 132.5 us -0.8%
itemsview - set 27.1 us 27.7 us +2.1%

The last four are inside this machine's run-to-run spread.

Drafted with Claude Opus 5; reviewed by @asvetlov.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 22, 2026
@codspeed

codspeed Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 15.42%

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

⚡ 10 improved benchmarks
✅ 300 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_cimultidict_getall_istr_hit_many_values[c] 2.6 ms 2.1 ms +24.11%
⚡ test_multidict_getall_str_hit_many_values[cs-c] 2.7 ms 2.2 ms +23.45%
⚡ test_multidict_getall_str_hit_many_values[ci-c] 2.8 ms 2.3 ms +23.09%
⚡ test_multidict_getall_str_hit[cs-c] 3.1 ms 2.7 ms +14.58%
⚡ test_cimultidict_getall_istr_hit[c] 3.2 ms 2.8 ms +14.11%
⚡ test_cimultidict_getall_istr_hit_nonascii[c] 3.3 ms 2.9 ms +13.44%
⚡ test_multidict_getall_str_hit_nonascii[cs-c] 3.2 ms 2.8 ms +12.87%
⚡ test_multidict_getall_str_hit[ci-c] 4 ms 3.6 ms +11.18%
⚡ test_multidict_getall_str_hit_large_table[cs-c] 601 µs 547.9 µs +9.7%
⚡ test_multidict_getall_str_hit_nonascii[ci-c] 4.7 ms 4.3 ms +9.01%

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/multidict-iteration-refactor-cad55f (046b160) with master (a794a6e)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 22, 2026 22:41
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 22, 2026 22:41
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (3) · Last reviewed commit: "Rename the news fragment to the assigned..."

Comment thread CHANGES/1522.feature.rst Resolved
@greptile-apps

This comment has been minimized.

finder.h exported a resumable iterator (finder_t plus finder_init(),
find_next() and finder_cleanup()) for walking every entry matching one
identity. Nothing needed it to be resumable: both drivers, getall() and
the items view set algebra, collected every match into a list and only
then ran a user __eq__ against it, because a re-entrant mutation must
not happen mid-walk.

What the protocol did cost was a ~4.5 KB struct declared by each caller,
a "not zero-initialized, cleanup only needs nvisited_few" contract for
each of them to honour, and a finder_cleanup() on every error path;
finder_collect() carried a second failure label for that reason alone.

The header becomes walk.h and exports one function, md_walk_key(), which
owns the probe walk and the visited-entry bitmap and calls a visitor per
match. Its two consumers move next to their own callers: getall() into
hashtable.h beside popall(), and the collect helper into views.h above
the six set operations that use it.

Keeping the walk's position in registers instead of reloading it from
the finder on every step makes getall() on a key with many values about
30% faster, and itemsview.isdisjoint() about 10%.
@asvetlov
asvetlov force-pushed the claude/multidict-iteration-refactor-cad55f branch from bf59419 to 046b160 Compare September 22, 2026 23:25
@codecov

codecov Bot commented Sep 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (1cdd934) to head (046b160).
⚠️ Report is 3 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1522   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           38        38           
  Lines         6406      6455   +49     
  Branches       579       591   +12     
=========================================
+ Hits          6406      6455   +49     
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
asvetlov merged commit 3e98f6f into aio-libs:master Sep 23, 2026
61 checks passed
@asvetlov
asvetlov deleted the claude/multidict-iteration-refactor-cad55f branch September 23, 2026 07:25
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 23, 2026
Upstream's aio-libs#1522 replaced finder_t/find_next()/finder_cleanup() with a
single md_walk() callback, and aio-libs#1518 renamed md_version() to
load_version(). _md_foreach_key() now calls md_walk() directly, since
its visitor signature already matches MultiDict_ItemVisitor, and
MultiDict_GetVersion() calls load_version(). No behavior change.
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.
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