Skip to content

perf(agents): remove per-token quadratic work from the streaming fanout - #118192

Merged
steipete merged 1 commit into
mainfrom
perf/stream-hot-path-118027
Aug 2, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/stream-hot-path-118027

Conversation

@steipete

@steipete steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

What Problem This Solves

Issue #118027: the gateway event loop saturates around 8 concurrent streaming turns (cpuCoreRatio ~1.0, Control UI shell 6.7 s, delayP99 2.6 s). Profiling-by-reading found the dominant cost is per-token work proportional to the full accumulated turn text — several independent O(n²) patterns in the stream fanout, none of them needed for correctness.

Why This Change Was Made

Each provider delta previously paid:

  • extractThinkingFromTaggedStream re-running matchAll over the entire delta buffer per token → now an incremental scanner whose state shares the delta buffer's lifecycle; byte-identical outputs proven by randomized prefix-equivalence tests against the full-buffer reference.
  • normalizeLiveAssistantBufferedText + projection over the whole merged chat buffer (up to 500K chars) BEFORE the 150 ms broadcast throttle → projection is now computed lazily behind ChatRunState.resolveBuffer, memoized on the raw buffer, and every reader (broadcast, flush, abort snapshot/partials) goes through the accessor. Sanitization still always operates on the complete merged buffer — ordering only.
  • assembleAssistantBuffer(full, 4096) on the full cumulative text per token in session activity notes → full-snapshot assembly now throttled to 150 ms with forced exact sync at every consumer/flush; delta-only producers keep the historical bounded path.
  • parseAssistantTextSignature JSON.parsing the same blocks 3-5× per token → WeakMap cache keyed on block identity + signature text reference (streaming mutates blocks in place; a stale hit is impossible because the text reference is compared).
  • two content.toReversed() array copies per token → reverse index loops.
  • EventStream dequeue via splice(0,1) (O(queue), quadratic exactly when the consumer lags) → cursor dequeue with bounded compaction.

Not changed: channel partial sanitization (normalizeStreamingText) also serves unthrottled CLI/QA/typing/tool-result callers; moving it behind the draft-loop throttle needs an explicit deferred-normalization contract and is deferred as a follow-up rather than forced into this no-behavior-change patch.

User Impact

No behavior change: emitted payloads, persisted transcripts, and channel output are byte-identical (regression tests assert equivalence and sanitizer-call counts). Streaming turns stop costing O(turn-length) CPU per token on the gateway main loop, directly raising the concurrent-streaming ceiling from #118027.

Evidence

  • 130 agent/scanner/session tests, 347 gateway tests, 158 signature/payload/EventStream tests, 108 observer/narrator tests passed; pnpm tsgo:core and git diff --check clean.
  • New regressions: randomized incremental-parser prefix equivalence; sanitize-count O(broadcasts) not O(deltas) with cross-frame tag proof; activity-note flush/delta/protected-context; signature cache hit/invalidation; EventStream ordering + compaction boundary.
  • Autoreview (Codex gpt-5.6-sol, high): clean, "patch is correct (0.98)".
  • Production delta +136 (scanner state, lazy projection owner, signature cache, queue cursor), tests +279.

Part of #118027. Siblings: feat/event-loop-observability-118027 (adds the concurrency benchmark that measures this), perf/sessions-list-118027.

@steipete
steipete marked this pull request as ready for review August 2, 2026 20:47
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 2, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 2, 2026, 4:53 PM ET / 20:53 UTC.

ClawSweeper review

What this changes

This PR removes repeated per-token full-buffer parsing, projection, signature parsing, and queue copying from agent streaming and gateway fanout while preserving chat, abort, and session-note outputs.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 3 items remain

Keep open. Current main still performs full-buffer sanitization/projection before the broadcast throttle and removes queued events with head splices; this PR replaces those repeated hot-path costs with lifecycle-owned incremental state and a shared lazy buffer accessor. The source and focused regression coverage support the design, but the PR body does not include inspectable after-fix load evidence for its gateway-concurrency claim.

Priority: P3
Reviewed head: 6f06933ee89b33751875d2a52d21bf46370d7bc7

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is coherent and regression-focused, but the real behavior proof gate remains unmet for this performance claim.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The PR provides focused tests and CI claims, but no inspectable after-fix live or benchmark output demonstrating improved gateway behavior under concurrent streaming; attach redacted runtime evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The PR provides focused tests and CI claims, but no inspectable after-fix live or benchmark output demonstrating improved gateway behavior under concurrent streaming; attach redacted runtime evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Current-main performance path: Current main normalizes and projects the complete merged assistant buffer on every agent event before checking the 150 ms broadcast throttle, so the reported repeated work remains present.
Current-main queue behavior: Current main removes each queued EventStream value with splice(0, 1), retaining the queue-head copying cost the PR targets.
Canonical lazy-projection boundary: The proposed resolveBuffer caches projection only for the exact raw buffer and is used by broadcast, abort, and snapshot consumers, keeping complete-buffer sanitization at one owner boundary.
Findings None None.
Security None None.

