Skip to content

Skip the watcher checks on unwatched deletes, replaces and pops - #1604

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:unwatched-delete-replace
Sep 26, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:unwatched-delete-replace

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

del d[key], d[key] = value and pop() tested md->watch for every event they might record. Stores and decrefs in between force a reload each time, and the extra code made the probe loop spill. On a multidict nobody watches, that was most of the regression #1551 left in these rows. Each operation now reads md->watch once under its critical section. When it is NULL, the operation runs a copy of its locked body with no watcher code in it; the watched copy is COLD. The not-found md_add_with_hash() call moved out of _md_replace() so the hot path keeps a single inlined copy of it.

The second copies use up GCC's inline budget, which is already at inline-unit-growth for this translation unit. GCC reacted by outlining _md_del_at() from popitem() and htkeys_set_index() from the free-threaded insert path. Both are now ALWAYS_INLINE.

Callgrind ir_per_op, multidict_c, against 2f84475 (rows that moved by more than 0.1%):

operation GIL 3.14.7 free-threaded 3.14.7t
del d[key] 250.8 -> 237.5 (-5.3%) 408.6 -> 383.3 (-6.2%)
d[key] = v, existing key 329.6 -> 325.5 (-1.2%) 505.1 -> 506.9 (+0.4%)
d[key] = v, new key 403.1 -> 398.4 (-1.2%) 610.5 -> 609.0 (-0.2%)
d.pop(key) 390.8 -> 389.8 (-0.3%) 537.8 -> 533.8 (-0.7%)
d.getall(key) flat 856.1 -> 844.2 (-1.4%)
d[key] = v, istr key 876.0 -> 884.9 (+1.0%) 1028.8 -> 1032.6 (+0.4%)

GIL delitem is back to 237.5, against 236.5 before #1551. The istr setitem row is the one that got worse: the watch tests fell from 13 to 3 Ir per call, but the case-insensitive compare in the probe loop got a worse register allocation. Every other row is unchanged.

Are there changes in behavior for the user?

No, except in a corner of the watchers C API. A watcher that a __del__ attaches while del d[key] is still running now sees none of that delete. Before, it received the remaining DELETED events and a BATCH_END with no BATCH_BEGIN. A new test covers this.

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

No. The watched and unwatched paths share one body and differ only in a constant bool. The watchers API is C-extension only, so the pure-Python implementation is not affected.

Related issue number

Follows up on #1551 and #1600.

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, existing contributor)
  • 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

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

Agent run details (optional, for reviewers)

Measured with benchmarks/callgrind_driver.py --impl multidict_c --include-multidict-only, one git worktree and one venv per build, .so rebuilt from scratch and timestamp-checked before each run. Base and change were built in the same tree. The 6e6ac72 comparison comes from a separate re-measure that reproduced the previous published tables exactly.

Per-function callgrind for GIL delitem: all +14.3 Ir/op against 6e6ac72 sat in md_del. 7 Ir were the md->watch tests (watch.h lines) and the rest were spills in the probe loop.

tools/codegen_diff.py --ref 2f84475 (3.14.7 and 3.14.7t): new symbols are the three cold copies plus out-of-line htkeysiter_next and reflist_push. objdump shows those two called only from the cold copies and existing .cold partitions, never from a hot path. On free-threaded builds the standalone htkeys_set_index is gone.

Variants tried and dropped: one body with the flag read into a runtime local (GIL delitem only -4.2%); the same for _md_replace (setitem_replace +0.2%, setitem_istr +1.2%); passing &flush to the cold helper (turned on the stack protector in md_pop_one, GIL pop +1.8%).

Tests: pytest passes on 3.14.7, 3.14.7t, 3.10.17 and pure Python (MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions, 3.13.2), each in its own tree copy and venv.
make doc-spelling: passes.

md_del(), md_replace() and md_pop_one() now read md->watch once and run
a copy of their locked body with no watcher code when nothing is
watching. Testing md->watch per record reloaded it after every store
and decref, and the extra code cost spills in the probe loop.

