Repository navigation
fix(openai): validate video binary responses at the owner boundary - #117227
Conversation
|
Codex review: needs maintainer review before merge. Reviewed August 2, 2026, 4:50 PM ET / 20:50 UTC. ClawSweeper reviewWhat this changesThe PR validates OpenAI generated-video downloads as binary video before buffering them, rejects empty bodies, preserves the existing byte-cap error, and adds malformed-response and transport-release coverage. Merge readinessThis PR remains necessary: current main accepts successful JSON, text, or empty video-download payloads as video bytes. The proposed owner-boundary repair matches the landed OpenAI TTS pattern, preserves the shipped overflow wording, and has no actionable correctness finding; the Priority: P1 Review scores
Verification
How this fits togetherThe OpenAI plugin turns a completed OpenAI video job into a downloaded media attachment. Its download owner receives an HTTP response, validates and bounds the binary body, then releases the selected public or guarded-private transport. flowchart LR
A[Completed OpenAI video job] --> B[Download response]
B --> C[OpenAI video provider]
C --> D{Valid binary video?}
D -->|yes| E[Bounded body read]
D -->|no| F[Cancel unread body]
E --> G[Generated video attachment]
F --> H[Visible error and transport release]
Decision needed
Why: The patch is technically clean, but the repository's Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +11, Tests +266. Total +277 across 2 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Land the focused OpenAI provider repair after the protected maintainer review confirms the exact current head and required checks; retain the provider-local overflow callback and nonblocking invalid-body cancellation pattern. Do we have a high-confidence way to reproduce the issue? Yes. The final-head regression starts a real local HTTP server that returns a 200 JSON body which never ends, then verifies rejection and server-observed socket closure for both transport routes. Is this the best way to solve the issue? Yes. Validating at the OpenAI video-download owner before buffering is the narrow canonical fix; it reuses the shared content contract while retaining the provider-specific overflow error that the generic combined reader would replace. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b35b8e286df0. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
Yigtwxx
left a comment
There was a problem hiding this comment.
Reviewed at 822a5df. The core change is right — swapping the raw read for the canonical bounded binary contract is the correct owner-boundary fix, and I confirmed by mutation that the malformed-response coverage is real rather than mock-theater: deleting the cancel call turns four named tests red, including both real-node:http never-ending-server cases. Three separate things came out of it, in descending order of how much I'd want them settled before merge.
1. await response.body?.cancel() (L281) can hang, and it gates release(). The repo documents this exact failure mode at src/proxy-capture/runtime.ts:41-46 — a Response.clone() tee branch never settles its cancel while the sibling is live — and extensions/google/video-generation-provider.ts:241-243 uses void for that reason, in a comment naming the dispatcher release. Both transports here reach the tee when debug capture is on. Suggestion inline. Genuinely split convention in-tree (byteplus and runway also await), so this is a judgment call, but this site is the only one of the four where the await has a release() queued behind it.
2. Operator-visible overflow message leaves a cross-provider convention. readProviderBinaryResponse hardcodes its own onOverflow after the opts spread, so adopting it necessarily drops the custom message: ... download exceeds N bytes becomes ... download: video response exceeds N bytes. Eleven other generated-video downloaders emit the original form, and src/cli/capability-cli/video.ts:175-176 states it as a deliberate convention — which is likely why byteplus and runway used the split assertProviderBinaryResponseContent + readResponseWithLimit form instead. Details inline.
3. One added assertion doesn't test what it appears to. expect(cancel).not.toHaveBeenCalled() passes with the !response.bodyUsed guard deleted; I ran it with a control mutation to be sure the harness can fail. Inline has the three-run table and the WHATWG reason. Low severity — the guard is harmless — but the PR body cites that behavior as covered.
Separately, on the rootCount: 1 framing. The same unvalidated binary read is still live one file away in the same extension. extensions/openai/tts.ts:183-187 at this head:
await assertOkOrThrowProviderError(response, "OpenAI TTS API error");
return await readResponseWithLimit(response, maxBytes, {
onOverflow: ({ maxBytes: maxBytesLocal }) =>
new Error(`OpenAI TTS audio response exceeds ${maxBytesLocal} bytes`),
});That is the pattern this PR removes: a 200 carrying application/json, text/html, or zero bytes comes back as an audio buffer. It's reached from extensions/openai/speech-provider.ts:301,333. The sharper part is that the OpenAI-compatible speech path already went the other way — src/tts/openai-compatible-speech-provider.ts:399 uses readProviderBinaryResponse — so the OpenAI owner is currently inconsistent with itself: compatible speech guarded, native speech unguarded, video guarded as of this PR. Since it's the same owner directory, folding it in here seems reasonable; the ~12 other sites across google/xai/minimax/together/fal/vydra and src/cli/capability-cli/video.ts are clearly follow-up territory.
One thing I'd soften in the PR body rather than the code: assertProviderBinaryResponseContent rejects application/json, *+json, and text/*, and returns early when content-type is absent (src/agents/provider-http-errors.ts:411-414), with this owner defaulting to video/mp4 at L263. So a 200 with no content type, or application/octet-stream, still becomes a "video/mp4" attachment. The guarantee delivered is "non-empty and not obviously JSON/text", which is a real improvement — just not "a valid MP4/WebM".
| } finally { | ||
| // Header validation can reject before either transport's response body is consumed. | ||
| if (!response.bodyUsed) { | ||
| await response.body?.cancel().catch(() => undefined); |
There was a problem hiding this comment.
Awaiting this cancel can hang, and because it sits before await release() on L283 it would hold the pinned dispatcher with it.
The repo already documents the mechanism, in src/proxy-capture/runtime.ts:41-46:
Unlike media-core's readResponseWithLimit this never awaits reader.cancel(): the body here is one branch of a
Response.clone()tee whose sibling (the caller-facing response) is still live, and cancelling such a branch never settles (it only resolves once BOTH branches cancel). Awaiting it would hang the capture pipeline and retain the buffered prefix forever, so we cancel fire-and-forget.
Both transports here reach that tee when debug-proxy capture is enabled — the guarded path through captureGuardedFetchExchange in src/infra/net/fetch-guard.ts, and the public path because installDebugProxyGlobalFetchPatch (src/proxy-capture/runtime.ts:292-340) tees every outbound response. The capture branch is read fire-and-forget and only cancels its own side after its 16 MiB bound, so for precisely the threat this PR is closing — a 200 response whose body never ends — the await blocks until the peer has pushed 16 MiB. .catch(() => undefined) doesn't help, since a promise that never settles is not a rejected one.
The sibling that hit this uses void and says why, extensions/google/video-generation-provider.ts:241-243:
// A debug-capture clone can keep the tee open, so waiting for cancel
// would hang before the HTTP error and dispatcher can be released.
void response.body?.cancel().catch(() => undefined);src/infra/net/fetch-guard.ts uses the same void form on its redirect path.
| await response.body?.cancel().catch(() => undefined); | |
| void response.body?.cancel().catch(() => undefined); |
Fair caveats: the repo is genuinely split — extensions/byteplus/video-generation-provider.ts:204 and extensions/runway/video-generation-provider.ts:323 also await here, so this isn't a settled convention. And it needs OPENCLAW_DEBUG_PROXY_ENABLED, so it's a debug/dev-mode hang rather than a default-production one. What makes this call site the sharpest of the four is that the await gates a transport release(); the other two await in a catch with nothing queued behind them. The PR's tests can't see this either way, since they mock fetchWithTimeoutGuarded and never install the capture patch.
| try { | ||
| const mimeType = normalizeOptionalString(response.headers.get("content-type")) ?? "video/mp4"; | ||
| const buffer = await readResponseWithLimit(response, params.maxBytes, { | ||
| const bytes = await readProviderBinaryResponse(response, deadline.label, "video", { |
There was a problem hiding this comment.
Adopting readProviderBinaryResponse here also drops the custom onOverflow, which changes an operator-visible message. That isn't avoidable with this helper — it writes its own onOverflow after spreading ...opts (src/agents/provider-http-errors.ts:433-437), so a caller can't keep one.
The cap message goes from
OpenAI generated video download exceeds 1 bytes
to
OpenAI generated video download: video response exceeds 1 bytes
and the branch updates its own assertion to match, so nothing in CI flags it.
That string shape looks like a deliberate cross-provider convention rather than an accident. Grepping non-test sources at this head, eleven other generated-video downloaders emit the identical form — byteplus, fal, google (×2), minimax (×2), openrouter, runway, together, xai, and the shared src/video-generation/dashscope-compatible.ts:429. src/cli/capability-cli/video.ts:175-176 reproduces it with the reason spelled out:
The overflow error reports only the provider label and byte cap (never the raw URL, which may be signed/tokenized) to match the sibling generated-media downloaders.
That also explains why byteplus (:201-208) and runway (:320-327) adopted the split form instead of readProviderBinaryResponse — assertProviderBinaryResponseContent(...) for the header/emptiness contract, then readResponseWithLimit(..., { onOverflow }) to keep the message. Using the split form here would give you the same validation this PR is adding while leaving OpenAI on the shared wording:
assertProviderBinaryResponseContent(response, deadline.label, "video");
const bytes = await readResponseWithLimit(response, params.maxBytes, {
timeoutMs: deadline.timeoutMs ?? bodyTimeoutMs,
onTimeout: ...,
onOverflow: ({ maxBytes }) =>
new Error(`OpenAI generated video download exceeds ${maxBytes} bytes`),
});Not a suggestion block because I haven't checked that the argument shapes line up exactly at this call site — treat it as the direction rather than a patch. If the divergence is intentional and the provider: subject prefix is where these messages are heading, that's a reasonable answer too; it's just worth being an explicit decision, since the PR body currently reports the byte cap as unchanged (true of the cap, not of its message).
| model: "sora-2", | ||
| metadata: { seconds: "4", size: "720x1280", status: "completed", videoId: "vid_completed" }, | ||
| }); | ||
| expect(cancel).not.toHaveBeenCalled(); |
There was a problem hiding this comment.
This assertion passes whether or not the !response.bodyUsed guard exists, so it doesn't back the "successfully consumed bodies are never canceled" claim.
Measured at this head with three runs of this file:
| run | change | result |
|---|---|---|
| baseline | none | 1 failed / 27 passed |
| mutant A | deleted the if (!response.bodyUsed) guard, kept the cancel |
1 failed / 27 passed — identical |
| mutant B (control) | deleted the cancel call entirely | 5 failed / 23 passed |
The single baseline failure is does not advertise video generation for OAuth-only OpenAI profiles, unrelated to this path and present in all three runs.
Mutant B is the control and it behaves exactly as it should — removing the cancel turns four named tests red (cancels unread malformed 'public' video responses and closes their upstream socket, its guarded private twin, and both keeps the malformed public video error when ... body cancellation fails cases). So the cancel itself is genuinely load-bearing and the real-node:http tests are doing real work.
Mutant A is the finding: nothing in the suite notices the guard's removal, this line included.
The mechanism is that on the happy path readResponsePrefixFromReader (src/infra/http-body.ts:160-195) reads to done and then releaseLock(), leaving the stream in state "closed" and unlocked. Per WHATWG, cancelling a stream already in "closed" returns an already-resolved promise without invoking the underlying source's cancel algorithm — so the vi.fn() spy never fires regardless of the guard. By the same reasoning the guard is inert in every reachable state here: closed is a no-op, errored and locked both produce a rejected promise that the existing .catch() swallows.
Not arguing for removing it — defensive code at a finally boundary is cheap. The narrow point is that the PR-body bullet it supports has no test behind it, and this line reads like it does.
Somewhat related, one gap in the download coverage: the video-edit happy path at L887-907 still feeds a duck-typed object ({ headers, arrayBuffer }, no .body), so it short-circuits response.body?. and never exercises the new reader or the cancel branch. The submission happy path was upgraded to a real Response with a ReadableStream in this PR (L291-302) — the edit one looks like it was just missed.
822a5df to
49a47ce
Compare
Exact-head OpenAI video owner-boundary repairThe previous revision had two independently reproduced review findings:
The updated existing PR now mirrors the already-landed OpenAI text-to-speech owner pattern: canonical binary MIME/header validation, nonblocking fire-and-forget cleanup for invalid cloned streams, the existing provider-owned bounded reader and exact original shipped overflow text, explicit empty-binary rejection, and unchanged public/private transport release behavior. Hosted Blacksmith focused proof on byte-for-byte identical reviewed production and test files: The 30 real provider-owner cases include authentic never-ending WHATWG The remote run used a same-baseline Testbox checkout whose two files were independently verified byte-for-byte identical to this final PR owner: The actual Testbox lease freshness guard accepted the common repository/dependency/environment baseline; no stale-lease override was used. Exact remote wrapper result: Fresh independent full-owner |
49a47ce to
48d417e
Compare
|
Refreshed this existing PR onto current main after exact-head CI failed on an unrelated TUI PTY Ctrl+D integration with |
|
Merged via squash.
|
Co-authored-by: Peter Steinberger <[email protected]>
Summary
Response.clone()stream.v2026.7.1:OpenAI generated video download exceeds <limit> bytes.Root Cause and Canonical Repair
OpenAI video downloads previously accepted invalid successful payloads. An earlier revision also awaited cancellation of one branch of a WHATWG tee while a debug-capture
Response.clone()kept the other branch open, producing a real indefinite cleanup deadlock; its generic bounded-reader adoption changed an already-shipped operator-visible overflow message.The final provider owner now uses the shared binary content assertion, the existing provider-owned bounded reader with its exact historical overflow callback, explicit empty rejection, fire-and-forget cleanup for invalid cloned bodies, and the existing transport release ordering. The same pattern already landed for the sibling OpenAI audio/TTS provider. No SDK surface, public protocol, config, schema, live-provider access, or auth-policy change is introduced.
Real Owner / Dependency Proof
Response.clone()uses a tee whose cancellation promise does not settle until both branches cancel.v2026.7.1confirms the exact original OpenAI video overflow wording; the final regression restores that exact assertion.node scripts/run-vitest.mjs extensions/openai/video-generation-provider.test.ts— 1 suite, 30/30 passing.Response.clone()streams for both public and guarded-private fetch, exact shipped overflow text, malformed MIME/JSON/plaintext/HTML/empty bodies, valid binary, and public/private transport release.gpt-5.6-solhigh-reasoning P1 structured review: clean, confidence 0.98.Final reviewed head:
48d417e8e3dbd7e964a6942fa65660a6fa8553c1.The existing PR was refreshed onto current
mainafter its old 1,025-commit-behind base exposed an unrelated TUI PTY failure (Session transcript parent entry was not persisted). The new base already contains the exact canonical session fix from #117260; both reviewed OpenAI production/test files retain identical SHA-256 bytes after the conflict-free refresh.