How this fits together

Provider streaming deltas pass through embedded-agent handlers into live gateway buffers, session activity notes, and async stream consumers. Those buffers are sanitized and projected before broadcasts, abort snapshots, history recovery, and user-visible channel output.

flowchart LR
  Provider[Provider stream deltas] --> Agent[Embedded agent handler]
  Agent --> Reasoning[Thinking-tag extraction]
  Agent --> Notes[Session activity notes]
  Agent --> Buffer[Gateway live buffer]
  Buffer --> Projection[Sanitize and project]
  Projection --> Fanout[Gateway chat fanout]
  Fanout --> Clients[Chat and channel clients]
  Agent --> Queue[Async event queue]
  Queue --> Consumers[Stream consumers]
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The PR provides focused tests and CI claims, but no inspectable after-fix live or benchmark output demonstrating improved gateway behavior under concurrent streaming; attach redacted runtime evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - The PR body reports tests and pre-fix production symptoms but does not provide inspectable after-fix concurrent-streaming evidence, so the claimed event-loop improvement remains unverified outside mocks and unit-level regressions.
  • Complete next step (P2) - No mechanical defect was found to repair automatically; the remaining merge gate is real concurrent-streaming proof, and the maintainer label requires human handling.
Agent review details

Security

None.

PR surface

Source +136, Tests +279. Total +415 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 14 237 101 +136
Tests 6 281 2 +279
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 518 103 +415

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/agents/session-activity-notes.test.ts, serialized state: src/agents/session-activity-notes.ts, serialized state: src/shared/chat-message-content.test.ts, serialized state: src/shared/chat-message-content.ts, unknown-data-model-change: src/agents/session-activity-notes.test.ts, unknown-data-model-change: src/agents/session-activity-notes.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #118027
Summary: This PR is a candidate fix for the streaming-fanout component of the canonical gateway concurrency report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Add real load proof before merge (recommended)
    Run the changed streaming path under representative concurrent load and attach redacted before/after gateway delay and output-integrity evidence.
  2. Accept unit-only performance evidence
    A maintainer may merge based on the focused equivalence tests and CI alone, accepting that the stated concurrency ceiling has not been independently re-measured.

Technical review

Best possible solution:

Keep the unified lazy resolveBuffer ownership model, then add a redacted before/after concurrent-streaming run that records event-loop delay, utilization, and preserved output/abort behavior before merging.

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

Yes at source level: current main normalizes/projects the cumulative chat buffer before its 150 ms throttle and dequeues EventStream values with splice(0, 1). A local concurrent-load run was not performed in this read-only review.

Is this the best way to solve the issue?

Yes: centralizing lazy projection in ChatRunState.resolveBuffer is the best fix shape because broadcast, abort, and snapshot readers need the same complete-buffer sanitization result; throttling only the broadcast caller would leave sibling consumers inconsistent.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P3: The related load report describes scaling headroom with graceful recovery and no reported delivery loss, so this is useful but not currently urgent.
  • add merge-risk: 🚨 availability: The patch changes the single gateway event-loop streaming fanout path, and its promised responsiveness gain still lacks attached after-fix runtime evidence.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR provides focused tests and CI claims, but no inspectable after-fix live or benchmark output demonstrating improved gateway behavior under concurrent streaming; attach redacted runtime evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P3: The related load report describes scaling headroom with graceful recovery and no reported delivery loss, so this is useful but not currently urgent.
  • merge-risk: 🚨 availability: The patch changes the single gateway event-loop streaming fanout path, and its promised responsiveness gain still lacks attached after-fix runtime evidence.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR provides focused tests and CI claims, but no inspectable after-fix live or benchmark output demonstrating improved gateway behavior under concurrent streaming; attach redacted runtime evidence before merge. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Current-main performance path: Current main normalizes and projects the complete merged assistant buffer on every agent event before checking the 150 ms broadcast throttle, so the reported repeated work remains present. (src/gateway/server-chat.ts:910, b35b8e286df0)
  • Current-main queue behavior: Current main removes each queued EventStream value with splice(0, 1), retaining the queue-head copying cost the PR targets. (packages/llm-core/src/utils/event-stream.ts:66, b35b8e286df0)
  • Canonical lazy-projection boundary: The proposed resolveBuffer caches projection only for the exact raw buffer and is used by broadcast, abort, and snapshot consumers, keeping complete-buffer sanitization at one owner boundary. (src/gateway/server-chat-state.ts:270, 6f06933ee89b)
  • Incremental parser equivalence coverage: The PR adds randomized prefix-by-prefix tests comparing the incremental thinking-tag extractor to the complete-buffer reference implementation. (src/agents/embedded-agent-utils.test.ts:103, 6f06933ee89b)
  • Flush and protected-context coverage: The new session-activity tests cover throttled cumulative updates, forced flushes, split internal-context filtering, and the existing bounded delta-only path. (src/agents/session-activity-notes.test.ts:19, 6f06933ee89b)
  • PR provenance and current-main status: The proposed change is commit 6f06933ee89b33751875d2a52d21bf46370d7bc7 by Peter Steinberger on August 2, 2026; it is not an ancestor of current main, so the work is neither merged nor superseded on this checkout. (src/gateway/server-chat-state.ts:270, 6f06933ee89b)

Likely related people:

  • Vincent Koc: The available current-main history attributes the central gateway chat-state and streaming files to the recent gateway lease-handoff commit; the shallow history limits stronger ownership attribution. (role: recent area contributor; confidence: low; commits: 1704ea591820; files: src/gateway/server-chat-state.ts, src/gateway/server-chat.ts, src/agents/embedded-agent-utils.ts)

Rank-up moves

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

  • Attach a redacted before/after concurrent-streaming benchmark showing event-loop delay or utilization and unchanged delivery behavior.

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 commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

ClawSweeper rank-up move handling: skipping the optional before/after concurrent-streaming benchmark in this PR. The benchmark harness and load measurement are owned by the named sibling feat/event-loop-observability-118027; duplicating that observability surface here would broaden this behavior-neutral hot-path patch and make the two landing lanes overlap.

For this PR, the accepted proof is the exact-head green CI plus focused byte-equivalence, sanitizer-call-count, flush/abort, signature-cache, and EventStream ordering/compaction regressions already listed in the body. The coordinator also ran the required Codex autoreview on this patch and it completed clean at 0.98. This consciously accepts unit/regression evidence for the no-behavior-change refactor; the sibling benchmark will provide the inspectable concurrent-load measurement.

@steipete
steipete merged commit 70876c9 into main Aug 2, 2026
183 of 195 checks passed
@steipete
steipete deleted the perf/stream-hot-path-118027 branch August 2, 2026 21:07
@steipete

steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Aug 2, 2026
* origin/main:
  feat(gateway): track event-loop degradation persistence and add concurrency benchmark (#118193)
  fix(config): preserve secret ownership when configuration rows move (#118149)
  fix(cron): deliver failure alerts after persistence (#118200)
  chore(lint): clear 172 lint:all baseline violations in five batches (#118098)
  perf(gateway): remove streaming hot-path rescans (#118192)
  test(gateway): use in-memory task registry (#118191)
  test(macos): fix three races in the bounded process suites (#118196)
  refactor(migrate-hermes): consolidate test fixtures (#118182)
  test(android): share Wear transport fixtures (#118177)
  test(ui): deduplicate control UI e2e setup (#118180)
  fix(plugins): unblock prerelease validation (#118103)
  test(cli): reduce redundant process launches (#118141)
  test(gateway): compact terminal observer fixtures (#118179)
  fix(agents): make requested threads sidebar-visible (#118073)
  test(plugins): canonicalize native resolver fixtures (#118174)
  test: deduplicate agent runner fixtures (#118176)
  refactor(policy): consolidate doctor test fixtures (#118173)
  fix(plugins): remove disabled channel plugin configuration on uninstall (#118127)
  refactor(matrix): consolidate monitor test fixtures (#118175)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 3, 2026
* origin/main:
  feat(gateway): track event-loop degradation persistence and add concurrency benchmark (openclaw#118193)
  fix(config): preserve secret ownership when configuration rows move (openclaw#118149)
  fix(cron): deliver failure alerts after persistence (openclaw#118200)
  chore(lint): clear 172 lint:all baseline violations in five batches (openclaw#118098)
  perf(gateway): remove streaming hot-path rescans (openclaw#118192)
  test(gateway): use in-memory task registry (openclaw#118191)
  test(macos): fix three races in the bounded process suites (openclaw#118196)
  refactor(migrate-hermes): consolidate test fixtures (openclaw#118182)
  test(android): share Wear transport fixtures (openclaw#118177)
  test(ui): deduplicate control UI e2e setup (openclaw#118180)
  fix(plugins): unblock prerelease validation (openclaw#118103)
  test(cli): reduce redundant process launches (openclaw#118141)
  test(gateway): compact terminal observer fixtures (openclaw#118179)
  fix(agents): make requested threads sidebar-visible (openclaw#118073)
  test(plugins): canonicalize native resolver fixtures (openclaw#118174)
  test: deduplicate agent runner fixtures (openclaw#118176)
  refactor(policy): consolidate doctor test fixtures (openclaw#118173)
  fix(plugins): remove disabled channel plugin configuration on uninstall (openclaw#118127)
  refactor(matrix): consolidate monitor test fixtures (openclaw#118175)
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 maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant