Skip to content

Commit f4f5150

Browse files
Pick-catnebulacoder-v8.0steipete
authored
fix(video-generation): DashScope downloads hang when CDN body stalls after headers (#109394)
* fix(video-generation): bound stalled DashScope download body reads * test(video-generation): narrow DashScope download asset for tsgo * test(video-generation): narrow optional DashScope video buffer for tsgo * test(video-generation): bind DashScope buffer before tsgo asserts * fix(video-generation): fail closed on exhausted DashScope download budget When the operation deadline passes a function that returns 0, the previous resolver gate (resolved > 0) dropped the exhausted budget and fell back to the 120s default. Also, readResponseWithLimit skips chunk idle timeout when chunkTimeoutMs is 0/falsy, so a zero budget would read the body unbounded instead of failing fast. Now the resolver preserves zero/negative values and the body stage throws immediately when the remaining budget is exhausted. Co-Authored-By: nebulacoder-v8.0 <[email protected]> * fix(video-generation): reject exhausted download deadline before fetch Check the resolved download timeout before fetchWithTimeoutGuarded so an already-exhausted operation does not initiate network I/O. Previously the deadline guard ran after headers, which still sent bytes over the wire. Co-Authored-By: nebulacoder-v8.0 <[email protected]> * fix(video-generation): release failed DashScope downloads --------- Co-authored-by: nebulacoder-v8.0 <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
1 parent e4a4815 commit f4f5150

2 files changed

Lines changed: 186 additions & 3 deletions

File tree

Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
// DashScope-compatible download regressions: body idle after headers.
2+
import { describe, expect, it, vi } from "vitest";
3+
import { downloadDashscopeGeneratedVideos } from "./dashscope-compatible.js";
4+
5+
function neverChunkingVideoResponse(): Response {
6+
return new Response(
7+
new ReadableStream({
8+
start() {
9+
// Headers only — never enqueue so chunk idle must win.
10+
},
11+
}),
12+
{
13+
status: 200,
14+
headers: { "content-type": "video/mp4" },
15+
},
16+
);
17+
}
18+
19+
describe("downloadDashscopeGeneratedVideos", () => {
20+
it("aborts a stalled generated video body via chunk idle timeout", async () => {
21+
const fetchFn = vi.fn(async () => neverChunkingVideoResponse());
22+
const timeoutMs = 80;
23+
const startedAt = Date.now();
24+
25+
await expect(
26+
downloadDashscopeGeneratedVideos({
27+
providerLabel: "Alibaba Wan",
28+
urls: ["https://example.com/out.mp4"],
29+
timeoutMs,
30+
fetchFn: fetchFn as unknown as typeof fetch,
31+
maxBytes: 10 * 1024 * 1024,
32+
}),
33+
).rejects.toThrow("Alibaba Wan generated video download stalled: no data received for 80ms");
34+
35+
const elapsedMs = Date.now() - startedAt;
36+
expect(elapsedMs).toBeGreaterThanOrEqual(timeoutMs - 20);
37+
expect(elapsedMs).toBeLessThan(2_000);
38+
expect(fetchFn).toHaveBeenCalledTimes(1);
39+
});
40+
41+
it("persists a complete generated video body before the idle deadline", async () => {
42+
const fetchFn = vi.fn(
43+
async () =>
44+
new Response(
45+
new ReadableStream({
46+
start(controller) {
47+
controller.enqueue(new TextEncoder().encode("mp4-bytes"));
48+
controller.close();
49+
},
50+
}),
51+
{
52+
status: 200,
53+
headers: { "content-type": "video/mp4" },
54+
},
55+
),
56+
);
57+
58+
const videos = await downloadDashscopeGeneratedVideos({
59+
providerLabel: "Alibaba Wan",
60+
urls: ["https://example.com/ok.mp4"],
61+
timeoutMs: 5_000,
62+
fetchFn: fetchFn as unknown as typeof fetch,
63+
maxBytes: 10 * 1024 * 1024,
64+
});
65+
66+
expect(videos).toHaveLength(1);
67+
const video = videos[0];
68+
const buffer = video?.buffer;
69+
expect(video).toBeDefined();
70+
expect(buffer).toBeInstanceOf(Buffer);
71+
if (!buffer) {
72+
throw new Error("expected downloaded video asset buffer");
73+
}
74+
expect(buffer.toString("utf8")).toBe("mp4-bytes");
75+
expect(video?.mimeType).toBe("video/mp4");
76+
});
77+
78+
it("fails closed before fetch when a function-valued remaining budget is exhausted", async () => {
79+
const fetchFn = vi.fn(async () => neverChunkingVideoResponse());
80+
const startedAt = Date.now();
81+
82+
await expect(
83+
downloadDashscopeGeneratedVideos({
84+
providerLabel: "Alibaba Wan",
85+
urls: ["https://example.com/out.mp4"],
86+
// Function-valued timeout returns 0: header fetch consumed the entire
87+
// deadline. Must fail closed before any network I/O, not reset to the
88+
// full default timeout.
89+
timeoutMs: () => 0,
90+
fetchFn: fetchFn as unknown as typeof fetch,
91+
maxBytes: 10 * 1024 * 1024,
92+
}),
93+
).rejects.toThrow("remaining budget exhausted");
94+
95+
const elapsedMs = Date.now() - startedAt;
96+
// Should reject quickly (0ms budget), not wait for the 60s default.
97+
expect(elapsedMs).toBeLessThan(2_000);
98+
// Exhausted deadline is checked before fetch — no network I/O is initiated.
99+
expect(fetchFn).not.toHaveBeenCalled();
100+
});
101+
102+
it("releases the guarded fetch when the remaining-budget resolver throws", async () => {
103+
vi.useFakeTimers();
104+
try {
105+
let requestSignal: AbortSignal | undefined;
106+
const cancelBody = vi.fn();
107+
const timeoutMs = vi
108+
.fn<() => number>()
109+
.mockReturnValueOnce(100)
110+
.mockImplementationOnce(() => {
111+
throw new Error("remaining-budget resolver failed");
112+
});
113+
const fetchFn = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
114+
requestSignal = init?.signal ?? undefined;
115+
return new Response(new ReadableStream({ cancel: cancelBody }), {
116+
status: 200,
117+
headers: { "content-type": "video/mp4" },
118+
});
119+
});
120+
121+
await expect(
122+
downloadDashscopeGeneratedVideos({
123+
providerLabel: "Alibaba Wan",
124+
urls: ["https://example.com/out.mp4"],
125+
timeoutMs,
126+
fetchFn: fetchFn as typeof fetch,
127+
maxBytes: 10 * 1024 * 1024,
128+
}),
129+
).rejects.toThrow("remaining-budget resolver failed");
130+
131+
expect(timeoutMs).toHaveBeenCalledTimes(2);
132+
expect(cancelBody).toHaveBeenCalledOnce();
133+
expect(cancelBody.mock.calls[0]?.[0]).toMatchObject({
134+
message: "remaining-budget resolver failed",
135+
});
136+
expect(requestSignal?.aborted).toBe(false);
137+
await vi.advanceTimersByTimeAsync(100);
138+
expect(requestSignal?.aborted).toBe(false);
139+
} finally {
140+
vi.useRealTimers();
141+
}
142+
});
143+
});

