Skip to content

Skip zeroing hash table entries that are about to be overwritten - #1540

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/freelist-skip-zeroing
Sep 24, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:claude/freelist-skip-zeroing

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

Two places built a table's entries array twice over.

md_clone_from_ht() allocated with a raw PyMem_Malloc() and then
memcpy'd the source over every byte, so it neither used the pool nor
needed the initialisation htkeys_new() would have done. It now takes
uninitialised storage from the same pool, which skips both memsets.

_md_resize() allocated a zeroed entries array and then wrote the front
of it from the old table, so everything it copied had just been zeroed
for nothing. The new table now comes back untouched and only the part
past the copy is zeroed. The count comes from the copy itself rather
than from md->used: the two agree, and there is an assert saying so,
but taking it from the copy means a table can never be published over
entries nothing has written, which ASSERT_CONSISTENT() would read.

Neither memset can simply be shortened to the used prefix instead.
_md_resize() zeroes oldkeys->nentries before retiring while the
entries still hold stale non-owning pointers, so a table arriving at
_md_free_retired() from a resize reports no dirty entries and has
them; and ASSERT_CONSISTENT() reads every entry a table has room for,
not just the used prefix.

The resize half needs no pool and is the only part that moves on a
free-threaded build.

Are there changes in behavior for the user?

No. Faster copying and resizing, nothing observable otherwise.

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

No. The byte count of a table is now derived in one place,
htkeys_alloc_size(), from log2_size alone, with htkeys_sizeof()
reading the same number back off an existing table under an assert that
the two agree.

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

Second of five, stacked on #1539 and including its commit until it lands.
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.

@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 12.71%

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

⚡ 18 improved benchmarks
✅ 292 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_multidict_insert_str[cs-c] 14.6 ms 12.4 ms +17.79%
⚡ test_multidict_add_str[cs-c] 15.4 ms 13.1 ms +17.24%
⚡ test_cimultidict_insert_istr[c] 15.5 ms 13.3 ms +16.44%
⚡ test_multidict_merge_str[cs-c] 7.7 ms 6.6 ms +15.86%
⚡ test_cimultidict_insert_str_lower_case[c] 15.7 ms 13.6 ms +15.85%
⚡ test_multidict_update_str[cs-c] 8.7 ms 7.6 ms +14.13%
⚡ test_multidict_merge_str[ci-c] 8.3 ms 7.3 ms +13.29%
⚡ test_cimultidict_add_istr[c] 19.5 ms 17.3 ms +13.11%
⚡ test_multidict_add_str[ci-c] 19.8 ms 17.5 ms +12.59%
⚡ test_multidict_update_str[ci-c] 9.2 ms 8.2 ms +12.25%
⚡ test_cimultidict_update_istr[c] 9.4 ms 8.4 ms +11.94%
⚡ test_multidict_add_same_key[cs-c] 10.6 ms 9.5 ms +11.47%
⚡ test_cimultidict_insert_str_mixed_case[c] 29 ms 26.3 ms +10.1%
⚡ test_multidict_update_str_with_duplicates[cs-c] 11.7 ms 10.6 ms +10.02%
⚡ test_multidict_update_str_with_duplicates[ci-c] 12.2 ms 11.1 ms +9.45%
⚡ test_multidict_add_same_key[ci-c] 12.8 ms 11.7 ms +9.45%
⚡ test_multidict_extend_str[cs-c] 8.3 ms 7.6 ms +9.37%
⚡ test_cimultidict_update_istr_with_duplicates[c] 12.3 ms 11.2 ms +9.15%

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-skip-zeroing (4a7b9ba) with master (8b5dd23)

Open in CodSpeed

@asvetlov
asvetlov force-pushed the claude/freelist-skip-zeroing branch 2 times, most recently from d3f08b5 to 45771f1 Compare September 23, 2026 19:31
@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 (8b5dd23) to head (4a7b9ba).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1540   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         6949      6960   +11     
  Branches       605       606    +1     
=========================================
+ Hits          6949      6960   +11     
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 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>
@asvetlov
asvetlov force-pushed the claude/freelist-skip-zeroing branch from 45771f1 to 54b4c7e 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>
Two places built a table's entries array twice over.

md_clone_from_ht() allocated with a raw PyMem_Malloc() and then memcpy'd
the source over every byte, so it neither used the pool nor needed the
initialisation htkeys_new() would have done. It now takes uninitialised
storage from the same pool, which skips both memsets.

_md_resize() allocated a zeroed entries array and then wrote the front of
it from the old table, so everything it copied had just been zeroed for
nothing. The new table now comes back untouched and only the part past
the copy is zeroed. The count comes from the copy itself rather than from
md->used: the two agree, and there is an assert saying so, but taking it
from the copy means a table can never be published over entries nothing
has written, which ASSERT_CONSISTENT() would read.

Neither memset can simply be shortened to the used prefix instead.
_md_resize() zeroes oldkeys->nentries before retiring while the entries
still hold stale non-owning pointers, so a table arriving at
_md_free_retired() from a resize reports no dirty entries and has them;
and ASSERT_CONSISTENT() reads every entry a table has room for, not just
the used prefix.

The byte count of a table is now derived in one place,
htkeys_alloc_size(), from log2_size alone, with htkeys_sizeof() reading
the same number back off an existing table under an assert that the two
agree. That is what makes "a clone is exactly the size class the pool
keys on" structural rather than two formulas that happen to match.

Instructions per operation on a GIL build, against the previous commit:
copying a 5-item CIMultiDict -13.5%, constructing one from an existing
5-item CIMultiDict -12.9%, copy-then-clear of a 100-item MultiDict -4.5%,
growing a MultiDict to 1000 items by repeated insert -2.5%, to 5000 items
-2.0%. The growth cases are the resize half and are the only ones that
move on a free-threaded build, where nothing is pooled: -1.8% and -1.5%.
@asvetlov
asvetlov force-pushed the claude/freelist-skip-zeroing branch from 54b4c7e to 4a7b9ba Compare September 24, 2026 06:23
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 06:26
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 06:26
@greptile-apps

greptile-apps Bot commented Sep 24, 2026

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

No blocking issue was established; the change appears safe to merge.

What we checked:

  • Built the C extension with debug assertions before and after the change. T-Rex
  • Executed the resize stress script and compared results against the pure-Python implementation across deletion, updates, growth, clear-and-refill, and size-class boundaries. T-Rex
  • Built the parent C extension and ran the same clone-and-pool-reuse probe against the parent, changed C extension, and the pure-Python backend. T-Rex
  • All three runs exited zero and produced identical per-case digests with no stale entries or lookup corruption. T-Rex
  • The before-and-after C-extension runs produced the same passing result, the pure-Python control also passed, and validation was limited to Python 3.11 with the GIL; no free-threaded build was tested. T-Rex

Reviews (1) · Last reviewed commit: "Add a CHANGES fragment"

@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

@asvetlov

Copy link
Copy Markdown
Member Author

merged

@asvetlov
asvetlov merged commit 3336132 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/freelist-skip-zeroing branch September 24, 2026 06:53
@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Skip zeroing hash table entries that are about to be overwritten

Correct change, well reasoned; the remaining notes are all structural and non-blocking.

The two hot paths are genuinely safe as written, and I checked the parts that could have gone wrong rather than taking the description's word for it:

  • Nothing reads newkeys' entries between htkeys_new_unfilled() and the zeroing in _md_resize(): _update_marks_remap() only reads newkeys->usable and stores the pointer in the bitmap (update_marks.h:78-100), and publication via store_keys() happens after htkeys_zero_entries(), so no lock-free reader can see the uninitialised window.
  • The filled == numentries assert is sound. _md_del_at_for_upd_deferred() leaves a half-deleted entry with identity non-NULL and still counted in md->used, so the copy loop's count matches md->used in every state the resize can catch.
  • The new assert in htkeys_sizeof() cannot fire on empty_htkeys (whose log2_index_bytes of 3 does not match its log2_size of 0): the only external caller, multidict_sizeof() at _multidict.c:1244, guards on it.
  • htkeys_log2_index_bytes() reproduces the old inline ladder exactly, including the 32-bit SIZEOF_VOID_P case, and htkeys_new() zeroes the same byte range the old memset did.
  • The error path is an improvement: the duplicate PyErr_NoMemory() in md_clone_from_ht() is gone now that _htkeys_alloc_sized() sets it.
  • feature is the right CHANGES category here; Pool small hash tables in the module state #1539, Shrink the walk bitmap's inline buffer #1543 and Give istr its own vectorcall #1537 all use it for speedups.

Worth addressing before or after merge:

  • htkeys_sizeof() still writes the size formula a second time under an assert, which is what the refactor claims to have removed; it can delegate to htkeys_alloc_size().
  • The allocation path is four functions deep, with htkeys_alloc_raw() a single-caller pass-through and _htkeys_alloc_sized()'s size parameter an assert-only contract; two functions would do.
  • htkeys_zero_entries() is only correct while nentries == 0 and the assert does not check that, so the ordering dependency in _md_resize() is invisible at the call site.
  • _md_resize() trusts filled for the memset but numentries for build_indices() and nentries, which makes the release-build behaviour incoherent with the comment's rationale.
  • test_copies_interleaved_with_clears never puts a dirty block in the pool: md_clear() zeroes entries on the way in, so the "copied byte for byte" case the test names is not reached.

🟢 Suggestions

1. htkeys_sizeof() still writes the size formula a second time
multidict/_multilib/htkeys.h:409-418

The PR description says the byte count "is now derived in one place, htkeys_alloc_size()", but the arithmetic is in fact written twice: once at lines 398-405 and again here, with an assert bolted on to prove the two copies agree.

Why it matters: the duplication is the exact thing the refactor set out to remove, and it is load-bearing in release builds (the assert is compiled out), so a future edit to one formula and not the other goes unnoticed outside a debug build.

Since nothing ever builds a table whose log2_index_bytes differs from htkeys_log2_index_bytes(log2_size) (htkeys_new_unfilled() at line 473 is the only writer, and md_clone_from_ht() copies it), this can collapse to a delegation and keep the invariant as the assert:

static inline Py_ssize_t
htkeys_sizeof(htkeys_t* keys)
{
    assert(keys->log2_index_bytes == htkeys_log2_index_bytes(keys->log2_size));
    return (Py_ssize_t)htkeys_alloc_size(keys->log2_size);
}
    Py_ssize_t size =
        (Py_ssize_t)(sizeof(htkeys_t) + ((size_t)1 << keys->log2_index_bytes) +
                     sizeof(entry_t) * usable);
    assert(size == (Py_ssize_t)htkeys_alloc_size(keys->log2_size));
2. Four-deep allocation chain, one link of which is a pass-through
multidict/_multilib/htkeys.h:420-445

Allocating a table now goes htkeys_new() -> htkeys_new_unfilled() -> htkeys_alloc_raw() -> _htkeys_alloc_sized(). htkeys_alloc_raw() has exactly one caller (line 467, verified with git grep) and does nothing but supply the size argument, and _htkeys_alloc_sized()'s size parameter exists solely so md_clone_from_ht() can hand over a number it already computed.

Why it matters: the parameter is a contract the type system does not state and only a debug assert checks, so in a release build a caller that passes a mismatched size gets a silently undersized block. That is a lot of surface for a saving that is hard to measure: both htkeys_sizeof() and htkeys_alloc_size() are static inline over log2_size, so the compiler folds the second computation anyway.

Suggested shape, two functions instead of four:

  • drop size from _htkeys_alloc_sized() and rename it htkeys_alloc() (it computes htkeys_alloc_size(log2_size) itself);
  • delete htkeys_alloc_raw();
  • in md_clone_from_ht(), call htkeys_alloc(MD_POOLS(md), src->log2_size) and keep htkeys_sizeof(src) only as the memcpy() length.
static inline htkeys_t*
htkeys_alloc_raw(pool_t* pools, uint8_t log2_size)
{
    return _htkeys_alloc_sized(pools, log2_size, htkeys_alloc_size(log2_size));
}
3. htkeys_zero_entries() silently assumes nentries == 0
multidict/_multilib/htkeys.h:450-457

The function zeroes keys->usable - from entries, which is the tail of the array only while usable is still the full capacity. Once nentries > 0 the real capacity is nentries + usable (see _md_entries_capacity() in update_marks.h), so a call on a partly-filled table would stop nentries entries short of the end, leaving stale entries that _md_check_consistency() walks (it loops to USABLE_FRACTION(nslots), not to nentries).

Both current callers are fine: htkeys_new() calls it right after usable is set, and _md_resize() calls it before line 352 decrements usable. But the assert on line 453 only checks from <= keys->usable, which does not catch the misuse, and the ordering dependency in _md_resize() is invisible at the call site.

Either add assert(keys->nentries == 0); alongside the existing assert, or make the function independent of the field ordering by deriving the capacity from log2_size:

Py_ssize_t capacity = USABLE_FRACTION(htkeys_nslots(keys));
assert(from >= 0 && from <= capacity);
memset(htkeys_entries(keys) + from, 0, (size_t)(capacity - from) * sizeof(entry_t));
    assert(from >= 0 && from <= keys->usable);
    memset(htkeys_entries(keys) + from,
           0,
           (size_t)(keys->usable - from) * sizeof(entry_t));
