Repository navigation
Make watcher registration thread safe and retire stale watch bits - #1583
Merged
Merged
Conversation
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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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
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:
|
Contributor
|
This comment has been minimized.
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
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>
4 of 6 tasks
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What do these changes do?
MultiDict_AddWatcher()andMultiDict_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 atwatch.hagainst both functions. Registration now serializes on aPyMutexand publishes through newfreethreading.haccessors, following CPython'sPyDict_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'suser_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
CONTRIBUTORS.txt(N/A)CHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtDrafted 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.
MULTIDICT_DEBUG_BUILD=1, Cython harness required: 2860 passed, 37 skippedMULTIDICT_NO_EXTENSIONS=1 --no-c-extensions: 1282 passedMULTIDICT_NO_FREELIST=1,PYTHONMALLOC=malloc,tests/test_capi.py: 139 passed, no reports-k "churn or reused": two data races on the slot table with the old C code, none with this changemake doc-spelling: pass