Skip to content

Drop ASSERT_CONSISTENT()'s update flag - #1629

Merged
asvetlov merged 15 commits into
aio-libs:masterfrom
asvetlov:assert-consistent-drop-update
Sep 28, 2026
Merged

asvetlov merged 15 commits into
aio-libs:masterfrom
asvetlov:assert-consistent-drop-update

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

ASSERT_CONSISTENT(md, update) took a flag that relaxed the debug-only consistency check for the half-deleted entries (key == NULL, identity kept) that update() used to leave in the table mid-batch. #1628 removed half-deletion and made the check strict on every call, leaving the flag ignored; this drops it from the macro, _md_check_consistency() and every call site.

Are there changes in behavior for the user?

No. The macro compiles to nothing in release builds.

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

No, it removes a parameter.

Related issue number

Follows #1628.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist (N/A, no behavior change; the debug suites exercise every call site)
  • 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)

tools/codegen_diff.py --ref upstream/master (9684a61, #1628 merged): 0 of 256 functions differ on 3.14.7, 0 of 265 on 3.14.7t (release flags). Full suite with MULTIDICT_DEBUG_BUILD=1, where every ASSERT_CONSISTENT() runs: GIL 3.14.7 3028 passed, FT 3.14.7t 3016 passed.

Lint: pre-commit clean.

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

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.
It relaxed the check for the half-deleted entries update() used to leave
in the table. update() no longer makes any, the check has been strict on
every call since, and the flag was ignored.
@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:assert-consistent-drop-update (a99af77) with master (2800fef)

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.47%. Comparing base (9684a61) to head (a99af77).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1629   +/-   ##
=======================================
  Coverage   98.47%   98.47%           
=======================================
  Files          47       47           
  Lines        9069     9071    +2     
  Branches      777      777           
=======================================
+ Hits         8931     8933    +2     
  Misses        133      133           
  Partials        5        5           
Flag Coverage Δ
CI-GHA 98.47% <ø> (+<0.01%) ⬆️
pytest 98.47% <ø> (+<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.

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.
…ive-reentrancy

# Conflicts:
#	multidict/_multilib/hashtable.h
…-drop-update

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

greptile-apps Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Refactors core update and merge logic with structural changes.

No outstanding findings block merging.

Reviews (2) · Last reviewed commit: "Merge branch 'update-marks-survive-reent..."

Comment thread multidict/_multilib/bulk_update.h Resolved
@greptile-apps

This comment has been minimized.

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.
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.
…-drop-update

# Conflicts:
#	multidict/_multilib/hashtable.h
@asvetlov
asvetlov merged commit 07f7734 into aio-libs:master Sep 28, 2026
52 of 53 checks passed
@asvetlov
asvetlov deleted the assert-consistent-drop-update branch September 28, 2026 19:15
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.
asvetlov added a commit that referenced this pull request Sep 29, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

#1628 split the pure-Python `update()` match test into two `if ...
continue` checks, to call `id()` only on a key match. That left
`continue` after `e.identity != identity` reachable only by two keys
with the same full hash, which the tests cannot produce for `str`, and
Codecov reported it on #1629 (1 missing line, 1 partial branch). This
folds the two back into one condition, so every line runs.

The C implementation is unaffected.

## Are there changes in behavior for the user?

No.

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

No.

## Related issue number

Follows #1628.

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A, existing tests now cover
every line)
- [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>

`pytest --cov=multidict --cov-branch` on GIL 3.14.7: master reports
`_multidict_py.py` line 1344 missing; this branch reports only the
free-threaded and PyPy-only lines other CI jobs cover. 3028 passed.

Callgrind Ir per pure-Python `copy().update()`, master -> branch:
duplicates shape 4082346 -> 4082572 (`MultiDict`), 4235458 -> 4235684
(`CIMultiDict`); plain 5231909 -> 5232009 and 5536876 -> 5536976, all
under 0.01%.

Lint: pre-commit clean.
</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