Repository navigation
perf(gateway): reduce stalls when many sessions start - #159102
Conversation
Share a per-projection publication budget across event producers, revalidate prepared rows after yielding, coalesce pending recaps within their generation, and join accepted publications before shutdown disposes the projection.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 26, 2026, 7:10 PM ET / 23:10 UTC (Revision 4). ClawSweeper reviewWhat this changesThe branch schedules Gateway session-row event broadcasts in bounded slices, coalesces pending activity summaries, joins publications during shutdown, and updates tests and protocol documentation. Merge readiness⛔ Blocked before merge - 3 items remain The current main branch still lacks this shared publication budget, and the branch has a coherent performance improvement supported by protocol-client measurements. The Gateway’s required public session-creation proof remains outstanding. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway receives session changes, prepares current session rows, and broadcasts events to subscribed clients. During shutdown it must finish admitted publications before disposing the row projection. flowchart LR
A[Session changes and recaps] --> B[Session row projection]
B --> C[Shared publication budget]
C --> D[Current row check]
D --> E[Gateway broadcaster]
E --> F[Subscribed clients]
C --> G[Shutdown drain]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +181, Tests +402, Docs +5. Total +588 across 12 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the shared projection-owned budget and shutdown drain if an isolated Gateway run confirms that non-main creation notices remain usable after publication, with measured test cost recorded. Do we have a high-confidence way to reproduce the issue? No current-main reproduction was run in this read-only review. The PR supplies a concrete Testbox protocol-client A/B scenario that measured baseline event-loop stalls. Is this the best way to solve the issue? Yes, provisionally: scheduling at the existing row-preparation owner shares one budget across event producers and retains current row checks. The public creation-notice proof is still needed to establish safe delivery. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against fb720291b0a3. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Merge main with the canonical WhatsApp shutdown fixture fix in #159115. The same-upsert messages can cross separate debounce windows during asynchronous admission; delivery and close ordering remain correct. Register queued recap work synchronously with the publication owner so a drain cannot finish before deferred row preparation starts.
|
CI note: the only failure on 3dca763 was |
Native registration invalidates registry discovery at both admission and settlement. Concurrent history reads and Talk transcript broadcasts could surface AgentDatabaseRegistryChangedError during initial source discovery or final revalidation, including the unrelated CI failures in #158587 and #159102. Retry only the registry metadata read up to twice, retaining the original state admission and physical source bindings. Keep topology revalidation, revocation, and worker settlement checks; never replay history or writes. Schemas, permissions, retention, and update behavior stay unchanged. Extend the real history-reader fixture to force registration across both read phases. All four cases fail on the original code and pass after the fix. The focused Talk, history, broadcast, and source suites pass 56 tests. Independent review through P2 is clean.
Native registration invalidates registry discovery at both admission and settlement. Concurrent history reads and Talk transcript broadcasts could surface AgentDatabaseRegistryChangedError during initial source discovery or final revalidation, including the unrelated CI failures in openclaw#158587 and openclaw#159102. Retry only the registry metadata read up to twice, retaining the original state admission and physical source bindings. Keep topology revalidation, revocation, and worker settlement checks; never replay history or writes. Schemas, permissions, retention, and update behavior stay unchanged. Extend the real history-reader fixture to force registration across both read phases. All four cases fail on the original code and pass after the fix. The focused Talk, history, broadcast, and source suites pass 56 tests. Independent review through P2 is clean.
* perf(gateway): bound prepared session publication bursts Share a per-projection publication budget across event producers, revalidate prepared rows after yielding, coalesce pending recaps within their generation, and join accepted publications before shutdown disposes the projection. * perf(gateway): grant bounded publication retries in FIFO order * test(gateway): verify publication drain through kernel teardown * test(gateway): name burst keys in publication drain tests * test(gateway): avoid shadowed options in shutdown drain test * test(gateway): cover prepared publication drain dependency
Related: #158587 (disjoint sections of the protocol reference; chat/agent framing is untouched).
What Problem This Solves
When many users start turns together, prepared session updates can spend over 150 ms broadcasting without letting the Gateway process other I/O.
User Impact
Burst-time send acknowledgments arrive sooner, and long event-loop stalls decrease. Lifecycle, capacity, transcript, deletion, and clearing receipts retain their existing semantics.
Why This Change Was Made
Independent event producers now share a publication budget at the existing preparation owner. They yield after 8 publications or 6 ms; waiting publishers receive FIFO retry grants and reacquire current row facts before delivery. Preparation for unrelated rows remains concurrent. Pending activity summaries for the same physical session generation share the latest snapshot. Shutdown joins admitted publications before disposing their projection.
The budget is checked between publications: an individual fanout remains atomic. Cancellation receipts still publish synchronously inside their existing kill hold. Wire payloads, protocol versions, and configuration/SQLite schemas are unchanged.
Evidence
Same Blacksmith Testbox, four available CPUs, Node 26.9.0. Each size ran A, B, A, B: 100 subscribed Control UI protocol clients, 50 or 100 simultaneous senders, one turn each, and a mock provider emitting word chunks every 25 ms. All eight runs completed with 600 successful turns and no failed/pending turns, protocol errors, or disconnects. These are protocol-client measurements, not Chromium rendering or live-provider evidence.
Values below are medians of two runs per variant. Delay counts and ELD maximum cover the first ten seconds; CPU includes the full load and drain. Latency cells contain p50 / p95 in milliseconds.
CPU decreased 11.4% at 50 senders and was effectively flat at 100 (−0.5%; individual pairs −1.85% and +0.79%). First-delta p50 at 100 senders worsened by about one second, while p95 was nearly unchanged. Two pairs are scoped evidence, not a capacity guarantee. The A/B comparison used main
1844d933b2dc; the original main rebase preserved changed production files byte-for-byte. These measurements predate the final synchronous recap-admission tracking correction described below.Validation:
node scripts/check-changed.mjswas attempted on the rebased tree, but the Testbox expired during source staging before the gate executed. This is an explicit unrun check, not a pass; hosted CI is authoritative under the campaign’s environmental exception.--max-warnings 0).git diff --checkpasses.Production: +189/−8 (+181 net); tests/support: +410/−8 (+402 net); docs: +5. The added production code supplies the cross-producer budget, bounded retry grants, shutdown joining, and generation-safe recap coalescing. Shutdown assertions reuse the existing kernel fixture and add no Gateway boots.
CI follow-up
The WhatsApp failure was an existing fixture race, not a publication-drain regression. Its real 20 ms debounce window did not guarantee that asynchronous admissions from one upsert would produce one callback. Both unmodified local replays passed (PR head: 17 tests / 33.55 s; main: 17 tests / 55.42 s). A controlled admission gap on main reproduced the exact
secondversussecond\nthirdassertion while all three messages were delivered in order before socket close. The same failure also occurred on #151608, independently of this PR.Main's canonical repair in #159115 (
32e46c9bb1bc) is now merged into this branch. It controls both same-window and split-window schedules and preserves exact delivery, read-receipt, durable-claim, and socket-close assertions. The WhatsApp runtime was not changed by this repair.Fresh review separately caught a recap admission gap in this PR: queued summary work was tracked only after its preparation microtask began. It now registers synchronously with the existing publication owner. The new regression demonstrated an early drain before the fix and now proves that drain waits for the held preparation and delivery. The coordinator's named-key and shadowed-option fixes are preserved, and auto-merge remains enabled.
After the coordinator refreshed the branch from main, CI on
f38275fc80dffailed inserver-shutdown.runtime.test.tsbecause the new publication dependency was absent from its mocked shutdown inventory. The unmocked module loaded the real plugin metadata graph, which reachedgetScopedPluginCacheson the deliberately narrow plugin-cache mock. The exact error reproduced locally in 66.85 s after an initial cold-cache timeout (152.87 s total). Production already resolves and retains the drain during preparation, as required for shutdown after installed chunks are replaced.The repair adds the publication dependency to the existing fixture and verifies that its captured reference survives simulated chunk removal without being invoked during preparation. Production is unchanged by this follow-up; test delta is +15/−0. Validation on the repaired branch:
node scripts/run-vitest.mjs src/gateway/server-shutdown.runtime.test.ts --maxWorkers=1: 1 test passed, 6.54 s wall / 100 ms test time.--max-warnings 0; formatting andgit diff --checkpassed. Deslop found no additional cleanup. Fresh Codex autoreview is scoped-clean through P2.Exact-head CI succeeded for
befbe13606964ae1c563db139618940700eb3954in run 36278222479. The repaired shutdown-preparation test passed in 2 ms in hosted CI. No rerun was needed. The existing auto-merge request completed at 2026-09-26 23:18:58 UTC with merge commit6dc31b2eca9e865544564c62c65d0853d720382c, verified by ancestry on fetched main.