Skip to content

Drop a hash table through one release helper - #1618

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:htkeys-alloc-release-cleanup
Sep 28, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:htkeys-alloc-release-cleanup

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

_md_rebuild() and md_clear() each had their own #ifdef for dropping a table they had just unpublished: retire it on free-threaded builds, free it on GIL ones. md_clear()'s GIL arm also released the entries with its own loop, a copy of the one _md_free_retired() ran for retired tables. _md_release_keys() now makes the build choice for both callers, and the one loop, _htkeys_dispose() (renamed from _md_free_retired()), serves both the GIL release and the free-threaded drain.

_htkeys_dispose() is NOINLINE: inlined, it grew every md_clear() caller by about 400 bytes and cost ctor_empty 2% on GIL.

C extension only; no behaviour change.

Are there changes in behavior for the user?

No.

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

No; it removes a duplicated loop and two #ifdef blocks.

Related issue number

N/A

Checklist

  • I think the code is well written
  • Unit tests for the changes exist: N/A, no behaviour change; covered by the existing suite
  • Documentation reflects the changes: N/A
  • 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 Opus 5.5 (Claude Code); reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Callgrind (benchmarks/callgrind_driver.py --include-multidict-only, PYTHONHASHSEED=0, CPython 3.14.7 and 3.14.7t) against master 512f00a, MultiDict and CIMultiDict:

  • GIL: every row within 0.33% (ctor_empty 615 -> 617 Ir).
  • FT: every row within 0.36% (copy_small 2749 -> 2759 Ir).

Also tried and dropped: collapsing htkeys_alloc_sized() and _htkeys_alloc_raw() into one htkeys_alloc(pools, log2_size). Computing the size inline pushed md_clone_from_ht() out of copy() (copy_small +0.9% on GIL), and moving the PyMem_Malloc miss path out of line fixed GIL but cost FT, which has no pools and so always misses (copy_small +1.1%, ctor_small +0.5%).

Tests, each leg in its own venv and tree copy, all passing: GIL 3.14.7 and FT 3.14.7t C extension, 3.10.17, MULTIDICT_DEBUG_BUILD=1 on GIL and FT, and pure Python with --no-c-extensions. ASan+UBSan (MULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1, PYTHONMALLOC=malloc) clean with and without MULTIDICT_NO_FREELIST=1. pre-commit and make doc-spelling pass.

pyperf wall clock, idle box, pinned to one P-core, benchmarks/benchmark.py -p 12 -n 3 -w 1 --impl multidict_c, two interleaved master/PR rounds per build (master against itself moved single rows by up to 4% on GIL and 3% on FT). Rows that moved in both rounds were re-checked with an interleaved harness (9 alternating process pairs, dict as a control that stayed within 2.5%):

build row master PR pyperf (2 rounds) interleaved
GIL copy_small 207 ns 186 ns -10.6% -23.1%
GIL ctor_small 415 ns 385 ns -7.2% -12.5%
GIL add 35.0 ns 36.8 ns +5.3% -2.2%
GIL clear 452 ns 463 ns +2.5% +2.7% [-1.3, +3.3]
FT update 3485 ns 3614 ns +3.7% +2.5% [+0.7, +4.0]

Every other row is within the A/A noise, and the geometric mean is flat on both builds. Callgrind has all of these rows within 0.4% (FT update is 0.24% fewer instructions), so the GIL speedups on small tables and the FT update slowdown come from code layout, not from work done.

_md_rebuild() and md_clear() each carried their own #ifdef for getting
rid of a table they had just unpublished: retire it on free-threaded
builds, free it on GIL ones, and md_clear()'s GIL arm released the
entries itself with a loop that duplicated _md_free_retired()'s.
_md_release_keys() now makes that choice for both, and the one loop,
_htkeys_dispose(), serves the GIL release and the free-threaded drain.

_htkeys_dispose() is NOINLINE: inlined, it grew every md_clear() caller
by about 400 bytes and cost ctor_empty 2%.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 27, 2026
@codspeed

codspeed Bot commented Sep 27, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 674 untouched benchmarks


Comparing asvetlov:htkeys-alloc-release-cleanup (3d6a7fc) with master (512f00a)

Open in CodSpeed

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

