Skip to content

perf(agents): share stable stream observers - #184797

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-stream-layer-collapse-round2-20261026
Oct 26, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-stream-layer-collapse-round2-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Responses transport diagnostics add a forwarding generator to every raw event. This change uses one shared stable-continuation observer in llm-core and ports both Responses observation and the model-call diagnostic iterator introduced in #184369 onto it. The remaining-layer inventory extends #184742 with real installers and promise accounting.

The helper owns FIFO next()/return()/throw() scheduling, active-context resumption, source versus observer errors, and exactly-once finalization. Callers retain their policies: Responses logs lazily and closes like its generator; model diagnostics retain bounded cleanup, shared return promises, final-result ownership, and their existing unopened-return behavior. The two private FIFO implementations are removed. No package dependency edge or user configuration is added.

Runtime delta against main is +123 lines, not a net deletion: shared helper +191, existing diagnostics owner −74, Responses owner +5, export +1. This is 27 fewer runtime lines than the original proposal while also migrating the second owner. The remaining growth preserves the explicitly requested FIFO/context/error contracts and diagnostic eager-return exception. Tests compare the helper with the language generator and test the diagnostic caller against unchanged main.

Evidence

Five-pair owner measurements

Acceptance: preserve delivered bytes and lifecycle contracts; retain one added promise per ordinary event; report both owners independently and all five counterbalanced pairs. These are local owner measurements, not whole-Gateway claims. The explicit fast-path exception applies; no Team access, Testbox lease, or ten-minute Gateway stress campaign was used.

Both comparisons use 5 alternating AB/BA pairs, 60,000 delivered events per arm/pass (3,000 events ×20 turns), plus 15,000 warmup events. CPU uses an uninstrumented pass; allocation uses a separate 512-byte sampling pass. No subscriber sinks; model diagnostics uses real lifecycle/context and 1,000 history entries/40 tools. Baseline owner files are byte-identical between rebased main eaaa6f1 and captured main 2cb5b0c.

Layer Pair/order CPU ns/event base → candidate Sampled B/event base → candidate Host 1m load timing base/candidate
responses-observer 1 AB 345.42 → 355.48 715.90 → 321.54 9.35/13.65
responses-observer 2 BA 380.72 → 358.13 719.39 → 319.87 13.34/13.20
responses-observer 3 AB 391.67 → 369.00 718.90 → 321.03 13.44/13.08
responses-observer 4 BA 395.93 → 366.93 717.59 → 323.18 13.31/13.31
responses-observer 5 AB 388.88 → 353.32 721.99 → 321.68 12.87/13.36
model-diagnostics 1 AB 763.38 → 750.82 1176.01 → 1209.97 13.72/13.72
model-diagnostics 2 BA 720.53 → 740.05 1173.29 → 1213.70 12.38/12.84
model-diagnostics 3 AB 692.38 → 755.67 1166.20 → 1218.95 11.55/11.55
model-diagnostics 4 BA 749.37 → 773.93 1174.49 → 1215.54 12.40/11.91
model-diagnostics 5 AB 718.72 → 774.58 1171.51 → 1209.85 11.89/11.66
Layer / metric Base mean (min–max) Candidate mean (min–max) Relative / absolute delta
responses-observer / timing 380.52 (345.42–395.93) 360.57 (353.32–369.00) -5.24% / -19.95
responses-observer / allocation 718.76 (715.90–721.99) 321.46 (319.87–323.18) -55.28% / -397.30
model-diagnostics / timing 728.88 (692.38–763.38) 759.01 (740.05–774.58) +4.13% / +30.13
model-diagnostics / allocation 1172.30 (1166.20–1176.01) 1213.60 (1209.85–1218.95) +3.52% / +41.30

The Responses allocation win remains clear. Diagnostics already had a stable continuation, so this is a consolidation: its apparent +41.30 B/event allocation and +30.13 ns/event CPU costs are reported rather than claimed as another optimization. No A/A-based adverse classification or whole-Gateway inference is made from these small owner deltas. Timing and allocation passes are separate; traced CPU is not used for the timing comparison.

