Skip to content

feat(llm): stream-resume client slice (gw#123 client half) - #163

Merged
dahai80 merged 1 commit into
mainfrom
feat/stream-resume-client
Aug 27, 2026
Merged

dahai80 merged 1 commit into
mainfrom
feat/stream-resume-client

Conversation

@dahai80

@dahai80 dahai80 commented Aug 27, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the fusion-code client half of the gateway resumable-SSE contract (gw#123 server half already merged on fusion-gateway). When a local MLX stream drops mid-generation (timeout-class error, NOT user abort), the client reconnects to GET /v1/messages/{sid}/events carrying the last processed cursor (Last-Event-ID: <sid>:<seq>) and merges the replayed frames + live tail via STATE-CONTINUATION, instead of restarting the turn from scratch.

Reverses prior Defer Item 1 (fusion-code-enhance-0819.md item 15(b) "gateway reconnect + stream-resume" — blocker "no stream-resume infra" now removed by gw#123).

Server contract (gw#123, read-only for fusion-code)

  • Engagement: routing.stream.resume_enabled (default false) AND route == LocalBackend
  • sid = request X-Request-ID; response header X-Fusion-Stream-ID: <sid>
  • Every SSE event id: <sid>:<seq> (monotonic); bounded buffer (256 events / 1 MiB / 10m TTL)
  • Resume endpoint GET /v1/messages/{sid}/events, cursor via Last-Event-ID header (precedence) or ?last_event_id=
  • Two phases: replay-after-cursor + live drain. 404 = disabled/unknown/evicted

The crux — cursor is lost in 3 places in the MLX translation layer

The fusion-code MLX path rewrites /v1/messages → POST /v1/chat/completions. The gateway returns OpenAI SSE with X-Fusion-Stream-ID + id: lines, but the translation layer destroys the cursor:

  1. transformMLXStreamToAnthropic parses data: lines only → id: stripped
  2. encodeStreamToAnthropicSSE spreads original response headers → X-Fusion-Stream-ID passes through (no change needed)
  3. streamViaSeam drops evt.id

Approach

Cursor capture — teeCursor side-channel (option B). A small teeCursor(rawResponseBody) helper wraps the raw body BEFORE transform, splits SSE frames, extracts id: <sid>:<seq> into a mutable CursorRef, passes frames through unchanged (byte-identical for transform). sid read from X-Fusion-Stream-ID header. Surgical: one helper + one hook + read ref in catch; no upstream-of-transform signature changes.

Merge — STATE-CONTINUATION (the crux). A FRESH transform on resumed frames re-synthesizes message_start + FRESH content_block indices (0,1,...) that misalign with claude.ts's pre-drop contentBlocks (→ RangeError) and lose mid-tool-call args (id/name don't re-arrive after cursor). Fix: seed the resumed transformMLXStreamToAnthropic with a deep clone of the pre-drop StreamState (contentIndex/textBuffer/emittedTextLen/textBlockOpen/thinkingBlockOpen/currentToolCall). The transformer continues seamlessly — correct indices, emits only NEW text (slice from emittedTextLen), appends mid-tool args to the existing block, suppresses spurious content_block_start (open-block flags already true). The merge generator's only filter: drop the resumed stream's unconditional startup message_start.

Drop detection (claude.ts catch). Resume-eligible = timeout-class ONLY (isTimeoutErrorLike / streamIdleAborted) — drained-pipe-only, lag=0, cursor+state consistent. Hard transport reset EXCLUDED (pipe lag → cursor races ahead of consumption → replay drop → corruption). APIError 4xx and user abort re-thrown as today.

Bounds + gate

  • FUSION_CODE_STREAM_RESUME_ENABLED (default unset = off, byte-identical) — read via isEnvTruthy, NOT feature() runtime cast (avoids PR fix: SessionEnd hook crash when script outputs no JSON #9 build bug: feature() requires string-literal args for DCE)
  • FUSION_CODE_STREAM_RESUME_MAX_ATTEMPTS (default 3)
  • 404 (disabled/evicted/TTL) OR exhaustion OR repeated transport error → fall through to EXISTING non-streaming fallback. No new failure mode — worst case = today's behavior.

Files

  • NEW src/services/llm/streamResume.ts — teeCursor (cursor side-channel), resumeStreamFetch (real global fetch, bypasses adapter interceptor), mergeResumedStream (seed-continuation merge), isResumeEligibleError, gate helpers, ResumeRefs WeakMap
  • MOD src/services/api/fusion-mlx-stream.ts — optional seedState? + stateRef? params on transformMLXStreamToAnthropic (byte-identical when undefined); export StreamState
  • MOD src/services/api/fusion-mlx-adapter.ts — streaming branch: wrap body with teeCursor, create stateRef, attach refs via WeakMap (off → unchanged)
  • MOD src/services/api/claude.ts — while-loop wrap for-await, resume-eligible branch in catch (off → today's path verbatim)
  • NEW src/__tests__/llm/streamResume.test.ts — 34 tests: teeCursor, seedState continuation, mergeResumedStream, resumeStreamFetch (mock fetch), isResumeEligibleError, gate, ResumeRefs, end-to-end state-continuation merge

Verification

  • bun run typecheck — 0 errors
  • bun test src/__tests__/ — 690 pass / 0 fail (incl. 34 new)
  • bun run lint — 0 new errors (2 new files clean; 3 MOD files match main baseline)
  • bun run build:dev — green (no feature() runtime cast)
  • byte-identical default-off proof: env unset → adapter skips tee/stateRef → claude.ts sid="" → catch rule 1 false → today's fallback/throw verbatim

Defer

  • Option A (full id: end-to-end threading through transform/encode/seam/sseToChunk/types = 5-file signature change) → DEFERRED; option B (teeCursor side-channel) preferred. Revisit if cursor fidelity issues surface.
  • End-to-end manual test against a live gateway with resume_enabled=true — requires gateway-side env; tracked separately.

Co-Authored-By: Claude Fable 5 [email protected]

Implement fusion-code client half of the gateway resumable-SSE contract
(gw#123 server half already merged on fusion-gateway). When a local MLX
stream drops mid-generation (timeout-class error, NOT user abort), the
client reconnects to GET /v1/messages/{sid}/events carrying the last
processed cursor (Last-Event-ID: <sid>:<seq>) and merges the replayed
frames + live tail via STATE-CONTINUATION, instead of restarting the
turn from scratch.

Cursor capture — teeCursor side-channel (option B):
The MLX translation layer strips the per-event id: in 3 places
(transformMLXStreamToAnthropic parses data: only; streamViaSeam drops
evt.id). teeCursor wraps the raw response body BEFORE transform, splits
SSE frames, extracts id: <sid>:<seq> into a mutable CursorRef, and
passes frames through unchanged (byte-identical for transform). sid is
read from the X-Fusion-Stream-ID response header (encodeStreamToAnthropicSSE
spreads original headers through — no header change needed).

Merge — STATE-CONTINUATION (the crux):
A FRESH transform on resumed frames would re-synthesize message_start +
FRESH content_block indices (0,1,...) that misalign with claude.ts's
pre-drop contentBlocks (RangeError) and lose mid-tool-call args (id/name
don't re-arrive after cursor). Fix: seed the resumed
transformMLXStreamToAnthropic with a deep clone of the pre-drop
StreamState (contentIndex/textBuffer/emittedTextLen/textBlockOpen/
thinkingBlockOpen/currentToolCall). The transformer continues
seamlessly — correct indices, emits only NEW text (slice from
emittedTextLen), appends mid-tool args to the existing block, suppresses
spurious content_block_start (open-block flags already true). The merge
generator's only filter: drop the resumed stream's unconditional startup
message_start.

Drop detection (claude.ts catch):
Resume-eligible = timeout-class ONLY (isTimeoutErrorLike /
streamIdleAborted) — drained-pipe-only, lag=0, cursor+state consistent.
Hard transport reset EXCLUDED (pipe lag → cursor races ahead of
consumption → replay drop → corruption). APIError 4xx (server rejection)
and user abort re-thrown as today.

Bounds + gate:
FUSION_CODE_STREAM_RESUME_ENABLED (default unset = off, byte-identical)
read via isEnvTruthy, NOT feature() runtime cast (avoids PR #9 build
bug: feature() requires string-literal args for DCE).
FUSION_CODE_STREAM_RESUME_MAX_ATTEMPTS (default 3). 404
(disabled/evicted/TTL) OR exhaustion OR repeated transport error falls
through to EXISTING non-streaming fallback — no new failure mode, worst
case = today's behavior.

Reverses prior Defer Item 1 (fusion-code-enhance-0819.md item 15(b)
"gateway reconnect + stream-resume" — blocker "no stream-resume infra"
now removed by gw#123).

Build gates: typecheck 0 errors; 690 tests pass; lint adds 0 new errors
(2 new files clean; 3 MOD files match main baseline); build:dev green.

Co-Authored-By: Claude Fable 5 <[email protected]>
@dahai80
dahai80 merged commit 20e441e into main Aug 27, 2026
1 check passed
@dahai80
dahai80 deleted the feat/stream-resume-client branch August 27, 2026 15:16
dahai80 added a commit that referenced this pull request Aug 27, 2026
Add § "Stream Resume seam" to docs/model-providers.md (background, server
contract, cursor-loss points, teeCursor side-channel + STATE-CONTINUATION
merge approach, gate/bounds, files, defer). Add streamResume.ts entry to
CLAUDE.md LLM Adapter Seam subsystem list with pointer to the doc section.

Co-Authored-By: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Aug 30, 2026
…udit 2.2.2)

Stream-resume (PR #163, default-off) was dead for the idle-watchdog drop
due to two defects in claude.ts:

1. Abort block threw a synthetic APIConnectionTimeoutError for ANY abort-shaped
   error without a user signal, BEFORE the resume check (:2532). The idle
   watchdog cancels the body (body.cancel(), not signal.abort()) so
   signal.aborted stays false and the idle drop hit the throw — short-circuiting
   resume and bypassing the fallback_cause:"watchdog" telemetry.

2. Even with the throw skipped, resume refs were dead: the watchdog's
   releaseStreamResources() nulls streamResponse before the catch reads it, and
   getResumeRefs reads a WeakMap keyed by the (now-GC-eligible) Response, so
   refs=undefined and the resume try-block was skipped regardless.

Fix (resume-on + idle only; resume-off byte-identical):
- shouldDeferIdleAbortToResume(idle, enabled): gate the synthetic throw on
  !defer, so resume-on + idle falls through to the resume check.
- resolveResumeRefs(response, survivor): survivor captures refs in the watchdog
  BEFORE releaseStreamResources() nulls streamResponse; catch falls back to it
  when the Response is gone, so the resume attempt has live refs.
- survivor reset on resume success (no stale reuse on a later drop).

Both helpers are pure exports (the fix's testable contract; the prior bug was
this inline logic wrong with no test). Gated on FUSION_CODE_STREAM_RESUME_ENABLED
— off = no capture, old throw, undefined refs (byte-identical).

Tests: src/__tests__/llm/stream-resume-idle-gate.test.ts (10) cover the gate
matrix + refs survivor (incl. the dead-refs state: resolveResumeRefs(undefined,
survivor) === survivor) + defer=>resume-eligible fall-through.

Co-Authored-By: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Sep 1, 2026
… R12)

Add §6 to docs/enterprise-hardening.md covering the stream-resume seam
(PR #163, default-off FUSION_CODE_STREAM_RESUME_ENABLED). Documents
the enterprise MLX enablement config: client env (ENABLED/MAX_ATTEMPTS=3
/FETCH_TIMEOUT_MS=30000) + gateway routing.stream.resume_enabled=true,
both ends must be on. Mechanism notes (timeout-only trigger,
STATE-CONTINUATION merge, non-streaming fallback, LocalBackend-only) and
verification (34 unit tests, e2e tracked via cross-repo gw#123).

Satisfies audit acceptance 'docs/config template contains the env'.
Does NOT flip provider default — preserves byte-identical-off contract
and cloud/first-party non-recoverable semantics. e2e path (B) heavy
(real model + gateway env), gateway half LANDED cross-repo gw#123,
fusion-code e2e manual verification tracked separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
dahai80 added a commit that referenced this pull request Sep 4, 2026
External architecture audit (~/fusion/audit/fusion-code-audit-result-0905.md)
found 3 client-fixable P0 runtime risks. Cross-repo P0s (fusion-mlx KV-cache
#798, fusion-gateway cluster admission #163) filed as issues per workflow.

P0-A — zombie task leak on shutdown:
  gracefulShutdown only ran runCleanupFunctions; per-task cleanup only deleted
  the state entry, never called taskImpl.kill → subprocesses reparented to init,
  holding MLX memory/FD/worktree locks forever. Wire killAllActive into the
  cleanup registry via taskReaper.startTaskReaper. Default-on, byte-safe no-op
  when no accessors/running tasks (headless/-p). FUSION_CODE_TASK_KILL_ON_SHUTDOWN=0
  disables.

P0-B — MLX client no concurrency throttle (thundering herd):
  20 subagents firing 20 parallel requests into single-slot MLX → OS socket
  queue → connection failure → MAX_RETRIES=1 retry → doubled request rate.
  Add in-process semaphore (acquireMlxSlot/releaseMlxSlot) wrapping the outer
  mlxFetchWithRetry; inner mlxFetchWithRetryInner handles recursive retry
  without re-entering the semaphore (no double-count). Default cap=2,
  FUSION_MLX_MAX_CONCURRENT override, 0=unlimited (byte-identical off).

P0-C — workflow unbounded concurrency (OOM):
  maxConcurrentWorkflows returned Infinity when env unset → admission check was
  a no-op by default. Change to finite default cap=4; env override; 0=
  explicit unlimited (legacy compat, requires opt-in).

Gates: typecheck 0 / 1172 tests pass / lint:layers OK / lint:flags 88=88 /
build:dev 3792 modules / smoke boot OK.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant