Repository navigation
Add a watchers C API - #1551
Add a watchers C API#1551
Conversation
Let another C extension be notified when a MultiDict or CIMultiDict changes, following CPython's PyDict_AddWatcher family with two differences. The callback is passed two context pointers: watcher_data, fixed when the callback is registered, and user_data, belonging to one watched multidict. One registered callback can therefore serve any number of multidicts and still know what owns the one that changed. Events are recorded during the mutation and delivered once the operation has finished and every lock on the multidict is released, rather than mid-mutation as CPython does. Several of the update paths run with the table deliberately inconsistent, so calling out to a client there is the shape behind aio-libs#1469 and aio-libs#1489; recording only allocates, which never suspends a critical section. The events are multi-value aware, since add() on a present key is an append rather than a modification and one __setitem__ can both replace a pair and delete several. Each event that concerns a key carries the identity alongside it, already lowercased for a CIMultiDict.
The LOST test arms _testcapi.set_nomemory(), and the harness callback allocates its event tuple like any other client would. When the injected failure lands there, multidict reports it with PyErr_WriteUnraisable, as documented -- but pytest's unraisable plugin then fails the test. Which allocation the counter picks varies by version, so it passed on 3.14t and failed on 3.10 through 3.13. Also keep the arm/call/disarm on one physical line; the formatter had split it, letting a tracer line event take the injected failure.
_testcapi.set_nomemory() installs its hooks with PyMem_SetAllocator(), which writes _PyRuntime's allocator table. On a free-threaded build that races any other live thread calling PyMem_RawFree(), and the CI ThreadSanitizer job caught it against pytest's own faulthandler watchdog thread. Neither stack has a multidict frame. test_no_refleak_on_memory_error already skips free-threading for its own reason; this is the same set_nomemory() restriction.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1551 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 41 41
Lines 7213 7634 +421
Branches 632 641 +9
==========================================
+ Hits 7213 7634 +421
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The capsule has not been released yet, so the watcher entry points can be appended without a version bump; no client can have been built against version 1 without them.
…pi-d08c30 # Conflicts: # multidict/_multilib/state.h
|
This comment has been minimized.
This comment has been minimized.
An event that concerns a key already carries the identity multidict looked it up by; the hash of that identity is in hand at every recording site too, so pass it along. A watcher keeping its own table can then reuse it instead of hashing the key again. Events with no key report -1, which no Python hash ever is.
…pi-d08c30 # Conflicts: # docs/spelling_wordlist.txt
The flush copied the bit mask and user_data once per snapshot, so a callback that unwatched during the first event of a bulk operation still received the rest of that operation, carrying the user_data it had just disowned; a client that freed its context on the unwatch got called back with a dangling pointer. Read both afresh for each event instead, under the object's own critical section, which delivery already runs outside of. Also covers two watchers on one multidict, which had no test.
_md_del_at_for_upd_deferred() reserves before it touches the entry, so the first reservation can fail with the pair still in place. Recording DELETED beforehand told a watcher about a removal that a MemoryError then cancelled. Read the fields before the half-delete nulls them, and record after it reports success; the objects stay alive in the deferred list across the call.
MultiDict_ClearWatcher() leaves the watch bit on every multidict the watcher was watching. The docs said that bit resolves to the empty slot and is skipped, which holds only while the slot stays free: the next MultiDict_AddWatcher() takes the same ID, and those multidicts then report to the new callback with the old user_data, which multidict does not own and cannot keep alive.
…pi-d08c30 # Conflicts: # multidict/_multilib/hashtable.h
|
@aiolibsbot rr |
Both take effect from the next event on, including when called from a callback, which is what lets a client free its user_data on the unwatch. The cost is that a watcher can join or leave part-way through a bulk operation and see one half of its bracket: the docs claimed the brackets always come in pairs, which is true per operation but not per watcher.
Three review findings were answered with a contract rather than code: the reused watcher slot, the batch bracket that pairs per operation and not per watcher, and the appended capsule entry points that need no version bump. Each now says so where the code is, with a pointer to the documented rule.
|
@aiolibsbot rr |
They were inserted next to the ForEach tests, above the Watcher class their signatures annotate, so importing tests/test_capi.py raised NameError everywhere except 3.14, where PEP 649 defers annotation evaluation and hid it locally.
PR Review — Add a watchers C APICareful, well-instrumented feature with one real contract break on an allocation-failure path; everything else is non-blocking. The design work here is genuinely strong and it shows in the details:
One blocking item:
Non-blocking:
🟡 Important
1. popall() can emit BATCH_BEGIN with no BATCH_END
|
Rebase with requested adjustmentsBranch Warning Force-push safety check — the rewrite of Commits whose patch changed in-flight and whose content could not be verified as preserved — check these survived:
Previous PR head: Changes applied
StatsActions performed
CI statusCI will be checked asynchronously. Automated by Kōan |
<!-- Thank you for your contribution! --> ## What do these changes do? Raises `MULTIDICT_MAX_WATCHERS` from 8 to 32. The occupancy mask becomes a `uint32_t`. Two changes keep the higher limit from costing anything: - Delivery walks only the set bits of the mask, using ctz. Previously it scanned every slot and copied the whole `user_data` array once per event, which would have made each event cost more at 32 slots. - The per-multidict record sizes `user_data` to one past the highest watcher ID that multidict was watched through, and grows with `PyMem_Realloc` when needed. Every access to `md->watch` happens under the multidict's critical section or in dealloc, so moving the record is safe. `md_watch_detach` now ignores an ID beyond the record. C extension only; the watchers API has no pure-Python counterpart. ## Are there changes in behavior for the user? Up to 32 watchers can be registered at a time instead of 8. Watchers are not in a release yet, so nothing shipped changes. ## Is it a substantial burden for the maintainers to support this? No. The change stays inside `watch.h`, plus the constant and the docs. ## Related issue number Follow-up to #1551. ## 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, no such file in this repo) - [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> Callgrind instruction counts on CPython 3.14.7 (GIL). The free-threaded build shows the same pattern. | | master (8, fixed) | 32, fixed array | this PR (32, sized record) | |---|---|---|---| | one event, watcher in slot 0 | 7599 | 7738 | 7537 | | one event, watcher in the top slot | 7729 | 8372 | 7520 | | one event, 8 watchers | 39513 | 39652 | 39598 | | unwatched `md[k] = v` | 1654 | 1654 | 1654 | | create, watch via slot 0, one event, dealloc | 12132 | 12152 | 12139 | | memory per multidict watched via slot 0 | 105 B | 297 B | 49 B | | memory per multidict watched via the top slot | 105 B | 297 B | 297 B | The "32, fixed array" column is the constant bumped with the old scan and memcpy. It is shown to explain the delivery change. The slowest case is attaching every ID to one multidict in turn, one realloc each: +5% against a fixed 32-slot array. Full registry (`benchmarks/callgrind_driver.py --include-multidict-only`), GIL build: 50 of 52 C cells unchanged. `clear` moved by +32 Ir. That comes from glibc heap layout: padding the heap moves the unchanged base build by the same amount. The free-threaded registry was not usable as a comparison on this machine, since a base-against-base control moved 33 of 52 cells by more than 1%. Sweep of the fixed-array layout: per-event cost is flat from 8 to 64 slots once delivery walks set bits. At 64 slots the record is 553 B, above pymalloc's 512-byte limit. Tests: - 3.14.7 release build with `MULTIDICT_TEST_REQUIRE_CYAPI=1`: 2841 passed. - 3.10.17: 2696 passed. - 3.14.7t: 2683 passed. - Pure Python (`MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`): 1272 passed. - ASan + UBSan with `MULTIDICT_NO_FREELIST=1`: 2829 passed. - The new `test_every_watcher_slot_gets_its_own_events` fails when the mask is left as `uint8_t`. `make doc-spelling` passes. </details> Drafted with Claude Code (Claude Opus 5.5); reviewed by @asvetlov.
) <!-- Thank you for your contribution! --> ## What do these changes do? `MultiDict_AddWatcher()` and `MultiDict_ClearWatcher()` wrote the module-wide slot table with plain stores, while event delivery on another thread read it with no lock. On the free-threaded build that is a data race, and TSan reports it at `watch.h` against both functions. Registration now serializes on a `PyMutex` and publishes through new `freethreading.h` accessors, following CPython's `PyDict_AddWatcher()`. Delivery stays lock-free. `ClearWatcher()` also bumps a per-slot generation, and each watch records the generation it was attached under. A multidict left watched through a cleared ID used to report to the next registration under that ID, passing the old registration's `user_data`. That bit is now ignored until the multidict is watched again. CPython's dict watchers still have the same reuse hazard; the heap-allocated per-multidict record makes it cheap to close here. This only affects the C extension: watchers are a C API feature and have no pure-Python counterpart. ## Are there changes in behavior for the user? Yes, for C API clients only. Both registration functions are now safe to call from any thread, and a cleared watcher's leftover watches no longer reach a later registration that reuses its ID. The docs drop the warning about that reuse. ## Is it a substantial burden for the maintainers to support this? No. The mutation hot path is unchanged: an unwatched multidict still pays one pointer test per mutation. ## Related issue number Follow-up to #1551 and #1574. ## 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` Drafted with Claude Code (Claude Opus 5.5); to be reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Each leg ran in its own venv and tree copy. - GIL 3.14.7: 2727 passed, 169 skipped - Free-threaded 3.14.7t, `MULTIDICT_DEBUG_BUILD=1`, Cython harness required: 2860 passed, 37 skipped - GIL 3.10.17: 2727 passed, 169 skipped - Pure Python 3.14.7, `MULTIDICT_NO_EXTENSIONS=1 --no-c-extensions`: 1282 passed - ASan+UBSan, `MULTIDICT_NO_FREELIST=1`, `PYTHONMALLOC=malloc`, `tests/test_capi.py`: 139 passed, no reports - TSan (3.14.7t-tsan), `-k "churn or reused"`: two data races on the slot table with the old C code, none with this change - Both new tests fail against the old C code and pass with this change - pre-commit on the changed files and `make doc-spelling`: pass </details>
<!-- Thank you for your contribution! --> ## What do these changes do? A failing watcher callback is now reported the way CPython's `_PyDict_SendEvent()` reports a failing dict watcher. The message names the event and the multidict's type and address, for example `Exception ignored in MultiDict_EVENT_ADDED watcher callback for <multidict._multidict.MultiDict object at 0x...>`, and the multidict itself is no longer passed to `sys.unraisablehook`. Previously every event except DEALLOCATED passed the multidict, so the default hook would `repr()` it and could run arbitrary code (a subclass `__repr__`) while an error was being reported. On 3.13+ this uses `PyErr_FormatUnraisable()`. On 3.10 to 3.12, which lack it, it uses `_PyErr_WriteUnraisableMsg()`, and the address is formatted with `PRIxPTR` because MSVC's `%p` omits the `0x`. This only affects the C extension: watchers have no pure-Python counterpart. ## Are there changes in behavior for the user? Yes, for C API clients whose watcher callbacks fail: `sys.unraisablehook` now receives `object=None` and a descriptive `err_msg`. ## Is it a substantial burden for the maintainers to support this? No. It is one cold function with a version branch. ## Related issue number Follow-up to #1551. ## 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` Drafted with Claude Code (Claude Opus 5.5); to be reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> Each leg ran in its own venv and tree copy. - GIL 3.14.7: 2734 passed - Free-threaded 3.14.7t, `MULTIDICT_DEBUG_BUILD=1`, Cython harness required: 2866 passed - GIL 3.10.17 (covers the `_PyErr_WriteUnraisableMsg()` branch): 2734 passed - Pure Python 3.14.7, `--no-c-extensions`: 1286 passed - pre-commit on the changed files and `make doc-spelling`: pass This touches `_md_watch_call()` in `watch.h`, as #1583 does, so whichever lands second needs a small rebase. </details>
<!-- Thank you for your contribution! --> ## What do these changes do? Adds an "Invalidating a cache" example to `docs/capi.rst`, after the existing watcher example. It shows the pattern CPython's JIT uses for a module's globals: the callback clears the cache and unwatches itself, the next rebuild watches again, and after a fixed number of rebuild attempts the cache stops trying on a multidict that keeps changing. An event goes to whoever is watching when the operation finishes, so it can reach a rebuild that already saw its change, under the GIL too once `parse()` runs Python code. The cache therefore records the version it was built from: the callback discards only a cache the multidict has moved past, and never unwatches while a rebuild owns the watch. On the free-threaded build the fields also need a lock, which sits behind `Py_GIL_DISABLED`, so one source serves both builds and works back to 3.10. Bare BATCH brackets are ignored, and a failed parse stops listening. ## Are there changes in behavior for the user? No, documentation only. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number Follow-up to #1551. ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, documentation only) - [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); to be reviewed by @asvetlov. <details> <summary>Agent run details (optional, for reviewers)</summary> The example code is extracted verbatim from `docs/capi.rst` into a small extension (stubs only for `my_mod_state` and `parse()`), built with `-Wall -Wextra -Werror -std=c11` against the installed `multidict_capi.h` for 3.14.7, 3.14.7t and 3.10.17. - Behaviour tests on all three builds, 5 passed: the cache holds until a change; empty `update()`/`extend()`/`merge()` and self-update keep it; a failed parse leaves no watch; a parse that mutates every time hits the limit of 8 and then receives no further events; concurrent writers never leave it stale. - Stress, cap lifted, 60 s each, 3 readers against 1 writer, checking at quiescence that the cache matches the multidict and that the next change clears it: GIL 3.14 309 rounds, free-threaded 3.14t 2889 rounds, GIL 3.10 1689 rounds, 0 failures. The previous revision failed this (2 of 8297 rounds left a stale value that no watch would clear). - `make doc-spelling` and pre-commit: pass </details>
<!-- Thank you for your contribution! --> ## What do these changes do? Prepares the news fragments for 7.0.0. The public C API (#1480) and the watchers API (#1551) are new in this release, so the fragments describing later changes to them describe states that never shipped. They are folded into the entries that added the APIs: the visitor's identity and hash (#1552, #1561) into `1478`, and the 32-watcher limit, the watcher registration race fix and the failing-callback report (#1574, #1583, #1585) into `1551`. The `MultiDict_SetDefault(NULL)` half of `1553` is dropped for the same reason. Intermediate header names that never shipped are removed as well: `1510` no longer mentions `deferred_decref.h`, which #1530 merged into `reflist.h`, and `1513` names `debug.h` directly, so `1576` goes. `1572`, a fix to a tool added this cycle, is folded into `1529`. `1560` and the last sentence of `1556` go too, since the release refresh of the benchmark tables supersedes those intermediate ones. Finally, the fragments that did not lead with a past-tense verb or described the change as "now ..." are rewritten per `AGENTS.md`. The benchmark table refresh from `RELEASE.md` step 2 is still to be added to this branch before it leaves draft. ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number N/A ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, changelog only) - [x] 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 (N/A, edits existing fragments; the benchmark refresh will add a `doc` fragment) - [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); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> `python -Im towncrier build --draft --version 7.0.0` renders cleanly. The symlinked pairs `1512` -> `1492` and `1562` -> `1555`, and both `1535` fragments, are intentional and left alone. </details>
<!-- Thank you for your contribution! --> ## What do these changes do? Finishes the 7.0.0 changelog and refreshes the benchmark tables, the part of #1597 that did not make it in before it merged. The four PRs that followed the bisect fix slowdowns introduced earlier in this cycle, so they are folded into the entries whose changes they amend rather than listed as speedups over 6.9.1. `1599` (one thread-local version counter) becomes a symlink to `1587`. `1598` (references in `update()` only when `lower()` can run code) becomes a symlink to `1581`, which now says the extra references are limited to those keys. `1600` and `1601` (out-of-line slot operations and insert-path resize) merge into one `1600` entry with `1601` symlinked to it. Towncrier lists both numbers under each merged entry. The tables in `docs/benchmark.rst` are refreshed per `RELEASE.md` step 2, collected at d66879b. Against the previous tables (6e6ac72), `for k, v in d.items()` needs 58% to 66% fewer instructions on both builds, `popitem()` 34% to 54% fewer, and `CIMultiDict` lookups 15% to 39% fewer; free-threaded `update()` got 8% to 13% cheaper. Three case-sensitive `MultiDict` rows stay 5% to 6% above the old tables: `del d[key]` on the GIL build (the watcher check from #1551, still open), and 20-item construction and `pop()` on the free-threaded build. The README and docs index quoted the pure-Python backend at "7 to 80 times" the C extension, a range that already left out the empty constructor at 105 times; they now give the average, about 40 times (geometric mean over the 20 operations: 38.5x `MultiDict`, 36.8x `CIMultiDict`). ## Are there changes in behavior for the user? No. ## Is it a substantial burden for the maintainers to support this? No. ## Related issue number Follow-up to #1597. ## Checklist - [x] I think the code is well written - [ ] Unit tests for the changes exist (N/A, docs and changelog only) - [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); pending review by @asvetlov before leaving draft. <details> <summary>Agent run details (optional, for reviewers)</summary> Benchmarks: `benchmarks/callgrind_driver.py` on CPython 3.14.7 and 3.14.7t, fresh venv per build in a separate tree at d66879b, `__pycache__` warmed with `--self-check`, `.so` timestamps checked. The previous tables' commit 6e6ac72, re-measured earlier today in the same setup, reproduced them exactly, so the comparison above is between code, not environments. Changelog: `python -Im towncrier build --draft --version 7.0.0` renders the merged entries with both issue numbers. `make doc-spelling` passes. </details>
<!-- Thank you for your contribution! --> ## 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 - [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 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. </details>
What do these changes do?
Add a watchers C API, so another C extension can be notified when a
MultiDictorCIMultiDictchanges. It follows CPython'sPyDict_AddWatcherfamily, with two deliberate differences.The callback gets two context pointers:
watcher_data, fixed when thecallback is registered, and
user_data, belonging to one watchedmultidict. That is the point of the API: one registered callback can serve
any number of multidicts and still know, on every event, what owns the one
that changed. CPython does not need this because its dict watchers are
static functions inside the interpreter.
Events are delivered after the operation finishes, not mid-mutation.
Several of the update paths run with the table deliberately inconsistent
(
_md_del_at_for_upd_deferredleaves an entry half-deleted but stillreachable until
md_post_updatesweeps it, and_md_replace/_md_updatecarry a
reflist_tof not-yet-decref'd objects), so calling out to aclient there is the shape behind #1469 and #1489. Events are recorded into
a per-multidict log instead, which only allocates, and delivered once the
critical section is released.
The events are multi-value aware, since
add()on a key that is alreadypresent is an append rather than a modification, and one
__setitem__canboth replace a pair and delete several. Each event that concerns a key
carries the identity alongside it, already lowercased for a
CIMultiDict,so a watcher matching
"content-length"needs nolower()of its own, andthe identity's hash with it, so a watcher keeping its own table does not
have to hash the key again.
C-extension only, like the rest of the capsule API:
_multidict_py.pyand_abc.pyare untouched, andtests/test_capi.pyskips on the pure-Pythonleg as it already does.
MultiDict_CAPI_VERSIONstays at 1: version 1 has not shipped, since 7.0is unreleased, so no client can exist that was built against a capsule
without these entry points.
One thing a reviewer may want to overrule:
MultiDictObjectgrows one pointer,md_watch_t *watch, NULL until thefirst
MultiDict_Watch().tp_basicsizegoes 56 to 64 on GIL 3.12+, 64to 72 on 3.10/3.11 and 88 to 96 free-threaded, but what the allocator
reserves is what actually costs. Measured as RSS over a million empty
multidicts:
tp_basicsizeSo only 3.10 and 3.11 pay, and they pay 16 rather than 8: pymalloc's
size classes are 16 bytes apart, and those are the versions that still
carry an explicit
weaklistpointer, which puts the object on a classboundary. Everywhere else the rounding absorbs it.
The alternative (an occupancy bitmask in the existing padding after
is_ci, which is free, plus a side table inmod_state) saves those 16bytes on two versions, at the price of a keyed lookup at every recording
site and, on free-threaded builds, a lock over globally shared state
taken inside the per-object critical section.
Are there changes in behavior for the user?
No. Nothing fires until a client registers a watcher and watches a
multidict, and no Python-level API changes.
Is it a substantial burden for the maintainers to support this?
The four entry points are small and the event set is fixed. The ongoing
cost is that every new mutation path has to record its events; a debug
build asserts the log is empty at dealloc, which catches a missed flush.
Related issue number
N/A
Checklist
CONTRIBUTORS.txt— N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted with Claude Opus 5 (Claude Code); reviewed by @asvetlov.
Agent run details (optional, for reviewers)
Branched from
9682ba1, withupstream/mastermerged in at7b84e1b.Everything below was re-run on the merge commit.
Tests, all green:
MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest -q— 2793 passed, 35 skippedMULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions— 1272 passed, 11 skippedMULTIDICT_DEBUG_BUILD=1 MULTIDICT_ASAN_BUILD=1,LD_PRELOAD=libasan.so ASAN_OPTIONS=detect_leaks=0 PYTHONMALLOC=malloc python -m pytest tests -q -k "not test_leak"— 2637 passed, no reports(add/setitem/extend/update/popall/getall in a loop) delivers 47,987 events
with zero ThreadSanitizer reports, and
tests/test_capi.pygives 126 passed,also with zero reports. The whole suite was run under TSan before the merge
and was clean apart from two pure-Python deadlock tests,
test_pure_python_reciprocal_view_ops_no_deadlockandtest_pure_python_reciprocal_raw_iterator_ops_no_deadlock, which fail thesame way on the base commit: they exercise
_multidict_py.py, which thisbranch does not touch, and TSan's slowdown trips their 40-second timeout.
make doc-spelling,make lint(full pre-commit) — passPerf, callgrind on GIL 3.13.2 with
PYTHONHASHSEED=0,__pycache__warmedfirst, 2000 iterations over 16 keys per case, base and head each built from a
clean
git archiveof its own commit.delitemis the one row thehashfield moved, from +0.21% to +0.31%, about six instructions per delete at the
recording site even though the multidict is not watched:
tools/codegen_diff.py --ref 7b84e1b, with a--probetranslation unitwrapping the always-inlined helpers, agrees:
md_get_one,md_containsandmd_lendo not appear in the report at all, andmd_get_allis 535 -> 535instructions with call targets unchanged. The read paths get no call. The
write paths gain one
UNLIKELYpointer test per mutation site, branching to aCOLDrecorder, plus onemd_watch_pending()read inside the criticalsection each mutator already holds.
Before the merge, CodSpeed reported one regression on this branch,
test_multidict_extend_str[cs-c]at -9.51%, with the other 309 benchmarksunchanged. I do not think it was real, and here is why rather than just
asserting it:
That comparison crossed a CPU vendor change, AMD EPYC 7763 to Intel
Xeon 6973P-C. CodSpeed's Simulation mode derives its cache model from
the physical CPU, so the estimate moves on identical source.
The control says the same: comparing two commits of this branch that
differ only in test files, with no C change at all (
4a357c7->66367ff), CodSpeed reports 310 unchanged and zero regressions, andtest_multidict_extend_str[cs-c]is flat there despite also beinglisted under a CPU difference.
The three sibling extend benchmarks CodSpeed calls unchanged are the
tell: a real 9.5% regression in
extend()would move all four. Runlocally under callgrind, reproducing each benchmark body exactly:
MultiDict[cs-c]CIMultiDict[ci-c][cs-c]with kwargs[ci-c]with kwargsThe one CodSpeed flagged measures +0.50% here, not -9.51%.