Added promises/event: Responses 4 → 1; diagnostics 1 → 1. Total source/consumer-inclusive slopes are 6 → 3 and 3 → 3, respectively (32 versus 240 events).

Byte-identical 240-event replay SHA-256, base and candidate:

  • Responses: 31f1b4c7c61d8dba562b7659241ff192682841e311747ecaadae6fb419f31a99.
  • Model diagnostics, including final-result bytes: 7c738c9fe4e7ca90f1e7a98aa34db303cb83cc4642e8a117f7ecbd8dae39f802.

Rerun either responses-observer or model-diagnostics:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/agent-stream-update-measure.ts --layer responses-observer --mode timing --events 3000 --turns 20 --warmup 5
# Repeat with --mode allocation, alternating AB/BA for five pairs.
node --import ./scripts/tsx.mjs scripts/perf/agent-stream-update-measure.ts --layer responses-observer --mode promises --events 240 --turns 1 --warmup 1
node --import ./scripts/tsx.mjs scripts/perf/agent-stream-update-measure.ts --layer responses-observer --mode verify --events 240 --turns 1 --warmup 1

Proof and review

  • Responses promise-count regression fails unchanged main (30 versus expected 20 synchronous promises for ten reads), passes the shared helper. Diagnostic metadata test passes both.
  • All 35 diagnostic tests, including seven new lifecycle cases, pass both main and candidate. The new cases now live in a focused sibling file to retain the existing file-size budget.
  • Shared-owner tests exercise native-generator parity for overlapping reads, return during a pending read, queued throw, rejected return value, source/result/value/observer errors, error identity, cleanup once, and active async context. Caller tests preserve distinct diagnostic cleanup, return sharing, and result ownership.
  • Focused tests, prefix-stability, scoped lint/format, targeted core and benchmark-script typechecks, export-name collisions, and wrapper import/planner checks. The wrapper closure inventory includes the new shared owner.
  • CI caught a potentially undefined benchmark recording entry; the verification-only lookup now asserts fixture presence. Its focused script typecheck and both replay hashes pass; the timed and production paths are unchanged.
  • Independent subagent review (autoreview route unavailable): clean through P2. The native Codex helper refused the configured provider because it does not match the operator configuration; no configuration changed. Review caught and resolved source-result accessor error settlement before final measurements.

Exact-head PR CI supplies broad validation. Leave this PR unmerged for the requesting maintainer.

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

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L labels Oct 26, 2026
@steipete
steipete marked this pull request as ready for review October 26, 2026 16:24
@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-26T17:58:15.455424Z 0af1741 New commits
ℹ️ 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.

@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. P2 Normal backlog priority with limited blast radius. 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. and removed 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 consolidates Responses and model-diagnostic stream observation into one shared iterator and extends the performance probe.

Example: Observing 240 Responses events containing text, reasoning, and tool-call updates.

  • Before: The forwarding observer adds four promises per event.
  • After: The observer adds one promise per event, with matching replay hashes reported.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and has no identified defect; proof is focused production-owner measurement and lifecycle tests rather than a shipped-entry-point run.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied paired measurements exercise both real observation owners with synthetic streams and matching replay hashes, without claiming shipped Gateway or live-transport coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Streaming responses perform avoidable promise allocation in the diagnostic forwarding layer.
Reason: Maintainer direction is established, the Responses allocation reduction is measured, and the small diagnostics cost is explicitly disclosed and accepted.

Merge readiness

✅ Ready for maintainer review

Keep this maintainer-authored PR open: the shared observer has a measured allocation benefit, and source review found no actionable correctness or security defect.

Priority: P2
Reviewed head: b1431d9be52097a0d6bb656618aa6b427a184236

Before merge

None.

Findings

None.

Agent review details

How this fits together

Provider streams enter the observation layer, which records transport and model-call diagnostics before forwarding events to existing stream consumers.

