Skip to content

Add a watchers C API - #1551

Merged
asvetlov merged 15 commits into
aio-libs:masterfrom
asvetlov:claude/watchers-api-d08c30
Sep 24, 2026
Merged

asvetlov merged 15 commits into
aio-libs:masterfrom
asvetlov:claude/watchers-api-d08c30

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

What do these changes do?

Add a watchers C API, so another C extension can be notified when a
MultiDict or CIMultiDict changes. It follows CPython's
PyDict_AddWatcher family, with two deliberate differences.

The callback gets two context pointers: watcher_data, fixed when the
callback is registered, and user_data, belonging to one watched
multidict. 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_deferred leaves an entry half-deleted but still
reachable until md_post_update sweeps it, and _md_replace/_md_update
carry a reflist_t of not-yet-decref'd objects), so calling out to a
client 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 already
present 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,
so a watcher matching "content-length" needs no lower() of its own, and
the 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.py and
_abc.py are untouched, and tests/test_capi.py skips on the pure-Python
leg as it already does.

MultiDict_CAPI_VERSION stays at 1: version 1 has not shipped, since 7.0
is unreleased, so no client can exist that was built against a capsule
without these entry points.

One thing a reviewer may want to overrule:

  • MultiDictObject grows one pointer, md_watch_t *watch, NULL until the
    first MultiDict_Watch(). tp_basicsize goes 56 to 64 on GIL 3.12+, 64
    to 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:

    build tp_basicsize bytes per instance
    3.10.17 64 -> 72 80.4 -> 96.4
    3.11.13 64 -> 72 80.4 -> 96.2
    3.13.2 56 -> 64 96.2 -> 96.4
    3.14.7t 88 -> 96 112.1 -> 112.1

    So 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 weaklist pointer, which puts the object on a class
    boundary. 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 in mod_state) saves those 16
    bytes 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

  • 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, no such file in this repo
  • 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 Opus 5 (Claude Code); reviewed by @asvetlov.

Agent run details (optional, for reviewers)

Branched from 9682ba1, with upstream/master merged in at 7b84e1b.
Everything below was re-run on the merge commit.

Tests, all green:

  • C extension, 3.14t, MULTIDICT_TEST_REQUIRE_CYAPI=1 pytest -q — 2793 passed, 35 skipped
  • Pure Python, MULTIDICT_NO_EXTENSIONS=1 pytest -q --no-c-extensions — 1272 passed, 11 skipped
  • ASan + UBSan on GIL 3.13.2, MULTIDICT_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
  • TSan on 3.14.7t-tsan: an 8-thread stress of a watched multidict
    (add/setitem/extend/update/popall/getall in a loop) delivers 47,987 events
    with zero ThreadSanitizer reports, and tests/test_capi.py gives 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_deadlock and
    test_pure_python_reciprocal_raw_iterator_ops_no_deadlock, which fail the
    same way on the base commit: they exercise _multidict_py.py, which this
    branch does not touch, and TSan's slowdown trips their 40-second timeout.
  • make doc-spelling, make lint (full pre-commit) — pass

Perf, callgrind on GIL 3.13.2 with PYTHONHASHSEED=0, __pycache__ warmed
first, 2000 iterations over 16 keys per case, base and head each built from a
clean git archive of its own commit. delitem is the one row the hash
field moved, from +0.21% to +0.31%, about six instructions per delete at the
recording site even though the multidict is not watched:

case base Ir head Ir delta
ctor 156,514,577 156,623,555 +0.07%
getitem 161,482,936 161,486,000 +0.00%
contains 160,617,767 160,620,968 +0.00%
getall 188,679,273 188,650,405 -0.02%
add 174,618,041 174,822,990 +0.12%
setitem 193,751,920 193,872,931 +0.06%
extend 157,940,969 158,070,000 +0.08%
update 188,320,260 188,573,291 +0.13%
delitem 187,412,355 187,991,366 +0.31%
iterate 149,685,057 149,687,945 +0.00%

