Skip to content

Document a cache-invalidating watcher in the C API docs - #1586

Merged
asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:watcher-invalidate-example
Sep 25, 2026
Merged

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:watcher-invalidate-example

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

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

  • I think the code is well written
  • Unit tests for the changes exist (N/A, documentation only)
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt (N/A)
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt

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

Agent run details (optional, for reviewers)

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

The example unwatches from its own callback, watches again on the next
rebuild, uses the version to discard a result that changed underneath,
and stops caching a multidict that keeps changing, the same shape as
CPython's JIT globals watcher.
@codspeed

codspeed Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:watcher-invalidate-example (1779516) with master (47e2e6b)

Open in CodSpeed

@asvetlov
asvetlov marked this pull request as ready for review September 25, 2026 14:12
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 25, 2026 14:12
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Low risk] Documents a C API watcher pattern with example code.

No outstanding findings block merging.

Reviews (3) · Last reviewed commit: "Lock the cache example only on the free-..."

Comment thread docs/capi.rst Resolved
Comment thread docs/capi.rst Resolved
Comment thread docs/capi.rst Resolved
Comment thread docs/capi.rst Resolved
@greptile-apps

This comment has been minimized.

An event goes to whoever is watching when the operation finishes, so it
can reach a rebuild that already saw its change. The callback now keeps
the version the cache was built from and discards only a cache the
multidict has moved past, never unwatches while a rebuild owns the
watch, and does both under a lock the rebuild also stores under.

The example also ignores bare BATCH brackets, stops listening after a
failed parse, and counts every rebuild attempt toward the limit.
@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 25, 2026
@asvetlov

Copy link
Copy Markdown
Member Author

@aiolibsbot rr

@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1586   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7701      7797   +96     
  Branches       643       650    +7     
=========================================
+ Hits          7701      7797   +96     
Flag Coverage Δ
CI-GHA 100.00% <ø> (ø)
pytest 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.

@aiolibsbot

Copy link
Copy Markdown
Contributor

@asvetlov: @aiolibsbot rr

Re-reviewed at c36ba35. Both earlier bot findings read as resolved: brackets now return early at line 864, and publication is version-checked under c->lock at line 921, so a mutation racing the publish either moves the version past V (no cache) or reaches the watch registered before parse() (cache cleared). Three non-blocking notes filed: no DEALLOCATED branch in on_change, MAX_REBUILDS acting as a lifetime cap rather than the failure heuristic the prose describes, and one 84-column line.

@aiolibsbot

Copy link
Copy Markdown
Contributor

PR Review — Document a cache-invalidating watcher in the C API docs

Documentation-only addition that is genuinely correct under free threading; merge-ready with three non-blocking notes.

The hard part here is the concurrency argument, and it holds up. I traced it against _multilib/watch.h and freethreading.h:

  • Versions come from a process-global counter (next_version, freethreading.h:82) that is never reused, so c->version is a sound identity for "the state I parsed", and every content-changing path bumps it.
  • Reading the version before MultiDict_Watch and re-checking it under c->lock before publishing closes both directions: a mutation that lands before the watch moves the version past V so the result is never cached, and one that lands after is delivered to the watch registered earlier, because _md_watch_recipients() re-reads the recipient set per event.
  • The rebuilding flag holds the invariant the prose claims: a value is only ever published by the exclusive rebuilder, which always watched first, and the callback never unwatches while that rebuilder is live. So "a cached value always has a watch that will clear it" is accurate.
  • Deferring Py_XDECREF(old) until after PyMutex_Unlock is the right call and easy to miss; a __del__ under c->lock would have been a nasty footgun.

On the two prior bot findings, both look resolved at head c36ba35: the bracket events are now skipped outright (line 864), and the publish path is version-checked under the same lock that the callback takes, which is what the P1 stale-cache report was about.

  • on_change has no MultiDict_EVENT_DEALLOCATED branch and passes info->self to MultiDict_GetVersion/MultiDict_Unwatch, which docs/capi.rst:489 forbids. Unreachable given the example's own strong-ref rule, but the preceding example checks for it and this one does not say why it needn't.
  • MAX_REBUILDS is a hard lifetime cap: a cache that was rebuilt eight times and used heavily in between is retired just like one that is thrown away every time, which is not what the paragraph at 831-834 implies.
  • Line 912 is 84 columns, the only code line in the file over the ColumnLimit: 79 the repo's own .clang-format sets.

🟢 Suggestions

1. `on_change` passes a refcount-zero `self` to the C API on DEALLOCATED
docs/capi.rst:864-873

on_change filters only the two bracket events, then falls through to MultiDict_GetVersion(state->capi, info->self) and possibly MultiDict_Unwatch(..., info->self). On MultiDict_EVENT_DEALLOCATED that is exactly what this same page forbids at docs/capi.rst:489:

self is at refcount zero: use it as an identity and nothing else. Do not incref it and do not pass it to any function on this page.

Within the example's own ownership rule the event cannot arrive: the struct comment says headers is a strong ref that is "unwatched before it is released", which is one of the two disciplines MultiDict_Watch documents. So the snippet is self-consistent, and this is not a live bug.

Why it still matters: the preceding example (on_header_change, line 782) opens with an explicit DEALLOCATED branch, so a reader comparing the two sees the second one silently drop a check the first one makes, with no note saying why it is allowed to. A reader who copies on_change into a design where the cache does not own the multidict gets a critical-section acquisition on an object in tp_dealloc.

Cheapest fix is an early return that also documents the invariant:

if (info->event == MultiDict_EVENT_DEALLOCATED) {
    /* Cannot happen here: `c` holds a strong ref and unwatches
       before releasing it. Bail out anyway, `self` is refcount 0. */
    return 0;
}
       if (info->event == MultiDict_EVENT_BATCH_BEGIN ||
           info->event == MultiDict_EVENT_BATCH_END) {
           /* A bracket alone changes nothing: an empty update() sends one. */
           return 0;
       }
2. `MAX_REBUILDS` is a lifetime cap, not a "thrown away every time" heuristic
docs/capi.rst:893-899

c->rebuilds is incremented on every started rebuild and never reset, so after 8 rebuilds the cache stops caching permanently. The prose at lines 831-834 sells it differently: "Counting rebuild attempts lets a cache that is thrown away every time stop trying".

Those are not the same policy. A long-lived cached whose headers change eight times over its life, with each parsed value served a million times in between, also stops caching forever; nothing distinguishes it from the pathological case the paragraph describes. A reader reaching for this pattern for connection- or request-scoped state will not expect that from the sentence they read.

Two ways to close the gap, either is fine:

  • Say it plainly in the prose, e.g. that the counter is a hard lifetime cap on rebuilds and a cache that earns its keep is retired along with one that does not, which is the conservative choice.
  • Or count only wasted work: increment when the publish check at line 921 fails, and reset to 0 when it succeeds. That matches "thrown away every time" literally, at the cost of watching forever on a multidict that changes between every call.
       bool rebuild =
           parsed == NULL && !c->rebuilding && c->rebuilds < MAX_REBUILDS;
       if (rebuild) {
           /* Counted whether or not the result ends up cached. */
           c->rebuilds++;
3. One snippet line exceeds the repo's 79-column C style
docs/capi.rst:912

At 84 columns this is the only code line in the whole of docs/capi.rst over 79 (the other long lines are .. c:function:: signatures, which cannot wrap). .clang-format:4 sets ColumnLimit: 79, and every other example in this file honours it, so the snippet reads as pre-formatted repo C right up to this line.

Wrap it like the MultiDict_Unwatch calls above and below:

if (MultiDict_Watch(state->capi, state->watcher_id,
                    c->headers, c) == 0) {
       if (MultiDict_Watch(state->capi, state->watcher_id, c->headers, c) == 0) {

Checklist

  • Concurrency: cache publication and invalidation are ordered correctly on free-threaded builds
  • Example obeys the documented C API contracts on this page — suggestion #1
  • Prose matches the behaviour of the code it describes — suggestion #2
  • CHANGES fragment present, correct category, past tense, signed
  • No em-dashes or AI tells in prose; house style followed
  • Snippet formatting matches the repo's C style — suggestion #3
  • Diff scope matches the PR description (docs + fragment only)

Automated review by Kōan (Claude) HEAD=c36ba35 6 min 42s

@aiolibsbot

Copy link
Copy Markdown
Contributor

Rebase with requested adjustments

Branch watcher-invalidate-example was rebased onto master and review feedback was applied.

Changes applied

  • Done.
  • Added an early MultiDict_EVENT_DEALLOCATED return in on_change, per Kōan suggestion CIMultiDict.pop is case sensitive. #1: the callback otherwise passes info->self to MultiDict_GetVersion/MultiDict_Unwatch, which the enumerator docs forbid at refcount 0. Kept the invariant in the comment, matching the earlier example on this page.
  • Rewrote the MAX_REBUILDS prose (Kōan Python MultiDict constructor discards generator content #2) to say it is a lifetime cap on rebuilds, not a rate, and that a long-lived cache retires the same way. Left the counting as is; counting only wasted work means watching forever on a multidict that changes between calls.
  • Wrapped the MultiDict_Watch call at 84 columns (Kōan Don't double-iterate during MultiDict initialization #3) to fit .clang-format's 79-column limit, like the MultiDict_Unwatch calls around it.

Not changed (and why)

  • Greptile P1 "Concurrent changes leave stale cache": already fixed at HEAD (9b2ab64). The rebuild reads the version before watching, publishes only if the version is unchanged under c->lock, and the callback drops a cache the multidict moved past. Greptile ran against the earlier revision; Kōan's checklist confirms the ordering on the current one.
  • Greptile P2 "Empty batches discard cache": already fixed at HEAD. on_change returns early on BATCH_BEGIN/BATCH_END, so a no-op bulk operation touches neither the cache nor the rebuild counter.
  • 
    

Stats

2 files changed, 121 insertions(+)
Actions performed
  • Already-solved check: negative (confidence=high, reasoning=No cache-invalidation watcher example exists in docs/capi.rst on master, and no recent commit adds o)
  • Rebased watcher-invalidate-example onto upstream/master
  • Applied review feedback
  • Pre-push CI check: previous run passed
  • Force-pushed watcher-invalidate-example to origin
  • Private review gate skipped: disabled by config
  • Force-push guard: all original PR content verified preserved
  • CI check enqueued in ## CI (async)

CI status

CI will be checked asynchronously.


Automated by Kōan

The version check and the rebuild flag are needed under the GIL too,
since parse() running Python code lets another thread mutate the
multidict; only the lock is free-threaded specific. Put it behind
Py_GIL_DISABLED so one source serves both builds, and save the parse
error with PyErr_Fetch() so the example works back to 3.10.
@asvetlov
asvetlov merged commit 9d2a676 into aio-libs:master Sep 25, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the watcher-invalidate-example branch September 25, 2026 15:42
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