Skip to content

Commit d03a43a

Browse files
ZengWen-DTsteipete
andauthored
fix(openai): keep embedding batch waits within timeout (#111675)
* fix(openai): keep embedding batch waits within timeout * test(openai): isolate batch poll timers from provider body guards --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 7280844 commit d03a43a

2 files changed

Lines changed: 140 additions & 21 deletions

File tree

‎extensions/openai/embedding-batch.test.ts‎

Lines changed: 99 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Openai tests cover embedding batch plugin behavior.
22
import { createServer } from "node:http";
3-
import { describe, expect, it, vi } from "vitest";
3+
import { afterEach, describe, expect, it, vi } from "vitest";
44
import { runOpenAiEmbeddingBatches } from "./embedding-batch.js";
55

66
const jsonlEncoder = new TextEncoder();
@@ -82,7 +82,105 @@ async function closeServer(server: ReturnType<typeof createServer>): Promise<voi
8282
});
8383
}
8484

85+
afterEach(() => {
86+
vi.restoreAllMocks();
87+
vi.useRealTimers();
88+
});
89+
8590
describe("OpenAI embedding batch output", () => {
91+
it.each([
92+
{
93+
name: "pending status",
94+
pollIntervalMs: 2_000,
95+
expectedWaits: [500],
96+
retryFirstStatus: false,
97+
},
98+
{
99+
name: "retry backoff",
100+
pollIntervalMs: 500,
101+
expectedWaits: [500, 500],
102+
retryFirstStatus: true,
103+
},
104+
])("clamps $name waits to the remaining batch timeout", async (scenario) => {
105+
vi.useFakeTimers();
106+
vi.setSystemTime(0);
107+
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
108+
// Provider error-body reads own independent 10s chunk timers; only poll
109+
// delays belong to the embedding batch's 1s operation deadline.
110+
const pollTimeoutCalls = () =>
111+
setTimeoutSpy.mock.calls.filter(([, timeout]) =>
112+
scenario.expectedWaits.includes(Number(timeout)),
113+
);
114+
let statusCalls = 0;
115+
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
116+
const url = fetchInputUrl(input);
117+
if (url.endsWith("/files") && init?.method === "POST") {
118+
return jsonResponse({ id: "file-0" });
119+
}
120+
if (url.endsWith("/batches") && init?.method === "POST") {
121+
return jsonResponse({ id: "batch-0", status: "in_progress" });
122+
}
123+
if (url.endsWith("/batches/batch-0")) {
124+
statusCalls += 1;
125+
if (scenario.retryFirstStatus && statusCalls === 1) {
126+
return jsonResponse({ error: { message: "retry status" } }, 503);
127+
}
128+
return jsonResponse({ id: "batch-0", status: "completed", output_file_id: "output-0" });
129+
}
130+
if (url.endsWith("/files/output-0/content")) {
131+
return new Response(
132+
JSON.stringify({
133+
custom_id: "0",
134+
response: { status_code: 200, body: { data: [{ embedding: [1] }] } },
135+
}),
136+
);
137+
}
138+
return new Response("unexpected request", { status: 500 });
139+
});
140+
141+
const result = runOpenAiEmbeddingBatches({
142+
openAi: {
143+
baseUrl: "https://openai-compatible.example/v1",
144+
headers: { Authorization: "Bearer test" },
145+
model: "text-embedding-3-small",
146+
fetchImpl,
147+
},
148+
agentId: "main",
149+
requests: [
150+
{
151+
custom_id: "0",
152+
method: "POST",
153+
url: "/v1/embeddings",
154+
body: { model: "text-embedding-3-small", input: "payload" },
155+
},
156+
],
157+
wait: true,
158+
concurrency: 1,
159+
pollIntervalMs: scenario.pollIntervalMs,
160+
timeoutMs: 1_000,
161+
debug: (message) => {
162+
if (!scenario.retryFirstStatus && message.includes("batch-0 in_progress")) {
163+
vi.setSystemTime(500);
164+
}
165+
},
166+
});
167+
const rejection = expect(result).rejects.toMatchObject({
168+
message: "openai batch batch-0 timed out after 1000ms",
169+
...(scenario.retryFirstStatus ? { cause: { status: 503 } } : {}),
170+
});
171+
172+
for (const [index, waitMs] of scenario.expectedWaits.entries()) {
173+
for (let attempt = 0; attempt < 100 && pollTimeoutCalls().length < index + 1; attempt++) {
174+
await Promise.resolve();
175+
}
176+
expect(pollTimeoutCalls()).toHaveLength(index + 1);
177+
expect(pollTimeoutCalls()[index]?.[1]).toBe(waitMs);
178+
await vi.advanceTimersByTimeAsync(waitMs);
179+
}
180+
await rejection;
181+
expect(statusCalls).toBe(scenario.retryFirstStatus ? 1 : 0);
182+
});
183+
86184
it("reads a completed error file before downloading successful output", async () => {
87185
let outputFetched = false;
88186
const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {

‎extensions/openai/embedding-batch.ts‎

Lines changed: 41 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@ import {
2424
} from "openclaw/plugin-sdk/memory-core-host-engine-embeddings";
2525
import {
2626
assertOkOrThrowProviderError,
27+
createProviderOperationDeadline,
2728
readProviderJsonResponse,
2829
readProviderTextResponse,
30+
resolveProviderOperationTimeoutMs,
31+
waitProviderOperationPollInterval,
2932
} from "openclaw/plugin-sdk/provider-http";
3033
import { normalizeStringEntries } from "openclaw/plugin-sdk/string-coerce-runtime";
3134
import type { OpenAiEmbeddingClient } from "./embedding-provider.js";
@@ -90,11 +93,13 @@ async function submitOpenAiBatch(params: {
9093
async function fetchOpenAiBatchStatus(params: {
9194
openAi: OpenAiEmbeddingClient;
9295
batchId: string;
96+
signal?: AbortSignal;
9397
}): Promise<OpenAiBatchStatus> {
9498
return await fetchOpenAiBatchResource({
9599
openAi: params.openAi,
96100
path: `/batches/${params.batchId}`,
97101
label: "openai.batch-status",
102+
signal: params.signal,
98103
parse: async (res) => readProviderJsonResponse<OpenAiBatchStatus>(res, "openai.batch-status"),
99104
});
100105
}
@@ -134,13 +139,15 @@ async function fetchOpenAiBatchResource<T>(params: {
134139
openAi: OpenAiEmbeddingClient;
135140
path: string;
136141
label: string;
142+
signal?: AbortSignal;
137143
parse: (res: Response) => Promise<T>;
138144
}): Promise<T> {
139145
const baseUrl = normalizeBatchBaseUrl(params.openAi);
140146
return await withRemoteHttpResponse({
141147
url: `${baseUrl}${params.path}`,
142148
ssrfPolicy: params.openAi.ssrfPolicy,
143149
fetchImpl: params.openAi.fetchImpl,
150+
signal: params.signal,
144151
init: {
145152
headers: buildBatchHeaders(params.openAi, { json: true }),
146153
},
@@ -256,34 +263,52 @@ async function waitForOpenAiBatch(params: {
256263
debug?: (message: string, data?: Record<string, unknown>) => void;
257264
initial?: OpenAiBatchStatus;
258265
}): Promise<BatchCompletionResult> {
259-
const start = Date.now();
266+
const deadline = createProviderOperationDeadline({
267+
label: `openai batch ${params.batchId}`,
268+
timeoutMs: params.timeoutMs,
269+
});
260270
const pollBackoff = createOpenAiBatchPollBackoff(params);
261271
let current: OpenAiBatchStatus | undefined = params.initial;
262272
while (true) {
263273
let status: OpenAiBatchStatus;
274+
let statusSignal: AbortSignal | undefined;
264275
try {
265-
status =
266-
current ??
267-
(await fetchOpenAiBatchStatus({
276+
if (current) {
277+
status = current;
278+
} else {
279+
statusSignal = AbortSignal.timeout(
280+
resolveProviderOperationTimeoutMs({
281+
deadline,
282+
defaultTimeoutMs: params.timeoutMs,
283+
}),
284+
);
285+
status = await fetchOpenAiBatchStatus({
268286
openAi: params.openAi,
269287
batchId: params.batchId,
270-
}));
271-
} catch (error) {
272-
if (!params.wait || !isRetryableOpenAiBatchPollError(error)) {
273-
throw error;
288+
signal: statusSignal,
289+
});
274290
}
275-
if (Date.now() - start > params.timeoutMs) {
291+
} catch (error) {
292+
if (statusSignal?.aborted) {
276293
throw new Error(`openai batch ${params.batchId} timed out after ${params.timeoutMs}ms`, {
277294
cause: error,
278295
});
279296
}
297+
if (!params.wait || !isRetryableOpenAiBatchPollError(error)) {
298+
throw error;
299+
}
280300
const delayMs = pollBackoff.nextDelayMs();
281301
params.debug?.(
282-
`openai batch ${params.batchId} status check failed: ${formatOpenAiBatchDiagnostic(error)}; waiting ${delayMs}ms`,
302+
`openai batch ${params.batchId} status check failed: ${formatOpenAiBatchDiagnostic(error)}; waiting up to ${delayMs}ms`,
283303
);
284-
await new Promise((resolve) => {
285-
setTimeout(resolve, delayMs);
286-
});
304+
try {
305+
await waitProviderOperationPollInterval({ deadline, pollIntervalMs: delayMs });
306+
resolveProviderOperationTimeoutMs({ deadline, defaultTimeoutMs: params.timeoutMs });
307+
} catch {
308+
throw new Error(`openai batch ${params.batchId} timed out after ${params.timeoutMs}ms`, {
309+
cause: error,
310+
});
311+
}
287312
current = undefined;
288313
continue;
289314
}
@@ -316,18 +341,14 @@ async function waitForOpenAiBatch(params: {
316341
if (!params.wait) {
317342
throw new Error(`openai batch ${params.batchId} still ${state}; wait disabled`);
318343
}
319-
if (Date.now() - start > params.timeoutMs) {
320-
throw new Error(`openai batch ${params.batchId} timed out after ${params.timeoutMs}ms`);
321-
}
322344
const delayMs = pollBackoff.nextDelayMs();
323345
params.debug?.(
324346
`openai batch ${params.batchId} ${state}${formatOpenAiBatchProgress(
325347
status,
326-
)}; waiting ${delayMs}ms`,
348+
)}; waiting up to ${delayMs}ms`,
327349
);
328-
await new Promise((resolve) => {
329-
setTimeout(resolve, delayMs);
330-
});
350+
await waitProviderOperationPollInterval({ deadline, pollIntervalMs: delayMs });
351+
resolveProviderOperationTimeoutMs({ deadline, defaultTimeoutMs: params.timeoutMs });
331352
current = undefined;
332353
}
333354
}

0 commit comments

Comments
 (0)