tools/codegen_diff.py --ref 7b84e1b, with a --probe translation unit
wrapping the always-inlined helpers, agrees: md_get_one, md_contains and
md_len do not appear in the report at all, and md_get_all is 535 -> 535
instructions with call targets unchanged. The read paths get no call. The
write paths gain one UNLIKELY pointer test per mutation site, branching to a
COLD recorder, plus one md_watch_pending() read inside the critical
section 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 benchmarks
unchanged. 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, and
    test_multidict_extend_str[cs-c] is flat there despite also being
    listed 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. Run
    locally under callgrind, reproducing each benchmark body exactly:

    extend variant base Ir head Ir delta
    MultiDict [cs-c] 251,327,159 252,576,459 +0.50%
    CIMultiDict [ci-c] 281,511,710 282,361,010 +0.30%
    [cs-c] with kwargs 320,532,998 322,408,298 +0.59%
    [ci-c] with kwargs 366,117,561 367,392,861 +0.35%

    The one CodSpeed flagged measures +0.50% here, not -9.51%.

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.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/watchers-api-d08c30 (6154cfb) with master (9d97ce5)

Open in CodSpeed

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

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (53690d2) to head (6154cfb).
⚠️ Report is 3 commits behind head on master.

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     
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.

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
@asvetlov
asvetlov marked this pull request as ready for review September 24, 2026 09:51
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 24, 2026 09:51
@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

Do not merge while the two open watcher issues remain: callbacks can receive an unmatched batch end, and deallocation callbacks can pass a refcount-zero object to MultiDict_Watch.

Reviews (7) · Last reviewed commit: "Move the two callback tests into the wat..."

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

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
Comment thread multidict/multidict_capi_struct.h Resolved
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
@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

Comment thread multidict/_multilib/watch.h Resolved
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.
Comment thread multidict/_testcyapi.pyx Resolved
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.
@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

Comment thread tests/test_capi.py Resolved
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.
@aiolibsbot

aiolibsbot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

PR Review — Add a watchers C API

Careful, 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:

  • Deferring delivery into a per-object log instead of calling out mid-mutation is the right call, and the reasoning is tied to specific hazards (_md_del_at_for_upd_deferred leaving an entry half-deleted, _md_replace carrying an undrained reflist_t) rather than asserted in the abstract.
  • md_watch_flush()'s PyErr_Fetch/PyErr_Restore around delivery is exactly right, and test_a_failing_operation_keeps_its_own_exception pins the behaviour. I checked whether the modern PyErr_GetRaisedException pair was available instead — the vendored pythoncapi_compat.h does not ship it, so PyErr_Fetch is the correct portable choice here.
  • Ordering md_watch_on_dealloc() before Py_TRASHCAN_BEGIN and NULLing md->watch first is a subtle trashcan-reentry case handled correctly, and the comment explains why.
  • Recording after the mutation succeeds in _md_update (the gone_identity/gone_key/gone_value reads) closes the "DELETED for an entry that is still there" window; the earlier automated findings on stale watch bits and unwatch-during-delivery are both genuinely resolved by re-reading recipients per event in _md_watch_deliver.
  • I traced every mutation entry point and every Py_BEGIN_CRITICAL_SECTION in _multidict.c and hashtable.h: the record/flush pairing is complete, and fresh objects (tp_new, _multidict_vectorcall_impl, multidict_copy) correctly record nothing because _md_shell_alloc() zeroes the recycled shell.

One blocking item:

  • 🟡 _md_pop_all_locked() (hashtable.h:1590) returns -1 on reflist_push() failure after BATCH_BEGIN has already been recorded, delivering an unmatched bracket. docs/capi.rst promises pairing, and the overflowed/EVENT_LOST fallback does not necessarily cover it, so a watcher that rebuilds on BATCH_END can be left permanently stale. Fix is one line, or move the bracket out to md_pop_all() the way md_replace() does.

