Skip to content

Make watcher registration thread safe and retire stale watch bits - #1583

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

asvetlov merged 3 commits into
aio-libs:masterfrom
asvetlov:watcher-slot-publish

Conversation

@asvetlov

Copy link
Copy Markdown
Member

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

  • 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)
  • 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)

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

AddWatcher() and ClearWatcher() wrote the module-wide slot table with
plain stores while delivery on another thread read it without a lock.
They now serialize on a mutex and publish through freethreading.h
accessors, the way CPython's PyDict_AddWatcher() does.

ClearWatcher() also bumps a per-slot generation that every watch records,
so a multidict left watched through a cleared ID no longer reports to the
next registration under that ID with the previous one's user_data.
@codspeed

codspeed Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:watcher-slot-publish (624a6e8) with master (cd03110)

Open in CodSpeed

@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 (e5e4391) to head (624a6e8).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1583   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7689      7776   +87     
  Branches       643       650    +7     
=========================================
+ Hits          7689      7776   +87     
Flag Coverage Δ
CI-GHA 100.00% <100.00%> (ø)
pytest 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Critical risk] Rewrites watcher registration and delivery for thread safety.

No outstanding findings block merging.

Reviews (2) · Last reviewed commit: "Reject a watch whose registration was cl..."

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

This comment has been minimized.

MultiDict_Watch() read the generation under watcher_mutex, then attached
under md's critical section. A clear and re-registration of the ID, plus
the new owner's own watch of md, could land in between, and the stale
call then overwrote that watch with a retired generation, so neither
registration received events. Recheck the generation under md's lock and
fail with ValueError, as if the call had come after the clear.
@asvetlov
asvetlov merged commit 0f245d0 into aio-libs:master Sep 25, 2026
61 of 62 checks passed
@asvetlov
asvetlov deleted the watcher-slot-publish branch September 25, 2026 14:30
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 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant