Skip to content

Track duplicate-key walks in a private bitmap instead of marking entry hashes - #1505

Merged
asvetlov merged 11 commits into
aio-libs:masterfrom
asvetlov:claude/bitmap-inlined-buffer-56db2f
Sep 21, 2026
Merged

asvetlov merged 11 commits into
aio-libs:masterfrom
asvetlov:claude/bitmap-inlined-buffer-56db2f

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Duplicate-key walks in the C extension used to dedupe by OR-ing a high bit into entry->hash and restoring it afterwards (setitem, update(), merge(), to_dict()), or by a linearly scanned visited list (getall() and the views). This replaces both with bitmap_t, an entry-index bitmap private to the call. It keeps a 4 KB inline buffer (32768 entries) and moves to the heap for bigger tables; nothing is zeroed or allocated until the first mark. Bitmaps of up to 64 words are zeroed outright, larger ones lazily through a small summary bitmap. Words are size_t, so 32-bit targets don't emulate 64-bit arithmetic.

getall() and the views record their first matches in a short list and only start the bitmap past it: after 8 matches when the bitmap fits its inline buffer, after 32 on bigger tables, where it would need a heap allocation.

update() and merge() keep two per-batch bitmaps (entries written, entries half-deleted). The batch's own resizes rebuild them for the new layout; a mutation from outside the batch (Python code run between items, another thread) is detected and falls back to the old full-table sweep. md_post_update() visits only the recorded deletions instead of every slot.

With nothing marking the table, MD_HASH_MARK is gone, together with the masking it forced on lock-free readers, htkeys_build_indices() and the consistency check. The pure-Python backend is unchanged; it keeps its own hash marks and the observable behaviour is the same.

CodSpeed against master: getall() on keys with many values +23 to +28%, __setitem__ +10 to +18%, to_dict() +11 to +17%, insert +10 to +11%, the rest unchanged, except update() with many duplicate keys, which is 11% slower (test_multidict_update_str_with_duplicates, test_cimultidict_update_istr_with_duplicates). That is an accepted trade-off: the old code got its "already written by this batch" check for free from the hash comparison it made anyway, while the bitmap costs a few memory reads per candidate entry. Two attempts to shave it (a sweep-or-walk heuristic in md_post_update() and hoisting the bitmap state into locals) made it worse under cachegrind and were dropped.

Are there changes in behavior for the user?

No, apart from speed. One corner case is now unspecified on the C side only: if Python code run between the items of an update() (for example a generator) mutates the same multidict, repeated keys later in that batch may overwrite rather than append. The table stays consistent.

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

No. It removes the mark/unmark protocol that several recent free-threading fixes had to work around, and the new code lives in self-contained headers: bitmap.h, update_marks.h, and identity.h plus finder.h split out of hashtable.h.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes (N/A, internal)
  • 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 (Opus 5); to be reviewed by @asvetlov.

Agent run details (optional, for reviewers)

All runs on be30b7d (rebased onto e4ad2d0, #1510), isolated venv.

  • C extension, CPython 3.13.2 release: pytest tests 2160 passed, 19 skipped.
  • Pure Python (--no-c-extensions): 1080 passed, 15 skipped.
  • MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1 with libasan preloaded and PYTHONMALLOC=malloc, -k "not test_leak": 2149 passed, 19 skipped.
  • CPython 3.14.7t debug build, -k "not test_leak": 2137 passed, 31 skipped. TSan not run.
  • gdb on a debug build confirmed tests/test_update_marks.py reaches the bitmap remap on resize, the compacting shrink mid-batch, the heap bitmap and the lost-marks fallback sweep; the finder spills after 8 matches on a 1024-entry table and after 32 on a 40040-entry one.
  • The 8/32 finder limits were picked with cachegrind (data references per getall(), 65536-entry table): a limit of 32 beats master by 8 to 13% for 12 to 48 values per key, while 8 lost to master between 9 and about 20 values and 16 or 24 lost just past their limit.
  • Every new header compiles on its own. pre-commit hooks and make doc-spelling pass.

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

codspeed Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 11.77%

⚠️ 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
❌ 2 (👁 2) regressed benchmarks
✅ 286 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_cimultidict_getall_istr_hit_many_values[c] 3.8 ms 3 ms +27.68%
⚡ test_multidict_getall_str_hit_many_values[ci-c] 3.9 ms 3.1 ms +26.68%
⚡ test_multidict_getall_str_hit_many_values[cs-c] 3.7 ms 3 ms +23.23%
⚡ test_multidict_setitem_str[cs-c] 8.7 ms 7.4 ms +18.15%
⚡ test_multidict_to_dict_str[cs-c] 10.8 ms 9.3 ms +17.11%
⚡ test_cimultidict_setitem_istr[c] 9.3 ms 7.9 ms +16.82%
⚡ test_multidict_insert_str[cs-c] 16.3 ms 14.7 ms +11.03%
⚡ test_multidict_to_dict_str[ci-c] 10.9 ms 9.8 ms +10.92%
⚡ test_cimultidict_insert_istr[c] 17.2 ms 15.5 ms +10.36%
⚡ test_multidict_setitem_str[ci-c] 16.7 ms 15.2 ms +9.73%
👁 test_cimultidict_update_istr_with_duplicates[c] 11 ms 12.3 ms -10.75%
👁 test_multidict_update_str_with_duplicates[cs-c] 10.3 ms 11.6 ms -11.36%

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/bitmap-inlined-buffer-56db2f (be30b7d) with master (e4ad2d0)

Open in CodSpeed

@codecov

codecov Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e4ad2d0) to head (be30b7d).

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1505   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           37        38    +1     
  Lines         6227      6325   +98     
  Branches       565       573    +8     
