Skip to content

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

openai-compat: retry a provider stream cut after tool calls or streamed text

skygunnera91ee14e1c77
diff --git a/server/drivers/openai-chat-stream-retry.test.ts b/server/drivers/openai-chat-stream-retry.test.ts
index b026f5e9f5..36580db0e3 100644
--- a/server/drivers/openai-chat-stream-retry.test.ts
+++ b/server/drivers/openai-chat-stream-retry.test.ts
@@ -1,5 +1,5 @@
-// The chat runtime may resend a stream the provider closed before any completion marker; these
-// tests pin that one protocol error's retry and the guards that keep a resend side-effect free.
+// A stream cut retries the one model call even after output streamed or a tool call ran earlier in the
+// turn; these tests pin that resend and the side-effect budget it keeps.
import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -66,18 +66,19 @@ describe("createOpenAIChatRuntime stream truncation retry", () => {
expect(requests).toBe(3);
});
- it("does not resend once answer text streamed, even with a clean retry available", async () => {
- const { events, requests } = await runTurn([
- () => sse('data: {"choices":[{"index":0,"delta":{"content":"Hel"}}]}\n\n'),
- answer,
- ]);
- expect(events.some((event) => event.type === "turn.retrying")).toBe(false);
- expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: "Stream ended before completion" });
- expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "error" });
- expect(requests).toBe(1);
+ it("resends a cut that streamed answer text and still finishes the turn", async () => {
+ const cutAfterText = () => sse('data: {"choices":[{"index":0,"delta":{"content":"Hel"}}]}\n\n'
+ + 'data: {"error":"terminated"}\n\n');
+ const { events, requests } = await runTurn([cutAfterText, answer]);
+ expect(events.filter((event) => event.type === "turn.retrying"))
+ .toEqual([expect.objectContaining({ attempt: 1, reason: "stream_cut" })]);
+ expect(events.find((event) => event.type === "runtime.error")).toBeUndefined();
+ expect(events.find((event) => event.type === "item.completed")).toMatchObject({ text: "hi" });
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
+ expect(requests).toBe(2);
});
- it("does not resend a truncation after a tool call ran, so its effect happens once", async () => {
+ it("resends a cut in a round after a tool call ran, without running the tool twice", async () => {
const dir = mkdtempSync(join(tmpdir(), "omb-chat-trunc-tool-"));
const script = join(dir, "fake-mcp.mjs");
const receipt = join(dir, "receipt.log");
@@ -105,8 +106,8 @@ describe("createOpenAIChatRuntime stream truncation retry", () => {
vi.stubGlobal("fetch", vi.fn(async (input: unknown, init?: RequestInit) => {
if (!String(input).endsWith("/chat/completions")) return new Response(JSON.stringify({ data: [] }));
bodies.push(JSON.parse(String(init?.body)));
- // The tool result goes back up, and that second attempt's stream is the truncation.
- return new Response(bodies.length === 1 ? callBody : "", { headers: { "content-type": "text/event-stream" } });
+ // The tool call runs first, the next round's stream is the cut, and its resend answers clean.
+ return bodies.length === 1 ? sse(callBody) : bodies.length === 2 ? truncated() : answer();
}));
const instance = await OpenAICompatDriver.create({
instanceId: "trunc", displayName: "Synthetic", enabled: true,
@@ -121,11 +122,12 @@ describe("createOpenAIChatRuntime stream truncation retry", () => {
integrations: { custom: { fx: { command: script, args: [], env: {} } } },
});
await vi.waitFor(() => expect(events.some((event) => event.type === "turn.completed")).toBe(true), { timeout: 10_000 });
- expect(bodies).toHaveLength(2);
- expect(bodies[1]?.messages.some((message) => message.role === "tool")).toBe(true);
- expect(events.some((event) => event.type === "turn.retrying")).toBe(false);
- expect(events.find((event) => event.type === "runtime.error")).toMatchObject({ message: "Stream ended before completion" });
- expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "error" });
+ expect(bodies).toHaveLength(3);
+ expect(bodies[2]?.messages.some((message) => message.role === "tool")).toBe(true);
+ expect(events.filter((event) => event.type === "turn.retrying"))
+ .toEqual([expect.objectContaining({ attempt: 1, reason: "stream_truncated" })]);
+ expect(events.find((event) => event.type === "runtime.error")).toBeUndefined();
+ expect(events.at(-1)).toMatchObject({ type: "turn.completed", ok: true });
expect(readFileSync(receipt, "utf8").trim().split("\n")).toEqual(["write"]);
} finally {
await instance.dispose();
diff --git a/server/drivers/openai-chat.test.ts b/server/drivers/openai-chat.test.ts
index e50e859e3e..4ca0d3d6e8 100644
--- a/server/drivers/openai-chat.test.ts
+++ b/server/drivers/openai-chat.test.ts
@@ -17,6 +17,12 @@ import { whopLikeCatalog } from "../testing/whop-like-catalog.ts";
afterEach(() => vi.unstubAllGlobals());
+// A stream cut now retries; real backoff would only slow these tests (retry.ts's own suite covers the schedule).
+vi.mock("./retry.ts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./retry.ts")>();
+ return { ...actual, computeBackoff: () => 0 };
+});
+
const sse = (body: string) => new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });
/** `body` is every request's stream, or a factory per chat completion (the catalog fetch then gets a 404). */
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index dc723fdc71..1ab6a1bf5c 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -721,9 +721,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
tools.definitions.length = 0;
continue;
}
- // Never replay a handled call. A stream closed before any completion marker ran nothing upstream, so it may resend even where the caller never opted into retries.
+ // A stream cut retries the one model call even after earlier output — the resend may re-run a side-effectful tool call under a fresh ID, still better than failing the whole turn; without a caller opt-in only the cut itself retries.
const truncation = error instanceof StreamTruncatedError, retryScale = truncation ? options.retryScale ?? 1 : options.retryScale;
- if (retryScale === undefined || abort.signal.aborted || streamed || seenCalls.size || error instanceof RuntimeNoticeError || (!truncation && (error instanceof ChatProtocolError || !verdict.transient)) || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
+ if (retryScale === undefined || abort.signal.aborted || error instanceof RuntimeNoticeError || (!truncation && ((error instanceof ChatProtocolError && verdict.reason !== "stream_cut") || !verdict.transient)) || (verdict.reason !== "stream_cut" && (streamed || seenCalls.size)) || attempt >= RETRY_MAX_ATTEMPTS - 1) throw error;
const delayMs = computeBackoff(attempt++);
emit({ ...base(turn.threadId, turnId), type: "turn.retrying", attempt, delayMs, reason: truncation ? "stream_truncated" : verdict.reason });
await interruptibleDelay(delayMs * retryScale, abort.signal).promise;
diff --git a/server/drivers/retry.test.ts b/server/drivers/retry.test.ts
index c058aee437..23c0c8e9d6 100644
--- a/server/drivers/retry.test.ts
+++ b/server/drivers/retry.test.ts
@@ -76,6 +76,16 @@ describe("classifyError", () => {
});
});
+ it("calls a provider stream cut transient with reason stream_cut", () => {
+ // undici ends a cut stream read with the bare word "terminated"; the provider's SSE error chunk wraps the same word.
+ expect(classifyError(new Error("terminated"))).toEqual({ transient: true, reason: "stream_cut" });
+ expect(classifyError(new Error("terminated", { cause: new Error("other side closed") })))
+ .toEqual({ transient: true, reason: "stream_cut" });
+ expect(classifyError({ text: "provider returned a streaming completion error: terminated" }))
+ .toEqual({ transient: true, reason: "stream_cut" });
+ expect(classifyError(new Error("Stream ended before completion"))).toEqual({ transient: true, reason: "stream_cut" });
+ });
+
it.each([
["Internal error: Internal service failure (session/new, ServiceUnavailableError)", "server_error"],
["ServiceUnavailableError: upstream unavailable", "server_error"],
diff --git a/server/drivers/retry.ts b/server/drivers/retry.ts
index cb80642a26..85d1dbcf05 100644
--- a/server/drivers/retry.ts
+++ b/server/drivers/retry.ts
@@ -13,7 +13,8 @@ export type TransientReason =
| "overloaded"
| "server_error"
| "connection_reset"
- | "timeout";
+ | "timeout"
+ | "stream_cut";
export type TerminalReason =
| "auth"
@@ -43,6 +44,8 @@ const TRANSIENT_PATTERNS: Array<{ pattern: RegExp; reason: TransientReason }> =
reason: "connection_reset",
},
{ pattern: /\btimeout(ed)?\b|\btimed? out\b/i, reason: "timeout" },
+ // A provider stream cut: undici ends the read with the bare word "terminated", the SSE error chunk says "streaming completion error: terminated".
+ { pattern: /\bstreaming completion error: terminated\b|^terminated\b|\bstream ended before completion\b/i, reason: "stream_cut" },
];
/** A subscription's usage running out: terminal even when phrased as a rate limit. Claude Code 2.1.295