Skip to content
Source
Sign inSign up
TanStack/ai

openai-base: leaving a Responses stream at `response.completed` aborts its request, so complete calls are logged as client-closed (499) #1965

CloseddinodeSimon(GitHub profile, opens in a new tab) opened this issue 0 comments

Versions: @tanstack/openai-base 1.0.0, @tanstack/ai-openai 1.0.1, @tanstack/ai 1.0.1, openai 7.43.0

What happens: some streamed OpenAI calls that answered in full, and were billed in full, are logged by Cloudflare AI Gateway with status 499, the client closing the request. In our runs, 2 of 11 gpt-6-luna calls were affected, and they weren't the same calls each time.

Why: since #1489 (and #1492 for OpenRouter), processStreamChunks returns at response.completed, and the structured-output stream breaks there, so chat() isn't held by a body that stays open (#1445). That part is right, and should stay. But leaving an openai SDK Stream early aborts its request at once: core/streaming.js calls controller.abort() in the iterator's finally unless the SSE stream was done. Only a [DONE] sentinel spares it, and the Responses API sends none. So when the body would have ended a moment after its last event, which is the usual case, the fetch is aborted in its last bytes, and a proxy or gateway logs the request as closed by the client. It's a race: if the end has already arrived when the loop leaves, nothing is aborted.

#1494's incomplete-stream check is unaffected: it is about a stream that ends before its last event.

Repro, with no network:

import { chat } from "@tanstack/ai";
import { createOpenaiChat } from "@tanstack/ai-openai";

const ev = (type: string, rest: object) => `event: ${type}\ndata: ${JSON.stringify({ type, ...rest })}\n\n`;
const r = { id: "resp_1", model: "gpt-6-luna", status: "completed" };
const events = [
  ev("response.created", { sequence_number: 0, response: { ...r, status: "in_progress", output: [] } }),
  ev("response.output_text.delta", { sequence_number: 1, item_id: "m1", output_index: 0, content_index: 0, delta: "Hi." }),
  ev("response.completed", { sequence_number: 2, response: { ...r, output: [{ type: "message", id: "m1", role: "assistant", content: [{ type: "output_text", text: "Hi.", annotations: [] }] }], usage: { input_tokens: 5, output_tokens: 2, total_tokens: 7 } } }),
];
let aborted = false;
const fetch = async (_url: unknown, init?: RequestInit) => {
  init?.signal?.addEventListener("abort", () => { aborted = true; });
  let i = 0;
  // The body ends 20 ms after its last event, as a real one's end can.
  const body = new ReadableStream({ async pull(c) {
    if (i < events.length) c.enqueue(new TextEncoder().encode(events[i++]));
    else { await new Promise((res) => setTimeout(res, 20)); c.close(); }
  } });
  return new Response(body, { headers: { "content-type": "text/event-stream" } });
};
const adapter = createOpenaiChat("gpt-6-luna", "key", { baseURL: "https://provider.test/v1", fetch });
for await (const _ of chat({ adapter, threadId: "t", runId: "r", messages: [{ role: "user", content: "Hi" }] })) {}
console.log({ aborted }); // { aborted: true }: the request was aborted though the body was about to end

Suggested fix: a bounded drain. Keep leaving the loop at the last event, as #1489 does, so nothing waits. In the background, read what is left for a short time, then abort if the body is still open. Abort through the stream's controller: the iterator's return() would wait for a read pending on an open body. A consumer that stops before a last event should still abort at once. For example:

const LAST_EVENTS = new Set(["response.completed", "response.failed", "response.incomplete", "error"]);
const DRAIN_MS = 250;
async function* drainAfterLast(stream) {
  const it = stream[Symbol.asyncIterator]();
  let ended = false, last = false;
  try {
    while (true) {
      const step = await it.next();
      if (step.done) { ended = true; return; }
      last = LAST_EVENTS.has(step.value?.type);
      yield step.value;
    }
  } finally {
    if (!ended) {
      if (last) {
        const timer = setTimeout(() => stream.controller?.abort(), DRAIN_MS);
        (async () => { try { while (!(await it.next()).done); } catch {} clearTimeout(timer); })();
      } else await it.return?.();
    }
  }
}

Pass drainAfterLast(response) to processStreamChunks, and loop over drainAfterLast(stream) in the structured-output stream. With it, the repro logs { aborted: false }; #1489's case (a body that never ends) still finishes chat() at once, and is aborted after 250 ms; and in our runs, 4 of 4 calls through the gateway logged 200. The same applies to the OpenRouter adapter (#1492).

  1. github-actions[bot](GitHub profile, opens in a new tab) added labelswaiting-on: maintainer

  2. tombeckenham closed this

Sign in to join this conversation.