Skip to content

Pool small hash tables in the module state - #1539

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/freelist-htkeys-pools
Sep 24, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:claude/freelist-htkeys-pools

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

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

  • 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

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.

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

@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/freelist-htkeys-pools (1b7767b) with master (9682ba1)

Open in CodSpeed

@asvetlov
asvetlov force-pushed the claude/freelist-htkeys-pools branch from 770ce48 to b515800 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 (937fd76) to head (1b7767b).
⚠️ Report is 10 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##            master     #1539    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           40        41     +1     
  Lines         6820      6949   +129     
  Branches       596       605     +9     
==========================================
+ Hits          6820      6949   +129     
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 marked this pull request as ready for review September 23, 2026 19:55
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 19:55
@greptile-apps

greptile-apps Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge; the remaining test-coverage concern is non-blocking.

Reviews (2) · Last reviewed commit: "Let tests drain the pools before injecti..."

Comment thread tests/test_freelist.py Resolved
@greptile-apps

This comment has been minimized.

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>
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, and a pool that was never given a capacity
misses every time, so the zeroed module state is already usable.

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

Measured on a GIL build, cycles per allocate/free round trip: the pool is
flat at about 10, against 26 to 55 for pymalloc and 117 to 158 for libc
malloc above the 512-byte cutoff. Nothing is pooled on a free-threaded
build: a shared pool needs an atomic exchange to pop and another to push,
which measured at a flat 41 cycles against mimalloc's 30 to 52, and
mimalloc already gives every thread its own freelist. Instruction counts
say the opposite, 22 against 108 to 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() has
nothing to visit; 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, which AGENTS.md says to do.

Instructions per operation on a GIL build: constructing a 20-header
CIMultiDict -3.6%, a 100-item MultiDict -2.6%, copy-then-clear of a
100-item MultiDict -2.1%. getall() and iteration are unchanged.
test_no_refleak_on_memory_error() fails the n-th allocation of an insert,
for each n, and checks nothing leaks; its `assert n > 0` says the call
reached the allocator at all. A pooled table makes that false: on 3.10
the table is the only allocation a 20-item update makes, so a warm pool
left the injected failure with nothing to fire on. Worse than the failing
assert, the resize recovery path stopped being exercised at all.

_freelist_clear() empties the pools, and the test calls it before arming,
so every iteration starts cold and the path is back in reach. Private and
C-extension only, like getversion().

Found by CI, on the legs that reach Python 3.10. It does not reproduce on
3.13 or 3.14, where CPython itself allocates elsewhere in that call.
@asvetlov
asvetlov force-pushed the claude/freelist-htkeys-pools branch from b515800 to 1b7767b Compare September 23, 2026 20:35
@asvetlov
asvetlov merged commit 8b5dd23 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/freelist-htkeys-pools branch September 24, 2026 06:20
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

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

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

---

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.

<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 to asvetlov/multidict that referenced this pull request Sep 24, 2026
Takes master's copies of hashtable.h, atomic_helpers.h and the 1546
fragment: aio-libs#1546 landed there, so the copies this branch carried are
redundant and master's also has aio-libs#1539, aio-libs#1549 and aio-libs#1550 on top.
asvetlov added a commit to asvetlov/multidict that referenced this pull request Sep 24, 2026
aio-libs#1539, aio-libs#1549 and aio-libs#1550 landed since these were collected, and the add
row moved most: 876 to 765 on the GIL build, 1,035 to 939 free-threaded.

Also restore the note that d.add() starts from an empty mapping and
inserts 200 keys. Without it the lead-in describes every row as running
against a 200-key mapping, which is true of the other two but not of
that one.
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 `istr` section already tells people to build their keys once and
reuse them, but not what that buys. This adds the instruction counts,
for both builds, next to the plain `str` equivalents, and points out
that a key which is not already lower case saves more still, since it
has to be copied into a lower-cased string whose hash is not cached.

Numbers come from `benchmarks/callgrind_driver.py
--include-multidict-only`,
the same harness and machine as the tables in `docs/benchmark.rst`.

#1546 has landed, so this is down to its own two files. The figures were
re-measured against master afterwards, since #1539, #1549 and #1550 also
moved them; `d.add()` shifted most, 876 to 765 on the GIL build.

## Are there changes in behavior for the user?

No, documentation only.

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

No, though the table joins `docs/benchmark.rst` in needing a refresh
when the figures move.

## Related issue number

None.

## Checklist

- [x] I think the code is well written — N/A, documentation only
- [ ] Unit tests for the changes exist — N/A
- [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 Opus 5 in Claude Code; reviewed by @asvetlov.

---------

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
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.

1 participant