Skip to content

Release the old pairs after re-initializing, not before - #1619

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:init-single-publish
Sep 28, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:init-single-publish

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

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

  • 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)
  • 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)

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.

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.

_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%.
md_init() and md_clone_from_ht() cleared the multidict, which ran the old
values' finalizers while it looked empty, and then stored the new table
over whatever those finalizers had added, losing and leaking it. Install
the new table in one store and release the old one afterwards, as the
pure-Python implementation already does.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 28, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 28, 2026 06:25
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 28, 2026 06:25
# Conflicts:
#	multidict/_multilib/hashtable.h
@codspeed

codspeed Bot commented Sep 28, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 674 untouched benchmarks


Comparing asvetlov:init-single-publish (ef31229) with master (73e853a)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Changes memory management order in the C hashtable implementation.

No blocking issue identified; the reviewed changes appear safe to merge.

What we checked:

  • Executed a focused C-extension script that reinitialized live MultiDict and CIMultiDict objects from the same-kind mappings and proxies, while old-value finalizers were reinitialized or cleared in the destination. T-Rex
  • Ran a focused C-extension script that cloned from the destination itself or its proxy and checked object lifetimes, finalizer mutations, mapping contents, and watcher-event order, with both parent and PR extensions preserving the cloned key and value until a later clear and finalizer-added entries surviving; CLONED, CLEARED, ADDED, ADDED were recorded in order. T-Rex
  • At hashtable.h:471-475, the replacement table was published with its CLONED event before the old table was released; all eight PR cases preserved the finalizer’s changes, emitted events in that order, and passed the cleanup check, while the pre-PR comparison lost the finalizer’s changes. T-Rex
  • Both backends preserved the cloned key and value until a later clear, their finalizers added surviving entries, and both recorded CLONED, CLEARED, ADDED, ADDED in that order; the parent commit behaved the same in this scenario. T-Rex

Reviews (1) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..."

@codecov

codecov Bot commented Sep 28, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1619   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           44        44           
  Lines         8205      8268   +63     
  Branches       697       703    +6     
=========================================
+ Hits          8205      8268   +63     
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 merged commit 43978bd into aio-libs:master Sep 28, 2026
65 checks passed
@asvetlov
asvetlov deleted the init-single-publish branch September 28, 2026 07:20
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds `reinit_items` (`d.__init__(items)`) and `reinit_clone`
(`d.__init__(other)` with `other` of the same kind, the
`md_clone_from_ht()` path) to `benchmarks/operations.py`, each at 200
and 20 items, plus four matching CodSpeed benchmarks. The existing
`ctor_*` rows always build a fresh object whose table is empty, so
replacing a live table (`_md_install_keys()`, #1619) was never measured;
#1619 needed a one-off script.

The target stays populated after each call, so the setup hands back the
same object and nothing is rebuilt inside the timed region. The rows are
multidict-only: `dict.__init__` on a live dict updates rather than
replaces. Multidict-only rows are not rendered into
`docs/benchmark.rst`, so the tables keep their shape and are not
regenerated; the exclusion paragraph gained one sentence saying why
re-initializing is left out. The CodSpeed tests carry no shard mark and
run in shard 1 next to the `create_*` benchmarks; recent runs show the
two shards within a few percent of each other on both builds.

## Are there changes in behavior for the user?

No.

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

No; four rows in the registry and four CodSpeed tests following the
existing patterns.

## Related issue number

Follow-up to #1619.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist (`callgrind_driver.py
--self-check` asserts the re-initialized size)
- [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 Code (Claude Opus 5.5); reviewed by @asvetlov.

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

New rows, instructions per operation, `callgrind_driver.py
--include-multidict-only`, CPython 3.14.7, `PYTHONHASHSEED=0`, bracketed
counting, drift 0:

| Operation | GIL `MultiDict` | GIL `CIMultiDict` | FT `MultiDict` | FT
`CIMultiDict` |
| --- | ---: | ---: | ---: | ---: |
| `reinit_items` | 45,484 | 56,424 | 68,102 | 78,442 |
| `reinit_items_small` | 4,860 | 5,840 | 7,322 | 8,242 |
| `reinit_clone` | 26,238 | 26,239 | 29,580 | 29,582 |
| `reinit_clone_small` | 2,686 | 2,687 | 3,275 | 3,276 |

For comparison, `ctor_items` is 44,850 / 55,930 (GIL) and 67,679 /
78,106 (FT); `copy` is 25,472 / 25,612 (GIL) and 29,063 / 29,150 (FT).

Tests: `pytest -q` passed on 3.14.7 GIL (2893 passed) and 3.14.7t FT
(2881 passed) with the C extension; `MULTIDICT_NO_EXTENSIONS=1 pytest -q
--no-c-extensions` passed from a clean tree copy (1356 passed); the
reinit CodSpeed tests pass on 3.10 pure Python.
Self-check: `callgrind_driver.py --self-check` passed on both builds
(140 cells).
Lint: pre-commit on the changed files and `make doc-spelling` passed.
</details>
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds a threaded stress test for the case #1619 left uncovered: one
thread re-initializes a shared `MultiDict` / `CIMultiDict`, alternating
`d.__init__(pairs)` (`md_init()` then extend) and
`d.__init__(same_kind_md)` (`md_clone_from_ht()`), with values whose
`__del__` reads the multidict and adds to it. Four other threads run
lock-free `get()`, `getone()`, `__getitem__`, `__contains__` and
`len()`, iterate `items()` / `keys()` / `values()`, and take `copy()`
snapshots. On free-threaded builds almost every finalizer runs in a
reader's drain, not the writer. Every snapshot must hold a prefix of one
generation plus `"late"` tokens, and after two `clear()` calls every
token must be freed.

Under TSan the test found two data races, both fixed here:

- `md_clone_from_ht()` did one `memcpy()` of the whole source table,
header included, so it read `num_readers` while lock-free readers of the
source updated it atomically. On free-threaded builds the copy now skips
the reader fields and zeroes them; GIL builds keep the single
`memcpy()`.
- `_md_install_keys()` stored `md->is_ci` on every re-init while
lock-free lookups read it in `md_calc_identity()`. It now stores only
when the value changes. A re-init through the type's own `__init__()`
never changes it.

Neither race was seen to crash. The first reads a value that is thrown
away and the second writes the value already there, but both are
undefined behaviour, and CI's TSan job (`halt_on_error=1`) would fail on
this test without the fixes.

## Are there changes in behavior for the user?

No.

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

No. The test runs in about 0.5s on a free-threaded release build.

## Related issue number

Follow-up to #1619.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes (N/A, no documented behaviour
changed)
- [ ] 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 (Claude Opus 5.5); reviewed by <pending human
review>.

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

Each leg used its own venv and its own copy of the tree.

- FT 3.14.7t release: full suite 2867 passed, 186 skipped; new test
about 0.4s per class.
- FT 3.14.7t `MULTIDICT_DEBUG_BUILD=1`: full suite 2867 passed; new test
10/10.
- GIL 3.14.7 and 3.10.17: full suite 2879 passed, 174 skipped;
`tests/test_free_threading.py` at 100% line and branch coverage on FT
release, FT debug and 3.10.
- Pure Python (`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`): 1355
passed.
- TSan (3.14.7t `--with-thread-sanitizer`, `MULTIDICT_DEBUG_BUILD=1
MULTIDICT_TSAN_BUILD=1`, clang): new test before the fix gave 199, 300
and 763 reports over three runs (the `memcpy()` in `md_clone_from_ht()`
against `_md_reader_enter()` / `_md_reader_exit()`, and
`_md_install_keys()` against `md_calc_identity()`). After the fix, 0
over three runs. CI's full TSan command gave 0 reports. Two pure-Python
tests,
`test_pure_python_reciprocal_{view,raw_iterator}_ops_no_deadlock`, go
past their 20s join under local TSan. They fail the same way on
unmodified master and don't touch the C extension.
- Regression check: with the drain made to ignore `num_active_readers`
and per-table `num_readers`, freed tables poisoned, and a 20µs
`Py_BEGIN_ALLOW_THREADS` + `nanosleep()` inside the lock-free `get()` /
`__contains__`, the FT debug build aborted on an assert 3/3. Without the
sleep, 1 run in 5. These changes were reverted.
- callgrind, `PYTHONHASHSEED=0`: GIL `ctor_*`, `copy*` and `update` +1
to 2 Ir (at most +0.27%, on `ctor_empty`); no other row moved. FT
`copy_small` +5 Ir (+0.18%), `ctor_*` +1 Ir.
- `make doc-spelling`, pre-commit: pass.
</details>
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`benchmarks/callgrind_driver.py` gave different instruction counts for
identical code depending on where the checkout lived. Every path the
interpreter allocates at startup, and the listing of every directory it
imports from, shifts the heap the measured loop runs on. An allocating
operation such as an `istr` lookup (it copies its key) then takes
pymalloc's pool-full/pool-used transition on every iteration in one tree
and never in the other: identical code measured 700.5 vs 721.5 Ir on
`getitem_istr` from two trees whose paths differ by one character. That
is what made the #1619 measurement look like a +127 Ir `ctor_items`
regression.

The children now run under `-S` from a fixed-length temporary directory
holding a link to the base interpreter, a copy of their own scripts, and
one import directory with a link to each module they actually import
(for `multidict`, only its imported files, so stray build products do
not count either). They also get a private bytecode cache and a reduced
environment. The result records what was staged under `metadata.stage`.

While proving that, the free-threaded build turned out to be
nondeterministic between two runs of one tree. mimalloc seeds its arena
address from `getrandom()` and purges on a timer.
`MIMALLOC_ARENA_RESERVE=2GiB` (a reservation mimalloc leaves the kernel
to place) and `MIMALLOC_PURGE_DELAY=-1` pin both.

The driver also refuses to run without the Valgrind client requests (no
`pytest-codspeed`), whose whole-process counts cannot be compared with
bracketed ones, unless given `--whole-process`. Both traps are
documented in `docs/benchmark.rst` and AGENTS.md.

## Are there changes in behavior for the user?

No; this only touches the benchmark tooling. Contributors now need
`pytest-codspeed` installed (or `--whole-process`) to run the Callgrind
driver. Absolute counts shift once, since the children's heap changed.

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

No. The staging is self-contained in the driver, and the child's
`--probe` reports what to stage, so nothing needs updating when
`operations.py` gains imports.

## Related issue number

Related to #1619

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist: N/A, benchmark tooling; verified
with the base-to-base controls below
- [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 Code (Claude Opus 5.5); reviewed by <pending human
review>.

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

All controls measure one commit (73e853a) from several checkouts on
CPython 3.14.7 and 3.14.7t with Valgrind 3.26.0 and pytest-codspeed
5.0.3: `a/tree`, `ab/tree` (one character longer) and
`a-considerably-longer-directory-name-to-shift-paths/tree`, each with
its own venv.

**Before** (old driver, GIL, `--include-multidict-only --impl
multidict_c`, Ir/op):

| row | a | ab (+1 char) | long (+50 chars) |
| --- | ---: | ---: | ---: |
| getitem_istr | 700.5 | 721.5 | 698.5 |
| setitem_istr | 882.7 | 884.7 | 881.7 |
| copy | 25474.5 | 25458.5 | 25452.0 |
| update | 37024.0 | 37000.0 | 37000.0 |
| ctor_items | 44700.5 | 44700.5 | 44711.0 |

Old driver, FT, three runs of the same tree: `update` 46363 / 46371 /
46491.

Root cause (callgrind per-line diff, a vs ab, getitem_istr): +8000 Ir in
`_PyObject_Free` (`insert_to_usedpool`), +5600 in `_PyObject_Malloc`
(`pymalloc_pool_extend` unlinking a full pool) and a different branch in
`__memcmp_avx2_movbe`, over 800 ops.

Intermediate: path staging alone made FT worse, with getitem_istr at
805.8 to 979.0 across runs of one tree. A syscall trace showed
mimalloc's 1 GiB arena at 0x2ab30000000 in one run and 0x49502000000 in
another. With `MIMALLOC_ARENA_RESERVE=2GiB` and
`MIMALLOC_PURGE_DELAY=-1`, four concurrent runs matched exactly.

**After** (final driver, `--include-multidict-only`, all five
implementations, comparing raw Callgrind points):

- GIL, a vs ab vs long: 0 of 124 cells differ.
- FT, a vs a (second run) vs long: 0 of 124 cells differ.
- Earlier revision: still 0 of 124 after adding a junk directory to one
tree's root and a fake `.so` to its `multidict/`.

Other checks:

- `--whole-process` refusal: a venv without pytest-codspeed exits 1 with
the message; with `--whole-process` it writes JSON with `bracketed:
false`.
- `python benchmarks/callgrind_driver.py --self-check`: passed, 124
cells.
- Tests: C extension `2851 passed, 172 skipped`; pure Python
(`MULTIDICT_NO_EXTENSIONS=1`, `--no-c-extensions`) `1336 passed, 20
skipped`.
- `pre-commit` (PYENV_VERSION=3.13.2) and `make doc-spelling`: pass.
- Pre-existing and out of scope: the driver cannot run on a
pure-Python-only install, since `self_check()` loads every
implementation. The old driver fails the same way.

</details>
asvetlov added a commit that referenced this pull request Sep 28, 2026
…1626)

<!-- Thank you for your contribution! -->

## What do these changes do?

The pure-Python `__init__()` with a multidict of the same kind replaced
`_keys` and only then set `_used` from the source, overwriting the count
of whatever a finalizer of an old value added in between: the pair
stayed but `len()` was off. It now sets the size before swapping the
table, the order #1619 gave the C implementation. The generic path also
sets `_used = 0` right before its swap rather than before parsing the
argument, so user code the argument runs no longer sees an empty count
over the old table.

The C implementation is unaffected; #1619 already fixed it.

## Are there changes in behavior for the user?

Yes, only on the pure-Python backend: `len()` is right after such a
re-init.

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

No, it reorders two assignments.

## Related issue number

Follows #1619; found by the finalizer audit in #1631.

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

The existing `test_reinit_finalizer_sees_and_keeps_new_contents` gains a
`len()` check, which fails on the four pure-Python `same_kind`/`proxy`
cases against master and passes here.

Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2899
passed), FT 3.14.7t (2887), 3.10.17 (2899), `MULTIDICT_DEBUG_BUILD=1`
GIL (2899) and FT (2887), pure Python with `MULTIDICT_NO_EXTENSIONS=1
--no-c-extensions` (1358), and ASan+UBSan on a debug GIL build with
`PYTHONMALLOC=malloc` (2887, `test_leaks` deselected) and again with
`MULTIDICT_NO_FREELIST=1` (2887). The Cython harness was not built, so
its cases skipped.

Lint: pre-commit clean; `make doc-spelling` passes.
</details>

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`popitem()` built its result while it still pointed at the popped entry,
and read the entry's value afterwards. Building the result can run
Python code that mutates the multidict: a `str` subclass key's
`__str__()` when a `CIMultiDict` makes its `istr`, and on Python 3.10
and 3.11 a garbage collection the tuple allocation triggers, whose
finalizers run there. If that code replaced the table, the value came
from freed memory (a wrong value, or a crash). The C implementation now
takes its own references, removes the pair, and only then builds the
result, the order the pure-Python implementation already used.

The pure-Python `popitem()` decremented its size after building the key,
so it miscounted `len()` in the same case, and kept the old entry list
alive in a local until it returned; both are fixed.

## Are there changes in behavior for the user?

Yes: the use-after-free is gone. If building the key raises, the pair is
removed before the exception propagates, as the pure-Python
implementation always did; the C one used to leave it in place.

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

No.

## Related issue number

Found by the finalizer audit in #1631; same class as #1619.

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

New tests: `test_popitem_key_str_mutates` (fails on both backends
against master: C returns the value `'1'` read from the freed table,
pure Python miscounts `len`), `test_popitem_key_str_raises`, and
`test_popitem_collection_mutates`, which arms a collection at each of 12
allocation offsets; on 3.10 against master it fails 6 C cases with wrong
values.

Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2951
passed), FT 3.14.7t (2939), 3.10.17 (2951), `MULTIDICT_DEBUG_BUILD=1`
GIL (2951) and FT (2939), pure Python with `MULTIDICT_NO_EXTENSIONS=1
--no-c-extensions` (1384), and ASan+UBSan on a debug GIL build with
`PYTHONMALLOC=malloc` (2939, `test_leaks` deselected) and again with
`MULTIDICT_NO_FREELIST=1` (2939). The Cython harness was not built, so
its cases skipped.

Callgrind, `PYTHONHASHSEED=0`, `benchmarks/callgrind_driver.py
--include-multidict-only`, base master 9802f1b, Ir per op: rows that
moved by 0.5% or more:

| row | GIL MultiDict | GIL CIMultiDict | FT MultiDict | FT CIMultiDict
|
|---|---|---|---|---|
| popitem | 502.6 -> 489.4 (-2.6%) | 1507.1 -> 1495.9 (-0.7%) | 646.6 ->
564.4 (-12.7%) | 1698.0 -> 1613.8 (-5.0%) |
| delitem | 237.5 -> 234.5 (-1.3%) | 290.2 -> 287.2 (-1.0%) | 392.2 ->
396.2 (+1.0%) | 443.9 -> 447.9 (+0.9%) |
| setitem_replace | 327.5 -> 321.5 (-1.8%) | | | |
| setitem_insert | 402.5 -> 395.7 (-1.7%) | | | |
| iter_items | 129.7 -> 127.7 (-1.5%) | 133.7 -> 131.7 (-1.5%) | 188.7
-> 186.7 (-1.1%) | 189.7 -> 187.7 (-1.1%) |
| iter_keys | 60.1 -> 59.1 (-1.7%) | 64.1 -> 63.1 (-1.6%) | | |
| getall | 812.9 -> 807.9 (-0.6%) | | | |

`popitem()` takes over the entry's references (`_md_unlink_at()`, split
out of `_md_del_at()`) instead of adding its own; a first cut that did
`Py_NewRef()` three times cost +6.3% on GIL `popitem`.

`md_next()` is `ALWAYS_INLINE` here too (the same hunk as #1628): after
the rebase onto 9802f1b, GCC 15 pushed it out of the FT items iterator,
and `tools/check_inlining.py` failed its #1601 rule; pinned, all 8 rules
pass on GIL and FT with GCC 13 and 15. Lint: pre-commit clean; `make
doc-spelling` passes (adds `finalizers`).
</details>

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
asvetlov added a commit that referenced this pull request Sep 29, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds `tests/finalizer_helpers.py`, a key, a value and an argument item
that run a callback from their finalizer behind a `Fuse` that keeps them
quiet during setup and inspection, and
`tests/test_finalizer_reentrancy.py`, which runs every mutating method
of `MultiDict` and `CIMultiDict` (`[]=`, `del`, `add`, `setdefault`,
`pop`, `popone`, `popall`, `popitem`, `clear`, `extend`, `update` from
pairs, a dict and a multidict, `merge`, `__init__` from pairs and a
multidict, `copy`) with finalizers on keys or values, under nine actions
(add, add the same key, set it, update it, remove another key, clear,
re-init, grow past a resize, popitem). It compares result, contents,
`len()` and finalizer count between the C implementation and the
pure-Python one, and asserts whether each call runs a finalizer at all:
`add`, `setdefault` and `copy` never do, and the pop family hands the
removed value back. 612 cases; before the fixes, 177 of the first 544
failed.

The fixes the audit found have all merged: #1625, #1626, #1627, #1628
and #1630, with #1629 and #1635 as follow-ups and #1634 tracking a
remaining corner case.

## Are there changes in behavior for the user?

No, tests only.

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

No. A new mutating method or a new way to drop a reference is one more
entry in `_METHODS` or `_ACTIONS`.

## Related issue number

Follows #1619, which fixed the first bug of this class.

## 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>Audit summary</summary>

Every C path that drops a reference or calls code that can run Python
(`__eq__`, `__hash__`, `lower()`, `__str__`, an iterator, and on 3.10
and 3.11 any GC-tracked allocation) and then touches md state, in
`hashtable.h`, `bulk_update.h`, `walk.h`, `views.h`, `iter.h`,
`_multidict.c` and `capsule.h`:

Bugs, each with its own PR and a test that fails first:

- `popitem()`: `istr` key or result tuple built before the removal,
entry read after (#1625).
- `del`/`popall()`: the post-decref restart removed pairs a finalizer
re-added (#1627).
- `update()`/`merge()`: half-deleted entries visible to code run between
items, and marks lost on any mutation (#1628).
- `to_dict()` on 3.10/3.11: `PyList_New()` collection, entry read after
(#1630).
- Pure Python only: `__init__(multidict)` overwrote `_used` (#1626);
`del`, `popall()`, `[]=` and `popitem()` freed entries mid-scan (#1627,
#1625); `update()` returned `None` for doomed pairs (#1628).

Safe, with the reason:

- `md_clear()`, `md_init()`, `md_clone_from_ht()`: publish, then release
(#1619).
- `md_replace()`, `_md_update()`: replaced pairs deferred to after the
critical section.
- `popone()`: bookkeeping complete before its decrefs; only the version
bump follows.
- `md_next()`/`md_prev()`, `md_walk*()`, `md_repr()`,
`md_eq_to_mapping()`, `md_to_dict()`'s key insert: own references,
version re-checked after anything that can run Python.
- `md_eq()`: own refs around `__eq__`, arrays reloaded, bounds re-read
each step; the result under mutation is unspecified but memory-safe.
- `md_ensure_key()`: own refs, cache only if the version held.
- `md_update_from_ht/dict/seq()`: own refs where `lower()` or an
iterator runs; the table is re-read per item.
- Items iterator tuple reuse: new items set before the old ones are
dropped.
- Views: matches materialized before `__eq__`.
- `capsule.h`: wraps the `md_*` functions above.

Deliberate: a `CIMultiDict` caches the `istr` on first key read and
drops the original `str` subclass key then, so its finalizer runs at
read time, where the pure-Python implementation keeps the key.
</details>

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

Tests on the merge with master 74b96d7 (all fixes in): GIL 3.14.7 3692
passed, FT 3.14.7t 3680, 3.10.17 3696, pure Python with
`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions` 1471 (the new test is
C-extension only and deselected there). An earlier full run, on the
merge with 9802f1b, also passed the debug GIL and FT builds and both
ASan passes.

`tools/check_inlining.py`: all 8 rules pass on GIL and FT with GCC 13
and 15. 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