Non-blocking:

  • A callback that mutates on every event recurses on the C stack with no Python frame, so it crashes rather than raising RecursionError; Py_EnterRecursiveCall would fix it.
  • The ClearWatcher slot-reuse hazard is documented rather than fixed. Fair, and CPython does the same, but multidict's version hands the old client's user_data to the new callback; a per-slot generation byte in the already-heap-allocated md_watch_t would close it for free.
  • md_watch_t.bits is uint8_t with no static assertion tying it to MULTIDICT_MAX_WATCHERS; a future bump silently no-ops watchers 8-15.
  • docs/cyapi.rst's register() example references an undefined state and casts a Python object to void* without keeping it alive.
  • Duplicate MultiDict_EVENT_ADDED cimport in _testcyapi.pyx; test_cython_trampoline_reports_a_raising_callback takes an unused api fixture and so runs twice identically.
  • Structural: the BATCH_BEGIN/END/md_watch_pending trio is now copy-pasted across 18 branches in _multidict.c, where a missed line fails silently in release builds; __sizeof__ omits the watch record; the 560-line watchers block in test_capi.py would split cleanly.

🟡 Important

1. popall() can emit BATCH_BEGIN with no BATCH_END
multidict/_multilib/hashtable.h:1590-1599

_md_pop_all_locked() has one failure exit inside the match loop, and it sits after the point where the bracket has already been opened.

Sequence: first match pushes fine, sets batched = true, records BATCH_BEGIN + DELETED. On the second match reflist_push() fails (allocation failure) and the function return -1s directly, skipping the if (batched) md_watch_record_simple(md, BATCH_END) at line 1617.

md_pop_all() then reads flush = md_watch_pending(md) (true) and delivers the log, so the watcher receives BATCH_BEGIN, DELETED and never the matching end. docs/capi.rst promises the opposite under MultiDict_EVENT_BATCH_BEGIN: "An operation that emits one emits both", with the only documented exception being a watcher that joins or leaves mid-bracket. A client that defers its rebuild until BATCH_END — exactly the usage the docs recommend — is then stuck holding stale derived state indefinitely, long after the memory pressure has passed.

This is not covered by the overflowed/EVENT_LOST escape hatch either: reflist_push()'s reservation can fail while the current 63-slot watchlog block still has room, so no LOST is emitted to force a resynchronize.

Every other multi-event path already gets this right — _md_del_locked() has no failure exit in its loop, md_replace() brackets outside _md_replace(), and md_post_update() always records the end. Two ways to match them:

  • record BATCH_END on the error path before return -1; or
  • move the bracket out to md_pop_all() around the _md_pop_all_locked() call, the way md_replace() does, so no early return inside can unbalance it.

