Skip to content

fix(streaming): decode Workers AI byte SSE and unify cancellation, breakers, and accounting #110

Open

Description

@stackbilt-admin

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

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

  1. added
    bug
    on Oct 11, 2026
  2. stackbilt-admin commented on Oct 13, 2026

    @stackbilt-admin
    MemberAuthor

    Local implementation checkpoint — 2026-10-12

    This work is uncommitted/unpushed on main, based on 8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff is docs/maintenance/issue-sweep.md; it will travel with the code.

    Implemented the transport and terminal-lifecycle core:

    • Shared demand-driven SSE decoder for all six adapters: split UTF-8, CR/LF/CRLF, multiline data, comments, [DONE], protocol errors and final unterminated frames. Workers AI byte chunks now yield text; object/string binding forms remain supported.
    • Consumer cancellation propagates to the reader and aborts HTTP fetches, including pending headers. Usage resolves on close, error, cancel and schema drift; reported partial usage survives.
    • Provider timeout covers the stream body. Streaming breaker outcomes settle at actual completion; cancellation is neutral.
    • Factory wrapper honors consumer demand, exposes generateManagedResponseStream() with { stream, completion }, awaits quota accounting on terminal paths and avoids post-output failover/replay. Settlement errors are observable.
    • First-read failure with reported usage is accounted; known unbilled admission/HTTP errors are not charged. Vendor quota exhaustion quarantines the affected streaming account.

    Evidence: provider-stream.ts, six adapters/base/factory, managed public types/methods, and 35 stream-lifecycle.test.ts cases. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions