Skip to content

perf: reuse owned provider response buffers - #135014

Merged
steipete merged 2 commits into
mainfrom
codex/perf-provider-binary-copy
Sep 1, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf-provider-binary-copy

Conversation

@steipete

@steipete steipete commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The bounded provider response reader already returns an owned Buffer, but its Uint8Array return type hid that fact. Speech and generated-media callers consequently copied the complete response with Buffer.from before returning it.

Why This Change Was Made

Preserve Buffer in the shared reader's return type and return those already-owned bytes directly from all affected buffered speech, video and music callers. The transport is still released only after the read completes; content-type, empty-body, timeout and size-limit behavior stays at the shared reader.

The OpenAI-compatible speech tests, including the DeepInfra and OpenRouter factories, also contained handwritten binary-reader replacements that returned a different runtime type. They now use the real reader, deleting those duplicate implementations while preserving byte, request-header and transport-release assertions.

User Impact

Buffered speech and generated-media downloads avoid an additional response-sized allocation and copy. The public helper already returned Buffer at runtime, so Uint8Array consumers remain compatible. Production LOC +32/-48 (net -16).

Evidence

  • Actual video and music asset helpers downloaded identical 32 MiB payloads over loopback HTTP. Each path made one full-buffer copy before and zero after; byte-for-byte content, SHA-256 and transport release matched. This removes 32 MiB of copy allocation per probe download, not a claimed constant reduction in whole-process RSS.
  • A real OpenAI speech request through the changed plugin returned a valid 91,244-byte WAV Buffer; RIFF/WAVE headers and non-empty audio were verified.
  • The shared HTTP reader already establishes independent byte ownership. Node's Buffer documentation confirms Buffer.from(Buffer) copies those bytes again.
  • All 141 tests passed across ten shared-reader, generated-media and speech-provider files. They cover response bytes, request construction, size limits, timeouts, cancellation/release, empty responses and malformed content. Eleven additional DeepInfra/OpenRouter tests pass after removing their inaccurate reader mocks. The initial CI run exposed those sibling fixtures; the OpenRouter failure was reproduced locally before the test cleanup. Test LOC +44/-79 (net -35); only internal mock-call assertions were removed, while observable output and lifecycle assertions remain.
  • Independent source investigation and fresh Codex autoreview found no accepted findings in the selected scope and priority.
  • Full check-changed passed, including core and plugin typechecks, lint and guards. Full pnpm build passed, including generated SDK declarations and built plugin checks.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review September 1, 2026 08:27
@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Requesting the initial pre-merge review for 4839d73e5b9a43982271007448f1b60533fe3443. All 141 focused tests, full checks and build passed. The PR body includes actual video/music HTTP byte parity and allocation proof plus a real OpenAI speech request. The shared reader already returns an owned Buffer; the change exposes that fact in its type and removes the additional copy in every affected caller. Production net -16 LOC, tests net -13 by replacing a handwritten reader mock with the real reader. Exact-head CI is running.

@clawsweeper

clawsweeper Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 1, 2026
@clawsweeper

clawsweeper Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 1, 2026, 5:00 AM ET / 09:00 UTC.

ClawSweeper review

What this changes

The branch changes the shared provider binary reader to declare its existing Buffer result and removes redundant full-response copies from speech, music, and video downloads.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This maintainer-authored PR should remain open for normal maintainer handling. The bounded reader already creates the owned Buffer and the introduced callers retain its validation and transport-release boundary; no blocking defect was found. Likely related people: steipete (recent shared-HTTP contributor, medium confidence) and Dallin Romney (bounded-response consolidation contributor, low confidence).

Priority: P3
Reviewed head: c868bdd991e6754c3e829a402ab76986ef0df40e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, net-negative optimization accurately exposes the reader's existing Buffer result and preserves the established validation and lifecycle boundaries.
Proof confidence 🌊 off-meta tidepool Not applicable: This is a maintainer-authored PR; the external-contributor proof gate does not apply. Its supplied body nevertheless describes loopback asset-download and real OpenAI speech observations consistent with the inspected bounded-reader path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This is a maintainer-authored PR; the external-contributor proof gate does not apply. Its supplied body nevertheless describes loopback asset-download and real OpenAI speech observations consistent with the inspected bounded-reader path.
Evidence reviewed 7 items Concrete buffer owner: The underlying bounded reader is explicitly typed as Promise<Buffer> and returns its constructed prefix buffer, so the shared provider wrapper can truthfully expose Buffer without a conversion.
Validation boundary unchanged: The provider reader delegates to the bounded reader, retains byte caps and idle timeout defaults, and returns the same non-empty validated bytes after binary content checks.
Consumer lifecycle retained: The OpenAI-compatible speech factory awaits the shared reader inside its existing try/finally, so release still occurs after consumption; equivalent direct-return changes cover the other buffered callers.
Findings None None.
Security None None.

How this fits together

Provider and plugin HTTP responses pass through a bounded binary reader before speech, music, and video features return downloaded bytes. The reader validates the response and produces an owned buffer that downstream features consume and release their transport around.

flowchart LR
  A[Provider HTTP response] --> B[Bounded binary reader]
  B --> C[Content and size validation]
  C --> D[Owned response buffer]
  D --> E[Speech synthesis]
  D --> F[Music and video downloads]
Loading

Before merge

  • Resolve merge risk (P1) - The public provider HTTP SDK re-export narrows its declared result from Uint8Array to Buffer; normal Uint8Array consumers remain structurally compatible, but externally typed test doubles that promise a generic Uint8Array may need adjustment.
  • Complete next step (P2) - The repository state identifies the author as a member and this PR carries the protected maintainer label, so it should receive normal maintainer handling rather than automated repair or cleanup.
Agent review details

Security

None.

PR surface

Source -16, Tests -35. Total -51 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 10 32 48 -16
Tests 3 44 79 -35
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 76 127 -51

Review metrics

Metric Value Why it matters
Production versus test delta production +32/-48 (net -16); tests +44/-79 (net -35) The production reduction removes redundant response-sized copies while the test edits replace divergent local reader mocks with the shared behavior.

Merge-risk options

Maintainer options:

  1. Retain the compatible narrowing (recommended)
    Merge with the Buffer declaration because the runtime value has always been a Buffer and callers typed to Uint8Array remain compatible.
  2. Preserve the broader declaration
    Keep the public return type as Uint8Array if maintainers prefer to avoid any external typed-mock churn over exposing buffer ownership.

Technical review

Best possible solution:

Keep one canonical owned Buffer at the bounded-reader boundary and merge the direct-return callers after ordinary exact-head checks confirm the intended public SDK declaration.

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

Not applicable: this PR is a performance and type-accuracy change rather than a report of broken behavior. Source inspection establishes the redundant copy and unchanged reader boundary.

Is this the best way to solve the issue?

Yes: exposing the concrete Buffer produced by the canonical bounded reader removes the copies at their consumers without duplicating validation or lifecycle policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P3: This is a bounded performance and type-accuracy improvement with no demonstrated user-visible regression.
  • add merge-risk: 🚨 compatibility: The exported provider HTTP helper has a narrower public TypeScript return declaration even though its runtime value and ordinary Uint8Array consumption remain compatible.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a maintainer-authored PR; the external-contributor proof gate does not apply. Its supplied body nevertheless describes loopback asset-download and real OpenAI speech observations consistent with the inspected bounded-reader path.

Label justifications:

  • P3: This is a bounded performance and type-accuracy improvement with no demonstrated user-visible regression.
  • merge-risk: 🚨 compatibility: The exported provider HTTP helper has a narrower public TypeScript return declaration even though its runtime value and ordinary Uint8Array consumption remain compatible.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a maintainer-authored PR; the external-contributor proof gate does not apply. Its supplied body nevertheless describes loopback asset-download and real OpenAI speech observations consistent with the inspected bounded-reader path.

Evidence

What I checked:

  • Concrete buffer owner: The underlying bounded reader is explicitly typed as Promise<Buffer> and returns its constructed prefix buffer, so the shared provider wrapper can truthfully expose Buffer without a conversion. (src/infra/http-body.ts:305, c868bdd991e6)
  • Validation boundary unchanged: The provider reader delegates to the bounded reader, retains byte caps and idle timeout defaults, and returns the same non-empty validated bytes after binary content checks. (src/agents/provider-http-errors.ts:96, c868bdd991e6)
  • Consumer lifecycle retained: The OpenAI-compatible speech factory awaits the shared reader inside its existing try/finally, so release still occurs after consumption; equivalent direct-return changes cover the other buffered callers. (src/tts/openai-compatible-speech-provider.ts:396, c868bdd991e6)
  • Existing behavior coverage: Shared reader tests cover oversized binary bodies, malformed binary responses, clone cancellation, and stalled binary reads at the owner boundary. (src/agents/provider-http-errors.test.ts:471, c868bdd991e6)
  • Public SDK surface: The helper is re-exported by the provider HTTP SDK surface; the PR changes only its concrete static return type from Uint8Array to the Buffer runtime value. (src/plugin-sdk/provider-http.ts:18, c868bdd991e6)
  • Current-main comparison: Fetched current main still declares the provider reader as Promise<Uint8Array>, so this PR remains necessary and is not implemented on main. (src/agents/provider-http-errors.ts:101, ce872444b9fe)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

@steipete

steipete commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Completed maintainer review, including the declared SDK return type. Retaining the Buffer declaration is intentional: the bounded reader already returns an owned Buffer, and Buffer is assignable to Uint8Array, so existing consumers retain their result contract. Returning the wider annotation would hide that ownership and keep the unnecessary consumer copies. Typed mocks returning generic Uint8Array may need correction; the affected in-tree fixtures now use the real reader instead of a divergent substitute. No compatibility wrapper is needed for real consumers.

The current head has green CI and completed native preparation. Owner/sibling tests, the actual 32 MiB HTTP asset probes, the real OpenAI WAV request, the full build and changed checks passed. There are no requested repair findings beyond the type decision and normal maintainer handling addressed here.

@steipete
steipete merged commit a7f9461 into main Sep 1, 2026
283 checks passed
@steipete
steipete deleted the codex/perf-provider-binary-copy branch September 1, 2026 09:22
@steipete

steipete commented Sep 1, 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
* perf(media): return owned provider response buffers

* test(tts): use real binary readers in provider fixtures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: deepinfra extensions: elevenlabs extensions: fish-audio Extension: fish-audio extensions: gradium extensions: openai extensions: openrouter extensions: xai maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. plugin: azure-speech Azure Speech plugin rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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