Skip to content

improve: reduce allocation in long OpenAI Responses streams - #207889

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-model-stream-iterator-wrapper-layers-20260919
Nov 29, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-model-stream-iterator-wrapper-layers-20260919

Conversation

@steipete

@steipete steipete commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long OpenAI Responses streams allocate extra promises for every delta after their HTTP response hook has already finished. The response hook sits in a forwarding generator, so its once-per-request work adds overhead until the stream ends.

User Impact

Responses streaming uses less allocation on long reasoning, text, and tool-call output. The response hook still runs before start, and the first-event deadline still includes time spent in the hook.

Why This Change Was Made

The SDK Responses recovery loop already opens and consumes each accepted attempt. It can await response preparation once and then consume the existing stream directly. Both managed and shared SDK Responses paths use the same readiness operation. Terminal drain, retry provenance, diagnostics, and transport context keep their existing owners.

The supplied Team profile at 90ab1fad (Nov 28 at 17:45 PST, 163 RPC/min) sampled 2,008 MB over about 30 seconds. The biggest inclusive iterator frame was observeModelCallIterator().next() at 144.6 MB over 289 samples, including 67.7 MB native and 9.5 MB self at the reported site. The attribution identified the Responses wrapper stack for investigation. The change removes a forwarding layer inside that stack.

Evidence

Five fresh-process A1/A2/B rounds using scripts/perf/openai-sdk-stream-measure.ts replayed the same synthetic SDK SSE response with 3,600 reasoning, text, and tool argument deltas per request and the first-event deadline enabled. Request and assistant-event hashes matched. A1 and A2 are independent runs of the parent 2f2edbf36836.

Managed SDK Responses A1 A2 Candidate Median paired change from A/A midpoint
Sampled bytes per delta 5,820 5,797 5,463 −6.3%
Process CPU µs per delta 6.44 6.26 6.23 −1.3%
Main-thread CPU µs per delta 5.22 5.05 4.98 −5.2%
Turn p95 wall time, ms 126.33 105.87 101.78 −9.6%

Median absolute A/A spread was 0.39% for sampled bytes, 4.53% for process CPU, 4.55% for main-thread CPU, and 24.79% for p95 wall time. The CPU and latency measurements give limited resolution on the busy host. An independent counting run saw 26.741 / 26.741 / 24.736 promises per delta, with the candidate removing 2.005 per delta. With the production model-call diagnostic iterator around the same transport, sampled allocation went from 7,534 / 7,499 to 7,236 B/delta (−3.5% paired, 0.53% A/A spread). Process CPU was 6.01 / 5.91 / 5.36 µs/delta (−3.0% paired, 9.38% A/A spread). The diagnostic path also removed 2.005 promises per delta.

Focused suites passed for Responses hook, timeout, retry, terminal drain, iterator ordering and cleanup, prompt prefix stability, and model-call diagnostics. The new integration cases cover mid-stream abort and provider failure after a text delta, with exact diagnostic event sequences. Existing tests cover unopened return and transport context across interleaved next, return, and throw. The added behavior checks also pass with the parent implementation. Allocation and promise counts establish the performance difference.

Codex autoreview completed on the staged change against 2f2edbf36836 with no actionable P0–P2 findings. Production +44/−36 (net +8), tests +120/−25 (net +95), benchmark +46/−5 (net +41). The production growth shares the same preparation logic with sibling transports that still use the standalone iterator.

Focused Chromium chat tests passed. The broad local UI run had browser and unit failures. Eight reproduced on the exact parent, and a worker stalled during shutdown. The isolated real-Gateway UI E2E Stop test passed with a synthetic Responses stream. The selected Send now case skipped under its existing gate.

The final committed-range pnpm check:changed passed typecheck, formatting, lint, and all other checks except the Knip export scan. Its three findings reproduced on a clean 2f2edbf36836 checkout. #202209 introduced AgentCommandPluginIngressOpts and exported clearNativeRepositorySourceModulesForTest for a test consumer. #207581 removed the final consumer of resolveUpdateInstallSurfaceMock. These are existing main regressions outside the streaming change.

Await HTTP response preparation once per accepted SDK Responses attempt, then consume the existing stream in recovery without a forwarding generator.
@clawsweeper

clawsweeper Bot commented Nov 29, 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.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 29, 2026
@steipete
steipete marked this pull request as ready for review November 29, 2026 01:58
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-29T01:59:49.686468Z ed13d5d Draft marked ready
ℹ️ 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 P2 Normal backlog priority with limited blast radius. clawsweeper:intake:feature Preliminary submission classification; full source review pending. 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:feature Preliminary submission classification; full source review pending. labels Nov 29, 2026
@clawsweeper

clawsweeper Bot commented Nov 29, 2026

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR prepares each SDK Responses attempt once before consuming its events, removing a forwarding generator from long streams.

Example: A synthetic Responses reply streams 3,600 reasoning, text, and tool-argument deltas.

  • Before: The reported baseline allocated 5,820 and 5,797 sampled bytes per delta in independent runs.
  • After: The candidate reported 5,463 bytes per delta and about two fewer promises per delta, with matching request and assistant-event hashes.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, apparently correct optimization with passing exact-head checks; synthetic replay supports the allocation claim but does not establish whole-product performance gains.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is exempt from the contributor proof gate; its strongest performance evidence is the reported synthetic SDK replay, supported by inspectable benchmark code and preservation tests that also pass on the parent.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Long Responses replies incur avoidable allocation for each streamed delta.
Reason: A measured allocation reduction supports this narrow maintainer-authored optimization without changing model requests, output contracts, or runtime settings.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused allocation improvement with no actionable correctness findings, preserved lifecycle boundaries, and passing exact-head CI.

Reviewed head: ed13d5de6a0ff5d1413a58d10de9da4c600855b4

Before merge

None.

Findings

None.

Agent review details

How this fits together

The AI transport layer converts provider Responses events into assistant events; response preparation gates readiness, while the existing recovery loop retains retry sequencing and stream cleanup.

flowchart TD
  A[Agent model call] --> B[Managed or shared Responses adapter]
  B --> C[SDK request and recovery owner]
  C --> D[Response hook and readiness]
  D --> E[Provider event stream]
  E --> F[Responses reducer]
  F --> G[Assistant events and diagnostics]
Loading

Technical review

Best possible solution:

Keep preparation shared and once per accepted attempt, with event consumption, cleanup, and retries owned by the existing recovery loop.

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

Source confirms that fetched main forwards every SDK Responses event through the response-hook generator; the reported allocation measurements were not rerun during this read-only review.

Is this the best way to solve the issue?

The patch removes recurring forwarding work at its existing owner while retaining one preparation implementation for both optimized callers and sibling transports.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1ff98e5 adds packages/ai/src/providers/openai-responses-shared.ts:294 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1ff98e5fbcd9; files: packages/ai/src/providers/openai-responses-shared.ts)
  • Vincent Koc: Raw commit 804f89d adds scripts/perf/openai-sdk-stream-measure.ts:29 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 804f89d08f0f; files: scripts/perf/openai-sdk-stream-measure.ts)
  • Onur Solmaz: Raw commit 1319e1e adds packages/ai/src/transports/transport-stream-shared.ts:341 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 1319e1e60652; files: packages/ai/src/transports/transport-stream-shared.ts)

PR surface

Source +8, Tests +95, Other +41. Total +144 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 44 36 +8
Tests 2 120 25 +95
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 46 5 +41
Total 7 210 66 +144

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus test changes Runtime +44/−36; tests +120/−25 The eight-line runtime increase shares preparation with retained sibling consumers; test growth covers distinct timeout and diagnostic failure boundaries.
Benchmark controls Three benchmark flags and one additional measurement mode The additions control delta count, first-event timeout, diagnostic wrapping, and promise counting without adding runtime user configuration.

Labels

Label changes:

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

  • 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 November 28, 2026, 9:20 PM ET / November 29, 2026, 02:20 UTC.

@steipete
steipete merged commit d328acb into main Nov 29, 2026
221 of 224 checks passed
@steipete
steipete deleted the steipete/perf-micro-model-stream-iterator-wrapper-layers-20260919 branch November 29, 2026 02:23
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Nov 29, 2026
…line

* commit 'c876514dc21154a07f3755320495d2a93584b46b': (538 commits)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  refactor(infra): simplify audit recovery write progress (#157141)
  fix: show restart blockers in service logs (#207879)
  test(infra): exercise group identity in session roundtrip (#207671)
  test(infra): exercise live owner expiry policy (#207672)
  feat: let Knowledge learn from your Gmail through Composio (#207266)
  test: stop the history-worker overload test from failing CI on slow runners (#207862)
  test(auth): assert SecretRef plaintext is absent from storage (#207698)
  chore(doctor): hold expired doctor migrations as removal-pending (#207865)
  fix: show ended one-time automations in History (#201280)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
* commit '2194d14488091e2047d2f87ebbb093212f30840e': (540 commits)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  refactor(infra): simplify audit recovery write progress (#157141)
  fix: show restart blockers in service logs (#207879)
  test(infra): exercise group identity in session roundtrip (#207671)
  test(infra): exercise live owner expiry policy (#207672)
  feat: let Knowledge learn from your Gmail through Composio (#207266)
  test: stop the history-worker overload test from failing CI on slow runners (#207862)
  test(auth): assert SecretRef plaintext is absent from storage (#207698)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
…seline

* commit '32403124cae2ccbcfc556e844b218682b133956e': (547 commits)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  chore: stop the Workboard resident-owner CLI test from failing on main (#207898)
  test(agents): isolate endpoint-based overflow classification (#207688)
  chore(doctor): record why the root defaultModel migration stays (#207890)
  ...
vincentkoc added a commit that referenced this pull request Nov 29, 2026
…eline

* commit 'eee1e0553d29456424ac367008c3cf080f9866ec': (550 commits)
  fix(acp): deliver bound channel replies to the pending question (#207035)
  fix(cron): keep required reports from going silent when nothing changes (#207044)
  test(sessions): assert participant queue rollback state (#207891)
  perf(gateway): skip session display preparation for transcript recall (#207916)
  test(agents): verify complete bracketed paste payload (#207733)
  test: stop timing out the cron recovery settlement test on slow runners (#207920)
  fix: show when worktree cleanup stopped or will retry (#207883)
  fix: show approval destinations only when the forwarding mode uses them (#207885)
  fix: keep inherited tools when changing agent settings (#207884)
  feat: let Knowledge add someone's email or other alias to a page without rewriting it (#207881)
  fix: stop reporting a child worker as finished when the Gateway loses contact (#207713)
  fix: keep the Activity visibility test stable at midnight (#207847)
  perf(agents): reuse prepared tool catalog executors (#207900)
  fix: show the Gateway command default beside host rules in Devices (#207887)
  fix: verify chat Stop recovery after dashboard pairing (#207888)
  test(activity): check midnight refresh against the elapsed window (#207859)
  test(ui): use one persisted message ID in queued-image handoff (#207861)
  test(agents): release configured MCP fixture resources (#207716)
  fix(workboard): clear CI failures in the session filter editor (#207858)
  perf(ai): reduce allocation in OpenAI Responses streams (#207889)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 29, 2026
)

Await HTTP response preparation once per accepted SDK Responses attempt, then consume the existing stream in recovery without a forwarding generator.
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: M 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