Repository navigation
Description
Priority and outcome
P0/P1 · impact H · effort M (ship in two PRs) · risk: terminal-event/usage semantics.
Streaming is a separate transport path, so it does not currently receive the resilience and accounting behavior promised for generateResponse.
Evidence
- src/providers/cloudflare.ts:1403: a byte ReadableStream is treated as object chunks with response/usage fields. Uint8Array chunks are silently dropped.
- src/providers/openai.ts:481, src/providers/groq.ts:353, src/providers/anthropic.ts:645: stream transports do not call executeWithResiliency.
- src/factory.ts:828 and src/factory.ts:1557: fallback is possible only before the first text read.
- src/factory.ts:1580: eager async start loop ignores downstream backpressure; no cancel handler.
- src/factory.ts:1595: accounting occurs only after successful drain; error bypasses it at line 1623.
- src/providers/openai.ts:550: schema-error return paths do not settle the usage promise.
- src/providers/base.ts:155: timeout ends once headers arrive, not after body consumption.
- src/tests/factory.test.ts:434: tests exercise pre-first-chunk fallback and successful final usage, not cancellation/partial failure.
Verified synthetic probes: a Cloudflare binding returning TextEncoder-generated SSE bytes produces an empty output stream; an OpenAI stream leaves breaker totalSuccesses at zero. No account access was used. Verify each binding's live byte framing with a recorded fixture before claiming universal compatibility.
PR 1: byte decoder and correct terminal handling
Decode Workers AI Uint8Array SSE into normalized text/usage events. Reuse a fetch-only incremental SSE parser that supports split UTF-8, CRLF, multiple events per chunk, comments/keepalives, data frames, terminal markers and protocol error events. Preserve supported object/string binding forms. Never treat byte chunks as response objects.
PR 2: single streaming lifecycle
Proposed additive result contract:
import type { TokenUsage } from './types.js';
export interface StreamCompletion {
outcome: 'success' | 'error' | 'cancelled';
emittedChars: number;
usage?: TokenUsage;
}
export interface ManagedTextStream {
stream: ReadableStream<string>;
completion: Promise<StreamCompletion>;
}
export function manageTextStream(
source: ReadableStream<string>,
readUsage: () => Promise<TokenUsage | undefined>,
settle: (result: StreamCompletion) => Promise<void>
): ManagedTextStream {
const reader = source.getReader();
let emittedChars = 0;
let terminal: Promise<StreamCompletion> | undefined;
let resolveCompletion!: (result: StreamCompletion) => void;
let rejectCompletion!: (reason: unknown) => void;
const completion = new Promise<StreamCompletion>((resolve, reject) => {
resolveCompletion = resolve;
rejectCompletion = reject;
});
void completion.catch(() => {});
function finish(outcome: StreamCompletion['outcome']) {
if (terminal) return terminal;
terminal = (async () => {
const result = {
outcome,
emittedChars,
usage: await readUsage()
};
try {
await settle(result);
resolveCompletion(result);
return result;
} catch (error) {
rejectCompletion(error);
throw error;
} finally {
reader.releaseLock();
}
})();
return terminal;
}
const stream = new ReadableStream<string>({
async pull(controller) {
try {
const chunk = await reader.read();
if (chunk.done) {
await finish('success');
controller.close();
return;
}
emittedChars += chunk.value.length;
controller.enqueue(chunk.value);
} catch (error) {
await reader.cancel(error).catch(() => {});
try {
await finish('error');
} finally {
controller.error(error);
}
}
},
async cancel(reason) {
await reader.cancel(reason).catch(() => {});
await finish('cancelled');
}
});
return { stream, completion };
}This helper requires the adapter usage promise to resolve on close/error/cancel; implement that invariant first. Integrate provider failure/success reporting and pre-emission retry with the same breaker context as non-streaming. Apply the request deadline and signal to headers, body reads and retry sleeps. Cancellation must not trigger failover. Retain partial reported usage (or conservative reservation), emit exactly one terminal telemetry event, and attach the settlement completion to Worker lifetime.
Keep generateResponseStream as the compatibility wrapper. Add a separate managed-result method so callers can observe completion/usage without exposing a hidden stream symbol.
Fallback contract: before any text is exposed, retry/fallback is safe under configured policy; after text is exposed, propagate the failure. Do not splice a second provider's answer into a partially delivered completion. Resumable generation is a different API.
Tests / acceptance
- Real-shaped Workers AI byte fixture yields text; chunk splits/UTF-8/CRLF are covered.
- Header failure, first-read failure, mid-stream failure and error event have distinct behavior.
- Consumer cancellation aborts upstream fetch/reader, stops retries and settles once.
- Slow consumer bounds buffering; no full output concatenation solely for token estimates.
- Streaming failures degrade/open breaker; success/recovery stats update.
- Partial usage survives errors; usage/completion promises never hang, including schema drift.
- Stalled first byte/body is stopped by request deadline.
- No post-emission fallback; no duplicate charge/terminal hook on cancellation races.
Semver and README
Byte decoding, cancellation and missing accounting are patches. New ManagedTextStream API is a minor. Keep the legacy string stream stable; typed tool/reasoning stream events can follow separately.
Suggested README text:
Streaming retries and fails over before the first text chunk. Once output begins, failures are surfaced to the caller. Cancellation aborts upstream work. The managed result exposes completion and reported or estimated usage, including partial failures.
Follow-up to closed #26/#41/#62: final usage on happy-path drain did not cover byte transport or terminal failure paths.
Activity
stackbilt-admin commentedon Oct 13, 2026
Local implementation checkpoint — 2026-10-12
This work is uncommitted/unpushed on
main, based on8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff isdocs/maintenance/issue-sweep.md; it will travel with the code.Implemented the transport and terminal-lifecycle core:
[DONE], protocol errors and final unterminated frames. Workers AI byte chunks now yield text; object/string binding forms remain supported.generateManagedResponseStream()with{ stream, completion }, awaits quota accounting on terminal paths and avoids post-output failover/replay. Settlement errors are observable.Evidence:
provider-stream.ts, six adapters/base/factory, managed public types/methods, and 35stream-lifecycle.test.tscases. Fixtures are synthetic and follow documented framing; they are not recorded live traces.Remaining: provider-level pre-output retries; one absolute deadline/signal across retries/fallbacks; recorded live-shaped fixtures; workerd cancellation/accounting test. The Workers AI binding cannot be aborted before it returns, so its eventual reader is cancelled. Keep the full issue open.
Validation for the combined local sweep: 605 tests pass across 27 files, TypeScript typecheck passes, Worker-targeted bundle/import smoke passes. Packed entrypoint exports/client methods and all 33 JavaScript sourcemaps were checked on Windows with Node 24.19.0/npm 11.17.0. No live/billable providers or workerd execution; this does not prove minimum Node-version compatibility.
feat: streaming lifecycle, tenant-safe caching, client-scoped resilie…