The second is the sturdier one: it makes the invariant structural rather than something each return has to remember.

        if (_str_cmp(identity, entry->identity)) {
            if (reflist_push(values, Py_NewRef(entry->value)) < 0) {
                return -1;
            }
            uint64_t version = next_version(md->state);
            store_version(md, version);
            if (!batched) {
                batched = true;
                md_watch_record_simple(md, MultiDict_EVENT_BATCH_BEGIN);
            }

🟢 Suggestions

2. A mutating callback recurses on the C stack until it segfaults
multidict/_multilib/watch.h:142-166

docs/capi.rst says a callback that mutates on every event "will not terminate". Reading the code, the failure mode is harsher than non-termination: it is unbounded C recursion.

Each round is md_add() -> md_watch_flush() -> _md_watch_deliver() -> _md_watch_call() -> client callback -> MultiDict_Add() -> md_add(). Because the callback is a C function, no Python frame is pushed, so nothing in the interpreter's recursion accounting ever fires. The process dies with a stack overflow rather than a RecursionError.

That is a rough edge for a public C API whose whole point is to hand control to third-party code: a client bug that would be a clean traceback with dict watchers becomes a crash with no diagnostic here.

Wrapping the callback invocation in Py_EnterRecursiveCall() / Py_LeaveRecursiveCall() (which counts C-level recursion via c_recursion_remaining) turns it into a normal RecursionError, reported through the existing PyErr_WriteUnraisable() path. Cheap, and it only costs anything on the already-COLD delivery path.

If you'd rather keep it out of the hot-ish delivery loop, a depth counter in md_watch_t bailing out past some small bound would do the same job.

COLD static void
md_watch_flush(MultiDictObject* md)
{
    /* Several callers flush on their failure path too, so an exception
       can already be in flight here. Park it: otherwise the first
       callback would be blamed for it below, and reporting it as
       unraisable would clear the one the caller is about to return. */
    PyObject *exc_type, *exc_value, *exc_tb;
    PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
    for (;;) {
        watchlog_t snapshot;
        bool taken = false;
        Py_BEGIN_CRITICAL_SECTION(md);
        if (md->watch != NULL && !watchlog_empty(&md->watch->log)) {
            watchlog_take(&md->watch->log, &snapshot);
            taken = true;
        }
        Py_END_CRITICAL_SECTION();
        if (!taken) {
            break;
        }
        _md_watch_deliver(md, &snapshot);
    }
    PyErr_Restore(exc_type, exc_value, exc_tb);
}
3. `bits` silently truncates if MULTIDICT_MAX_WATCHERS ever grows
multidict/_multilib/watch.h:29-33

bits is a uint8_t while the slot count lives in a separate macro in multidict_capi_struct.h. The two are only coupled by the comment above them.

Raising MULTIDICT_MAX_WATCHERS to, say, 16 compiles clean and produces a quietly broken build: md_watch_attach()'s (uint8_t)(1u << watcher_id) becomes 0 for ids 8-15, so those watchers are registered, accept a MultiDict_Watch() that returns 0, and then never fire. A silent no-op is the worst shape for that bug to take.

A one-line static_assert(MULTIDICT_MAX_WATCHERS <= 8, "md_watch_t.bits is uint8_t") next to the struct turns it into a compile error. (_multilib/ already targets C11 via <stdbool.h>/<stdint.h>; if static_assert is awkward across the supported compilers, the usual negative-array-size trick works too.)

struct _md_watch {
    uint8_t bits;
    void* user_data[MULTIDICT_MAX_WATCHERS];
    watchlog_t log;
};
4. The Cython `register()` example does not compile as written
docs/cyapi.rst:268-274

Two problems in the snippet readers are most likely to copy:

  • <void*>state references a name that appears nowhere in the example. Every other identifier in the block (_ctx, on_change, _capi) is defined or conventional; state is not. Either define it above or use NULL, since the example's on_change never reads watcher_data.

  • <void*>ctx_object hands a borrowed pointer to a Python object straight to MultiDict_Watch() and then returns, at which point ctx_object may be the caller's only reference. docs/capi.rst spells out that multidict holds no reference and the pointer must outlive the watch, but this example is where a Cython user will actually start, and it demonstrates the unsafe shape without the caveat. multidict/_testcyapi.pyx gets this right with its _watch_refs list; one line of the same here (or a sentence pointing at the rule) would keep the example honest.

Worth fixing because MultiDict_Watch's lifetime contract is the sharpest edge in the whole API, and this is the snippet that teaches it.

   def register(md, ctx_object):
       _ctx.callback = on_change
       _ctx.watcher_data = <void*>state
       cdef int watcher_id = MultiDict_AddCyWatcher(_capi, &_ctx)
       MultiDict_Watch(_capi, watcher_id, md, <void*>ctx_object)
5. The same six-line watch preamble is now copy-pasted across 18 branches
multidict/_multidict.c:744-790

multidict_tp_init, cimultidict_tp_init, multidict_extend, multidict_update and multidict_merge each have the same three-way critical-section dispatch, and this change adds the identical md_watch_record_simple(self, BATCH_BEGIN) / ... BATCH_END / flush = md_watch_pending(self) trio to every arm — roughly 18 near-identical insertions.

The pre-existing triplication is not this PR's doing, but the diff multiplies its cost, and the failure mode is silent: omit flush = md_watch_pending(self) from one arm and that arm's events sit in the log until the next mutation flushes them, or until the debug-only assert(watchlog_empty(...)) in md_watch_on_dealloc() fires in a build most people never run. Release builds would just deliver events late.

A pair of macros would make the omission impossible to write:

#define MD_WATCH_BATCH_BEGIN(md) md_watch_record_simple((md), MultiDict_EVENT_BATCH_BEGIN)
#define MD_WATCH_BATCH_END(md, flush)            \
    do {                                         \
        md_watch_record_simple((md), MultiDict_EVENT_BATCH_END); \
        (flush) = md_watch_pending(md);          \
    } while (0)

That is the minimal version. The more ambitious reframing — collapsing the three Py_BEGIN_CRITICAL_SECTION / ..._SECTION2 arms into one helper parameterised by UpdateOp and the source kind — would delete the triplication outright rather than papering over it, and is what actually stops the next feature from paying this tax again. Out of scope here, but worth naming as the direction.

        Py_BEGIN_CRITICAL_SECTION2(self, other);
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_BEGIN);
        ret = md_init(self, false, size);
        if (ret == 0) {
            ret = md_update_from_ht(self, other, Extend, NULL, NULL);
            if (ret == 0 && kwds != NULL) {
                ret = md_update_from_dict(self, kwds, Extend, NULL, NULL);
            }
            ASSERT_CONSISTENT(self, false);
        }
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_END);
        flush = md_watch_pending(self);
        Py_END_CRITICAL_SECTION2();
    } else if (arg_is_dict) {
        Py_BEGIN_CRITICAL_SECTION2(self, arg);
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_BEGIN);
        ret = md_init(self, false, size);
        if (ret == 0) {
            ret = md_update_from_dict(self, arg, Extend, NULL, NULL);
            if (ret == 0 && kwds != NULL) {
                ret = md_update_from_dict(self, kwds, Extend, NULL, NULL);
            }
            ASSERT_CONSISTENT(self, false);
        }
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_END);
        flush = md_watch_pending(self);
        Py_END_CRITICAL_SECTION2();
    } else {
        Py_BEGIN_CRITICAL_SECTION(self);
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_BEGIN);
        ret = md_init(self, false, size);
        if (ret == 0) {
            if (other != NULL) {
                ret = md_extend_self(self);
            } else if (arg != NULL) {
                ret = md_update_from_seq(self, arg, Extend, NULL, NULL);
            }
            if (ret == 0 && kwds != NULL) {
                ret = md_update_from_dict(self, kwds, Extend, NULL, NULL);
            }
            ASSERT_CONSISTENT(self, false);
        }
        md_watch_record_simple(self, MultiDict_EVENT_BATCH_END);
        flush = md_watch_pending(self);
        Py_END_CRITICAL_SECTION();
    }
    md_watch_flush_if(self, flush);
6. __sizeof__ does not account for the watch record
multidict/_multidict.c:1305-1319

multidict_sizeof() reports sizeof(MultiDictObject) plus the key table. A watched multidict additionally owns a heap-allocated md_watch_t (~80 bytes: bits plus eight void* plus the log header) and, transiently, one or more watchlog_block_t blocks at roughly 40 bytes times 63 entries each.

None of that shows up in sys.getsizeof(), so a process tracking multidict memory through __sizeof__ under-reports a watched instance. Given how carefully the PR description accounts for the eight-byte tp_basicsize growth, the heap allocation that only watched instances pay seems like the one worth surfacing.

Adding if (self->watch != NULL) size += sizeof(md_watch_t); inside the existing critical section covers the fixed part; walking the log blocks is optional since they are short-lived.

    Py_ssize_t size = sizeof(MultiDictObject);
    Py_BEGIN_CRITICAL_SECTION(self);
    htkeys_t* keys = self->keys;

Checklist

  • Documented event contract (batch pairing) holds on all paths — warning #1
  • Every mutation entry point records and flushes its events
  • No unflushed log survives to dealloc (debug assert holds)
  • Exception state preserved across delivery on failure paths
  • Callbacks never run under a critical section
  • Reentrancy from a callback is bounded — suggestion #2
  • Client-owned pointer lifetimes are safe or documented — suggestion #4
  • Refcounting correct on the DEALLOCATED path (C and Cython)
  • Free-threaded builds: watch state read/written under the object lock
  • Allocation failure during recording cannot fail the mutation
  • Compile-time invariants asserted — suggestion #3
  • Public docs compile-correct and complete — suggestion #4
  • Test coverage for new branches
  • CHANGES fragment present, correct category and attribution
  • Spelling wordlist additions sorted case-insensitively
  • Pure-Python backend untouched as claimed
  • Change leaves surrounding code no messier — suggestion #5
  • Public accounting APIs stay accurate — suggestion #6