=========================================
+ Hits          6227      6325   +98     
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 added a commit that referenced this pull request Sep 21, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`_md_add_with_hash()` and `_md_add_for_upd()` in `hashtable.h` incref
the identity, key and value and pass them to the `*_steal_refs()`
variants, which return -1 without consuming them when growing the table
fails. A `MemoryError` at that point leaked one reference to each. Both
wrappers now release them on failure. A plain `Py_DECREF` is safe even
inside an update batch that otherwise defers decrefs, since the caller
still holds its own references and none of the counts can reach zero.

The direct `*_steal_refs()` callers in `md_update_from_dict()`,
`md_update_from_kwnames()` and `md_update_from_seq()` already clean up
on failure, so they are unchanged. The pure-Python backend has no manual
refcounting and needs no change.

The new test fails the n-th allocation with `_testcapi.set_nomemory()`
for each n until the call succeeds, feeding items one at a time so the
table grows mid-insert, and checks the key and value refcounts after
every attempt. Without the fix it fails for `add`, `setdefault`,
`__setitem__`, `update` and `merge`. It is marked `c_extension` and does
not run on the pure-Python leg, because failing allocations inside
interpreted code hits CPython's own unraisable-error paths and leaves
refs held by a stray traceback.

## Are there changes in behavior for the user?

No, apart from the leak being gone.

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

No.

## Related issue number

N/A. The same fix is bundled in #1505, which will drop its copy once
this lands.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes (N/A, internal)
- [ ] 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 (Opus 5); to be reviewed by @asvetlov.

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

- All runs in an isolated venv on CPython 3.13.2, based on upstream
master 0a1770c.
- C extension: `pytest tests` 2088 passed, 19 skipped.
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`): 1043
passed, 15 skipped, 1048 deselected.
- `MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1` with libasan
preloaded and `PYTHONMALLOC=malloc`, `-k "not test_leak"`: 2077 passed,
19 skipped.
- New test with the C change reverted: 10 of 12 fail (`extend` passes,
it already cleaned up); with the change: 12 passed.
- Coverage of `tests/test_mutable_multidict.py` on the C run: 100% lines
and branches. The injection arms, calls and disarms on one line so the
coverage tracer never sees the failed allocation.
- Free-threaded build not run; the test skips there since `getrefcount`
is not reliable.
- `pre-commit` hooks and `make doc-spelling` pass.
</details>
@asvetlov
asvetlov force-pushed the claude/bitmap-inlined-buffer-56db2f branch from 89f248c to afd4808 Compare September 21, 2026 18:01
asvetlov added a commit that referenced this pull request Sep 21, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds three CodSpeed benchmarks for `getall()` on keys with many values,
to give #1505 a baseline on paths the current benchmarks miss.

After #1505, `getall()` keeps up to 8 matches in a short inline list and
only then starts a bitmap, which lives in a 4 KB inline buffer (32768
entries) and moves to the heap for bigger tables. The existing
`test_multidict_getall_str_hit_large_table` has 8 values per key, so it
no longer reaches the bitmap at all.

* `test_multidict_getall_str_hit_large_table_many_values`: 16 values per
key over 4096 keys (65536 entries), 128 lookups per run; covers the heap
bitmap.
* `test_multidict_getall_str_hit_many_values`: 64 values per key over 16
keys (1024 entries), each key looked up 8 times per run; covers the
inline bitmap.
* `test_cimultidict_getall_istr_hit_many_values`: the
`CIMultiDict`/`istr` twin of the previous one.

## Are there changes in behavior for the user?

No, benchmarks only.

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

No.

## Related issue number

Related to #1505

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist: N/A, benchmarks only
- [ ] 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>

Isolated venv on CPython 3.13.2, based on upstream/master 1ccffea.

C extension: `pytest tests/test_multidict_benchmarks.py -q`: 197 passed.
Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`): 100
passed, including all new cases.
`pre-commit run` on changed files: passed. `make doc-spelling`: build
succeeded.
</details>

Drafted with Claude Code (Claude Opus 5); reviewed by @asvetlov.
@asvetlov
asvetlov force-pushed the claude/bitmap-inlined-buffer-56db2f branch from fb1709a to 9a67107 Compare September 21, 2026 19:02
Replace the readonly finder's linearly scanned visited list with an
entry-index bitmap that keeps a 4 KB inline buffer and moves to the heap
only for larger tables. Storage is zeroed lazily and the first match is
kept outside the bitmap, so single-value lookups never touch it.
__setitem__ only needs to remember the one entry it keeps, since every
later match is deleted. to_dict() tracks collected entries in a bitmap,
so it no longer restores hashes afterwards and builds the dict in one
pass. The marking finder is gone; the bitmap one takes its name.
Entries written and half-deleted by an update()/merge() batch are now
recorded in per-batch bitmaps, carried across the batch's own resizes.
md_post_update() finishes off only the recorded deletions instead of
sweeping every slot, and falls back to the sweep when a mutation from
outside the batch invalidates the bitmaps.

With nothing marking the table any more, MD_HASH_MARK and the masking
it forced on lock-free readers, index rebuilds and the consistency
check are gone.
size_t words avoid emulated 64-bit arithmetic on 32-bit targets. The
count-trailing-zeros intrinsic is picked the same way as in
calculate_log2_keysize().
A bitmap of up to 64 words is zeroed outright when it starts and then
skips the summary lookup on every access, which is what update() batches
on ordinary tables pay for per matching entry.

getall() and the views record their first 8 matches in a short list and
only start the bitmap past it, moving the list into it once. Keys with a
handful of values then never touch the bitmap, so a big table no longer
needs a heap allocation for them, and an unused bitmap costs nothing.
identity.h holds the key/identity conversions, _str_cmp() and
_md_ensure_key(); finder.h holds md_finder_t with getall() and
md_finder_collect(), its two users. Both compile on their own.
They are self-contained helpers now, named like deferred_decref_t
rather than like the md_* hash table operations.
@asvetlov
asvetlov force-pushed the claude/bitmap-inlined-buffer-56db2f branch from 69c07d7 to 8e9ee64 Compare September 21, 2026 21:07
Past 32768 entries, starting the bitmap means a heap allocation, which
costs more than scanning a longer list. The list now takes 32 matches
there before spilling, so keys with 9 to 32 values stay off the heap;
tables whose bitmap fits the inline buffer still spill after 8.
@asvetlov
asvetlov marked this pull request as ready for review September 21, 2026 21:20
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 21, 2026 21:20
@greptile-apps

greptile-apps Bot commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

What we checked:

  • I built a 40,121-entry C-extension MultiDict with 41 values for a single key to stress capacity beyond the inline bitmap and short-list thresholds. T-Rex
  • I validated the exact ordered and complete getall("dup") results across 12 calls, including reentrant lookups and mutation interleaving. T-Rex
  • All checks passed with exit code 0. T-Rex
  • I reviewed the after.log, which reports PASS for heap-bitmap getall and reentrant/mutation interleaving, confirming the observed results. T-Rex
  • I examined the Finder 1505 validation script that accompanies the validation flow. T-Rex

Reviews (1) · Last reviewed commit: "Keep up to 32 getall() matches in the li..."

@asvetlov
asvetlov merged commit b280c8b into aio-libs:master Sep 21, 2026
61 checks passed
@asvetlov
asvetlov deleted the claude/bitmap-inlined-buffer-56db2f branch September 21, 2026 21:36
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 21, 2026
…ename

master (aio-libs#1505, aio-libs#1510) replaced the MD_HASH_MARK-based keyed walk with a
bitmap-tracked finder and dropped the md_ prefix from _multilib's
private names, since the directory is already namespaced. Follow both:
md_readonly_finder_t/_init/_find_next/_cleanup become the unified
finder_t/finder_init/find_next/finder_cleanup (the bitmap approach
needs no separate readonly variant, since it never marks the table),
and md_deferred_decref_t/_init/_release become deferred_decref_t/_init/
_release.

Also updates two comments left stale by the same upstream change:
capsule.h's and docs/capi.rst's reentrancy notes described a keyed walk
that could hide matches by reentering marked entries. The bitmap finder
never marks the table; the actual guard against reentrant mutation is
the version check both md_next and find_next already perform, raising
"MultiDict is changed during iteration" instead.
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