The watched copies spend inline budget, so _md_del_at() and
htkeys_set_index() are forced inline: without that GCC outlines them
from popitem() and, on the free-threaded build, from the insert path.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 26, 2026
@codspeed

codspeed Bot commented Sep 26, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:unwatched-delete-replace (3dbf65f) with master (72f7c3c)

Open in CodSpeed

@codecov

codecov Bot commented Sep 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (2f84475) to head (3dbf65f).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1604   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           43        43           
  Lines         7929      7940   +11     
  Branches       663       663           
=========================================
+ Hits          7929      7940   +11     
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 26, 2026 18:59
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 26, 2026 18:59
@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium risk] Optimizes watcher checks in delete and pop operations.

No blocking issue was found; the change is safe to merge.

What we checked:

  • Ran the Python reproducer against separate pre-change and post-change C extensions to exercise deletion with duplicate keys, pop, replacement, watcher attachment during finalization, and nested mutation, and observed that the nested add was delivered immediately in both builds while a subsequent add produced only its own event; in the changed build, the newly attached watcher received no events from the deletion in progress. T-Rex
  • Performed a deeper check comparing behavior across HEAD^ and HEAD: in both runs, the finalizer’s nested add was delivered immediately and a subsequent probe add produced only its own event; on HEAD^ deletion emitted later DELETED events and an unpaired BATCH_END for the newly attached watcher, while HEAD emitted neither, consistent with the new sampling rule; pop and replacement matched and no code was edited. T-Rex

Reviews (1) · Last reviewed commit: "Skip the watcher checks on unwatched del..."

@asvetlov
asvetlov merged commit 05315a4 into aio-libs:master Sep 26, 2026
62 checks passed
@asvetlov
asvetlov deleted the unwatched-delete-replace branch September 26, 2026 19:24
asvetlov added a commit that referenced this pull request Sep 26, 2026
…#1605)

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

## What do these changes do?

On free-threaded builds every mutation took its version from a
thread-local counter (#1587, #1599). In a shared object that is a
`__tls_get_addr()` call per mutation, about 23 instructions where the
old `lock xadd` was 4. That call accounted for nearly all of the
`ctor_small` regression (+18.6 Ir per inserted pair) and 18 of the 26 Ir
`pop` lost.

Each multidict now owns a block of 256 versions, and `md->version` is
the cursor into it, advanced under the multidict's own critical section.
Thread-local storage is touched only when a multidict needs a new block:
when it is created, and then after 255 mutations. Each thread still
reserves a batch from the process-wide counter, now 65536 versions (256
blocks) at a time. A block's base is never handed out. That keeps a new
multidict (version 0) and a spent block distinguishable with one mask
test, and versions stay unique across multidicts. `store_version(md,
next_version(md->state))` became `bump_version(md)`. On the GIL build
that is still `++state->global_version`, and `tools/codegen_diff.py`
reports 0 of 230 functions changed there.

Callgrind `ir_per_op`, `multidict_c`, free-threaded 3.14.7t, against
2f84475 (rows that moved by more than 0.1%):

| operation | before | after | |
| --- | --- | --- | --- |
| `cls(items)` | 69893.4 | 66265.3 | -5.2% |
| `cls(items)`, 20 items | 7135.6 | 6765.0 | -5.2% |
| `cls()` | 878.3 | 888.3 | +1.1% |
| `d.copy()`, 20 items | 2763.8 | 2744.8 | -0.7% |
| `d[key] = v`, existing key | 505.1 | 495.1 | -2.0% |
| `d[key] = v`, new key | 610.5 | 597.8 | -2.1% |
| `d.setdefault(key, v)`, new key | 730.1 | 711.4 | -2.6% |
| `del d[key]` | 408.6 | 392.5 | -3.9% |
| `d.pop(key)` | 537.8 | 519.8 | -3.3% |
| `d.popitem()` | 664.7 | 646.6 | -2.7% |
| `d.update(other)` | 44708.0 | 44514.0 | -0.4% |
| `d.clear()` | 8977.6 | 8957.0 | -0.2% |
| `iter(d)` | 784.0 | 786.0 | +0.3% |
| `d.add(key, v)` | 706.6 | 689.9 | -2.4% |
| `d[key] = v`, `istr` key | 1028.8 | 1015.8 | -1.3% |
| `d.add(key, v)`, `istr` key | 1044.5 | 1027.7 | -1.6% |

`ctor_small` is back to 6765, against 6763 before #1587. `cls()` pays
the one out-of-line call a new multidict now makes to take its block.

## Are there changes in behavior for the user?

No. `getversion()` is documented for equality tests only. Versions stay
unique across multidicts and still change on every mutation. As before,
they are not ordered across threads.

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

No. It replaces one counter scheme with another of the same size, and
only the free-threaded branch of `freethreading.h` changes. The
pure-Python implementation has no version batching, so it is not
affected.

## Related issue number

Follows up on #1587 and #1599.

## 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, existing contributor)
- [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>

Measured with `benchmarks/callgrind_driver.py --impl multidict_c
--include-multidict-only`, one git worktree and one venv per build,
`.so` rebuilt from scratch and timestamp-checked, and base and change
built in the same tree. GIL 3.14.7: every row is identical. A
base-to-base control across the two trees differed by at most 0.26%.

`objdump`: free-threaded `__tls_get_addr` call sites went from 25,
spread over every mutating function, to 2, both in the cold
`_new_version_block()` / `_refill_version_batch()`.

The first cut of `_new_version_block()` read and wrote the thread-local
separately, which was two TLS lookups and cost `cls()` +3.0%. One `+=`
brought that down to +1.1%.

On top of #1604 (merged into this branch, one-line conflict in
`_md_del_locked()`): free-threaded `ctor_small` 6765, `pop` 515.8,
`delitem` 374.2; GIL unchanged from #1604 alone.

Tests: `pytest` passes on 3.14.7, 3.14.7t, 3.10.17 and pure Python
(3.13.2), each in its own tree copy and venv. ThreadSanitizer
(`MULTIDICT_TSAN_BUILD=1`, 3.14.7t-tsan): `test_free_threading.py`,
`test_version.py` and `test_mutable_multidict.py` pass with 0 reports.
`make doc-spelling`: passes.
</details>
asvetlov added a commit that referenced this pull request Sep 28, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

Adds `tools/check_inlining.py` and an `Inlining` CI job on 3.14 and
3.14t. The script compiles `_multidict.c` with the interpreter's flags
plus the release flags from `setup.py`, disassembles it, and fails when
an entry point a rule names (a slot, method or `MultiDict_*` C API
function) reaches the rule's helper through any chain of out-of-line
calls; the report shows the chain. The first rules come from the
regressions in #1527, #1530, #1541, #1542, #1554, #1591 and #1604, each
of which slowed a benchmark on code the change never touched. AGENTS.md
now asks agents to run it, to add a rule whenever they fix an inlining
regression or pin a helper, and never to weaken a rule without a
measurement.

CI builds with GCC 13.3. The two rules it failed on master at first
(`md_calc_identity` out of line in `getall()` and `popall()` on
free-threaded builds) were fixed by #1614; master now passes every rule
with GCC 13 and GCC 15 on both builds.

## Are there changes in behavior for the user?

No.

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

No. A PR that moves an inlining decision on purpose edits the matching
rule.

## Related issue number

N/A

## Checklist

- [x] I think the code is well written
- [ ] Unit tests for the changes exist (N/A, a CI-only tool; verified by
reintroducing past regressions, see 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 @asvetlov.

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

Master passes on 3.14.7 and 3.14.7t with GCC 14 and GCC 15.

Each past regression reintroduced by hand was caught:
- dropping `ALWAYS_INLINE` from `htkeysiter_init`: out-of-line copy
reported, plus `md_contains` out of `isdisjoint`
- dropping `NOINLINE` from the view, iterator and shell pool helpers
(#1541/#1542): `md_contains` out of `isdisjoint`
- dropping `NOINLINE` from `_ci_str_to_identity` (#1527): failures
across getitem, getall, replace and `isdisjoint` on both builds

GCC 13.5 (`gcc:13` Docker image): the two failures listed above.
Lint: `pre-commit run` clean; `make doc-spelling` clean.
</details>
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