greptile-apps Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Refactors C extension hash table cleanup into a shared helper.

No blocking issue was identified in the exercised paths.

What we checked:

  • Ran the delete-then-clear and reentrant finalization tests, and the C runs exited with code 0, producing 70 finalizations in the delete-then-clear case and 25 in each reentrant path, while the trigger finalizer observed an empty mapping, and the pure-Python comparison also exited with code 0. T-Rex
  • Executed the reserve-check script and examined the before/after logs; both show ALL CHECKS PASSED and exit code 0, and the existing-tests log reports 421 passed, though uploaded references were not established. T-Rex

Reviews (1) · Last reviewed commit: "Drop a hash table through one release he..."

@asvetlov
asvetlov merged commit 73e853a into aio-libs:master Sep 28, 2026
65 checks passed
@asvetlov
asvetlov deleted the htkeys-alloc-release-cleanup branch September 28, 2026 05:49
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`md_init()` and `md_clone_from_ht()` called `md_clear()` and then stored
the new table a second time. `md_clear()` runs the old values'
finalizers while the multidict looks empty, so a `__del__` that added to
the multidict during `d.__init__(...)` on a live multidict had its pair
overwritten by the second store: the pair was lost, and the table it
went into leaked along with its references.

Both functions now go through one helper that publishes the new table,
`used` and the version in one step, records `CLEARED` or `CLONED`, and
only then drops the old table through `_md_release_keys()`. A finalizer
therefore sees the new contents (empty for the `md_init()` paths, since
the extend comes after; the copied pairs for the clone paths) and what
it adds stays. That is exactly what the pure-Python implementation
already did, so it needs no change. `md_clear()`'s own
publish-empty-first ordering is untouched, and a concurrent reader still
only ever sees a complete old or complete new table.

## Are there changes in behavior for the user?

Yes: a pair a finalizer adds while `__init__()` releases the old pairs
is kept instead of being lost and leaked. A watcher sees it reported
after `CLEARED` / `CLONED` instead of before, which is now documented in
`docs/capi.rst`.

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

No, it removes a publish and replaces two copies of the same sequence
with one helper.

## Related issue number

Follows #1618, which added `_md_release_keys()`.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [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>

Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2877
passed), FT 3.14.7t (2865 passed), 3.10.17 (2877 passed),
`MULTIDICT_DEBUG_BUILD=1` GIL (2877 passed) and FT (2865 passed), pure
Python with `MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions` (1348 passed).
The new `test_reinit_finalizer_sees_and_keeps_new_contents` fails on all
12 C cases against the base and passes on pure Python there. The Cython
harness was not built, so its two watcher cases skipped.

Callgrind, `PYTHONHASHSEED=0`, `benchmarks/callgrind_driver.py
--include-multidict-only`, base 3d6a7fc (identical tree to #1618's
merge, 73e853a) vs this branch, Ir per op:

| row | GIL MultiDict | GIL CIMultiDict | FT MultiDict | FT CIMultiDict
|
|---|---|---|---|---|
| ctor_empty | 617 -> 616 | 757 -> 756 | 892.9 -> 889.9 | 980.2 -> 977.2
|
| ctor_small | 4229 -> 4227 | 5349 -> 5347 | 6921.5 -> 6918.5 | 7928.9
-> 7925.9 |
| ctor_items | 44706 -> 44705 | 55786 -> 55785 | 67681.8 -> 67678.8 |
78109.2 -> 78106.2 |
| copy_small | 1890 -> 1889 | 2030 -> 2029 | 2759.2 -> 2757.2 | 2846.7
-> 2844.7 |
| copy | 25467 -> 25466 | 25607 -> 25606 | 29064.8 -> 29062.8 | 29152.2
-> 29150.2 |

No other row moved by 0.3% or more except FT `popitem` (649.6 -> 646.6).
A first run showed GIL `ctor_items` +127 and `getitem_istr` -10%; both
vanished when the two trees' paths were made the same length, so they
were environment artifacts. Re-initializing a live 20-item dict (not in
the registry): GIL `__init__(pairs)` 5489 -> 5480, `__init__(same kind)`
3394 -> 3383; FT 7928 -> 7921 and 4006 -> 3993.

Lint: pre-commit clean; `make doc-spelling` passes.
</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