flowchart TD
  A[Responses transport] --> C[Shared iterator observer]
  B[Model diagnostic adapter] --> C
  C --> D[Diagnostic callbacks]
  C --> E[Stream consumers]
  B --> F[Bounded cleanup and shared result]
Loading

Technical review

Best possible solution:

Retain the shared iterator with caller-owned cleanup policies and complete the existing merge gates before the requesting maintainer chooses to land it.

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

The base Responses observer visibly forwards through an async generator, and the committed probe exercises that production owner; the PR reports before/after promise counts, but no target code was executed during this review.

Is this the best way to solve the issue?

The consolidation removes the competing diagnostics queue, preserves caller-specific policies, and supports the measured Responses benefit without adding a fallback or cache.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 99f7a303e3ff.

Provenance checked

  • Responses observation keeps the original intent (fdfe512: Keep transport diagnostics separate from the canonical Responses processor; later correlation work added request and terminal metadata.)
  • Diagnostic iterator scheduling keeps the original intent (881caa4: Reduce per-delta promise work while preserving FIFO operations, context, single value reads, and cleanup ownership.)
  • Final-result ownership keeps the original intent (6f75467: Bare EOF must observe the shared final result so provider failures cannot be reported as successful completion.)
  • Performance probe and wrapper inventory keeps the original intent (f3b04e2: Measure real stream owners independently and distinguish isolated forwarding costs from whole-Gateway claims.)

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:35 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)
  • SunnyShu: Raw commit 6f75467 adds src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.ts:180 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)
  • Vincent Koc: Raw commit 0e7250f adds src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.ts:142 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0e7250f37bf3; files: src/agents/pi-embedded-runner/run/attempt.model-diagnostic-events.ts)

PR surface

Source +123, Tests +509, Docs +99, Other +421. Total +1152 across 11 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 4 251 128 +123
Tests 3 509 0 +509
Docs 1 99 0 +99
Config 0 0 0 0
Generated 0 0 0 0
Other 3 421 0 +421
Total 11 1280 128 +1152

Review metrics

Metric Value Why it matters
Runtime versus tests Runtime +123 lines; tests +509 lines Runtime growth replaces two observation implementations with shared FIFO and error handling; tests cover generator parity and distinct caller lifecycle contracts.
Configuration surface One developer probe flag: --layer The flag selects performance workloads; no user runtime setting, default, or persisted format changes.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded streaming allocation improvement with measurable owner-level value and no demonstrated urgent user-facing failure.
  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-26T16:42:48.348Z sha 19db3bb :: needs maintainer review before merge. :: none

Reviewed October 26, 2026, 1:38 PM ET / 17:38 UTC (Revision 2).

@steipete steipete changed the title perf(agents): reduce Responses stream observation allocations perf(agents): share stable stream observers Oct 26, 2026
@steipete
steipete force-pushed the steipete/perf-stream-layer-collapse-round2-20261026 branch from 19db3bb to b1431d9 Compare October 26, 2026 17:32
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL and removed size: L labels Oct 26, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Consolidated both observers into one shared llm-core lifecycle owner and removed the model-diagnostics FIFO implementation. Updated the PR body with both five-pair measurements, matching replay hashes, preserved caller contracts, +123 runtime LOC versus main, and independent review/proof. The diagnostic owner’s small measured cost is reported explicitly alongside the Responses allocation win.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete force-pushed the steipete/perf-stream-layer-collapse-round2-20261026 branch from b1431d9 to 0af1741 Compare October 26, 2026 17:55
@steipete
steipete merged commit 058b0ea into main Oct 26, 2026
209 of 213 checks passed
@steipete
steipete deleted the steipete/perf-stream-layer-collapse-round2-20261026 branch October 26, 2026 18:24
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
* perf(agents): reduce Responses stream observation allocations

* perf(agents): share stable stream observation lifecycle

* test(agents): check recorded stream fixture entries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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