Skip to content

perf(gateway): reduce stalls when many sessions start - #159102

Merged
steipete merged 10 commits into
mainfrom
perf/l91-publication-drain-0926
Sep 26, 2026
Merged

steipete merged 10 commits into
mainfrom
perf/l91-publication-drain-0926

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

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.

Metric 50 senders: before → after 100 senders: before → after
Delayed wakes >50 ms 12.5 → 4 12 → 5.5
Delayed wakes >100 ms 1.5 → 0 3 → 0
ELD max, ms 142.21 → 78.51 165.68 → 98.73
Send ACK p50 / p95, ms 604.15 / 1,091.19 → 558.35 / 928.90 1,190.90 / 1,542.96 → 1,011.14 / 1,358.95
First delta p50 / p95, ms 8,226.64 / 16,780.75 → 6,698.81 / 12,395.17 13,992.26 / 26,604.24 → 15,004.62 / 26,699.99
Total main-thread CPU, s 17.013 → 15.068 27.697 → 27.545
Publications emitted 745.5 → 701 1,490 → 1,400.5
Largest interval's synchronous fanout, ms 100.22 → 16.21 142.81 → 15.41

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:

  • Fairness regression fails on the baseline: all 11 ready rows publish before I/O. The reviewed retry fix also rejects the first candidate's 67 preparations for 12 publications, with a bound of 24. The old recap owner fails coalescing with three snapshots instead of two.
  • Refreshed publication/shutdown selection: 59 tests passed in 137.26 s, including the complete kernel file. The final recap file passed 7 tests in 12.79 s on its own.
  • Refreshed transcript/lifecycle/subscription siblings: 133 tests passed in 24.60 s. Cancellation, row parity, and ancestor contracts: 36 tests passed in 86.02 s.
  • WhatsApp delivery/dedupe file on the refreshed branch: 18 tests passed in 96.89 s. No live WhatsApp account or transport was used.
  • node scripts/check-changed.mjs was 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.
  • Complete baseline and candidate builds passed on the Testbox. Deslop passed. Fresh Codex autoreview is scoped-clean through P2 after resolving the retry-work and recap-admission findings. Scoped lint completed with zero warnings (--max-warnings 0). git diff --check passes.

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 second versus second\nthird assertion 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 f38275fc80df failed in server-shutdown.runtime.test.ts because the new publication dependency was absent from its mocked shutdown inventory. The unmocked module loaded the real plugin metadata graph, which reached getScopedPluginCaches on 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.
  • Publication preparation, recap, session-change, and kernel suites: 59 tests passed, 210.08 s wall.
  • Transcript/lifecycle/subscription, collector cancellation, row parity, and ancestor suites: 169 tests passed, 275.69 s wall.
  • All touched TypeScript files passed scoped type-aware lint with --max-warnings 0; formatting and git diff --check passed. Deslop found no additional cleanup. Fresh Codex autoreview is scoped-clean through P2.

Exact-head CI succeeded for befbe13606964ae1c563db139618940700eb3954 in 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 commit 6dc31b2eca9e865544564c62c65d0853d720382c, verified by ancestry on fetched main.

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.
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 18:45
@steipete
steipete enabled auto-merge (squash) September 26, 2026 18:50
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 26, 2026, 7:10 PM ET / 23:10 UTC (Revision 4).

ClawSweeper review

What this changes

The 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
Reviewed head: befbe13606964ae1c563db139618940700eb3954

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The bounded scheduler has focused regression coverage and useful real load measurements, but the required creation-notice proof remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.
Evidence reviewed 11 items Introduced publication scheduler: The pinned PR delta adds a projection-scoped budget, FIFO retry grants, row reacquisition after yielding, and a drain.
Shutdown custody: Kernel teardown drains admitted session-event publications before detaching and disposing the projection.
Current main remains different: Fetched main still calls the existing ready-row helper directly in this owner; the PR’s shared budget is a distinct unmerged change.
Findings None None.
Security None None.

How this fits together

The 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]
Loading

Before merge

  • Resolve merge risk (P1) - Deferring keyed publications may affect delivery of an explicit non-main session’s creation notice; the required public RPC followed by a post-publication read or turn has not been shown.
  • Resolve merge risk (P1) - The affected Gateway test files lack the scoped before/after wall-time comparison required by the Gateway review policy.
  • Complete next step (P2) - Add a redacted isolated-Gateway public sessions.create trace for an explicit non-main session, its notice, and a subsequent read or turn; also report before/after wall time for the affected Gateway test files. Redact private addresses, keys, and endpoints. Updating the PR body should trigger re-review; if it does not, ask a maintainer to comment @clawsweeper re-review.
Agent review details

Security

None.

PR surface

Source +181, Tests +402, Docs +5. Total +588 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 6 189 8 +181
Tests 5 410 8 +402
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 604 16 +588

Review metrics

Metric Value Why it matters
Production versus test growth production +181 net lines; tests and support +402 net lines The production growth is attributed to the shared budget, retry grants, and shutdown custody; the tests add focused fairness and lifecycle coverage.
Measured synchronous fanout 100 senders: 142.81 ms before, 15.41 ms after The reported reduction motivates the change, while the measurement predates the final recap-admission correction.

Merge-risk options

Maintainer options:

  1. Prove creation notice delivery (recommended)
    Capture the public non-main sessions.create notice and a subsequent read or turn in an isolated Gateway before merging the scheduling change.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement with measured burst-time benefit and an outstanding delivery proof gate.
  • merge-risk: 🚨 message-delivery: The PR defers session-event publication, and the required non-main creation-notice path has not been demonstrated through a public client.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Real behavior proof is not required for maintainer- or bot-authored pull requests.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Galin Iliev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Capture a redacted isolated-Gateway trace of public sessions.create for an explicit non-main session, including its publication and a subsequent read or turn.
  • Report before/after wall time for the affected Gateway test files using the scoped test command.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-26T19:03:01.671Z sha 6978f55 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T20:24:53.104Z sha 3dca763 :: blocked before merge. :: none
  • reviewed 2026-09-26T20:37:05.989Z sha 3dca763 :: blocked before merge. :: none

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.
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 26, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

CI note: the only failure on 3dca763 was extensions/browser/src/browser/server.agent-contract-form-layout-act-commands.test.ts > trace stop rejects traversal path outside trace dir, failing with fetch failed / ECONNREFUSED against the local browser control server (job https://github.com/openclaw/openclaw/actions/runs/36268722362/job/108479173109). This PR changes session-event publication scheduling only and does not touch the browser extension; fail-fast then cancelled the remaining jobs. The failed and cancelled jobs were re-run once (attempt 2).

steipete added a commit that referenced this pull request Sep 26, 2026
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.
@steipete
steipete merged commit 6dc31b2 into main Sep 26, 2026
204 checks passed
@steipete
steipete deleted the perf/l91-publication-drain-0926 branch September 26, 2026 23:19
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant