Repository navigation
improve(agents): reduce overhead while streaming long replies - #136180
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed September 2, 2026, 5:48 AM ET / 09:48 UTC. ClawSweeper reviewWhat this changesThe 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 readinessKeep 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 Review scores
Verification
How this fits togetherThe 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]
Decision needed
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
Agent review detailsSecurityNone. PR surfaceSource -11, Tests +169. Total +158 across 16 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
|
Merged via squash.
|
…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
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
9e6912ca0d2e0200bdcbcfc32bde2d27db262464and exact-head3e0330d9e85ac096e37317411af1a234847a2345builds, 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.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-lunacompleted 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-2569622fa03198fbf26215cada2ef4a1f282e82175904293aa4dd05ebc79dffeb9c), andcandidate-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)
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.