From d85b2ef8778397097626c07988b12ad779ceb905 Mon Sep 17 00:00:00 2001 From: Danny Mitchell Date: Sat, 14 Nov 2026 22:40:10 -0600 Subject: [PATCH] fix: verify SSE terminal framing through fetch seam --- CHANGELOG.md | 6 ++ README.md | 10 +-- docs/design.md | 10 +-- docs/testing-runbook.md | 35 +++++++++- src/runner.ts | 10 ++- src/sdk.ts | 11 ++- src/sse-completion.ts | 91 +++++++++++++++++++++++++ tests/helpers.ts | 2 +- tests/runner.test.ts | 5 +- tests/stream-completion.test.ts | 116 ++++++++++++++++++++++++++++++++ 10 files changed, 277 insertions(+), 19 deletions(-) create mode 100644 src/sse-completion.ts create mode 100644 tests/stream-completion.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ba5e1d5..d188b4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +- Require a complete SSE `[DONE]` event as well as a normal finish reason before accepting success. Report missing markers and unfinished trailing frames as protocol diagnostics while preserving received text. +- Observe framing through the existing custom fetch seam, keeping the pinned SDK for payload parsing and validation, with bounded framing state and source-reader cleanup. +- Add completion-framing regressions and correct the distinction between numeric Chat Completions error codes and string Responses API codes. + ## 0.1.1 — 2026-11-12 - Reject malformed API-key header values as input diagnostics before transport, with CLI exit 2 and no credential disclosure. Fixes [#1](https://github.com/dannymitchelldev/streamcheck/issues/1). diff --git a/README.md b/README.md index e909943..802bacd 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Omit `--env-file` when `OPENROUTER_API_KEY` is already in the environment. This | Outcome | Meaning | Default CLI exit | | --- | --- | ---: | -| `success` | Normal completion accepted through the SDK | 0 | +| `success` | Normal finish and complete `[DONE]` event observed | 0 | | `failed` | Failure before receiving text | 1 | | `interrupted` | Failure with received text preserved | 3 | | `cancelled` | Caller cancellation, with any text preserved | 130 | @@ -132,7 +132,7 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi `schemaVersion: 1` results include exact text, timing, observed HTTP status, first finish reason, and warnings. Unknown metadata is `null`. Failed/interrupted results add `error: { kind, phase, message, code? }`; cancellation records `reason: 'caller'`. See the [public TypeScript types](src/types.ts) for every field. - **Partial output:** true exactly when text is nonempty and normal completion was not accepted. Successful `length` and `content_filter` results set it false and carry `token_limit` / `content_filter` warnings. The flag does not judge answer quality. -- **Completion:** a normal finish reason is provisional while accounting frames drain. A later observable error, conflict, cancellation, or deadline can still win. Identical repeated reasons are harmless. Tool calls are unsupported. +- **Completion:** success requires a normal finish reason and a complete SSE `[DONE]` event. A normal finish remains provisional while accounting frames drain; EOF without `[DONE]` or with an unfinished trailing frame is a protocol diagnostic, with received text retained. A later provider error, conflict, cancellation, or deadline can still win. Identical repeated reasons are harmless. Tool calls are unsupported. - **Cancellation:** first accepted terminal outcome wins. Deadline and caller-abort handlers record their cause before aborting transport. A pre-aborted signal sends no request. Accepted success survives later cancellation. - **Callbacks:** each text delta is accumulated before synchronous `onText`. A thrown callback preserves its triggering delta. The first observed finish reason is retained even when a callback throws or cancels on the same frame. Do not pass async callbacks; promises and asynchronous rejections are outside this contract. - **Timing:** first-token time means time to the first nonempty text delta. It excludes initial module loading and is not a tokenizer measurement. Elapsed time ends when a terminal outcome is accepted, before final cleanup. @@ -143,11 +143,13 @@ Every input/configuration diagnostic exits **2**. Timeout exits **124**, includi | --- | --- | | HTTP 401 / 429 | Request failed before streaming: authentication / rate limiting | | HTTP 200 plus provider diagnostic | Valid provider error arrived inside the stream, possibly before any text | -| Protocol diagnostic | SDK rejected a payload, finish reason was missing/conflicting, or tool calls appeared | +| Protocol diagnostic | SDK rejected a payload, a finish reason or `[DONE]` was missing, a trailing frame was unfinished, finish reasons conflicted, or tool calls appeared | | Timeout after a finish reason | The finish remained provisional while the stream drained | | Null HTTP status | No response metadata was available; StreamCheck never assumes 200 | -The SDK is pinned to **1.5.91**. It accepts numeric chat-stream error codes; a documented string-code shape is rejected as a protocol error. Received text is still retained. The SDK also hides `[DONE]` and discards unfinished trailing SSE frames: after a valid finish reason, a truncated trailing error may remain undetectable. This is SDK-observed completion, not verified complete transport. +The SDK is pinned to **1.5.91**. It accepts numeric Chat Completions error codes; a string-valued `error.code` in a chat-stream chunk is rejected as a protocol diagnostic, with previously received text retained. Current [OpenRouter documentation](https://openrouter.ai/docs/api_reference/errors-and-debugging) specifies numeric codes for Chat Completions and string codes for the separate Responses API. + +StreamCheck observes SSE framing through its custom fetch seam while the official SDK parses and validates payloads. This detects a missing `[DONE]` or unfinished event at EOF. Observation ends at the first complete `[DONE]`, matching the SDK's cancellation behavior; it does not establish HTTP EOF, inspect bytes after that terminal event, or prove an upstream root cause. Configured API keys, authorization headers, and raw SDK exceptions are never logged. User prompts and model text are not automatically redacted and may themselves contain secrets. There is no telemetry or output persistence. diff --git a/docs/design.md b/docs/design.md index 5dd6489..9eb11a4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -6,19 +6,21 @@ One ESM TypeScript package, one text-stream operation through the official OpenR `runStreamCheck(LiveOptions): Promise` and `runDemo(DemoOptions?): Promise` expose success, failure without text, interruption with text, and caller cancellation. The CLI consumes these public functions. Defaults: 30,000 ms overall deadline, 256 maximum output tokens, interrupted demo. -Normal finish reasons are provisional until SDK iteration ends. Stop succeeds; length and content_filter succeed with warnings. Identical repeated normal reasons are accounting duplicates; conflicting normal reasons are protocol failures. Valid provider errors are provider failures. Tool calls are unsupported protocol failures. Schema-rejected events are protocol failures, with no attempt to mine rejected payloads for provider codes. +Normal finish reasons are provisional until SDK iteration ends and a complete SSE [DONE] event has been observed. Stop succeeds; length and content_filter succeed with warnings. EOF without [DONE] or with an unfinished trailing event is a protocol failure. Identical repeated normal reasons are accounting duplicates; conflicting normal reasons are protocol failures. Valid provider errors are provider failures. Tool calls are unsupported protocol failures. Schema-rejected events are protocol failures, with no attempt to mine rejected payloads for provider codes. Only completion choice index zero is supported. An unexpected index or duplicate choice entry is a protocol failure; text from an ambiguous frame is not merged into the selected stream. Previously accepted text is retained. Empty-choice accounting frames are allowed. `partialOutput` means nonempty received text exists and normal completion was not accepted. It is false for successful length/content_filter results; warnings describe their limitation. Text is appended before calling synchronous onText, including the delta whose callback throws. Async callbacks/rejections are outside the contract. -First accepted terminal outcome wins. Timeout and caller cancellation record their origin before aborting transport. A pre-aborted caller signal returns cancellation before a request. Success is accepted only at SDK iterator exhaustion, so an earlier observable error or timeout while draining wins. First-token latency is time to first nonempty text delta, not a tokenizer measurement. +First accepted terminal outcome wins. Timeout and caller cancellation record their origin before aborting transport. A pre-aborted caller signal returns cancellation before a request. Success is accepted only at SDK iterator exhaustion with both a normal finish and a complete [DONE], so an earlier observable error or timeout while draining wins. Framing checks at exhaustion do not override accepted provider, network, consumer, timeout, or cancellation outcomes. First-token latency is time to first nonempty text delta, not a tokenizer measurement. ## SDK boundary -Pin @openrouter/sdk 1.5.91. Disable retries and inject a no-op debug logger. Observe real response status without consuming or changing responses; use null when unavailable. Never infer 200. Preserve exact decoded text, not raw SDK exceptions or HTTP request metadata. +Pin @openrouter/sdk 1.5.91. Disable retries and inject a no-op debug logger. Observe real response status; use null when unavailable and never infer 200. The internal custom fetcher wraps successful SSE bodies with pull-based byte forwarding, preserving response status/headers and SDK input bytes. Forward cancellation and transport errors and release the source reader at EOF, error, or cancellation. Preserve exact decoded text, not raw SDK exceptions or HTTP request metadata. -The SDK hides whether [DONE] arrived and drops incomplete trailing frames at EOF. An observed normal reason followed by an incomplete trailing error frame can therefore succeed. StreamCheck reports SDK-observed completion, not verified complete transport. Numeric typed provider codes may be retained; rejected string-code errors are protocol diagnostics. +The SDK hides whether [DONE] arrived and drops incomplete trailing events at EOF. A separate bounded framing observer closes that visibility gap: it handles UTF-8/BOM and LF, CRLF, or CR line endings incrementally, retaining only a short line prefix and event flags. It requires an exact single data value [DONE] terminated by a blank line; matching text inside content, comments, or unrelated fields does not certify completion. JSON decoding and validation remain with the SDK. There is no tee or full-body buffering. + +The application boundary is the first complete [DONE] event, where the SDK cancels its reader. Bytes after that boundary and full HTTP EOF are not verified. Numeric typed Chat Completions provider codes may be retained; rejected string-code errors remain protocol diagnostics. Current OpenRouter documentation uses numeric codes for Chat Completions and string codes for the separate Responses API. ## CLI and boundaries diff --git a/docs/testing-runbook.md b/docs/testing-runbook.md index e592cc4..42df1fa 100644 --- a/docs/testing-runbook.md +++ b/docs/testing-runbook.md @@ -54,12 +54,43 @@ Tests release timers/readers/listeners. The package-consumer check removes only - Report actual platform/version checks separately from authored CI jobs. - CLI subprocess cases intentionally pay the SDK's cold import cost; the final 93-test suite took 54.60 seconds locally. Do not replace subprocess checks with assertions on a fake CLI. - SIGINT tests use an IPC harness to emit the Node process event portably, including after partial text. This establishes handler behavior, not physical Windows console Ctrl+C behavior. -- Tests exercise SDK-observable EOF semantics; no test can establish that the hidden [DONE] marker or a discarded partial frame was received. +- The SDK gate characterizes its hidden [DONE]/unfinished-event behavior. StreamCheck's completion regressions separately verify its raw framing observer: normal success requires a complete terminal event, and unfinished frames at EOF produce protocol diagnostics. - When changing argument parsing, cover missing option values before standalone --json, literal --prompt=--json, and the -- terminator. Strict and permissive Node argument parsing interpret missing values differently. - SDK fixtures must not let another choice's finish certify choice zero. Unexpected/duplicate choice entries are protocol failures; already retained text must survive. - A cold npm cache exposed an old ENOTCACHED failure: npm ci cached package files without all registry manifests needed by a separate --offline install. Consumer dependency installation now permits npm access. Runtime provider access remains blocked, and installed CLI resolution remains offline. - Cancellation fixtures must match native fetch signal precedence: `init?.signal ?? request.signal`. SDK 1.5.91 supplies a strongly retained signal through `RequestInit`; observing only the request's weakly linked signal can hang after Node garbage collection. This reproduced an intermittent 10-second compatibility-test timeout without any provider traffic; the fixture now observes the effective signal. +## SDK completion and error-code boundaries + +Last verified: 2026-11-14, using the installed `@openrouter/sdk` 1.5.91. Before the observer was added, the targeted regressions reproduced 13 failures, including false success and a source-reader lock left held after cancellation. + +### Purpose + +Reproduce the distinction between SDK-observed completion and verified receipt of the Chat Completions terminal event, and check error-code classification. + +### Setup and safe actions + +Use locked dependencies and synthetic HTTP/SSE fixtures. The commands below make no provider requests, need no credentials, and do not modify runtime code. No cleanup is required. + +### Verification commands + +```sh +npm run test:sdk +npm exec --offline -- vitest run tests/stream-completion.test.ts tests/runner.test.ts +``` + +Expected: the SDK gate passes 7 tests; the completion/runner command passes 78 tests. All 85 targeted checks passed after adding the observer. The completion file covers missing markers with and without text, unfinished JSON and marker framing, literal markers in unrelated fields/comments/text, fragmented UTF-8/BOM and LF/CRLF/CR, default fetch, source-reader cleanup, and provider/network precedence. + +Full verification on Windows / Node 24.18.0 / npm 11.16.0 passed `npm run check`: type checks, build, all 136 tests, and the actual packed-package consumer. `npm run example:demo` also passed. These are offline fixtures; no new live provider verification or cross-platform result is claimed. + +### Interpretation + +- Success requires an observed normal finish reason and a complete `[DONE]` data event. Missing `[DONE]` or EOF with an unfinished event produces a protocol failure without text, or interruption with exact previously accepted text preserved. Complete provider errors, source transport errors, consumer failures, cancellation, and deadlines retain their existing precedence. +- The SDK alone still hides the distinction between `[DONE]`, EOF, and EOF with an unfinished trailing event. StreamCheck now observes raw framing before SDK parsing. Even valid JSON without the event's final blank line is unfinished. Discarding an unfinished event follows the [SSE standard](https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation); StreamCheck reports the missing framing instead of accepting normal completion. +- A string-valued `error.code` in a Chat Completions chunk causes SDK schema rejection and a StreamCheck protocol diagnostic. Prior accepted text survives. This behavior alone does not establish rejection of a documented Chat Completions response: the current [OpenRouter error documentation](https://openrouter.ai/docs/api_reference/errors-and-debugging) specifies numeric codes for Chat Completions and string codes for the Responses API. Recheck the endpoint-specific documentation before claiming a schema mismatch. +- `createSdk` injects an `HTTPClient` and wraps either the native or injected fetcher. Its pull-based observer forwards original body bytes, cancellation, errors, and actual response metadata; it keeps bounded framing state without a tee, full-body buffer, or JSON parser. A substring search for `[DONE]` is insufficient. +- Observation ends at the first complete terminal event, matching SDK cancellation; it does not wait for HTTP EOF or inspect bytes after `[DONE]`. The underlying source reader must be released after EOF, transport errors, and cancellation. No raw frames or SDK exceptions are added to diagnostics or logs. + ## Release artifact verification ### Purpose @@ -206,7 +237,7 @@ Keep nonsecret evidence needed for review. Credential files and raw scratch outp - Missing or malformed credentials are setup diagnostics and do not verify provider connectivity. HTTP 401, 402, and 429 require inspecting credential validity, available credit, or rate limits respectively. - Record failed/interrupted outcomes as observed. A timeout, transport failure, or protocol rejection is not a passing provider check. - One successful generation establishes the observed model/platform combination at that time. Provider interruption recovery, rate limits, physical console Ctrl+C, other operating systems, and sustained reliability require separate evidence. -- Completion remains SDK-observed. The SDK's documented trailing-frame limitation still applies. +- This saved live receipt predates raw terminal-framing observation. It establishes SDK-observed completion on its recorded commit; the new terminal-event gate is verified separately by the offline completion regressions above. ## Manual live interruption checks diff --git a/src/runner.ts b/src/runner.ts index 0946234..7d4ea66 100644 --- a/src/runner.ts +++ b/src/runner.ts @@ -2,6 +2,7 @@ import type { Fetcher } from '@openrouter/sdk/lib/http.js'; import type { ChatStreamChunk } from '@openrouter/sdk/models'; import { validateHeaderValue } from 'node:http'; import { createSdk } from './sdk.js'; +import { SseCompletionObserver } from './sse-completion.js'; import type { Diagnostic, FailureResult, LiveOptions, ResultBase, RunResult, RunSource, WarningCode } from './types.js'; const DEFAULT_TIMEOUT = 30_000; @@ -59,6 +60,7 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, let normalReason: string | null = null; let phase: Diagnostic['phase'] = 'request'; const warnings: WarningCode[] = []; + const completion = new SseCompletionObserver(); const cancelReader = () => { if (reader && !cancelling) cancelling = reader.cancel().catch(() => { /* preserve the accepted outcome */ }); @@ -87,7 +89,7 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, const sdk = createSdk(options.apiKey, fetcher, response => { httpStatus = response.status; if (response.ok && response.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) phase = 'stream'; - }); + }, completion); const stream = await sdk.chat.send({ chatRequest: { model: options.model, @@ -106,8 +108,10 @@ export async function runWithTransport(options: LiveOptions, fetcher?: Fetcher, const next = await reader.read(); if (terminal) break; if (next.done) { - if (normalReason) accept({ outcome: 'success' }); - else fail('protocol', 'Stream ended without an observed normal finish reason'); + if (completion.truncated) fail('protocol', 'Stream ended with an unfinished SSE frame'); + else if (!completion.done) fail('protocol', 'Stream ended without an observed [DONE] event'); + else if (!normalReason) fail('protocol', 'Stream ended without an observed normal finish reason'); + else accept({ outcome: 'success' }); break; } const value = next.value; diff --git a/src/sdk.ts b/src/sdk.ts index aca0f6c..aed507a 100644 --- a/src/sdk.ts +++ b/src/sdk.ts @@ -1,11 +1,16 @@ import { OpenRouter } from '@openrouter/sdk'; import { HTTPClient, type Fetcher } from '@openrouter/sdk/lib/http.js'; +import { observeSseCompletion, type SseCompletionObserver } from './sse-completion.js'; const silentLogger = { log() {}, group() {}, groupEnd() {} }; -/** Internal seam: the SDK still owns requests, validation, and SSE parsing. */ -export function createSdk(apiKey: string, fetcher?: Fetcher, observe?: (response: Response) => void): OpenRouter { - const httpClient = new HTTPClient(fetcher ? { fetcher } : {}); +/** Internal seam: the SDK owns requests, JSON validation, and decoded SSE events. */ +export function createSdk(apiKey: string, fetcher?: Fetcher, observe?: (response: Response) => void, completion?: SseCompletionObserver): OpenRouter { + const observedFetcher: Fetcher | undefined = completion ? async (input, init) => { + const response = await (fetcher ?? fetch)(input, init); + return observeSseCompletion(response, completion); + } : fetcher; + const httpClient = new HTTPClient(observedFetcher ? { fetcher: observedFetcher } : {}); if (observe) httpClient.addHook('response', response => { observe(response); }); return new OpenRouter({ apiKey, diff --git a/src/sse-completion.ts b/src/sse-completion.ts new file mode 100644 index 0000000..c93bf2c --- /dev/null +++ b/src/sse-completion.ts @@ -0,0 +1,91 @@ +/** Internal framing observations only; the SDK still parses and validates JSON. */ +export class SseCompletionObserver { + done = false; + truncated = false; + private readonly decoder = new TextDecoder(); + // Only the longest possible terminal line, "data: [DONE]", is retained. + private line = ''; + private longLine = false; + private afterCR = false; + private pendingEvent = false; + private dataLines = 0; + private terminalData = false; + + observe(bytes: Uint8Array): void { + this.scan(this.decoder.decode(bytes, { stream: true })); + } + + end(): void { + this.scan(this.decoder.decode()); + this.truncated = !this.done && (this.pendingEvent || (this.line.length > 0 && !this.line.startsWith(':'))); + } + + private scan(text: string): void { + for (const char of text) { + // The SDK cancels at its first complete [DONE] event. Do not interpret + // bytes beyond that application boundary as another unfinished event. + if (this.done) return; + if (this.afterCR) { + this.afterCR = false; + if (char === '\n') continue; + } + if (char === '\r' || char === '\n') { + this.endLine(); + this.afterCR = char === '\r'; + } else if (this.line.length < 12) this.line += char; + else this.longLine = true; + } + } + + private endLine(): void { + if (this.line.length === 0) { + if (this.dataLines === 1 && this.terminalData) this.done = true; + this.pendingEvent = false; + this.dataLines = 0; + this.terminalData = false; + } else if (!this.line.startsWith(':')) { + this.pendingEvent = true; + if (this.line === 'data' || this.line.startsWith('data:')) { + this.terminalData = this.dataLines === 0 && !this.longLine + && (this.line === 'data:[DONE]' || this.line === 'data: [DONE]'); + this.dataLines = Math.min(2, this.dataLines + 1); + } + } + this.line = ''; + this.longLine = false; + } +} + +/** Pull-based forwarding avoids a tee, body copies, and an unbounded side queue. */ +export function observeSseCompletion(response: Response, completion: SseCompletionObserver): Response { + if (!response.ok || !response.body || !response.headers.get('content-type')?.toLowerCase().includes('text/event-stream')) return response; + const upstream = response.body.getReader(); + let cancelled = false; + const body = new ReadableStream({ + async pull(controller) { + try { + const chunk = await upstream.read(); + if (cancelled) return; + if (chunk.done) { + completion.end(); + upstream.releaseLock(); + controller.close(); + } else { + completion.observe(chunk.value); + controller.enqueue(chunk.value); + } + } catch (error) { + if (!cancelled) { + upstream.releaseLock(); + controller.error(error); + } + } + }, + async cancel(reason) { + cancelled = true; + try { await upstream.cancel(reason); } + finally { upstream.releaseLock(); } + }, + }, { highWaterMark: 0 }); + return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers }); +} diff --git a/tests/helpers.ts b/tests/helpers.ts index 2497e3d..c795238 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -37,7 +37,7 @@ export function controlledResponse() { return fixedFetcher(response)(input); }; return { - fetcher, requested, + fetcher, requested, response, emit(event: unknown) { if (!closed) body.enqueue(new TextEncoder().encode(`data: ${JSON.stringify(event)}\n\n`)); }, raw(wire: string) { if (!closed) body.enqueue(new TextEncoder().encode(wire)); }, end() { if (!closed) { closed = true; body.close(); } }, diff --git a/tests/runner.test.ts b/tests/runner.test.ts index 063e979..8db6518 100644 --- a/tests/runner.test.ts +++ b/tests/runner.test.ts @@ -21,6 +21,7 @@ describe('result and stream boundaries', () => { await vi.advanceTimersByTimeAsync(58); fixture.emit(chunk('🌍', 'stop')); fixture.emit(chunk('', 'stop', { usage: { prompt_tokens: 1, completion_tokens: 2, total_tokens: 3 } })); + fixture.raw('data: [DONE]\n\n'); fixture.end(); const result = await pending; expect(result).toMatchObject({ outcome: 'success', text: 'Hello 🌍', partialOutput: false, firstTokenMs: 42, elapsedMs: 100, httpStatus: 200, finishReason: 'stop', warnings: [] }); @@ -70,9 +71,9 @@ describe('result and stream boundaries', () => { expect(result).toMatchObject({ outcome: text ? 'interrupted' : 'failed', text, error: { kind: 'protocol', phase: 'stream' } }); }); - it('records the accepted SDK blind spot after an observed finish reason', async () => { + it('rejects the SDK blind spot after an observed finish reason', async () => { const response = new Response(`data: ${JSON.stringify(chunk('Complete', 'stop'))}\n\ndata: {"error":`, { headers: { 'content-type': 'text/event-stream' } }); - expect(await runWithTransport(valid, fixedFetcher(response))).toMatchObject({ outcome: 'success', text: 'Complete', partialOutput: false, finishReason: 'stop' }); + expect(await runWithTransport(valid, fixedFetcher(response))).toMatchObject({ outcome: 'interrupted', text: 'Complete', partialOutput: true, finishReason: 'stop', error: { kind: 'protocol', phase: 'stream' } }); }); it('rejects conflicting normal finish reasons', async () => { diff --git a/tests/stream-completion.test.ts b/tests/stream-completion.test.ts new file mode 100644 index 0000000..6637c5a --- /dev/null +++ b/tests/stream-completion.test.ts @@ -0,0 +1,116 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { runWithTransport } from '../src/runner.js'; +import { chunk, controlledResponse, fixedFetcher } from './helpers.js'; + +const options = { apiKey: 'synthetic-key', model: 'streamcheck/demo', prompt: 'offline test', timeoutMs: 1000 }; +const frame = (value: unknown) => `data: ${JSON.stringify(value)}\n\n`; +const response = (wire: string) => new Response(wire, { headers: { 'content-type': 'text/event-stream' } }); + +afterEach(() => vi.unstubAllGlobals()); + +describe('stream completion framing', () => { + it.each(['', 'Complete'])('rejects EOF after a normal finish without DONE, retaining %j', async text => { + const result = await runWithTransport(options, fixedFetcher(response(frame(chunk(text, 'stop'))))); + expect(result).toMatchObject({ + outcome: text ? 'interrupted' : 'failed', text, partialOutput: Boolean(text), + httpStatus: 200, finishReason: 'stop', error: { kind: 'protocol', phase: 'stream' }, + }); + if (result.outcome === 'failed' || result.outcome === 'interrupted') expect(result.error.message).toContain('[DONE]'); + }); + + it.each([ + ['partial JSON', 'data: {"error":'], + ['JSON without a blank line', `data: ${JSON.stringify(chunk('', 'error', { error: { code: 502, message: 'PRIVATE-TRAILING-DETAIL' } }))}`], + ['partial marker', 'data: [DON'], + ['marker without a blank line', 'data: [DONE]\n'], + ['partial field name', 'dat'], + ])('rejects a truncated trailing frame containing %s', async (_label, tail) => { + const result = await runWithTransport(options, fixedFetcher(response(frame(chunk('Retained', 'stop')) + tail))); + expect(result).toMatchObject({ + outcome: 'interrupted', text: 'Retained', partialOutput: true, finishReason: 'stop', + error: { kind: 'protocol', phase: 'stream' }, + }); + expect(JSON.stringify(result)).not.toContain('PRIVATE-TRAILING-DETAIL'); + if (result.outcome === 'interrupted') expect(result.error.message).toMatch(/unfinished.*frame/i); + }); + + it.each([ + ['text', frame(chunk('Literal [DONE] text', 'stop'))], + ['comment', frame(chunk('Retained', 'stop')) + ': data: [DONE]\n\n'], + ['ignored field', frame(chunk('Retained', 'stop')) + 'id: [DONE]\n\n'], + ])('does not accept a DONE substring inside %s as a terminal event', async (_label, wire) => { + expect(await runWithTransport(options, fixedFetcher(response(wire)))).toMatchObject({ + outcome: 'interrupted', partialOutput: true, finishReason: 'stop', error: { kind: 'protocol' }, + }); + }); + + it.each(['\n', '\r\n', '\r'])('accepts a fragmented terminal event with %j line endings', async newline => { + const text = 'A🌍 café'; + const wire = `\ufeff: heartbeat${newline}${newline}data: ${JSON.stringify(chunk(text, 'stop'))}${newline}${newline}event: message${newline}data:[DONE]${newline}${newline}`; + const bytes = new TextEncoder().encode(wire); + let offset = 0; + const source = new Response(new ReadableStream({ + pull(controller) { + if (offset < bytes.length) controller.enqueue(bytes.slice(offset, ++offset)); + else controller.close(); + }, + }), { headers: { 'content-type': 'text/event-stream' } }); + expect(await runWithTransport(options, fixedFetcher(source))).toMatchObject({ + outcome: 'success', text, partialOutput: false, finishReason: 'stop', warnings: [], + }); + }); + + it('observes the default fetch path as well as injected fetchers', async () => { + vi.stubGlobal('fetch', fixedFetcher(response(frame(chunk('Retained', 'stop'))))); + expect(await runWithTransport(options)).toMatchObject({ + outcome: 'interrupted', text: 'Retained', error: { kind: 'protocol', phase: 'stream' }, + }); + }); + + it('still requires a normal finish reason when DONE arrives', async () => { + expect(await runWithTransport(options, fixedFetcher(response(frame(chunk('Partial')) + 'data: [DONE]\n\n')))).toMatchObject({ + outcome: 'interrupted', text: 'Partial', finishReason: null, error: { kind: 'protocol' }, + }); + }); + + it('completes at DONE without waiting for HTTP EOF and releases the source reader', async () => { + const fixture = controlledResponse(); + const pending = runWithTransport(options, fixture.fetcher); + await fixture.requested; + fixture.emit(chunk('Complete', 'stop')); + fixture.raw('data: [DONE]\n\n'); + expect(await pending).toMatchObject({ outcome: 'success', text: 'Complete' }); + expect(fixture.cancellations).toBe(1); + expect(fixture.response.body?.locked).toBe(false); + }); + + it('keeps a provider error ahead of missing-DONE diagnostics', async () => { + const wire = frame(chunk('Retained', 'stop')) + frame(chunk('', 'error', { error: { code: 502, message: 'Synthetic failure' } })); + expect(await runWithTransport(options, fixedFetcher(response(wire)))).toMatchObject({ + outcome: 'interrupted', text: 'Retained', error: { kind: 'provider', code: 502 }, + }); + }); + + it('keeps a transport failure after a normal finish as a network diagnostic', async () => { + const fixture = controlledResponse(); + let received!: () => void; + const textReceived = new Promise(resolve => { received = resolve; }); + const pending = runWithTransport({ ...options, onText: received }, fixture.fetcher); + await fixture.requested; + fixture.emit(chunk('Retained', 'stop')); + await textReceived; + fixture.fail(); + expect(await pending).toMatchObject({ + outcome: 'interrupted', text: 'Retained', finishReason: 'stop', error: { kind: 'network', phase: 'stream' }, + }); + expect(fixture.response.body?.locked).toBe(false); + }); + + it('releases the source reader after EOF with an unfinished frame', async () => { + const source = response(frame(chunk('Retained', 'stop')) + 'data: [DON'); + expect(await runWithTransport(options, fixedFetcher(source))).toMatchObject({ + outcome: 'interrupted', text: 'Retained', error: { kind: 'protocol' }, + }); + expect(source.body?.locked).toBe(false); + }); +});