To rebase and address feedback, mention me: @aiolibsbot rebase critical (fixes 🔴 only), @aiolibsbot rebase important (fixes 🔴 + 🟡), or @aiolibsbot rebase --fix for all. (A bare @aiolibsbot rebase only rebases onto the base branch.)


Silent Failure Analysis

🟡 **7. MEDIUM** — assert-only invariant degrades to silent data loss
multidict/_multilib/watch.h:250-253

Risk: Release wheels are built with NDEBUG, so the assert vanishes and a mutation path that forgets its md_watch_flush_if() silently discards every queued event with no LOST event, no unraisable, and no other trace — exactly the bug the comment is trying to catch, invisible everywhere it matters.

/* A non-empty log here means some mutation entry point skipped its
   md_watch_flush(); the assert is the cheapest way to catch that. */
assert(watchlog_empty(&watch->log));
watchlog_drain(&watch->log);

Fix: Keep the assert but add a runtime arm: when the log is non-empty, drain it and deliver a MultiDict_EVENT_LOST (or at minimum PyErr_FormatUnraisable) before the DEALLOCATED event, so a missed flush surfaces in production instead of only in debug builds.

🟡 **8. MEDIUM** — error return discarded when reporting channel is a no-op
multidict/_multilib/watch.h:49-59

Risk: PyErr_WriteUnraisable() requires a live exception; a callback that returns -1 without setting one (the documented contract says it must, but nothing enforces it) produces no report at all in a release CPython and trips an assertion in a debug one, so the watcher's only failure channel disappears silently.

if (callback(state->watcher_data[id], user_data[id], info) < 0 ||
    PyErr_Occurred()) {
    PyErr_WriteUnraisable(info->event == MultiDict_EVENT_DEALLOCATED
                              ? NULL
                              : info->self);
}

Fix: Before reporting, materialise a fallback: if (!PyErr_Occurred()) PyErr_Format(PyExc_SystemError, "multidict watcher %d returned -1 without setting an exception", id); then call PyErr_WriteUnraisable().

🟡 **9. MEDIUM** — discarded error return in test harness
multidict/_testcyapi.pyx:388-392

Risk: These two callbacks drop the result of MultiDict_Watch()/MultiDict_Unwatch() and unconditionally report success, unlike their C counterparts in _testcapi.c which return it, so a genuine failure of the API under test is downgraded to an unraisable warning no assertion inspects and the Cython leg of test_a_callback_that_watches_joins_mid_batch / test_a_callback_that_unwatches_gets_no_further_events passes for the wrong reason.

cdef int _watching_event(void *watcher_data, void *user_data,
                         const MultiDict_WatchInfo *info) noexcept:
    (<object>watcher_data).append(<int>info.event)
    MultiDict_Watch(_capi, _watch_target_id, <object>info.md, watcher_data)
    return 0

Fix: Mirror the C harness: return MultiDict_Watch(...) / return MultiDict_Unwatch(...) so a failure propagates as the callback's own -1 and is reported.


Automated review by Kōan (Claude) HEAD=6154cfb 10 min 54s

@aiolibsbot

Copy link
Copy Markdown
Contributor

Rebase with requested adjustments

