Skip to content

perf(gateway): keep long chat streams responsive - #158489

Merged
steipete merged 4 commits into
mainfrom
perf/l02-incremental-live-directives
Sep 26, 2026
Merged

steipete merged 4 commits into
mainfrom
perf/l02-incremental-live-directives

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long streaming answers can stall other chat sessions because display filtering repeatedly scans and allocates the entire growing reply, especially when the answer contains literal reply-marker examples.

User Impact

Concurrent Control UI replies use substantially less projection work while preserving displayed text, suppression, media handling, recovery snapshots, and event ordering. The Gateway wire payload, configuration, and database schemas are unchanged.

Why This Change Was Made

The existing chat-run owner now retains one incremental display chain and carries prepared append deltas through to delivery. Every stage reuses its canonical transform when syntax requires it; ordinary appends use incremental activation checks. Literal directive ownership is shared with the embedded stream's existing Markdown logic. Corrections, cap rollover, and changed managed-media facts reset the chain, and final reads cannot release unfinished tails into live state.

This replaces the full-source projection cache and separate broadcast prefix comparison. Production grows by 244 lines (+419/-175); tests grow by 110 lines (+139/-29). The additional stage and lifecycle state preserves the existing normalization contracts; the shared parser logic and superseded comparison paths were consolidated rather than retained in parallel.

Evidence

Isolated measurements used Node 26.9.0 on an Apple M3 Ultra under shared-host load; these are owner/handler benchmarks, not live Gateway latency claims.

50 runs, 100-character boundaries Before sampled allocation After Before/after wall time
20,000 characters/run 120.2 MB 21.0 MB 199 / 21 ms
40,000 characters/run 430.0 MB 38.2 MB 909 / 41 ms
80,000 characters/run 1,659.2 MB 72.1 MB 3,365 / 68 ms

Allocation sampling includes objects collected by minor and major GC. The append workload now grows approximately linearly. Observed process RSS across these paired measurements was 183–194 MB; that is not a peak or retained-memory comparison.

The real event-handler comparison used 50 synthetic runs with cumulative provider snapshots and unchanged JSON encoding. The 20k marker case fell from 82.28 s to 0.47 s; ordinary 40k snapshots took 17.47 s before and 15.62 s after, with unchanged serialization dominating. Host timing variance was substantial, so allocation and exact byte comparisons are the stronger evidence. Both comparisons produced identical event counts, serialized byte counts, and SHA-256 hashes. Separate differential checks against the original built normalization matched 7,054 boundaries, including 20k/40k/80k replies, split directives, runtime context, media, control tokens, and changing Markdown references.

Already-flat cumulative snapshots reuse their validated raw bytes: 40k/50-run projection took 292 ms versus 2,074 ms before. This path allocates 46.3 MB versus 29.3 MB before because of linear state bookkeeping.

Validation:

  • Focused owner/merge tests: 73 passed; 335.44 s wall, dominated by shared-host transform/startup waits.
  • Registered handler, abort, close, maintenance, embedded stream, directive, and shared text-projection suites: 491 passed; 742.47 s wall, including automatic worker compilation.
  • New regression file: node scripts/run-vitest.mjs src/gateway/server-chat-state.projection.test.ts --maxWorkers=1 — 9 passed, 23.85 s wall; 1.98 s test execution.
  • Abort fixture after the line-cap repair: 50 passed, 48.53 s wall.
  • Final prepared-source correction: 269 focused owner/handler/shared-projection tests passed, 598.37 s wall including worker compilation.
  • node scripts/check-changed.mjs passed, including all 25 affected test typecheck graphs and policy guards; 4,544.37 s wall on the shared host.
  • Deslop completed. Final Codex autoreview: scoped-clean at P0/P1, no accepted/actionable findings.

Validation used isolated owner and handler fixtures; no live Gateway was started or modified.

Merge validation

Merged main 3ed4948024e3a9df038db0f67b36f3491a604f07 into the branch, preserving the bounded reply-tag reader and the lastActivityAt-based maintenance owner. The moved maintenance fixture now seeds and clears the run-owned display projector. Candidate: a3b3f0510608664148d51387747feee4f7552865. Display and wire contracts are unchanged.

The focused projection, state, stream-merge, agent-event, control-reply, directive-parser, and moved maintenance suites passed: 388 tests, 464.29 s local wall time including cold worker compilation. A disposable differential probe matched canonical display bytes, suppression, reconstructed deltas, replacements, and final reads at 4,184 delta/snapshot boundaries. Its initial replacement fixture mixed item identities; correcting that fixture required no product change.

node scripts/check-changed.mjs --base origin/pr-158489-proof-base passed on Blacksmith Testbox tbx_01m3dtgce2zrgykx1agv0snnrd, including all 25 affected test typecheck graphs, lint, formatting, and policy guards. Testbox run; delegated command 28m38s, exit 0, box stopped and verified completed. The backing Actions job can show cancelled because the one-shot lease owns shutdown. An external runner-portal sync timeout was a post-success warning.

Fresh Codex autoreview raised one performance concern about full parsing after an active stripped directive. Rejected as a regression finding: main already reparses that path, the approved design retains the canonical transform when syntax is active, and later Markdown can change earlier directive ownership. No accepted actionable findings remain. The conflicts and retired activity-field fixture identified by ClawSweeper are resolved; no live Gateway was started or changed.

@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 gateway Gateway runtime agents Agent runtime and tooling size: L labels Sep 26, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. 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: needs maintainer review before merge. Reviewed September 25, 2026, 11:40 PM ET / September 26, 2026, 03:40 UTC (Revision 4).

ClawSweeper review

What this changes

The branch incrementally filters Gateway chat streams, carries prepared text deltas into broadcasts, shares directive parsing with the agent stream, and adds projection lifecycle tests.

Merge readiness

✅ Ready for maintainer review

Keep open. Current main still normalizes the full growing chat buffer, so this performance change remains useful. The latest branch addresses the prior activity-clock fixture concern, and this review found no definite introduced defect.

Priority: P2
Reviewed head: a3b3f0510608664148d51387747feee4f7552865

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch is focused on the existing owner and has quantified handler evidence and focused regression coverage, with no definite correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its body reports production-handler measurements with synthetic events and matching serialized output, but no live Gateway run; the diff changes in-memory projection, not a stored-data contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its body reports production-handler measurements with synthetic events and matching serialized output, but no live Gateway run; the diff changes in-memory projection, not a stored-data contract.
Evidence reviewed 7 items Current-main behavior: Current main retains a full-buffer normalization call when a changed live buffer is resolved, so the central optimization is not already present.
Introduced owner change: The branch moves buffer merging and display projection into chat-run state, with append, correction, cap, and managed-media handling.
Protocol contract: The documented chat protocol sends append text in deltaText and marks non-prefix replacements with replace=true; the changed broadcast path continues to produce those forms.
Findings None None.
Security None None.

How this fits together

Agent text updates enter Gateway chat-run state, where internal directives are filtered before chat events reach Control UI clients. The embedded agent stream shares the directive parser used to distinguish literal Markdown examples from reply controls.

flowchart LR
  A[Agent text updates] --> B[Gateway chat run]
  B --> C[Display projection]
  C --> D{Append or correction?}
  D --> E[Chat deltas and snapshots]
  E --> F[Control UI clients]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +244, Tests +110. Total +354 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 9 419 175 +244
Tests 6 139 29 +110
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 558 204 +354

Review metrics

Metric Value Why it matters
Code growth production +244 net lines; tests +110 net lines The PR body attributes the production growth to incremental projection and run lifecycle state.
Synthetic marker workload 82.28 s before; 0.47 s after across 50 runs The reported handler measurement supports the performance goal but is not live Gateway latency.

Technical review

Best possible solution:

Retain one run-owned display projection while preserving the documented append and replacement event contract and the existing run cleanup lifecycle.

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

Yes in source: current main re-normalizes a changed growing buffer, and the PR body reports a measured long-stream workload. This read-only review did not execute that workload.

Is this the best way to solve the issue?

Yes. The branch changes the existing chat-run owner, resets projection on corrections and changed media facts, and retains the canonical transforms for activated syntax.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate. Its body reports production-handler measurements with synthetic events and matching serialized output, but no live Gateway run; the diff changes in-memory projection, not a stored-data contract.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Long streamed replies can delay other chats, but this is a bounded performance improvement rather than an emergency.
  • merge-risk: 🚨 message-delivery: The branch changes how chat append and replacement events are calculated, making display-byte preservation the relevant merge-risk surface.
  • 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 maintainer-authored PR is exempt from the external-contributor proof gate. Its body reports production-handler measurements with synthetic events and matching serialized output, but no live Gateway run; the diff changes in-memory projection, not a stored-data contract.

Evidence

What I checked:

  • Current-main behavior: Current main retains a full-buffer normalization call when a changed live buffer is resolved, so the central optimization is not already present. (src/gateway/server-chat-state.ts:295, 11ce05bac7c6)
  • Introduced owner change: The branch moves buffer merging and display projection into chat-run state, with append, correction, cap, and managed-media handling. (src/gateway/server-chat-state.ts:286, a3b3f0510608)
  • Protocol contract: The documented chat protocol sends append text in deltaText and marks non-prefix replacements with replace=true; the changed broadcast path continues to produce those forms. Public docs: docs/gateway/protocol/rpc-bootstrap-and-events.md. (docs/gateway/protocol/rpc-bootstrap-and-events.md:66, a3b3f0510608)
  • Prior finding addressed: The moved stale-run fixture now seeds state through the run owner while the maintenance path expires runs using lastActivityAt. This addresses the concrete concern retained from the previous ClawSweeper review. (src/gateway/server-maintenance.chat-state.test.ts:46, a3b3f0510608)
  • Reported validation: The captured PR body reports identical event counts, serialized byte counts, and SHA-256 hashes in before/after synthetic handler comparisons, plus 4,184 post-merge differential boundaries. It expressly says no live Gateway was started; these are contributor-reported results, not checks rerun in this read-only review. (a3b3f0510608)
  • Feature history: Recent merged work in the same Gateway and directive paths includes live-state cleanup, incomplete-directive handling, and streamed-reply preservation. This supports routing candidates without assigning fault or claiming source-line introduction. (src/gateway/server-chat-state.ts, 11ce05bac7c6)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): 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 (3 earlier review cycles)
  • reviewed 2026-09-26T00:39:45.129Z sha c3c59aa :: blocked before merge. :: none
  • reviewed 2026-09-26T00:47:26.937Z sha c3c59aa :: blocked before merge. :: none
  • reviewed 2026-09-26T01:36:45.070Z sha c3c59aa :: blocked before merge. :: [P2] Port stale-run fixtures to main's activity clock

@steipete
steipete marked this pull request as ready for review September 26, 2026 00:41
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 26, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
Preserve main’s bounded reply-tag parser and lastActivityAt maintenance ownership. Move projector cleanup fixture coverage into the dedicated chat-state maintenance suite. Keep display bytes and wire payload semantics unchanged.
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 26, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
@steipete
steipete merged commit e8bea93 into main Sep 26, 2026
199 checks passed
@steipete
steipete deleted the perf/l02-incremental-live-directives branch September 26, 2026 04:04
@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
* perf(gateway): project live chat displays incrementally

* test(gateway): seed abort buffers through the run owner

* perf(gateway): reuse prepared stream snapshots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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