Skip to content

Set the pure-Python size before releasing the old pairs on re-init - #1626

Merged
asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:pure-reinit-used-count
Sep 28, 2026
Merged

asvetlov merged 2 commits into
aio-libs:masterfrom
asvetlov:pure-reinit-used-count

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

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

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

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.

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.
@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:pure-reinit-used-count (dc7242a) with master (b27c7da)

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 100.00%. Comparing base (9802f1b) to head (dc7242a).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1626   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           44        44           
  Lines         8381      8383    +2     
  Branches       706       706           
=========================================
+ Hits          8381      8383    +2     
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 28, 2026 13:49
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 28, 2026 13:49
@greptile-apps

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Fixes a reference-counting bug in multidict initialization.

Safe to merge; the checked reinitialization paths retain consistent lengths.

What we checked:

  • Validated reinitialization behavior with tombstoned multidicts and confirmed that the parent and PR length reports align after mutations, while the targeted finalizer tests pass. T-Rex
  • Executed the parsing-error reproducer to exercise a finalizer that adds an item during parsing; in both revisions, mappings retained two items and the lengths matched the items. T-Rex
  • Reviewed the targeted code change in multidict_py.py around _from_md where _from_md sets _used before replacing _keys, which reconciles the reported lengths. T-Rex
  • Observed that initialization raised ValueError in both runs, the finalizer was registered late, and items() contained two entries, with lengths moving from 1 to 2 from pre-PR to PR head. T-Rex

Reviews (1) · Last reviewed commit: "Name the news fragment after the PR"

@asvetlov
asvetlov merged commit 081c1f4 into aio-libs:master Sep 28, 2026
66 checks passed
@asvetlov
asvetlov deleted the pure-reinit-used-count branch September 28, 2026 14:24
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