Skip to content

Refuse a mutation from a collection run inside to_dict() - #1630

Merged
asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:to-dict-gc-finalizer
Sep 29, 2026
Merged

asvetlov merged 5 commits into
aio-libs:masterfrom
asvetlov:to-dict-gc-finalizer

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

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

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

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.

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

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.
@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:to-dict-gc-finalizer (2b68648) with master (4224425)

Open in CodSpeed

@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.49%. Comparing base (4224425) to head (2b68648).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1630   +/-   ##
=======================================
  Coverage   98.48%   98.49%           
=======================================
  Files          47       47           
  Lines        9122     9167   +45     
  Branches      777      778    +1     
=======================================
+ Hits         8984     9029   +45     
  Misses        133      133           
  Partials        5        5           
Flag Coverage Δ
CI-GHA 98.49% <100.00%> (+<0.01%) ⬆️
pytest 98.49% <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.

@asvetlov
asvetlov marked this pull request as ready for review September 28, 2026 14:56
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 28, 2026 14:56
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Adds a guard against mutation during dictionary conversion.

No outstanding findings block merging.

Reviews (4) · Last reviewed commit: "Merge branch 'master' into to-dict-gc-fi..."

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

This comment has been minimized.

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

## What do these changes do?

`test_reinit_finalizer_vs_lock_free_readers` (#1621) timed out on the
Windows 3.10, 3.11 and 3.12 jobs, at `f.result(timeout=60)` for its
readers. The faulthandler dump from a 183 s run shows every reader still
inside `Value.__del__()` -> `probe()` after the writer finished, each
blocked in `coverage/collector.py: lock_data`. Under coverage's C tracer
(3.10 to 3.12) every traced line takes a lock the threads share, and the
readers are draining the finalizers of generations their `copy()`
snapshots outlived. That work is bounded (3216 finalizers, nesting depth
1), just slow: 0.4 s without coverage, 12 to 20 s with it on a Linux
3.11 box, and over three minutes on the Windows runners. The failure
reports also show every reader future finished by the time pytest
rendered them.

The writer now gets 300 s and the readers a shared 300 s deadline,
inside the job's 15-minute limit.

## Are there changes in behavior for the user?

No, tests only.

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

No.

## Related issue number

Follows #1621. Failed on #1625, #1628 (twice) and #1630; re-runs passed.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A, a test timeout)
- [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/test_free_threading.py`: GIL 3.14.7 10 passed, FT 3.14.7t 10
passed (without coverage); 3.11.13 with coverage, the two cases took
12.4 s and 19.9 s.

Lint: pre-commit clean.
</details>

Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
@asvetlov
asvetlov merged commit 74b96d7 into aio-libs:master Sep 29, 2026
54 checks passed
@asvetlov
asvetlov deleted the to-dict-gc-finalizer branch September 29, 2026 06:01
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