Skip to content

perf(gateway): avoid duplicate recipient row lookup - #159595

Merged
steipete merged 1 commit into
mainfrom
perf/l120-recipient-presentation
Sep 27, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/l120-recipient-presentation

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-row fanout repeats a row lookup for every recipient while many Control UI clients share one Gateway.

User Impact

The measured 100-client / 50-active workload used less main-thread CPU per completed turn and reached the first text delta sooner. Current recipient authorization, row freshness, ancestor receipts, and delivery ordering continue through the existing owners.

Why This Change Was Made

The publication already captures a row and checks its generation. presentation.snapshot(query) looked it up again, then called present, which independently refreshes and validates that captured row. Call present(record, enrichment) directly and allocate the constant enrichment options once per publication. This adds no cache or invalidation state.

The original profile attributed 6.465 s inclusive / 1.461 s self to the recipient callback. Final-frame serialization and socket send are sibling work outside that total. A proposed envelope-copy rewrite was discarded after representative object-shape benchmarks failed to show a reliable win.

Evidence

Same Blacksmith Testbox, 4 AMD EPYC cores, Node 26.9.0, pnpm 12.5.0. Exact baseline 3fb66f0aa4e41e605d65f5dcfb93cbef89f6bb81 and candidate 0d09190d400af40f696226f73d5718675f6711f5, separate builds, sequential A1–B1–B2–A2 runs. Each run: 100 protocol clients, 50 actively prompting, 120 s, seed 1, mock provider paced at 25 ms word chunks, CPU profile enabled, fresh isolated state. Builds and checks finished before measurement. Testbox run.

Run Completed turns Main CPU ms/completed turn First-delta p50 ms Recipient callback inclusive ms Callback ms/completed turn ELD p99 / max ms Blocks >100 ms
A1 baseline 327 360.75 10,145.25 6,480.67 19.82 39.19 / 303.56 4
B1 candidate 376 309.44 7,116.13 6,643.49 17.67 34.87 / 299.11 3
B2 candidate 393 307.38 6,962.26 6,692.73 17.03 33.29 / 214.70 5
A2 baseline 364 324.23 7,899.31 6,790.46 18.66 35.45 / 179.57 2

Both pairs improved CPU per completed turn. Two-run medians: 342.49 → 308.41 ms/turn (-9.95%), 9,022.28 → 7,039.20 ms first-delta p50 (-21.98%), and 19.24 → 17.35 sampled callback ms/completed turn (-9.81%). The directly affected describe/revalidation subtree fell from 2.881 → 2.043 sampled ms/completed turn (-29.09%).

All four runs completed with zero failed/pending turns, protocol errors, disconnects, integrity errors, active executions at close, or unattributed executions. Exact main CPU counters cover load plus drain; profile weights cover the load window and are sampled elapsed intervals, not independent function CPU counters. Raw callback load-window totals were roughly flat (6.636 → 6.668 s) while completed throughput increased. These are two pairs with cold first turns, not a stable capacity guarantee or evidence that the small lookup change alone explains every end-to-end difference.

Remaining limits: burst stalls did not consistently improve: median ELD max was 241.57 → 256.90 ms and >100 ms counts were 4/2 versus 3/5. Median peak RSS was 3,184 → 3,275 MiB. Host samples showed zero CPU steal and approximately 49–51% idle across four cores; A1 recorded 12 KiB of swap-in and subsequent runs recorded none. No browser contexts or live provider were involved.

Validation:

  • Baseline focused presentation/parity tests: 2 files, 6 tests passed, 38.76 s wall.
  • Candidate node scripts/run-vitest.mjs src/gateway/session-row-presentation.test.ts src/gateway/session-row-event-parity.test.ts src/gateway/session-row-event-trees.test.ts --maxWorkers=1: 3 files, 7 tests passed, 49.68 s wall. Existing coverage exercises recipient roles, source getters/proxies/mutations, active-run replacement and in-place changes, permission-pending changes, ancestor receipts, and list/event parity.
  • Testbox node scripts/check-changed.mjs --base 3fb66f0aa4e41e605d65f5dcfb93cbef89f6bb81: passed, 20:49.53 wall, including selected type graphs and lint with 0 warnings / 0 errors.
  • Testbox pnpm build: baseline 7:07.08, candidate 6:46.19, both exit 0. Both print the same pre-existing TypeScript experimental notices, startup CSS advisory, and startup JS gzip budget violation (362.7 KiB vs 362.6 KiB); these are outside the touched source and are reported without suppression.
  • Harness protocol tests: 16/16 passed on each ref, reported duration 71.60 / 80.17 ms.
  • Formatting and git diff --check: passed. Diff-scoped deslop: no findings. Independent Codex autoreview through P2: scoped-clean, no accepted/actionable findings.
  • Production LOC +2/-2 (net 0); test LOC +0/-0. No protocol, schema, configuration, streaming text framing, or changelog changes.

The first remote invocation stopped before builds because a scratch assertion expected the wrapper's synthetic carrier HEAD to equal the candidate SHA. The corrected script verified the exact source tree and restored the original commit identity only in the isolated build clones. No workload retry masked a failed sample. All recorded child processes and isolated state were verified removed; the owned Testbox is stopped. No open PR touching the production file was found in the pre-publication overlap check.

@clawsweeper

clawsweeper Bot commented Sep 27, 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 gateway Gateway runtime size: XS labels Sep 27, 2026
@steipete
steipete marked this pull request as ready for review September 27, 2026 10:40
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed September 27, 2026, 6:40 AM ET / 10:40 UTC.

ClawSweeper review

What this changes

The Gateway reuses a captured session row and shared presentation options when preparing session events for each connected client.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open. Current main still performs the redundant recipient lookup, and the proposed change retains the existing freshness and recipient presentation checks. No actionable patch defect was found.

Priority: P3
Reviewed head: 0d09190d400af40f696226f73d5718675f6711f5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused patch has relevant boundary coverage and detailed workload measurements, with raw Testbox traces unavailable for independent inspection.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.
Evidence reviewed 9 items Current main retains the extra lookup: The publication captures a row through describe, then calls the per-recipient snapshot method, which performs another describe.
Introduced change: The pinned PR delta replaces recipient snapshot(query) with present(record) and moves the unchanged options object outside the recipient callback. The verified test merge produces the same source change against pinned main.
Presentation owner: The presenter re-describes the captured physical row and returns null when it is no longer current; snapshot adds an initial describe before calling that same presenter.
Findings None None.
Security None None.

How this fits together

The Gateway turns session changes into recipient-specific WebSocket events for Control UI and other clients. It selects a session row, checks each recipient, and presents current row details before delivery.

flowchart LR
  A[Session change] --> B[Gateway row projection]
  B --> C[Captured session row]
  C --> D[Recipient scope check]
  D --> E[Freshness and sharing presentation]
  E --> F[WebSocket session event]
Loading

Before merge

  • Complete next step (P2) - Mark the draft ready for review when the author wants it considered for merge.
Agent review details

Security

None.

PR surface

Source 0. Total 0 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 2 2 0
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 2 2 0

Review metrics

Metric Value Why it matters
Measured Gateway CPU per turn 342.49 → 308.41 ms, down 9.95% The two baseline/candidate workload pairs report a lower median CPU cost per completed turn.

Technical review

Best possible solution:

Keep the existing recipient presenter and freshness checks as the single owner of session-row display, then land this focused lookup removal when the draft is ready.

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

Yes. Current-main source shows the captured row followed by a recipient snapshot that describes the row again; the PR body reports a controlled before/after Gateway workload, though this review did not execute it.

Is this the best way to solve the issue?

Yes. Calling the existing presenter with the captured row removes the extra lookup while retaining its current-row validation and recipient-specific shaping.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P3: This is a narrow internal performance improvement with no reported broken user workflow.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.

Label justifications:

  • P3: This is a narrow internal performance improvement with no reported broken user workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body records four before/after runs through Gateway protocol clients using the changed session-event path, with lower reported CPU per completed turn and no failed turns or protocol errors. The linked workflow is cancelled without a published artifact, so raw traces were not independently inspected. No stored-data contract changes.

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)
  • Shakker: 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.

@steipete
steipete enabled auto-merge (squash) September 27, 2026 10:43
@steipete
steipete merged commit 39f1d93 into main Sep 27, 2026
264 checks passed
@steipete
steipete deleted the perf/l120-recipient-presentation branch September 27, 2026 10:57
vincentkoc added a commit that referenced this pull request Sep 27, 2026
* commit '69809d7a94277d01be964bd1cbbb7aa0ebc58c9b': (219 commits)
  perf(agents): serialize large model requests once (#159574)
  refactor(cli): share capability agent-selection test cases (#159616)
  fix(workers): restore installation type checks (#159629)
  test(channels,qa,providers): remove low-value tests (batch d065) (#159627)
  test(doctor): run isolated migration cases concurrently (#159609)
  feat(apple): show agent identities in native chat (#159528)
  chore(i18n): refresh native locales (#159635)
  fix(gateway): keep node provisioning's installation contract after overlapped preparation
  fix(models): keep shared catalog requests alive for remaining callers (#157191)
  feat: let agents query online people and device activity (#159117)
  perf(gateway): first cloud dispatch prepares worker artifacts one after another (#159520)
  refactor(android): deslop Android app third pass (#159589)
  test(qa-lab,openshell,slack,reef,team-reports): remove low-value tests (batch d064) (#159607)
  fix: align process liveness checks (#151107) thanks @ekinnee
  fix: sessions model default does not clear the override (#159587)
  fix(ios): preserve typing during reentrant SwiftUI updates
  fix(ci): frozen 2026.8.33 validation fails on inherited test clock (#159594)
  perf(gateway): avoid duplicate recipient row lookup (#159595)
  refactor(gateway): deslop gateway fourth pass (#158786)
  test(agents): split subagent task-settlement test support under the line cap (#159584)
  ...
vincentkoc added a commit that referenced this pull request Sep 27, 2026
* commit '69809d7a94277d01be964bd1cbbb7aa0ebc58c9b': (219 commits)
  perf(agents): serialize large model requests once (#159574)
  refactor(cli): share capability agent-selection test cases (#159616)
  fix(workers): restore installation type checks (#159629)
  test(channels,qa,providers): remove low-value tests (batch d065) (#159627)
  test(doctor): run isolated migration cases concurrently (#159609)
  feat(apple): show agent identities in native chat (#159528)
  chore(i18n): refresh native locales (#159635)
  fix(gateway): keep node provisioning's installation contract after overlapped preparation
  fix(models): keep shared catalog requests alive for remaining callers (#157191)
  feat: let agents query online people and device activity (#159117)
  perf(gateway): first cloud dispatch prepares worker artifacts one after another (#159520)
  refactor(android): deslop Android app third pass (#159589)
  test(qa-lab,openshell,slack,reef,team-reports): remove low-value tests (batch d064) (#159607)
  fix: align process liveness checks (#151107) thanks @ekinnee
  fix: sessions model default does not clear the override (#159587)
  fix(ios): preserve typing during reentrant SwiftUI updates
  fix(ci): frozen 2026.8.33 validation fails on inherited test clock (#159594)
  perf(gateway): avoid duplicate recipient row lookup (#159595)
  refactor(gateway): deslop gateway fourth pass (#158786)
  test(agents): split subagent task-settlement test support under the line cap (#159584)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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