4. `filled` is trusted for the memset but not for nentries or the indices
multidict/_multilib/hashtable.h:344-353

The stated reason for filled is that "a table can never be published over entries nothing has written". That argument applies just as much to the two lines below: htkeys_build_indices() and newkeys->nentries both still take numentries (i.e. md->used).

Why it matters: in a release build, where the assert is gone, the mix is incoherent. If the two ever diverged, the tail would be zeroed from filled (good) but the table would still be published with nentries = numentries and indices built over entries filled..numentries, which are now the zeroed ones, so lookups would chase index slots pointing at empty entries. Picking one of the two values for all three uses makes the release behaviour match the comment's intent.

I verified the invariant itself holds, so this is about readability and defence in depth rather than a live bug: the half-deleted state that _md_del_at_for_upd_deferred() leaves keeps identity non-NULL and keeps the entry counted in md->used, so the copy loop's identity != NULL count always equals md->used.

Simplest fix: use filled for htkeys_build_indices() and newkeys->nentries too, and keep assert(filled == numentries) as the documentation of the invariant.

    assert(filled == numentries);
    htkeys_zero_entries(newkeys, filled);

    htkeys_build_indices(newkeys, newentries, numentries);

    newkeys->usable = newkeys->usable - numentries;
    newkeys->nentries = numentries;
5. New test never puts a dirty block in the pool before the copy
tests/test_freelist.py:77-94

The test's premise is that a clone "is copied over byte for byte rather than initialised", so the interesting block is one whose entries are not already zero. The blocks this loop recycles are all clean:

  • clone.clear() goes through md_clear(), which Py_CLEAR()s every live entry before htkeys_free() pushes the block (hashtable.h:1994-2008), so the block is fully zeroed on its way into the pool;
  • any_multidict_class(pairs) presizes in md_init() and never resizes, so no resize-retired block is produced either.

The only source of a dirty pooled block is _md_resize(), whose oldkeys keeps stale non-owning pointers in its entries when it is freed. Growing a multidict item by item first would make the test actually exercise the "overwrites every byte" claim:

grown = any_multidict_class()
for key, value in pairs:
    grown[key] = value  # each resize retires a block with stale entries
del grown
clone = base.copy()  # may land on one of them

As written the test is still a reasonable round-trip check, it just does not reach the case the change is about.

        clone = base.copy()
        assert list(clone.items()) == pairs
        clone.clear()
        fresh = any_multidict_class(pairs)

Checklist

  • No uninitialised memory can be read or published
  • Free-threaded publication ordering preserved
  • New asserts hold on every reachable table (including empty_htkeys)
  • Refactor removes duplication rather than relocating it — suggestion #1, suggestion #2
  • Helper contracts stated or enforced, not implied by call order — suggestion #3, suggestion #4
  • New behaviour exercised by the added test — suggestion #5
  • CHANGES fragment present, correct category and signature
  • PR description matches the diff — suggestion #1

Automated review by Kōan (Claude) HEAD=4a7b9ba 8 min 36s

asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Every `.items()`, `.keys()`, `.values()` and `iter()` allocated a GC
object and dropped it again a moment later. Those shells now come from
two more module-state pools, one for the three view types and one for
the three iterator types: within a family the types differ only in their
methods, so one shell fits any of them, which is the only thing that
makes sharing a pool safe.

A pooled shell keeps the GC preheader it was allocated with, which
`PyObject_GC_UnTrack()` leaves in the untracked state, so reuse only has
to redo what `PyObject_GC_New()` does to the object header. That is left
to `PyObject_Init()` rather than written out, so a debug interpreter's
refcount totals stay right. An interpreter built `--with-trace-refs`
turns the pools off instead, for the reason it cannot have freelists at
all: a shell is reused without ever being freed, so it is never taken
off the all-objects list that reusing it would put it back on.

The pool is reached through the view's multidict, so a shell the GC has
already cleared is freed rather than pooled.

## Are there changes in behavior for the user?

No. Views and iterators are cheaper to make, nothing observable
otherwise.

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

No. It is two more pools of the kind #1539 introduced, and the
`tp_free` path is still there for every shell a pool declines.

## Related issue number

None.

## 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`

---

Third of five, stacked on #1539 and #1540 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.

<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>
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## 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

- [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`

---

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.

<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>
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.

2 participants