Skip to content

Raise the watcher limit from 8 to 32 - #1574

Merged
asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/watchers-32-subscribers
Sep 25, 2026
Merged

asvetlov merged 1 commit into
aio-libs:masterfrom
asvetlov:claude/watchers-32-subscribers

Conversation

@asvetlov

@asvetlov asvetlov commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

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

  • 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
Agent run details (optional, for reviewers)

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.

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

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 25, 2026
@asvetlov
asvetlov marked this pull request as ready for review September 25, 2026 09:02
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 25, 2026 09:02
@greptile-apps

greptile-apps Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High risk] Raises the watcher limit and changes internal watcher storage.

No blocking issues were identified; the reviewed changes appear safe to merge.

What we checked:

  • Authored run showed ID 31 receiving events only after its reentrant attachment and not the earlier BATCH_BEGIN, while ID 0 remained unwatched and later saw its deallocation event. T-Rex
  • In the comparison run, ID 31 was attached before delivery and all four batch events were received; both runs exited with code 0 and no delivery or routing corruption was observed. T-Rex
  • In the injected run, one targeted realloc attempt occurred and one failure; the ID-0 watcher saw events before and after the failed attach with its original user data, while the ID-31 watcher received none; the baseline delivered events to both watchers. T-Rex
  • The changes implicate the watch handling in multidict/_multilib/watch.h, covering the delivery and reattachment paths that shaped these outcomes. T-Rex

Reviews (1) · Last reviewed commit: "Raise the watcher limit from 8 to 32"

@codspeed

codspeed Bot commented Sep 25, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 310 untouched benchmarks


Comparing asvetlov:claude/watchers-32-subscribers (39b004e) with master (78c1a12)

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 (026fcd3) to head (39b004e).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1574   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           41        41           
  Lines         7634      7655   +21     
  Branches       641       643    +2     
=========================================
+ Hits          7634      7655   +21     
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 merged commit e52b43c into aio-libs:master Sep 25, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/watchers-32-subscribers branch September 25, 2026 09:32
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 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

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.

1 participant