Skip to content

improve(gateway): reduce presence work for concurrent viewers - #158497

Merged
steipete merged 3 commits into
mainfrom
perf/l13-presence-cutover-0925
Sep 26, 2026
Merged

steipete merged 3 commits into
mainfrom
perf/l13-presence-cutover-0925

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Connecting or switching sessions with many Control UI viewers repeatedly rebuilt and serialized the complete presence roster and queried SQLite synchronously on the Gateway thread.

User Impact

Presence changes in the same event-loop turn share one publication. Hello snapshots and system-presence replies read current state immediately when sharing facts are ready, while pending topology uses the existing readiness owner. Recipient visibility, profile envelopes, connection sequence numbers, and admin access to declared incognito watches are preserved. No protocol, configuration, or database schema changes.

Why This Change Was Made

All presence consumers now use committed sharing and profile facts. One Gateway-owned publisher coalesces superseded work, retains the latest state while preparation is pending, and cancels publication on shutdown. Identical projected views share their payload encoding within a publication, with authorization rechecked for each recipient. The existing client registry also removes the redundant connection scan when recording activity.

The change removes the old synchronous presence lookup path and version-mutator plumbing, corrects the presence scope documentation, and keeps unexpected background publication failures from escaping the event loop.

Evidence

Synthetic production-function benchmark on Node 26.9.0 / Apple M3 Ultra, using the same fixture, real resident session projection, and an immediate socket sink:

Measurement Before After
Warm 100-recipient broadcast, median 24.37 ms 1.52 ms
Main-thread SQLite statements per warm broadcast 8 0
Bytes in one 100-recipient broadcast 4,318,290 4,318,290
Same-turn growing 100-client burst, broadcast frames 5,050 100
Burst bytes, including 100 immediate hello presence snapshots 65,274,997 2,836,310
Burst elapsed time 1,045.70 ms 27.15 ms

The burst drives publication requests in one turn; it is not a full network handshake or model-load benchmark. Shared-host contention affected timing: an earlier baseline broadcast median was 8.82 ms, and the final before/after p95 values were 103.37/26.30 ms. Frame counts, byte counts, and SQL counts are deterministic; these results do not establish a production latency SLO.

  • Focused contract run: 100 tests passed across nine files, node scripts/run-vitest.mjs with --maxWorkers=1 (files below), 509.67 s wall including cold worker preparation.
  • Final readiness/transport proof: 9 tests passed across server.auth.presence-audience.test.ts, server/presence-events.test.ts, and server/ws-connection/connect-hello.setup-completion.test.ts, 816.47 s wall. This covers actual hello/RPC/event visibility, admin incognito watches, cold configuration publication, preparation coalescing, cancellation, and publication failure recovery.
  • Earlier transport sibling run passed 140 tests in six files; its audience failure exposed the missing cold-read readiness and is covered by the passing final run above. The original encoding regression failed as intended: four encodings instead of two.
  • Initial health-snapshot checks exceeded their 120 s test deadline during cold worker compilation; an unchanged warm replay passed in 144.07 s wall. Worker preparation and validation dominate these local wall times; test timeouts were not increased.
  • Final central owner test: 6 tests passed, node scripts/run-vitest.mjs src/gateway/server-connection-state.test.ts --maxWorkers=1, 819.87 s wall; verifies zero host SQL for warm broadcasts/RPC/hello, dirty-row visibility, admin incognito watches, and committed revocation during fan-out.
  • Chat activity fixture: 8 tests passed, node scripts/run-vitest.mjs src/gateway/server-methods/chat.error-broadcast.test.ts --maxWorkers=1, 378.97 s wall.
  • Changed-lane gate remains incomplete due to the validation environment. Earlier local node scripts/check-changed.mjs attempts found three fixture/type issues, all fixed; production and 21 test graphs passed before the final fixture error. The next local run was stopped under the campaign's remote-only gate policy. Blacksmith Testbox tbx_01m3dhr0gebt51f9eq4p3k0e9r (run) then hit a source-sync timeout (351.09 s). The repository wrapper retry stalled before remote execution in local git init; a process sample showed an OS rename wait. The lease was stopped and the local staging process tree was terminated; its OS-blocked child remained pending termination. Neither remote attempt executed the check payload; hosted CI is authoritative for the remaining gate.
  • Production: +238 / -180, net +58 lines. Tests/support: +498 / -223, net +275. Documentation: +8 / -4, net +4. The production growth supplies bounded publication/preparation lifecycle state and revision-checked sharing reuse; no compatibility shim or new store was added.
  • Deslop pass completed. Independent Codex autoreview: scoped-clean through P1, no accepted/actionable findings.
Focused 100-test command
node scripts/run-vitest.mjs \
  src/gateway/server-broadcast.presence-serialization.test.ts \
  src/gateway/server-broadcast.serialization.test.ts \
  src/gateway/server-connection-state.test.ts \
  src/gateway/server-methods/system-event-routing.test.ts \
  src/gateway/server-request-context.presence.test.ts \
  src/gateway/server/client-presence.activity.test.ts \
  src/gateway/server/client-presence.test.ts \
  src/gateway/server/presence-events.test.ts \
  src/gateway/session-viewer-presence.test.ts --maxWorkers=1

Landing validation follow-up

The first exact-head CI run (36205860153) found five lint errors: four references to closure-backed publisher methods and one intentionally unawaited synchronous-response probe. Commit 56dd0350187e9ae0241354855b37d9f3b167ec70 makes publish/stop arrow callbacks and marks the probe's return as ignored, preserving its immediate-response assertions. The sibling CI cancellations followed the primary lint failure; no blind rerun was requested.

Formatting and targeted lint across all five reported sites passed (lint: 236.59 s wall). Independent Codex review of the repair was scoped-clean through P1. The three publisher lifecycle tests passed. The local connection-state run remained stalled after cold worker preparation (701.31 s); runner/worker samples showed event-loop waits without an assertion failure, and the owned run was interrupted after 1,484.44 s wall. That local run is incomplete evidence, not a pass; the cause remains unresolved. Exact-head hosted CI passed on 56dd0350187e9ae0241354855b37d9f3b167ec70: run 36208552952, with a green complete check rollup.

@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: XL labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 00:42
@github-actions

github-actions Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: 56dd0350187e9ae0241354855b37d9f3b167ec70
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/server/ws-connection/connect-hello.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 25, 2026, 9:55 PM ET / September 26, 2026, 01:55 UTC (Revision 3).

ClawSweeper review

What this changes

The branch batches Gateway presence updates and reuses prepared session-visibility facts and roster encodings for concurrent viewers, with accompanying tests and documentation.

Merge readiness

✅ Ready for maintainer review

Keep open. Current main still uses immediate presence broadcasts, and this fresh maintainer PR has a distinct, coherent purpose. The related typing PR does not replace it. I found no source-backed blocking defect.

Priority: P2
Reviewed head: 56dd0350187e9ae0241354855b37d9f3b167ec70

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The owner cutover, focused transport coverage, benchmark, and exact-head CI support a good rating, with latency evidence limited to a synthetic setup.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The external-contributor proof gate does not apply to this maintainer PR. Its changed Gateway publisher and projection have reported before/after production-function measurements and real-WebSocket audience tests for hello, RPC, and events; those observations do not establish a deployed latency SLO. No stored-data contract changed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The external-contributor proof gate does not apply to this maintainer PR. Its changed Gateway publisher and projection have reported before/after production-function measurements and real-WebSocket audience tests for hello, RPC, and events; those observations do not establish a deployed latency SLO. No stored-data contract changed.
Evidence reviewed 10 items Current main behavior: The fetched main revision still increments the presence version and broadcasts each snapshot immediately, so the central optimization is not already on main.
Introduced publication owner: The PR queues one presence publication per turn, waits for membership preparation, and stops queued publication during shutdown.
Recipient authority: The changed projection rechecks each client's read scope and session visibility; its sharing-target cache is invalidated when the projection revision changes.
Findings None None.
Security None None.

How this fits together

The Gateway receives connection activity and watched-session declarations from clients. It filters the resulting presence roster for each viewer and sends it through hello snapshots, presence replies, and WebSocket events.

flowchart LR
A[Client activity and watches] --> B[Gateway presence state]
B --> C[Publication queue]
C --> D[Session sharing facts]
D --> E[Per viewer access check]
E --> F[WebSocket presence events]
B --> G[Hello and presence replies]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +58, Tests +275, Docs +4. Total +337 across 37 files.

View PR surface stats
Area Files Added Removed Net
Source 19 238 180 +58
Tests 16 498 223 +275
Docs 2 8 4 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 37 744 407 +337

Review metrics

Metric Value Why it matters
Warm 100-viewer benchmark 24.37 ms → 1.52 ms median The PR reports a substantial reduction in its synthetic production-function benchmark; it does not establish deployed latency.
Production versus test growth production net +58 lines; tests/support net +275 lines The PR explains the production growth as publication lifecycle and prepared-sharing reuse, with most added lines in validation.

Technical review

Best possible solution:

Keep one Gateway-owned presence publisher while preserving immediate hello and RPC reads and checking sharing authority for every recipient before socket delivery.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: current main broadcasts each presence change immediately and prepares watched-session data on the presence path. The PR describes a 100-viewer before/after benchmark, which this read-only review did not rerun.

Is this the best way to solve the issue?

Yes. The change places batching with one Gateway publisher and keeps the access decision at each recipient, without adding configuration or a second persistent store.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against da49c7e45c4c.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway performance improvement with measured benefit and no reported urgent user outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor proof gate does not apply to this maintainer PR. Its changed Gateway publisher and projection have reported before/after production-function measurements and real-WebSocket audience tests for hello, RPC, and events; those observations do not establish a deployed latency SLO. No stored-data contract changed.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (2 earlier review cycles)
  • reviewed 2026-09-26T00:50:30.939Z sha fe9633a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T01:40:45.051Z sha 56dd035 :: needs maintainer review before merge. :: none

Use arrow callbacks for the closure-owned presence publisher and explicitly discard the synchronous presence test handler return. Repairs the five lint errors from CI run 36205860153 without changing publication or response timing.
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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
@steipete
steipete merged commit c817021 into main Sep 26, 2026
214 checks passed
@steipete
steipete deleted the perf/l13-presence-cutover-0925 branch September 26, 2026 02:24
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…aw#158497)

* perf(gateway): coalesce presence publications and reuse sharing facts

* test(gateway): use client registry for chat activity proof

* fix(gateway): make presence callbacks safe to pass unbound

Use arrow callbacks for the closure-owned presence publisher and explicitly discard the synchronous presence test handler return. Repairs the five lint errors from CI run 36205860153 without changing publication or response timing.
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 P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL 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