Skip to content

perf(agents): avoid promise assimilation for observed stream deltas - #184369

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-stream-observer-per-delta-20261026
Oct 26, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-stream-observer-per-delta-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Streaming model diagnostics create unnecessary promises for every delta by yielding concrete assistant events through an additional async generator. This is residual work after #183875, which is already an ancestor of the profiled build b70762fc.

User Impact

Small reduction in streaming allocation and main-thread CPU, with no intended change to event values, order, diagnostics, cleanup, or transport/plugin context.

Why This Change Was Made

Replace the generator with one serialized iterator. Sequential reads add one shared observation continuation; only overlapping operations chain behind an outstanding operation. Keep per-operation transport context entry and snapshot each source value once. Forwarding the original iterator-result object would re-read accessor-backed values and change the event consumers receive.

Production delta: +49 lines (100 added, 51 removed). The explicit FIFO/closed state replaces native generator serialization and preserves queued return/throw, unopened cleanup, rejected return values, and EOF result ownership. There is no parallel fallback, cache, new option, or public API.

Evidence

CI is blocked by a reproduced inherited failure, not green. On exact head f679a7d7ae5a2431f41eacf86428a73099a1085d, changed-test job 121458275766 fails the two finalizes opaque native usage only for its current/replaced writer cases in src/agents/embedded-agent-runner/run.shared-integration.test.ts. Both also fail on the unchanged main parent bfc4c09267ee5909ce050f80eed56c0f704523a3 with SqliteSessionMutationConflictError, operationLabel: session-entry.patch. This harness mocks runEmbeddedAttempt, so it does not execute the changed observer.

Head and parent reproduction (same pinned local Bun runtime as the failing CI shard):

node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run.shared-integration.test.ts \
  --maxWorkers=1 -t 'finalizes opaque native usage'

Each run: 2 failed / 154 skipped, same error signature. The failed CI job's other 154 cases passed. No CI rerun was requested. The PR is left ready and unmerged for the owning maintainer; the requested exact-head-green completion condition remains unmet.

The existing committed workload is scripts/perf/model-stream-observation-measure.ts, with a real diagnostic observer and PluginInstance binding around a synthetic streaming provider. Linux, Node 26.12.1; base source from c076148ee7e5600e581a60e7b338d83406ab09c3. Five concurrent synchronized pairs, alternating interleaved CPU sets under the sandbox quiet lock. Untraced timing and sampled-allocation passes are separate. Each timing arm runs 5,000 turns / 10,000 requests / 1,000,000 deltas; each allocation arm runs 2,000 turns / 4,000 requests / 400,000 deltas. Warm-up, interleaved request identities, exact event identity/sequence and terminal metrics are checked by the workload.

Metric, per 1,000 deltas Base mean Candidate mean Mean paired change
Sampled allocation 4.0308 MB 3.5918 MB −10.89%
Main-thread CPU 2.0389 ms 1.9226 ms −5.70%
Total GC 0.1924 ms 0.1811 ms −5.90%

Allocation and CPU improved in all five pairs. These are owner measurements, not a claim of an equivalent whole-Gateway improvement. This lane uses the requested focused fast-path proof exception; no 10-minute Gateway load campaign or live Gateway load was run. No sessions.list, server-handler latency, RSS/heap, or whole-Gateway CPU claim is made.

node --import ./scripts/tsx.mjs scripts/perf/model-stream-observation-measure.ts \
  --plugin-bound --listeners metrics --turns 5000 --chunks 100 \
  --mode timing --start-file <shared-future-start> --output <arm.json>
# Allocation pass: --turns 2000 --mode allocation.
# Base arm: --owner <base-source-snapshot-beside-original-module>.
Paired measurements and limits
Pair Allocation MB / 1k deltas, base → candidate CPU ms / 1k deltas GC ms / 1k deltas
1 4.0375 → 3.5944 2.0048 → 1.9614 0.1843 → 0.1850
2 4.0303 → 3.5925 2.0901 → 2.0182 0.2034 → 0.2058
3 4.0290 → 3.5980 2.0489 → 1.8396 0.1920 → 0.1653
4 4.0323 → 3.5860 2.0380 → 1.8914 0.1923 → 0.1599
5 4.0251 → 3.5879 2.0128 → 1.9024 0.1901 → 0.1895
Pair Event-loop p99 ms (samples), base → candidate Maximum GC pause ms Minor collections Shared host load, start → end
1 5.726 (570) → 6.275 (631) 19.353 → 19.923 137 → 124 3.63 → 3.74
2 6.713 (563) → 5.915 (624) 19.460 → 19.114 138 → 124 3.74 → 3.94
3 7.266 (566) → 5.988 (630) 19.776 → 19.106 137 → 124 3.94 → 3.79
4 6.787 (558) → 6.341 (627) 19.973 → 19.029 137 → 124 3.79 → 3.72
5 6.644 (569) → 5.698 (627) 18.287 → 22.458 137 → 124 3.72 → 4.24

Event-loop p99 is context only: each arm has fewer than 1,000 samples. Each arm has two major collections, so major-GC tails are also context only. Minor-GC totals across the five pairs: 810.17 → 742.83 ms; major: 147.02 → 156.87 ms; incremental: 4.93 → 5.88 ms. No adverse conclusion is drawn from those small major/incremental deltas; total GC/work improves. A/A rejection controls were therefore not triggered. Timing host load was 3.63–4.24; allocation-pass load rose to about 15, shared by both concurrent arms. Dirty pages stayed below 200 MB. An initial synchronization setup failed before producing measurements; those arms are excluded, and all five recorded pairs use a fresh start directory.

The regression does not assimilate concrete event values as promises fails on the base (then read 1, expected 0) and passes with the candidate, preserving event identity. Additional cases protect overlapping reads followed by return, throw, or a rejected return value. Existing frozen-provider/accessor and interleaved transport-context tests remain intact.

Validation: 87 focused tests passed across diagnostic events, lifecycle and stream custody; changed-file formatting, lint and the single targeted core typecheck. The larger stream-custody file takes 18 seconds of test execution because it exercises real replay repair, cancellation and tracked cleanup; the two diagnostic files take under one second of test execution together. No Testbox lease was used. Exact-head PR CI provides broad proof.

Review: independent subagent review (autoreview route unavailable), clean at P2; the configured autoreview helper rejected the requested provider route before inference. Configuration was not changed.

Replace the diagnostic async generator with a serialized iterator while preserving context, queued operations, source-value snapshots, and cleanup ownership. Five paired owner measurements reduce allocation 10.9% and main-thread CPU 5.7%.
@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review ended

ClawSweeper stopped reviewing this revision because the pull request closed.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T08:03:40.255079Z f679a7d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces the diagnostic stream’s async generator with a serialized iterator to reduce per-delta promise work.

Example: A model response emits 100 text deltas followed by its terminal event.

  • Before: The diagnostic generator performs promise assimilation for each yielded event.
  • After: The iterator delivers the same concrete events without assimilating their values.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused owner evidence supports the optimization and source review found no concrete defect; proof remains limited to an in-process workload, and required CI is unresolved.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR supplies focused real-owner benchmark results on Linux with Node 26.12.1 and real PluginInstance bindings around a synthetic provider; its explicitly accepted scope establishes owner-level savings without claiming live Gateway performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Diagnostic observation adds avoidable allocation and CPU work throughout streamed model responses.
Reason: The maintainer-authored direction is supported by paired measurements, and every introduced hunk serves the same bounded optimization.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR provides a measured streaming optimization, and source review found no actionable introduced defect; the required CI gate remains red.

Priority: P2
Reviewed head: f679a7d7ae5a2431f41eacf86428a73099a1085d

Before merge

None.

Findings

None.

Agent review details

How this fits together

The embedded agent’s diagnostic wrapper consumes provider streams, observes events and final results, and forwards them to agent consumers while retaining transport context and cleanup ownership.

flowchart LR
  A[Provider stream] --> B[Plugin binding]
  B --> C[Diagnostic iterator]
  C --> D[Agent consumer]
  C --> E[Diagnostic lifecycle]
  C --> F[Tracked cleanup]
Loading

Technical review

Best possible solution:

Retain the focused iterator replacement and resolve the required CI failure’s attribution before landing.

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

The base generator yields every observed chunk through promise assimilation, and the supplied regression reports a base failure on the event’s then-property read; this review executed no target code.

Is this the best way to solve the issue?

The replacement removes the identified work within the existing owner, preserves single-read event snapshots and tracked settlement, and introduces no competing implementation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 423ae422ef67.

Provenance checked

  • Generator serialization and tracked early-return cleanup keeps the original intent (0d1cf24: Retain admitted cleanup through session shutdown and explicitly close unopened iterators.)
  • Deferred EOF final-result observation keeps the original intent (6f75467: Bare EOF must await the shared final outcome for diagnostic classification without losing delayed result ownership.)
  • Single-read chunk snapshots and bound next method keeps the original intent (fix(agents): keep streamed chunks consistent with diagnostics #150682: Accessor-backed iterator values must be measured and delivered from the same read; the later bound-method optimization preserves the original receiver.)
  • Per-operation transport context keeps the original intent (c96b03f: Correlate lazy and asynchronous provider operations with the correct model request.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0d1cf24 adds src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts:32 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0d1cf24318b8; files: src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts)
  • Vincent Koc: Raw commit 7ba13fb adds src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.ts:30 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7ba13fbc2ba7; files: src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.ts)
  • SunnyShu: Raw commit 6f75467 adds src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts:154 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 6f75467d65d0; files: src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts)

PR surface

Source +49, Tests +101. Total +150 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 100 51 +49
Tests 1 101 0 +101
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 201 51 +150

Review metrics

Metric Value Why it matters
Production versus test growth Production +100/-51 (net +49); tests +101/-0 The added queue and closed state replace native generator serialization and cleanup semantics; the measured allocation reduction supports that bounded complexity.

Labels

Label changes:

  • add P2: A measured optimization of the shared model-stream path has useful but limited user impact.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: A measured optimization of the shared model-stream path has useful but limited user impact.
  • 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.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 26, 2026, 4:08 AM ET / 08:08 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

CI attribution update: the two finalizes opaque native usage only for its current/replaced writer failures also reproduce on the unchanged main parent bfc4c09267ee5909ce050f80eed56c0f704523a3, with the same SqliteSessionMutationConflictError and operationLabel: session-entry.patch as head f679a7d7ae5a2431f41eacf86428a73099a1085d.

Both local runs used the single failing file with --maxWorkers=1 -t 'finalizes opaque native usage': 2 failed / 154 skipped on each. The fixture mocks the embedded attempt and does not execute the stream observer. The PR body now includes this controlled comparison and the failed CI job link. No CI rerun was requested; this PR remains unmerged for maintainer handoff.

@steipete

Copy link
Copy Markdown
Contributor Author

Maintainer admin merge at the pinned head f679a7d7ae5a. The one red test job is a main failure.

I reverted attempt.model-diagnostic-events.ts to its main-parent version and reran the failing cases locally (node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run.shared-integration.test.ts --maxWorkers=1 -t 'finalizes opaque native usage'). Result: 2 failed, 154 skipped. That matches CI, including the same SqliteSessionMutationConflictError. These cases mock the embedded attempt and never execute the stream observer.

Equivalence review: the hand-written iterator matches the old async generator's semantics:

  • FIFO ordering through the pending chain.
  • An unopened return() still closes the source.
  • return() while suspended closes the source and emits completion exactly once.
  • After done or a source throw, the source is not returned.
  • throw() emits only once started. throwModelCallError is emitError plus rethrow, so the error path is the same.
  • After closure, every call reports done.

Owner benchmark: −10.9% allocation and −5.7% CPU per 1,000 deltas. Root-cause fixes for the main reds are tracked separately. No reruns.

@steipete
steipete merged commit 881caa4 into main Oct 26, 2026
126 of 129 checks passed
@steipete
steipete deleted the steipete/perf-stream-observer-per-delta-20261026 branch October 26, 2026 08:21
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…penclaw#184369)

Replace the diagnostic async generator with a serialized iterator while preserving context, queued operations, source-value snapshots, and cleanup ownership. Five paired owner measurements reduce allocation 10.9% and main-thread CPU 5.7%.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant