Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(drivers): retry transient failures for OpenAI-compatible drivers

Saim Shafique4cb246acdac0
diff --git a/server/drivers/chat-size-limit.test.ts b/server/drivers/chat-size-limit.test.ts
index c6c497d492..ef340b913f 100644
--- a/server/drivers/chat-size-limit.test.ts
+++ b/server/drivers/chat-size-limit.test.ts
@@ -243,14 +243,18 @@ describe("an OpenAI-compatible provider that refuses large requests", () => {
});
it.each([
- [500, "Internal Server Error", "upstream HTTP 500: Internal Server Error"],
- [429, '{"error":{"message":"Rate limit reached for requests"}}', "upstream HTTP 429: Rate limit reached for requests"],
- ])("retries an HTTP %i failure at full size, and doesn't take it for a request that is too large", async (status, body, message) => {
+ [500, "Internal Server Error", "upstream HTTP 500: Internal Server Error", "server_error"],
+ [429, '{"error":{"message":"Rate limit reached for requests"}}', "upstream HTTP 429: Rate limit reached for requests", "rate_limited"],
+ ])("retries an HTTP %i failure at full size, and doesn't take it for a request that is too large", async (status, body, message, reason) => {
const f = await provider(() => ({ status, body }));
const done = await f.run({ transcript: transcript(20, 3_000) });
expect(done).toMatchObject({ ok: false });
expect(f.requests).toHaveLength(3);
expect(new Set(f.requests.map((request) => request.bytes)).size).toBe(1);
+ expect(f.retries()).toEqual([
+ expect.objectContaining({ attempt: 1, reason }),
+ expect.objectContaining({ attempt: 2, reason }),
+ ]);
expect(f.errors()).toEqual([message]);
- });
+ }, 20_000);
});
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index cb4d61fda7..d4890e4a7e 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -557,9 +557,10 @@ describe("optional built-in question compatibility", () => {
});
await f.start({ integrations: undefined });
expect(await f.completed()).toMatchObject({ ok: false });
+ // A transient 429/500 is retried twice now; every attempt still carries the tools.
expect(f.requests).toHaveLength(status === 429 || status === 500 ? 3 : 1);
for (const request of f.requests) expect(request.tools?.map(tool => tool.function.name)).toEqual(["ask_user"]);
- });
+ }, 20_000);
it("retries a network failure as the same request, and never strips tools mounted by the person", async () => {
for (const network of [false, true]) {
@@ -570,11 +571,13 @@ describe("optional built-in question compatibility", () => {
});
await f.start(network ? { integrations: undefined } : {});
expect(await f.completed()).toMatchObject({ ok: false });
+ // A dropped connection is transient, so it goes again twice; the 400 stays a single attempt.
expect(f.requests).toHaveLength(network ? 3 : 1);
- for (const request of f.requests) expect(request.tools?.some(tool => tool.function.name === (network ? "ask_user" : "audit_write"))).toBe(true);
+ if (!network) expect(f.requests[0].tools?.some(tool => tool.function.name === "audit_write")).toBe(true);
+ else for (const request of f.requests) expect(request.tools?.map(tool => tool.function.name)).toEqual(["ask_user"]);
expect(f.effects()).toEqual([]);
}
- });
+ }, 20_000);
it("does not repeat an unsupported-tools rejection after its one plain retry", async () => {
const f = await fixture((_body, response) => {
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index 3d949151f6..b6c19bf1e4 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -924,7 +924,7 @@ describe("createOpenAIChatRuntime rejected keys", () => {
await instance.adapter.sendTurn({ threadId: "thread", text: "hi" });
await vi.waitFor(() => {
if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
- });
+ }, { timeout: 10_000 });
stop();
return events;
};
@@ -961,5 +961,46 @@ describe("createOpenAIChatRuntime rejected keys", () => {
await turn(instance);
expect(await instance.snapshot()).toMatchObject({ state: "available", authenticated: true });
await instance.dispose();
- });
+ }, 20_000);
+});
+
+describe("createOpenAIChatRuntime transient retries", () => {
+ // Like runTurn, but the turn waits out the retry backoff before it completes.
+ const runRetryTurn = async (respond: () => Response) => {
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) =>
+ String(url).endsWith("/chat/completions") ? respond() : new Response("", { status: 404 })));
+ const instance = await OpenAICompatDriver.create({
+ instanceId: "compat", displayName: "Compat", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "https://api.example.com/v1", apiKeyEnv: "K", model: "m" }),
+ environment: { K: "secret" },
+ });
+ const events: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => events.push(event));
+ await instance.adapter.sendTurn({ threadId: "thread", text: "hi" });
+ await vi.waitFor(() => {
+ if (!events.some((event) => event.type === "turn.completed")) throw new Error("turn still running");
+ }, { timeout: 10_000 });
+ await instance.dispose();
+ return events;
+ };
+ const rateLimited = () => new Response(JSON.stringify({ error: { message: "Rate limit reached", code: "rate_limit_exceeded" } }), { status: 429 });
+ const answer = () => sse('data: {"choices":[{"index":0,"finish_reason":"stop","delta":{"content":"Hello!"}}]}\n\ndata: [DONE]\n\n');
+
+ it("retries a 429 from an endpoint that omits retryScale, then answers", async () => {
+ let requests = 0;
+ const events = await runRetryTurn(() => ++requests === 1 ? rateLimited() : answer());
+ expect(requests).toBe(2);
+ expect(events.find((event) => event.type === "turn.retrying")).toMatchObject({ attempt: 1, reason: "rate_limited" });
+ expect(events.find((event) => event.type === "item.completed")).toMatchObject({ text: "Hello!" });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
+ }, 20_000);
+
+ it("gives up after three 429s and reports the last one", async () => {
+ let requests = 0;
+ const events = await runRetryTurn(() => (requests++, rateLimited()));
+ expect(requests).toBe(3);
+ expect(events.filter((event) => event.type === "turn.retrying")).toHaveLength(2);
+ expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("HTTP 429") });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false });
+ }, 20_000);
});
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index ec7c60171d..5cbdf3cf99 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -715,11 +715,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
continue;
}
// Once a call has been handled, never replay it through a turn retry.
- if (options.retryScale === undefined || abort.signal.aborted || streamed || seenCalls.size ||
+ if (abort.signal.aborted || streamed || seenCalls.size ||
error instanceof ChatProtocolError || !verdict.transient || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
const delayMs = computeBackoff(attempt++);
emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: verdict.reason });
- await interruptibleDelay(delayMs * options.retryScale, abort.signal).promise;
+ await interruptibleDelay(delayMs * (options.retryScale ?? 1), abort.signal).promise;
abort.signal.throwIfAborted();
}
}