Branch claude/watchers-api-d08c30 was rebased onto master and review feedback was applied.

Warning

Force-push safety check — the rewrite of claude/watchers-api-d08c30 needs attention.

Commits whose patch changed in-flight and whose content could not be verified as preserved — check these survived:

  • fc7299b Add a watchers C API
  • 5d6ebc8 Merge remote-tracking branch 'upstream/master' into claude/watchers-api-d08c30
  • 7ad8766 Merge remote-tracking branch 'upstream/master' into claude/watchers-api-d08c30
  • 1f1fab1 Merge remote-tracking branch 'upstream/master' into claude/watchers-api-d08c30

Previous PR head: 6154cfb444a83bc3a9303d7ba83a03e4fa1fe2ca — everything it contained is recoverable: git fetch origin 6154cfb444a83bc3a9303d7ba83a03e4fa1fe2ca && git switch -c koan-prerebase-6154cfb444a8 FETCH_HEAD

Changes applied

  • Done. Verified: full suite 2827 passed on C build; new reuse test fails without the fix, passes with it.
  • Closed the slot-reuse hole (greptile P1, capsule.h:412): added a per-slot watcher_epoch to mod_state, stamped into md_watch_t at watch time, and filtered through new md_watch_live_bits() in both delivery and dealloc. A watch now belongs to the registration that took it, so a reused watcher ID never receives old watches nor the previous client's user_data. Test test_a_reused_watcher_id_does_not_inherit_old_watches added; confirmed it fails with the filter stubbed out.
  • Rewrote the MultiDict_ClearWatcher warning in docs/capi.rst and the matching capsule.h comment, which documented the old hole as accepted.
  • Added a runtime arm at dealloc (watch.h): a non-empty log now reports a SystemError as unraisable instead of vanishing under NDEBUG; the assert stays.
  • Substituted a SystemError when a callback returns -1 with no exception set, so PyErr_WriteUnraisable() has something to report; documented in docs/capi.rst, harness silent_failing_event added to both _testcapi.c and _testcyapi.pyx, covered by test_a_callback_failing_without_an_exception_is_still_reported.
  • _testcyapi.pyx _watching_event/_unwatching_event now return the MultiDict_Watch()/MultiDict_Unwatch() result, matching _testcapi.c. Moved both to the Cython-facing callback form so except -1 carries a failure out through the trampoline rather than a de

Stats

18 files changed, 2610 insertions(+), 12 deletions(-)
Actions performed
  • Already-solved check: negative (confidence=high, reasoning=No recent master commit adds a watchers C API; recent work covers ForEach visitor args, pooling, and)
  • Resolved merge conflicts (1 round(s))
  • Rebased claude/watchers-api-d08c30 onto upstream/master
  • Applied review feedback
  • Pre-push CI check: previous run passed
  • Force-pushed claude/watchers-api-d08c30 to origin
  • Private review gate skipped: disabled by config
  • Force-push guard: original PR content was dropped, modified, or raced — see the warning at the top of this comment
  • CI check enqueued in ## CI (async)

CI status

CI will be checked asynchronously.


Automated by Kōan

@asvetlov
asvetlov merged commit e09ae77 into aio-libs:master Sep 24, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/watchers-api-d08c30 branch September 24, 2026 18:10
@asvetlov asvetlov mentioned this pull request Sep 25, 2026
5 of 6 tasks
asvetlov added a commit that referenced this pull request Sep 25, 2026
<!-- 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.
asvetlov added a commit that referenced this pull request Sep 25, 2026
)

<!-- 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>
asvetlov added a commit that referenced this pull request Sep 25, 2026
<!-- 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>
asvetlov added a commit that referenced this pull request Sep 25, 2026
<!-- 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>
asvetlov added a commit that referenced this pull request Sep 26, 2026
<!-- 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>
asvetlov added a commit that referenced this pull request Sep 26, 2026
<!-- 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>
asvetlov added a commit that referenced this pull request Sep 26, 2026
<!-- 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>
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.

2 participants