Skip to content

Test finalizer reentrancy across every mutating method - #1631

Merged
asvetlov merged 38 commits into
aio-libs:masterfrom
asvetlov:reentrancy-harness
Sep 29, 2026
Merged

asvetlov merged 38 commits into
aio-libs:masterfrom
asvetlov:reentrancy-harness

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

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

  • 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
Audit 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:

Safe, with the reason:

  • md_clear(), md_init(), md_clone_from_ht(): publish, then release (Release the old pairs after re-initializing, not before #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.

Agent run details (optional, for reviewers)

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.

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

__init__() with a multidict of the same kind replaced the keys first and
set _used afterwards, overwriting the count of whatever a finalizer of an
old value added in between. Assign the size first, as the C
implementation does since aio-libs#1619.
On 3.10 and 3.11, allocating a GC-tracked object can run a collection
whose finalizers mutate the multidict. to_dict() read the matched entry
right after allocating its value list, from a table the finalizer may
have freed. Check the version before reading it again, the way the key
hash and insert further down already are.
Building the result can run Python code that mutates the multidict: an
istr key runs a str subclass's __str__, and on 3.10 and 3.11 allocating
the tuple can run a collection whose finalizers do. The C implementation
read the popped entry afterwards, from a table the mutation may have
freed. Remove the pair first, from our own references, as the
pure-Python implementation already does, and decrement the pure-Python
used count before the call too.
Each match was decref'd as soon as it was unlinked, so a finalizer could
add the key back mid-scan; the scan then restarted and removed, and for
popall() returned, the new pair as well. Hold the removed pairs until
every match is gone: the first in place, any more in a reflist_t, which
keeps the usual single-match delete within 13 instructions of before.
Nothing in the loops can run Python any more, so the restart goes.

The pure-Python implementation freed each match mid-scan too, in
__setitem__() as well, and indexed a table the finalizer had replaced.
update() half-deleted the later matches of a key as it went, nulling
their key and value until md_post_update() finished them off, and kept
its marks keyed by entry index, dropping them whenever anything else
touched the table. Python code run between items (the argument's
iterator, a key's lower(), a finalizer) could therefore crash reading
a half-deleted entry, and any mutation it made lost the marks, so a
later item for the same key overwrote a value the call had just
written.

Doomed entries now stay whole, marked only in the batch's bitmap, and
md_post_update() removes them. The marks stay valid because nothing
reuses an entry index while a batch is in flight: md counts its batches
in the padding after is_ci, and while there are any, a resize keeps
every entry at its index, popitem() leaves its trailing holes, and a
clear or re-init starts the new table with a hole per old entry. A
generation bumped with every new table tells a batch to widen its
bitmaps. No remap and no sweep are left.

The pure-Python implementation had the same shape, with HASH_MARK and
key=None in the table; it now keeps its marks in dicts keyed by entry
id, and holds the replaced pairs until the call ends, as the C one
does.
# Conflicts:
#	tests/test_mutable_multidict.py
# Conflicts:
#	multidict/_multilib/hashtable.h
tests/finalizer_helpers.py holds a key, a value and an argument item
that run a callback from their finalizer, behind a fuse that keeps them
quiet while a test sets up and inspects the multidict. The new test runs
every mutating method of MultiDict and CIMultiDict with them, under
eight finalizer actions, and compares the C implementation's result,
contents, length and finalizer count against the pure-Python one.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 28, 2026
@codspeed

codspeed Bot commented Sep 28, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 706 untouched benchmarks


Comparing asvetlov:reentrancy-harness (bd91777) with master (74b96d7)

Open in CodSpeed

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?

`del md[key]` and `popall()` decref'd each match as soon as they
unlinked it. A finalizer of a removed key or value could add the key
back mid-scan; the scan then restarted (the restart #1512 added for
concurrent resizes) and removed that new pair too, and `popall()`
returned its value. The removed pairs are now held until every match is
gone: the first in place, which covers the usual single match, any more
in a `reflist_t`. With nothing in the loops able to run Python, the
restart is gone.

The pure-Python `__delitem__()`, `popall()` and `__setitem__()` freed
each match mid-scan as well, and with a finalizer that replaced the
table they raised `IndexError` or miscounted `len()`; they now keep the
removed entries alive until the scan ends. The C `__setitem__()` already
deferred its decrefs.

## Are there changes in behavior for the user?

Yes: pairs a finalizer adds during `del md[key]` or `popall()` stay in
the multidict.

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

No.

## Related issue number

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>

New `test_remove_all_keeps_what_a_finalizer_adds` (delitem, popall,
setitem x key/value side x both classes x both backends): against master
6 C and 6 pure-Python delitem/popall cases fail, and the 4 pure-Python
setitem ones.

Tests, one venv and tree copy per leg, full suite: GIL 3.14.7 (2923
passed), FT 3.14.7t (2911), 3.10.17 (2923), `MULTIDICT_DEBUG_BUILD=1`
GIL (2923) and FT (2911), pure Python with `MULTIDICT_NO_EXTENSIONS=1
--no-c-extensions` (1370), and ASan+UBSan on a debug GIL build with
`PYTHONMALLOC=malloc` (2911, `test_leaks` deselected) and again with
`MULTIDICT_NO_FREELIST=1` (2911). 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: GIL `delitem`
237.5 -> 251.5 (`MultiDict`, +5.9%) and 290.2 -> 307.2 (`CIMultiDict`,
+5.9%); FT `delitem` 392.2 -> 387.2 (-1.3%) and 443.9 -> 437.9 (-1.4%).
The `md_next()` pin below takes GIL `iter_items`/`iter_keys` down 1.5%
and `setitem_*` 1.7%; nothing else moved by 0.5% or more. A first cut
that pushed all three refs of every match into a `reflist_t` cost +61 Ir
on GIL `delitem`; holding the first pair in place brought that down.

`tools/check_inlining.py` first failed `multidict_items_iter_tp_iternext
-> md_next` on FT with GCC 15 (FT `iter_items` +19%);
`removed_pairs_release()` is `NOINLINE` for that; after the rebase onto
9802f1b it failed again, so `md_next()` is `ALWAYS_INLINE` as well (the
same hunk as #1628), and 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.
The merge of the popitem and del/popall branches attached the one
skipif both tests shared to the first of them only.
CodSpeed showed the pure-Python update() with duplicate keys 17% slower:
_post_update() walked a hash chain per doomed entry. Sweep the slots once
when there are any, as the old HASH_MARK version always did, and touch
the doomed set only when it is non-empty.
The test accepted the old result when the collection only ran after
to_dict() returned, so it could pass with the guard removed, and its GC
restore had an arm no run took. It now runs only on 3.10 and 3.11,
where a collection can run inside the call, sweeps the arming point
across the call's allocations in one test, requires at least one round
to collect inside it and every such round to be refused, and restores
GC unconditionally. With the guard removed it segfaults on 3.10 and
3.11.
…rancy

# Conflicts:
#	tests/test_mutable_multidict.py
…ive-reentrancy

# Conflicts:
#	multidict/_multilib/hashtable.h
# Conflicts:
#	tests/test_mutable_multidict.py
@asvetlov
asvetlov marked this pull request as ready for review September 28, 2026 16:37
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 28, 2026 16:37
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Low risk] Adds test helpers and test cases for multidict finalizer reentrancy.

Not ready to merge: the outstanding update() issue can discard a nested write.

Reviews (3) · Last reviewed commit: "Assert which harness calls run a finaliz..."

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

This comment has been minimized.

@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 98.50%. Comparing base (74b96d7) to head (bd91777).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1631      +/-   ##
==========================================
+ Coverage   98.49%   98.50%   +0.01%     
==========================================
  Files          47       49       +2     
  Lines        9167     9251      +84     
  Branches      778      784       +6     
==========================================
+ Hits         9029     9113      +84     
  Misses        133      133              
  Partials        5        5              
Flag Coverage Δ
CI-GHA 98.50% <100.00%> (+0.01%) ⬆️
pytest 98.50% <100.00%> (+0.01%) ⬆️

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.

A duplicate update() doomed stayed doomed even if code run between items
(a nested update(), say) wrote to that very entry, and the batch then
deleted the nested write. Record each doomed entry's key and value, held
so their addresses cannot be reused, and remove only entries that still
hold both, in C and in pure Python. Master's C implementation kept the
write through its half-deletion revival, which this branch removed.
A duplicate update() doomed stayed doomed even if code run between items
(a nested update(), say) wrote to that very entry, and the batch then
deleted the nested write. Record each doomed entry's value, held so its
address cannot be reused, and remove only entries that still hold it, in
C and in pure Python. Every write stores a new value; the key is no
guide, since reading a CIMultiDict's key swaps the stored str for its
istr. Master's C implementation kept the write through its half-deletion
revival, which this branch removed.
# Conflicts:
#	multidict/_multidict_py.py
#	multidict/_multilib/bulk_update.h
#	multidict/_multilib/update_marks.h
#	tests/test_update.py
Comment thread multidict/_multilib/bulk_update.h Resolved
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

`update()` half-deleted the later matches of a key as it went (key and
value set to `NULL`, identity kept) until `md_post_update()` finished
them off, and kept its marks keyed by entry index, dropping them
whenever anything else touched the table. Python code that runs between
the items of one `update()` (the argument's own iterator, a key's
`lower()`, a finalizer of a dropped item) could therefore:

- crash reading a half-deleted entry through `get()`, `getall()`,
`items()`, `copy()` or `popall()`;
- make a later item for the same key overwrite a value the call had just
written, since any mutation dropped the marks;
- have `merge()` skip a key a pending deletion was about to remove.

Doomed entries now stay whole until `md_post_update()` removes them,
marked only in the batch's bitmap. Each is recorded with the value it
held when doomed, referenced so the address cannot be reused, and is
removed only if it still holds it: a nested `update()` or `md[key] =
value` run between items that writes to it wins. (Only the value is
compared, since reading a `CIMultiDict` key swaps the stored `str` for
its `istr`.) The marks stay valid because nothing reuses an entry index
while a batch is in flight: `md` counts its batches in `is_ci`'s padding
(the object stays 64 bytes), and while there are any a resize keeps
every entry at its index, `popitem()` leaves its trailing holes, and a
clear or re-init starts the new table with a hole per old entry. A
generation bumped with every new table tells a batch to widen its
bitmaps. The remap, the sweep and the half-deletion all go.

The pure-Python implementation had the same shape with `HASH_MARK` and
`key=None` in the table, and returned `None` for doomed pairs; it now
keeps its marks in dicts keyed by entry id, and holds replaced pairs
until the call ends, as C does.

## Are there changes in behavior for the user?

Yes: no crash, and `update()`/`merge()` keep what they wrote when the
argument's iterator or a finalizer mutates the multidict. Watchers now
see a doomed pair's `DELETED` at the end of the batch, and a pair an
earlier item doomed and a later one reuses as `REPLACED` rather than
`DELETED` plus `ADDED`.

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

No: the invariant is "no index is reused while a batch runs", checked in
four places, and it removes more code than it adds.

## Related issue number

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>

New tests in `tests/test_update.py`: readers and mutators run from the
argument's iterator between two items of `update()` and `merge()`, marks
outgrowing the table, and
`test_update_keeps_what_code_between_items_wrote` for Greptile's
nested-write case on #1629 (a nested `update()`, `md[key] = value`,
`merge()` and a plain read between items; the nested `update()` cases
failed on both backends before the fix, the read case on C with a first
cut that also compared keys). Against master the C reader cases
segfault, 20 C mutator cases fail and 12 pure-Python cases fail.

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

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

| row | GIL MultiDict | GIL CIMultiDict | FT MultiDict | FT CIMultiDict
|
|---|---|---|---|---|
| update | 36996 -> 37476 (+1.3%) | 42636 -> 43316 (+1.6%) | 46411 ->
42898 (-7.6%) | 52311 -> 48798 (-6.7%) |
| ctor_items | 44842 -> 41660 (-7.1%) | 55923 -> 52741 (-5.7%) | | |
| ctor_small | 4228 -> 3927 (-7.1%) | 5349 -> 5048 (-5.6%) | | |
| reinit_items | 45468 -> 42285 (-7.0%) | 56413 -> 53230 (-5.6%) | | |
| reinit_items_small | 4854 -> 4552 (-6.2%) | 5839 -> 5537 (-5.2%) | | |

The construction gains are GCC re-planning its inlining after the
half-delete path went; nothing here targets them. `update()` with
duplicate keys, the CodSpeed `update_*_with_duplicates` shape (a
150-item copy updated with 100 items, 75 of them dooming an entry), per
call on GIL: 84107 -> 89769 (`MultiDict`, +6.7%) and 87530 -> 93192
(`CIMultiDict`, +6.5%), about 75 Ir per doomed entry for its record and
reference; that is the price of keeping a nested write.

Pure Python, callgrind Ir per `copy().update()`: plain update of 200
into 200 (`MultiDict`) 6044942 -> 5233224 (-13.4%) and `CIMultiDict`
-12.8%, since there is no full-table mark sweep unless something was
doomed; with duplicate keys (the CodSpeed `update_*_with_duplicates`
shape) 3779495 -> 3967045 (+5.0%) and +4.7%, down from the +17% CodSpeed
measured on the first push, which walked a hash chain per doomed entry.
A registration-list design that grew the object to 72 bytes cost ctor ~8
Ir and was dropped for the counters in the padding.

`tools/check_inlining.py` failed `multidict_items_iter_tp_iternext ->
md_next` on FT with GCC 15; `md_next()` is now `ALWAYS_INLINE` (the same
hunk as #1625 and #1627), and 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.
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?

On Python 3.10 and 3.11, allocating a GC-tracked object can run a
garbage collection on the spot, and its finalizers can mutate the
multidict. `to_dict()` allocates each key's value list with
`PyList_New()` and then read the matched entry, possibly from a table
the finalizer had freed. It now checks the version right after the
allocation and raises `RuntimeError`, as it already does when a key's
`__hash__()` mutates the multidict. 3.12 and later run collections from
the eval loop, never inside the call, so they are unaffected.

The pure-Python implementation already refuses the mutation through its
version check.

## Are there changes in behavior for the user?

Yes, on 3.10 and 3.11: `RuntimeError` instead of a use-after-free.

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

No, one version check.

## Related issue number

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>

New `test_to_dict_refuses_mutation_from_a_collection` (3.10 and 3.11
only; later versions never collect mid-call) arms a collection at each
of 12 allocation offsets, records whether the finalizer ran inside
`to_dict()`, and requires at least one round to land inside and every
such round to be refused. With the guard removed it segfaults on 3.10.17
and 3.11.13, release and debug builds alike; with it, it passes on both
backends.

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

Callgrind, `PYTHONHASHSEED=0`, `benchmarks/callgrind_driver.py
--include-multidict-only`, base master 9802f1b: no row moved by 0.5% or
more on GIL or FT.

`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.
# Conflicts:
#	multidict/_multilib/hashtable.h
add(), setdefault() and copy() never drop anything, and the pop family
hands the removed value back, so those cases compared the backends with
no finalizer run inside the call, which read as reentrancy coverage
(Greptile on aio-libs#1631). Each case now asserts whether its call fires one.
@asvetlov
asvetlov merged commit 7f00b5d into aio-libs:master Sep 29, 2026
53 of 54 checks passed
@asvetlov
asvetlov deleted the reentrancy-harness branch September 29, 2026 07:23
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