Repository navigation
perf(agents): reduce overhead for concurrent streaming replies - #135751
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs changes before merge. Reviewed September 1, 2026, 10:59 PM ET / September 2, 2026, 02:59 UTC. ClawSweeper reviewWhat this changesThe PR refactors built-in agent streaming, reply delivery, tool-call execution, and task activity updates to reduce overhead during concurrent long replies. Merge readinessKeep open: an introduced early usage commit can retain provisional token and cost data after the final provider snapshot arrives. Exact-head performance/CI evidence is also still pending before the recorded throughput tradeoff can be accepted for this head. Priority: P1 Review scores
Verification
How this fits togetherProvider events flow through the embedded agent subscriber, which prepares visible text, reply delivery, transcript state, and usage accounting before the Gateway settles an agent attempt. This PR changes those stream and lifecycle boundaries while retaining ordered tool execution. flowchart LR
A[Provider events] --> B[Embedded subscriber]
B --> C[Usage and stream state]
C --> D[Reply and transcript delivery]
C --> E[Agent attempt settlement]
D --> F[Gateway and task activity]
Decision needed
Why: The prior maintainer decision accepted the tradeoff for an earlier head, while the PR body explicitly leaves the corrected head's comparable evidence pending. Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource -6, Tests +1069, Docs +2, Other 0. Total +1065 across 41 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Keep usage pending until the final assistant message supplies authoritative provider totals, add a differing-nonzero done/error-to-message_end regression, then assess the corrected-head performance and control-latency evidence before merge. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible: send a nonzero done/error usage event followed by a final assistant message with different nonzero usage or cost; the commit flag prevents the final data from updating attempt totals. Is this the best way to solve the issue? No: committing provisional done/error usage before message_end is not the best ownership boundary because the final provider snapshot is explicitly authoritative. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against ef3b44744446. LabelsLabel justifications:
EvidenceAcceptance criteria:
What 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.
|
…law#135751) * perf(agents): reduce concurrent streaming overhead * fix(agents): preserve visibility across late stream phases
Put back upstream b1c68b9 content that the continuation line had silently reverted in shared files. Every row has a keep/restore disposition recorded in the round journal. Feature hunks are preserved. Production: - announce deps: use callSubagentLifecycleGateway for the wake and cleanup deps (openclaw#146369 inherited Gateway binding). - reply-delivery: clear blockSourceText on superseded deferred replies (openclaw#143722). - stream-rendering: record a block reply as delivered only when it has text (openclaw#135751). - gateway runtime handles: carry hotReloadStatus through the managed reload. - sweep-kill and sweeper: honor retired cancellations (reconcileRetiredSubagentCancellation), and pass the run's Gateway context resolver into sweep session deletes. - registry read: per-child snapshot reads (openclaw#154727), so the Gateway event loop is not blocked. - session delivery queue: read the post-enqueue status inside the SQLite worker instead of on the main thread, restoring the openclaw#147887 invariant. Tests restored to upstream's coverage: - task-registry kernel test: back to upstream's kernel functions. - double-announce: real outbound adapter retry outcomes (openclaw#131419). - side-question: listener-failure hooks case (openclaw#144828). - session-delivery storage: main-thread-SQL idle assertion (openclaw#157458). - media-only: the re-resolved auth selection assertion. - resume persistence: activation uses the real recovery-runtime shape. The resume "steered requester turn" test was adapted for upstream's async task lookup (openclaw#157634). Its stub now settles like the real waker, and the test waits for settle before an exact count, with a no-pending-wake assertion added. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Fq5EX9ESA3CG9cuZxVoKAK
What Problem This Solves
Concurrent built-in agent sessions repeatedly process growing reply snapshots and retain duplicate buffers. Long streamed replies therefore consume unnecessary CPU and allocations. Late provider phase metadata can also move raw text into a visible-text buffer with the wrong offsets.
Fixes #135750.
Why This Change Was Made
The subscriber carries append/correction facts into one pending-source buffer and records usage at event ingress. Corrections replace pending text without replaying delivered chunks. Final delivery owns directive completion and attachment selection. One shared tool driver replaces the duplicate sequential/parallel loops while preserving synchronous admission, ordered results and cancellation; adjacent stream transforms share one iterator. Redundant buffers, fallback flush paths and duplicate drain predicates are removed.
A late raw-to-visible transition now reprojects the received raw prefix under its newly known phase before switching the undrained buffer's coordinates. Consumed scopes and prepared terminal snapshots keep their ownership. Streaming final-answer sanitation uses the existing reasoning reducer's hidden-output policy: a queued delta can see future phase metadata while its own text is incomplete, so terminal malformed-output recovery must wait for completion. Complete/split voice directives and the canonical treatment of literal examples are preserved.
This optimizes the existing built-in runtime. Whole-loop workers and native Codex execution are outside this PR. There are no new configuration, dependency, persistence-schema or public-protocol surfaces.
Production LOC: +1,195/−1,201 (net −6). Tests/support: +2,810/−1,741 (net +1,069). Docs: +2. The complete diff is +1,065 lines across 41 files. Tests cover source coordinates, lifecycle ordering, real provider phase transitions, directives and terminal media selection.
Evidence
Final source:
116614bed307da4d3c02db50594839553c569dd7; fixed baseline:0ac185506ca7f4d2049e58d340279de808526850. Current main was inspected atb2f747df3dd2e723eea5a71e09ed0f310aa5d977: all 40 source/test/docs paths were unchanged from that baseline; only unrelated assertion-baseline entries differed.Three sequential alternating pairs (baseline/candidate, candidate/baseline, baseline/candidate) used Node 24.19.0 on an Apple M3 Ultra with 32 logical CPUs. Eight concurrent sessions streamed 4,096 payload chunks per final reply through a deterministic local Responses provider and the real Gateway
agent/agent.waitflow with hostread/exectools. Each archive owned its dependencies and build; provider transport outputs were identical. Complete source, output, dependency and native-binding inventories were checked before and after every run.sessions.listp95, msMedian wall time fell 78.1% (4.56× faster), measured CPU 74.1%, sampled peak RSS 23.0%, and work-end RSS 5.5%. Every pair was faster, used less measured CPU and had lower sampled RSS. Readiness and session-list probe medians worsened by 2.39× and 3.06×. These are application-overhead measurements, not OpenAI service throughput. CPU endpoint accounting can omit short-lived descendants; Gateway RSS excludes the tool processes, provider and harness. Three runs per side do not establish steady-state memory behavior, and shorter candidate phases contain fewer probe samples.
All six runs verified 13 successful tool turns and 13 complete durable replies each, 12 built-in-runtime projections, same-session ordering, cancellation of the owned exec child, session reuse, and clean Gateway exit. Every persisted reply was checked in full against its fixture, including nonce and SHA256.
A separate real-provider run at this same source/build passed with
openai/gpt-5.6-lunathroughhttps://api.openai.com: 13 successful hostread/execturns, including eight concurrent sessions, in 72.16 seconds overall. The credential-free verifier checked all 13 complete SQLite replies against their fixture nonce and SHA256, all 12 built-in-runtime projections, same-session serialization, owned-child cancellation, session reuse and clean Gateway exit. Full source/build/dependency/native inventories matched before and after. This establishes live correctness, not comparative provider throughput. A preceding verifier-only attempt stopped before any OpenAI request because Python represented an archive-root symlink as.instead of the build receipt’s empty string. That failed receipt was preserved; a separately versioned verifier corrected only that representation after containment checks.The canonical
sourcePerformancebuild passed all ten phases and included all 64 external plugin outputs. Its receipt covers 36,295 source files, 8,726 built files and 102,161 dependency files. 1,213 tests across 39 files passed on source hashes mapped to the final commit. The regression table runs the actual Responses parser → agent loop → subscriber and checks two queued deltas before completion, final block replies and stored text. Accepted regressions failed before their fixes. The full changed-file static gate and final independent Codex review passed; no accepted/actionable review findings remain.Exact-head CI attempt 2 passed on
116614bed307da4d3c02db50594839553c569dd7; the required openclaw/ci-gate passed at 2026-09-02 03:15:50 UTC. The first attempt failed two unchanged test-helper fixtures under startup/import deadlines. Both exact cases passed locally unchanged, and one rerun of the failed CI job passed; no production, test or timeout changes were made to obtain green CI.Receipt SHA256: build
f44751100a0137887458ea7849401fbab0afc9d9f774b5dec09765a674880e37; paired summarye4f4bdc8f279afab33fafbdc667b1b4d8dd1733ea20f1d93336b85886c035668; source/test mapping408eff4afdb483a9600f50f54b6485f67d93b9bac018ddb8967e62cb2cd8e31f; live report462ed77777333c17c7405660c54dc5f971bb9463ad22f4c3705d03dc3ffc9814; full live verification17c8edce88ca15cc05923017a5d20e98976c59bd8ab35c3f9d839a22c219870e.The latest ClawSweeper review was checked before landing. Its terminal-usage P1 and requested usage-change rank-up are not accepted for the supported runtime: the core producer forwards only incremental events as
message_update;done/errorinstead await the result and publishmessage_end. Session hooks complete before that final event reaches usage accounting. Provider/result wrappers do not synthesize a terminal update. The cited fixture bypasses that producer by injectingdoneinto a session stub, so it does not establish the alleged runtime sequence. No speculative production change was made. The corrected-head C8/live/CI rank-up is satisfied above, and the reviewer’s current-main source gap is covered by the source comparison recorded above.Maintainer Decision and Follow-ups
Accept the measured throughput/CPU benefit with the disclosed control-latency tradeoff under the explicit instruction to land. This records the decision requested by the ClawSweeper review. The current three pairs show lower sampled RSS, but earlier measurements at
8a641f3had higher work-end RSS, and a separate instrumented 65-second diagnostic found similar live heaps but higher candidate physical footprint. Lower sustained memory use remains unproven.Named follow-ups:
Improve control-probe tails and establish sustained memory behavior under a defined concurrent workload.
Separate test-fixture preparation from operation deadlines while retaining real kill/join and ordering assertions. The initial CI run failed two unchanged helper fixtures; no source or timeout changes were made to obtain the rerun.
Preserve warmup-worker exit observers during cleanup. Broad listener removal made a diagnostic counter stale despite a recorded clean worker exit; this was not evidence of a retained worker.
Preserve Markdown fence context when reasoning-looking literal text arrives in a later native content block. This pre-existing case needs coordinated promotion/sanitation ownership.
Replace or clearly label synthetic terminal-update fixtures and cover usage finalization through the actual provider → core → subscriber path.