Skip to content

perf(agents): reduce overhead for concurrent streaming replies - #135751

Merged
steipete merged 2 commits into
mainfrom
codex/perf-concurrent-agent-streaming-20260901
Sep 2, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf-concurrent-agent-streaming-20260901

Conversation

@steipete

@steipete steipete commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

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 at b2f747df3dd2e723eea5a71e09ed0f310aa5d977: 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.wait flow with host read/exec tools. 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.

C8 metric Baseline median (range) Candidate median (range)
Wall time, seconds 14.09 (13.55–16.10) 3.09 (2.98–3.26)
Process-tree CPU, seconds 15.30 (14.63–16.94) 3.96 (3.75–4.04)
Peak sampled Gateway RSS, MiB 1,602.9 (1,561.7–1,678.8) 1,233.7 (1,224.1–1,236.6)
Gateway RSS at work end, MiB 1,304.9 (1,284.6–1,359.3) 1,233.7 (1,224.1–1,236.6)
Readiness-probe p95, ms 22.6 (14.9–41.3) 53.9 (51.5–79.9)
sessions.list p95, ms 24.7 (16.8–69.1) 75.6 (67.3–78.0)

Median 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-luna through https://api.openai.com: 13 successful host read/exec turns, 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 sourcePerformance build 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 summary e4f4bdc8f279afab33fafbdc667b1b4d8dd1733ea20f1d93336b85886c035668; source/test mapping 408eff4afdb483a9600f50f54b6485f67d93b9bac018ddb8967e62cb2cd8e31f; live report 462ed77777333c17c7405660c54dc5f971bb9463ad22f4c3705d03dc3ffc9814; full live verification 17c8edce88ca15cc05923017a5d20e98976c59bd8ab35c3f9d839a22c219870e.

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/error instead await the result and publish message_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 injecting done into 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 8a641f3 had 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.

@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime 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 01:12
@steipete steipete self-assigned this Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed September 1, 2026, 10:59 PM ET / September 2, 2026, 02:59 UTC.

ClawSweeper review

What this changes

The PR refactors built-in agent streaming, reply delivery, tool-call execution, and task activity updates to reduce overhead during concurrent long replies.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep 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
Reviewed head: 116614bed307da4d3c02db50594839553c569dd7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The refactor has substantial behavior-focused coverage, but the introduced final-usage accounting error blocks merge and corrected-head performance evidence remains pending.
Proof confidence 🌊 off-meta tidepool Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its historical runtime evidence is useful context, but the PR itself correctly marks corrected-head C8, real-provider, and CI receipts as pending.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its historical runtime evidence is useful context, but the PR itself correctly marks corrected-head C8, real-provider, and CI receipts as pending.
Evidence reviewed 6 items Introduced premature usage commit: The final correction adds a commit for every done/error event, before the later message_end event records its authoritative assistant usage.
Final snapshot is blocked after commit: Usage recording returns once assistantUsageCommitted is set, while commitAssistantUsage merges the pending usage into the attempt accumulator exactly once.
Authoritative message_end usage arrives too late: The event handler records message.usage at message_end, but that call is ignored if a provisional done/error usage has already committed; attempt settlement reads the resulting aggregate.
Findings 1 actionable finding [P1] Keep final provider usage authoritative after done events
Security None None.

How this fits together

Provider 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]
Loading

Decision needed

Question Recommendation
After corrected-head C8 and live receipts are available, should the throughput gain be accepted if work-end RSS or control responsiveness remains worse? Require corrected-head evidence: Land only after the corrected head confirms the accepted throughput, memory, and responsiveness tradeoff.

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

  • Keep final provider usage authoritative after done events (P1) - done and error now commit provisional usage before message_end; recordAssistantUsage then ignores the final message snapshot. A streamed provider that reports revised nonzero token or cost totals at message_end therefore leaves incorrect attempt accounting. Defer the commit or permit final replacement, with a distinct-nonzero aggregate regression.
  • Resolve merge risk (P1) - A done or error event with provisional nonzero usage can lock in incorrect aggregate token and cost accounting even when message_end supplies different final provider totals.
  • Resolve merge risk (P1) - The PR body marks corrected-head C8 measurements, real-provider validation, and exact-head CI as pending; earlier-head measurements do not establish those results for this head.
  • Resolve merge risk (P1) - Current-main source blobs could not be read because the partial clone required unavailable DNS/network access.

Findings

  • [P1] Keep final provider usage authoritative after done events — src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts:117-120
Agent review details

Security

None.

PR surface

Source -6, Tests +1069, Docs +2, Other 0. Total +1065 across 41 files.

View PR surface stats
Area Files Added Removed Net
Source 19 1195 1201 -6
Tests 20 2810 1741 +1069
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 3 3 0
Total 41 4010 2945 +1065

Review metrics

Metric Value Why it matters
Production versus test delta production −6; tests/test support +1,069; docs +2 The production refactor is net-negative, while the large behavior suite must also cover the repaired usage-accounting boundary.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #135750
Summary: This PR is the implementation candidate for the open concurrent-streaming performance request; the other related items are explicitly separate work.

Members:

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

Merge-risk options

Maintainer options:

  1. Preserve final usage authority (recommended)
    Defer usage aggregation until message_end, or replace a provisional done/error aggregate with final provider usage, and cover distinct nonzero totals and cost.
  2. Accept provisional accounting
    Merge with the known possibility that usage and cost totals differ from the final provider snapshot.
  3. Pause pending benchmark evidence
    Hold the performance refactor until corrected-head resource and responsiveness receipts are available.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Defer usage aggregation until message_end or replace provisional done/error usage with the final provider snapshot; add a regression with different nonzero token and cost totals.

Technical review

Best 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:

  • [P1] Keep final provider usage authoritative after done events — src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts:117-120
    done and error now commit provisional usage before message_end; recordAssistantUsage then ignores the final message snapshot. A streamed provider that reports revised nonzero token or cost totals at message_end therefore leaves incorrect attempt accounting. Defer the commit or permit final replacement, with a distinct-nonzero aggregate regression.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The patch can silently persist incorrect model token and cost accounting for existing streamed assistant turns.
  • merge-risk: 🚨 session-state: The premature commit can make settled attempt usage diverge from the final provider message state.
  • merge-risk: 🚨 other: Corrected-head benchmark and real-provider evidence remain pending for the claimed concurrent-streaming tradeoff.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This MEMBER-authored PR is exempt from the external-contributor proof gate; its historical runtime evidence is useful context, but the PR itself correctly marks corrected-head C8, real-provider, and CI receipts as pending.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts.
  • [P1] node scripts/check-changed.mjs --dry-run -- src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: 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.

  • Defer or replace provisional done/error usage with final message usage, and cover distinct nonzero token and cost totals.
  • Complete and attach corrected-head C8, real-provider, and exact-head CI evidence.

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-02T01:20:53.497Z sha 8a641f3 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T02:49:30.343Z sha 116614b :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. 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. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed P2 Normal backlog priority with limited blast radius. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 2, 2026
@steipete steipete changed the title improve(agents): reduce streaming overhead for concurrent replies perf(agents): reduce overhead for concurrent streaming replies Sep 2, 2026
@steipete
steipete merged commit 48c9397 into main Sep 2, 2026
506 of 508 checks passed
@steipete
steipete deleted the codex/perf-concurrent-agent-streaming-20260901 branch September 2, 2026 03:31
@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 2, 2026
…law#135751)

* perf(agents): reduce concurrent streaming overhead

* fix(agents): preserve visibility across late stream phases
karmafeast pushed a commit to karmaterminal/openclaw that referenced this pull request Sep 26, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Reduce streaming overhead for concurrent agent replies

1 participant