‎src/video-generation/dashscope-compatible.ts‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,24 @@ export async function runDashscopeVideoGenerationTask(params: {
343343
}
344344
}
345345

346+
function resolveDashscopeVideoDownloadTimeoutMs(
347+
providerLabel: string,
348+
timeoutMs: ProviderOperationTimeoutMs | undefined,
349+
defaultTimeoutMs: number | undefined,
350+
): number {
351+
const resolved = typeof timeoutMs === "function" ? timeoutMs() : timeoutMs;
352+
const downloadTimeoutMs =
353+
typeof resolved === "number" && Number.isFinite(resolved)
354+
? Math.max(0, Math.floor(resolved))
355+
: (defaultTimeoutMs ?? DEFAULT_VIDEO_GENERATION_TIMEOUT_MS);
356+
if (downloadTimeoutMs <= 0) {
357+
throw new Error(
358+
`${providerLabel} generated video download stalled: remaining budget exhausted`,
359+
);
360+
}
361+
return downloadTimeoutMs;
362+
}
363+
346364
// Downloads task result URLs into generated video assets. The byte limit comes
347365
// from OpenClaw media config so provider URLs cannot overfill memory.
348366
export async function downloadDashscopeGeneratedVideos(params: {
@@ -361,12 +379,15 @@ export async function downloadDashscopeGeneratedVideos(params: {
361379
provider: params.providerLabel,
362380
stage: "download",
363381
operation: async () => {
382+
const downloadTimeoutMs = resolveDashscopeVideoDownloadTimeoutMs(
383+
params.providerLabel,
384+
params.timeoutMs,
385+
params.defaultTimeoutMs,
386+
);
364387
const guarded = await fetchWithTimeoutGuarded(
365388
url,
366389
{ method: "GET" },
367-
typeof params.timeoutMs === "function"
368-
? params.timeoutMs()
369-
: (params.timeoutMs ?? params.defaultTimeoutMs ?? DEFAULT_VIDEO_GENERATION_TIMEOUT_MS),
390+
downloadTimeoutMs,
370391
params.fetchFn,
371392
{
372393
...(params.allowPrivateNetwork ? { ssrfPolicy: { allowPrivateNetwork: true } } : {}),
@@ -388,9 +409,28 @@ export async function downloadDashscopeGeneratedVideos(params: {
388409
let buffer: Buffer;
389410
let mimeType: string;
390411
try {
412+
// Re-resolve after headers so the body uses the remaining operation budget.
413+
let downloadTimeoutMs: number;
414+
try {
415+
downloadTimeoutMs = resolveDashscopeVideoDownloadTimeoutMs(
416+
params.providerLabel,
417+
params.timeoutMs,
418+
params.defaultTimeoutMs,
419+
);
420+
} catch (error) {
421+
// The body reader normally owns cancellation. If deadline resolution
422+
// fails first, cancel here before release clears the guarded abort.
423+
await result.response.body?.cancel(error).catch(() => undefined);
424+
throw error;
425+
}
391426
buffer = await readResponseWithLimit(result.response, params.maxBytes, {
427+
chunkTimeoutMs: downloadTimeoutMs,
392428
onOverflow: ({ maxBytes }) =>
393429
new Error(`${params.providerLabel} generated video download exceeds ${maxBytes} bytes`),
430+
onIdleTimeout: ({ chunkTimeoutMs }) =>
431+
new Error(
432+
`${params.providerLabel} generated video download stalled: no data received for ${chunkTimeoutMs}ms`,
433+
),
394434
});
395435
mimeType = result.response.headers.get("content-type")?.trim() || "video/mp4";
396436
} finally {

0 commit comments

Comments
 (0)