Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(sdk): reject truncated TypeScript generation streams
svonavaf1bdaf93f909
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 23e7fd4bd..e053a077e 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -109,7 +109,7 @@ import {requireConnectorIdempotencyKey,} from "./jobs.js";import { packMessage, unpackMessage } from "./msgpack.js";-import { parseSseStream } from "./sse.js";+import { SSECompletion, parseSseStream } from "./sse.js";import {SYSTEM_ONE_OPTIONS,type SystemOneOptions,@@ -1689,6 +1689,8 @@ export class SIEClient {* - `signal.abort()` mid-stream → the generator throws* `SIEConnectionError` and releases the underlying reader, which* fires `StreamCancelGuard` on the gateway side.+ * - EOF before `[DONE]` or all requested choices finish → throws+ * `SIEConnectionError`. The request is never replayed.** `req.stream` is set to `true` automatically; any existing value is* overwritten. We do not validate `req.stream === false` because the@@ -1727,8 +1729,13 @@ export class SIEClient {}const body = { ...req, stream: true };const url = `${this.baseUrl}/v1/chat/completions`;- yield* this.consumeSseStream<ChatCompletionChunk>(url, body, req.model, signal, (chunk) =>- extractChatChunkError(chunk),+ yield* this.consumeSseStream<ChatCompletionChunk>(+ url,+ body,+ req.model,+ signal,+ (chunk) => extractChatChunkError(chunk),+ new SSECompletion(req.n ?? 1),);}@@ -1745,7 +1752,8 @@ export class SIEClient {** Error semantics match {@link streamChatCompletions}: pre-stream HTTP* errors throw normally, mid-stream `error` chunks throw- * {@link SIEStreamError}.+ * {@link SIEStreamError}. EOF before `[DONE]` or `done: true` throws+ * `SIEConnectionError` without replaying the request.** @example* ```typescript@@ -1794,6 +1802,7 @@ export class SIEClient {model,signal,(chunk) => extractGenerateChunkError(chunk),+ new SSECompletion(),{ pool, gpu },{ waitForCapacity, timeoutMs: options.timeoutMs },);@@ -1827,6 +1836,7 @@ export class SIEClient {model: string,signal: AbortSignal | undefined,extractError: (chunk: T) => SIEStreamError | null,+ completion: SSECompletion,routing?: { pool?: string; gpu?: string },provisioning?: { waitForCapacity?: boolean; timeoutMs?: number },): AsyncGenerator<T, void, undefined> {@@ -2038,7 +2048,7 @@ export class SIEClient {throw new RequestError("Streaming response has no body");}const reader = bodyStream.getReader();- for await (const payload of parseSseStream(reader, signal ?? controller.signal)) {+ for await (const payload of parseSseStream(reader, signal ?? controller.signal, completion)) {let chunk: T;try {chunk = JSON.parse(payload) as T;@@ -2049,8 +2059,10 @@ export class SIEClient {}const streamErr = extractError(chunk);if (streamErr) throw streamErr;+ completion.observe(chunk);yield chunk;}+ completion.requireComplete();} finally {if (signal) signal.removeEventListener("abort", onCallerAbort);}diff --git a/packages/sie_ts_sdk/src/sse.ts b/packages/sie_ts_sdk/src/sse.tsindex aa79dc666..8cd5978fb 100644--- a/packages/sie_ts_sdk/src/sse.ts+++ b/packages/sie_ts_sdk/src/sse.ts@@ -24,6 +24,56 @@ import { SIEConnectionError, SIEStreamError } from "./errors.js";const SSE_DONE = "[DONE]";+/** Track generation completion separately from a clean HTTP body EOF. */+export class SSECompletion {+ done = false;+ private nativeTerminal = false;+ private readonly chatChoices: number | undefined;+ private readonly finishedChoices = new Set<number>();++ constructor(chatChoices?: number) {+ this.chatChoices =+ chatChoices === undefined+ ? undefined+ : Number.isSafeInteger(chatChoices) && chatChoices > 0+ ? chatChoices+ : 1;+ }++ observe(chunk: unknown): void {+ if (typeof chunk !== "object" || chunk === null) return;+ const record = chunk as Record<string, unknown>;+ if (this.chatChoices === undefined) {+ if (record.done === true) this.nativeTerminal = true;+ return;+ }+ if (!Array.isArray(record.choices)) return;+ for (const choice of record.choices) {+ if (typeof choice !== "object" || choice === null) continue;+ const { index, finish_reason: finish } = choice;+ if (+ typeof index === "number" &&+ Number.isInteger(index) &&+ index >= 0 &&+ index < this.chatChoices &&+ typeof finish === "string" &&+ finish.length > 0+ ) {+ this.finishedChoices.add(index);+ }+ }+ }++ requireComplete(): void {+ if (this.done || this.nativeTerminal) return;+ if (this.chatChoices !== undefined && this.finishedChoices.size === this.chatChoices) return;+ throw new SIEConnectionError(+ "Connection lost during stream: response ended before generation completed",+ "other",+ );+ }+}+/*** Hard cap on the in-progress event buffer.*@@ -49,6 +99,8 @@ const MAX_SSE_BUFFER_CHARS = 8 * 1024 * 1024;* @param signal Optional `AbortSignal`; when fired, the generator throws* `SIEConnectionError` (kind `"other"`) and releases the* reader so the upstream fetch is cancelled.+ * @param completion Optional generation tracker; records explicit `[DONE]`+ * separately from transport EOF for the consuming client.* @returns A generator of `data:` payload strings. The generator* completes (without throwing) when the server emits* `[DONE]` or the underlying stream is closed cleanly.@@ -56,6 +108,7 @@ const MAX_SSE_BUFFER_CHARS = 8 * 1024 * 1024;export async function* parseSseStream(reader: ReadableStreamDefaultReader<Uint8Array>,signal?: AbortSignal,+ completion?: SSECompletion,): AsyncGenerator<string, void, undefined> {const decoder = new TextDecoder("utf-8");let buffer = "";@@ -195,6 +248,7 @@ export async function* parseSseStream(// Clean terminus: server signalled end-of-stream. No need to// cancel the body — it has already drained the relevant work.completedCleanly = true;+ if (completion) completion.done = true;return;}yield payload;@@ -211,7 +265,9 @@ export async function* parseSseStream(const tail = buffer.replace(/\r?\n$/, "");if (tail !== "") {const payload = extractDataPayload(tail);- if (payload !== null && payload !== SSE_DONE) {+ if (payload === SSE_DONE) {+ if (completion) completion.done = true;+ } else if (payload !== null) {yield payload;}}diff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex 3b30ef899..ab7d41710 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -155,6 +155,184 @@ function generateChunk(seq: number, text_delta: string, opts: Partial<GenerateChreturn JSON.stringify(chunk);}+describe("generation stream completion", () => {+ beforeEach(() => {+ mockFetch.mockReset();+ });++ function stream(surface: "chat" | "native", n = 1) {+ const client = new SIEClient("http://localhost:8080");+ return surface === "chat"+ ? client.streamChatCompletions({ model: "m", messages: [], n })+ : client.streamGenerate("m", "hello", { maxNewTokens: 8 });+ }++ async function collect(surface: "chat" | "native", n = 1) {+ const chunks: unknown[] = [];+ for await (const chunk of stream(surface, n)) chunks.push(chunk);+ return chunks;+ }++ for (const surface of ["chat", "native"] as const) {+ it.each(["empty", "comments", "partial"])(+ `rejects ${surface} %s EOF without replaying generation`,+ async (kind) => {+ const response =+ kind === "comments"+ ? new Response(": keep-alive\n\n", {+ headers: { "Content-Type": "text/event-stream" },+ })+ : sseResponse(+ kind === "empty"+ ? []+ : [+ surface === "chat"+ ? chatChunk("private output")+ : generateChunk(0, "private output"),+ ],+ { includeDone: false },+ );+ mockFetch.mockResolvedValueOnce(response);+ await expect(collect(surface)).rejects.toMatchObject({+ name: "SIEConnectionError",+ kind: "other",+ message: "Connection lost during stream: response ended before generation completed",+ });+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(response.body?.locked).toBe(false);+ },+ );++ it.each(["\n\n", ""])(`accepts ${surface} explicit DONE with ending %j`, async (ending) => {+ mockFetch.mockResolvedValueOnce(new Response(`data: [DONE]${ending}`));+ await expect(collect(surface)).resolves.toEqual([]);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it(`preserves ${surface} caller return before stream completion`, async () => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([surface === "chat" ? chatChunk("partial") : generateChunk(0, "partial")], {+ includeDone: false,+ }),+ );+ const iterator = stream(surface);+ expect((await iterator.next()).done).toBe(false);+ await expect(iterator.return()).resolves.toEqual({ done: true, value: undefined });+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+ }++ it.each(["\n\n", ""])("accepts native done=true before EOF with ending %j", async (ending) => {+ const terminal = generateChunk(1, "", { done: true, finish_reason: "stop" });+ mockFetch.mockResolvedValueOnce(new Response(`data: ${terminal}${ending}`));+ await expect(collect("native")).resolves.toEqual([JSON.parse(terminal)]);+ });++ it.each(["true", 1, false, null])(+ "does not accept native done=%j as completion",+ async (done) => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([JSON.stringify({ done, text_delta: "partial" })], { includeDone: false }),+ );+ await expect(collect("native")).rejects.toBeInstanceOf(SIEConnectionError);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ },+ );++ it("accepts EOF after all requested chat choices finish, preserving trailing usage", async () => {+ const payloads = [+ chatChunk("", {+ choices: [{ index: 1, delta: {}, finish_reason: "length", logprobs: null }],+ }),+ chatChunk("", { choices: [{ index: 0, delta: {}, finish_reason: "stop", logprobs: null }] }),+ chatChunk("", {+ choices: [],+ usage: { prompt_tokens: 2, completion_tokens: 3, total_tokens: 5 },+ }),+ ];+ mockFetch.mockResolvedValueOnce(sseResponse(payloads, { includeDone: false }));+ await expect(collect("chat", 2)).resolves.toEqual(+ payloads.map((payload) => JSON.parse(payload)),+ );+ });++ it("treats an explicit null chat n as one choice", async () => {+ const terminal = chatChunk("", {+ choices: [{ index: 0, delta: {}, finish_reason: "stop", logprobs: null }],+ });+ mockFetch.mockResolvedValueOnce(sseResponse([terminal], { includeDone: false }));+ await expect(collect("chat", null as unknown as number)).resolves.toEqual([+ JSON.parse(terminal),+ ]);+ });++ it("does not accept native done=true on chat with explicit null n", async () => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([generateChunk(0, "", { done: true })], { includeDone: false }),+ );+ await expect(collect("chat", null as unknown as number)).rejects.toBeInstanceOf(+ SIEConnectionError,+ );+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it.each([+ [{ index: 0, finish_reason: "stop" }],+ [+ { index: 0, finish_reason: "stop" },+ { index: 0, finish_reason: "length" },+ ],+ [+ { index: 0, finish_reason: "stop" },+ { index: 2, finish_reason: "stop" },+ ],+ [+ { index: 0, finish_reason: "stop" },+ { index: true, finish_reason: "stop" },+ ],+ [+ { index: 0, finish_reason: "stop" },+ { index: "1", finish_reason: "stop" },+ ],+ [+ { index: 0, finish_reason: "stop" },+ { index: 1, finish_reason: null },+ ],+ [+ { index: 0, finish_reason: "stop" },+ { index: 1, finish_reason: "" },+ ],+ ])("rejects EOF when chat n=2 is not complete: %j", async (...choices) => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([JSON.stringify({ choices })], { includeDone: false }),+ );+ await expect(collect("chat", 2)).rejects.toBeInstanceOf(SIEConnectionError);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });++ it("preserves a stream error after a semantic completion chunk", async () => {+ mockFetch.mockResolvedValueOnce(+ sseResponse(+ [+ generateChunk(0, "", { done: true, finish_reason: "stop" }),+ JSON.stringify({+ request_id: "req-error",+ error: { message: "generation interrupted", code: "transport_failure" },+ done: true,+ }),+ ],+ { includeDone: false },+ ),+ );+ await expect(collect("native")).rejects.toMatchObject({+ name: "SIEStreamError",+ code: "transport_failure",+ requestId: "req-error",+ });+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+});+describe("SIEClient.streamChatCompletions", () => {beforeEach(() => {mockFetch.mockClear();