Skip to content

improve(agents): reduce overhead while streaming long replies - #136180

Merged
steipete merged 2 commits into
mainfrom
codex/incremental-reply-stream-20260902
Sep 2, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/incremental-reply-stream-20260902

Conversation

@steipete

@steipete steipete commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long streamed replies repeatedly rescanned growing text and allocated temporary strings on the Gateway event loop. At 32 concurrent long replies, the baseline stress run exhausted the default JavaScript heap. This change reuses an incremental reply projection and consolidates overlapping sanitizer passes.

Why This Change Was Made

The subscriber owns one projection using the canonical sanitizer grammar. Marker-free appends reuse the existing prefix; marker activation and corrections retain the full grammar. Raw reply directives keep their raw parser coordinates. Dead pending partial-media state is removed; message completion remains the media producer and delivery boundary.

Production +645/−656 (net −11); tests +178/−9 (net +169). No configuration, database, provider API, or Gateway protocol changes. This is the first PR in the concurrent-agent performance series; prepared delivery and warm loop workers follow separately.

User Impact

Concurrent long replies consume substantially less CPU and peak memory in the measured workloads. Text, directive, reasoning, Markdown and final-media behavior retain the existing contracts. Control latency is mixed across whole-run samples; the measurements below include that tradeoff.

Evidence

Fresh baseline 9e6912ca0d2e0200bdcbcfc32bde2d27db262464 and exact-head 3e0330d9e85ac096e37317411af1a234847a2345 builds, pinned Node 24.19.0 and pnpm 12.1.0. Deterministic Gateway runs use real read/exec tools, same-session serialization, cancellation/reuse and exact 92,160-byte replies. Every accepted final matches both the sealed expected output and its full persisted transcript.

Workload Wall time, before → after CPU time, before → after Peak Gateway RSS, before → after
8 admitted turns, 256 updates, short burst 2.552 → 1.917 s 3.000 → 2.320 s 1,210 → 1,197 MiB
8 admitted turns, 4,096 updates, short burst 19.660 → 5.802 s 17.380 → 4.390 s 2,674 → 1,235 MiB
8 overlapping streams, 4,096 paced updates 15.447 → 6.946 s 15.970 → 4.100 s 2,523 → 1,231 MiB

The sustained eight-stream pair reduced wall time by 55.0%, CPU by 74.3%, and peak RSS by 51.2%. All eight provider streams overlapped for about 5.4 seconds. Independent control probes covered over 98% of that overlap: readiness p95 12.24 → 2.25 ms, sessions-list p95 21.82 → 6.14 ms. Across the entire concurrent phase, readiness p95 was 29.16 → 23.20 ms, while sessions-list p95 increased 32.71 → 38.07 ms (123 versus 60 samples). This is an accepted measured tradeoff, not an across-the-board latency claim. After all lifecycle cases, RSS at 5 seconds idle was 2,756 → 1,260 MiB, and at 30 seconds 614 → 587 MiB, without forced GC.

32-stream capacity result: the candidate completed 37 exact replies including lifecycle cases, 112 provider requests, tools, serialization and cancellation/reuse. Its concurrent phase took 12.039 s / 14.000 s CPU, peaked at 1,504 MiB, and returned to 594 MiB after 30 seconds idle. All 32 provider streams overlapped for 5.414 seconds; whole-phase readiness/sessions p95 was 53.12 / 108.47 ms. The subsequent baseline admitted all 32 streams but aborted with Reached heap limit / JavaScript heap out of memory. The eight-run batch stopped there: four repeat runs were never started. The original batch remains failed/incomplete; an independent offline verifier accepted only the three completed runs and recorded the baseline failure. There is one completed sustained eight-stream pair and one unpaired candidate 32-stream result, not repeated-pair or maximum-throughput evidence.

CPU uses alive process-tree snapshots and can omit exited tool processes. RSS includes Gateway workers and excludes the provider/harness/tools. Host load was uncontrolled. Short bursts overlapped only two to three provider requests; their small control samples regressed at 4,096 updates (readiness p95 66 → 114 ms; sessions 75 → 284 ms). The paced fixture supplies the stronger overlap evidence. These results do not prove statistical significance, retained-heap leaks, or parallel JavaScript execution. Source, dependencies, helper and built-output inventories remained unchanged; generated pnpm shims were compared with narrowly checked own-root normalization.

Real OpenAI: exact-head openai/gpt-5.6-luna completed nine successful turns plus cancellation, 27 model calls/usage events and eight reconciled session projections. Cold/warm execution, four concurrent long replies, same-session serialization, real read/exec, cancellation/reuse and clean shutdown passed. Every streamed final matched the full final message in a private copy of the closed SQLite transcript. Concurrent replies were 13,668 / 14,156 / 24,307 / 27,663 bytes, over 311 / 326 / 677 / 758 frames. Each call had an 8,192-output-token cap. Live timing is diagnostic, not a paired performance result. Credentials were neither printed nor persisted.

Correctness: 1,311 tests in 41 files passed, including subscriber lifecycle, shared sanitization and WhatsApp delivery. An independent original/current oracle compared 90,016 byte-identical observations across static prefixes, incremental partitions and real subscriber events. It caught duplicate-paragraph and raw/display-coordinate prototype regressions, which have failing-before/passing-after evidence. Final mechanical type/export/local-variable cleanup received focused tests, types, lint and review. Changed checks passed types, boundaries, formatting and dead exports; two final lint findings were corrected and the lint rerun passed. Three Codex autoreview rounds were clean at the configured P0 threshold.

Exact-head CI passed. The initial ready event hit GitHub's PR merge-ref startup race; one close/reopen produced the green run without product changes.

ClawSweeper follow-through: CPU/RSS and real-provider proof are supplied above. I accept the focused deterministic split-directive/final-media coverage alongside the live long-stream proof for this behavior-preserving refactor. A combined live directive/media trace is not claimed. The removed pending-media state had no production producer; partial parsing never produced media URLs, so this does not delay previously emitted media. The stored-data heuristic is a false positive: there is no schema, SQLite, migration or persistence change. Current-main commentary completion and delivery-gate bypass were inspected.

Local evidence index: .artifacts/threading/stream-redesign-20260902/. Key receipts: paired-c8-d256-v4-1/summary.json, paired-c8-d4096-v4-1/summary.json, sustained-partial-evidence-v1/summary.json (SHA-256 9622fa03198fbf26215cada2ef4a1f282e82175904293aa4dd05ebc79dffeb9c), and candidate-long-live-c4-1-oracle/verification.json. These are local evidence paths, not hosted artifact links. All failed attempts remain preserved.

Local verification commands (Node 24.19.0)
node scripts/run-vitest.mjs \
  src/agents/embedded-agent-helpers.sanitizeuserfacingtext.scaffolding.test.ts \
  src/agents/embedded-agent-helpers.sanitizeuserfacingtext.test.ts \
  src/agents/embedded-agent-subscribe.before-terminal-delivery.test.ts \
  src/agents/embedded-agent-subscribe.block-reply-rejections.test.ts \
  src/agents/embedded-agent-subscribe.callback-fatal.test.ts \
  src/agents/embedded-agent-subscribe.code-span-awareness.test.ts \
  src/agents/embedded-agent-subscribe.handlers.compaction.test.ts \
  src/agents/embedded-agent-subscribe.handlers.lifecycle.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.replies.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.stream-replies.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.update-commentary.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.update-source.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.update-stream-items.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.update-stream-phases.test.ts \
  src/agents/embedded-agent-subscribe.handlers.tools.media.test.ts \
  src/agents/embedded-agent-subscribe.handlers.tools.test.ts \
  src/agents/embedded-agent-subscribe.lifecycle-billing-error.test.ts \
  src/agents/embedded-agent-subscribe.partial-reply-lifecycle.test.ts \
  src/agents/embedded-agent-subscribe.raw-stream.test.ts \
  src/agents/embedded-agent-subscribe.reply-tags.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.block-reply-flushing.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.chunking-fences.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.compaction-and-tool-summaries.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.final-answer-delivery.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.final-tag-streaming.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.reasoning-delivery.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.source-reply-suppression.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts \
  src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.text-end-reconciliation.test.ts \
  src/agents/embedded-agent-subscribe.tool-result-ordering.test.ts \
  src/agents/embedded-agent-subscribe.tools.extract.test.ts \
  src/agents/embedded-agent-subscribe.tools.media.test.ts \
  src/agents/embedded-agent-subscribe.tools.reconcile-thread.test.ts \
  src/agents/embedded-agent-subscribe.tools.test.ts \
  src/agents/embedded-agent-subscribe.unsubscribe-tool-start.test.ts \
  src/agents/embedded-agent-utils.test.ts \
  src/auto-reply/reply/reply-utils.test.ts \
  src/shared/text/assistant-visible-text.test.ts \
  src/shared/text/text-projection.test.ts \
  extensions/whatsapp/src/channel-outbound.test.ts

node scripts/check-changed.mjs \
  -- \
  src/agents/embedded-agent-helpers/sanitize-user-facing-text.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.replies.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.stream-replies.test.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.stream.ts \
  src/agents/embedded-agent-subscribe.handlers.messages.update.ts \
  src/agents/embedded-agent-subscribe.handlers.types.ts \
  src/agents/embedded-agent-subscribe.reply-tags.test.ts \
  src/agents/embedded-agent-utils.ts \
  src/auto-reply/reply/reply-utils.test.ts \
  src/auto-reply/reply/streaming-directives.ts \
  src/auto-reply/reply/strip-inbound-meta.ts \
  src/shared/text/assistant-visible-text.ts \
  src/shared/text/code-regions.ts \
  src/shared/text/text-projection.test.ts \
  src/shared/text/text-projection.ts

The changed gate reached the final lint step with all earlier checks passing; its two parameter-reassignment findings were fixed and the exact file-scoped lint rerun passed. Exact-head hosted CI independently passed.

Carry append and replacement facts through the canonical visibility filters, normalize streamed whitespace and duplicate paragraphs incrementally, and consolidate XML and legacy text parsing. Preserve phase, directive, and final-media ownership while reducing production code.
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 2, 2026
@steipete
steipete marked this pull request as ready for review September 2, 2026 08:57
@clawsweeper

clawsweeper Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete steipete closed this Sep 2, 2026
@steipete steipete reopened this Sep 2, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 5:48 AM ET / 09:48 UTC.

ClawSweeper review

What this changes

The branch replaces repeated whole-reply sanitization during agent streaming with reusable incremental text projection while retaining reply directives and final-media handling at message completion.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep open for maintainer review. The incremental projection is not on current main, no introduced correctness defect was established, and the prior performance evidence was supplied; the remaining decision is whether deterministic directive/media coverage plus the described live long-stream run is sufficient without a targeted live directive/media trace.

Priority: P3
Reviewed head: 3e0330d9e85ac096e37317411af1a234847a2345
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has coherent owner-boundary coverage and no identified defect, but direct evidence for the changed directive/media delivery scenario is incomplete.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: Repository State identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless describes a real OpenAI long-stream run; the local receipts and the omitted live split-directive/final-media scenario remain unavailable for independent inspection.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless describes a real OpenAI long-stream run; the local receipts and the omitted live split-directive/final-media scenario remain unavailable for independent inspection.
Evidence reviewed 7 items Projection owner: The update handler creates or reuses the incremental projector before directive parsing, and accepts its delta only for safe append delivery.
Canonical filter composition: The new projector composes the established assistant-visible and user-facing filters instead of introducing a separate streaming grammar.
Final-media lifecycle: Message completion still parses the final text and resolves media URLs there, while intermediate pending directives retain only reply and voice intent.
Findings None None.
Security None None.

How this fits together

The embedded agent subscriber converts model text events into cleaned partial replies and a final outbound reply. This change sits between streaming text ingestion, visibility filtering, directive parsing, and channel-facing reply delivery.

flowchart LR
A[Model text events] --> B[Subscriber update handler]
B --> C[Incremental text projection]
C --> D[Reply directive parser]
D --> E[Partial reply events]
D --> F[Message completion]
F --> G[Final media delivery]
Loading

Decision needed

Question Recommendation
Should this PR merge on its deterministic directive/media coverage and documented real long-stream run, or require a targeted production-path trace for split directives and final media? Add targeted delivery trace: Publish a redacted production-path trace showing split reply directives and final media at message completion before merging.

Why: The branch changes partial-reply projection and final-media lifecycle boundaries; the supplied live run deliberately uses plain output, while focused tests cover the omitted directive/media case.

Before merge

  • Resolve merge risk (P1) - The described real OpenAI run exercises long plain streams, but it does not show split reply directives and final media through that live path; deterministic owner-boundary tests cover those semantics, so proof sufficiency remains a maintainer decision.
  • Complete next step (P2) - Resolve whether focused deterministic directive/media coverage is sufficient or add a redacted production-path trace for split directives and final media before merge.
Agent review details

Security

None.

PR surface

Source -11, Tests +169. Total +158 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 12 645 656 -11
Tests 4 178 9 +169
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 823 665 +158

Review metrics

Metric Value Why it matters
Production versus test LOC production +645/-656 (net -11); tests +178/-9 (net +169) The performance refactor is net-negative in production while adding focused projection and streaming-boundary coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/embedded-agent-helpers/sanitize-user-facing-text.ts, migration/backfill/repair: src/shared/text/assistant-visible-text.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Add a targeted delivery trace (recommended)
    Show split reply directives and final media flowing through the production delivery boundary so the changed partial/final handoff is directly observable.
  2. Accept the deterministic coverage
    A maintainer may accept the focused subscriber and lifecycle tests plus the supplied long-stream provider result as adequate evidence.

Technical review

Best possible solution:

Keep the single projection path and add a redacted production-path trace that demonstrates split directives and final media reaching completion delivery before merge.

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

A source-level reproduction path is clear: the prior update handler repeatedly rebuilt and sanitized cumulative stream text. The submitted benchmark describes a concrete pinned baseline/head scenario, but its local receipts could not be independently opened from this checkout.

Is this the best way to solve the issue?

Yes for the implementation shape: the projector is owned beside the canonical text filters and avoids a second stream-specific sanitizer. The remaining question is evidence sufficiency for directive/media delivery, not an alternative code architecture.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P3: This is a performance-focused internal streaming improvement rather than a demonstrated user-facing regression.
  • merge-risk: 🚨 message-delivery: The PR changes how partial reply text, directives, and final media cross the subscriber delivery boundary.
  • 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: Repository State identifies this as a MEMBER-authored PR, so the external-contributor proof gate does not apply. Its body nevertheless describes a real OpenAI long-stream run; the local receipts and the omitted live split-directive/final-media scenario remain unavailable for independent inspection.

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

  • Add a redacted production-path trace for split directives and final media, or have a maintainer explicitly accept the focused deterministic coverage.

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-02T09:04:25.636Z sha 3e0330d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T09:11:20.471Z sha 3e0330d :: needs maintainer review before merge. :: none

@steipete steipete self-assigned this Sep 2, 2026
@steipete
steipete merged commit 6c1dde5 into main Sep 2, 2026
361 of 365 checks passed
@steipete
steipete deleted the codex/incremental-reply-stream-20260902 branch September 2, 2026 10:12
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

* perf(agents): reuse incremental reply projections

Carry append and replacement facts through the canonical visibility filters, normalize streamed whitespace and duplicate paragraphs incrementally, and consolidate XML and legacy text parsing. Preserve phase, directive, and final-media ownership while reducing production code.

* style(agents): keep projection loop inputs immutable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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