Repository navigation
feat(llm): stream-resume client slice (gw#123 client half) - #163
Merged
Merged
Conversation
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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}/eventscarrying 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.mditem 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)
routing.stream.resume_enabled(default false) AND route == LocalBackendsid= request X-Request-ID; response headerX-Fusion-Stream-ID: <sid>id: <sid>:<seq>(monotonic); bounded buffer (256 events / 1 MiB / 10m TTL)GET /v1/messages/{sid}/events, cursor viaLast-Event-IDheader (precedence) or?last_event_id=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 withX-Fusion-Stream-ID+id:lines, but the translation layer destroys the cursor:transformMLXStreamToAnthropicparsesdata:lines only →id:strippedencodeStreamToAnthropicSSEspreads original response headers →X-Fusion-Stream-IDpasses through (no change needed)streamViaSeamdropsevt.idApproach
Cursor capture — teeCursor side-channel (option B). A small
teeCursor(rawResponseBody)helper wraps the raw body BEFORE transform, splits SSE frames, extractsid: <sid>:<seq>into a mutableCursorRef, passes frames through unchanged (byte-identical for transform).sidread fromX-Fusion-Stream-IDheader. 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+ FRESHcontent_blockindices (0,1,...) that misalign withclaude.ts's pre-dropcontentBlocks(→RangeError) and lose mid-tool-call args (id/namedon't re-arrive after cursor). Fix: seed the resumedtransformMLXStreamToAnthropicwith a deep clone of the pre-dropStreamState(contentIndex/textBuffer/emittedTextLen/textBlockOpen/thinkingBlockOpen/currentToolCall). The transformer continues seamlessly — correct indices, emits only NEW text (slicefromemittedTextLen), appends mid-tool args to the existing block, suppresses spuriouscontent_block_start(open-block flags already true). The merge generator's only filter: drop the resumed stream's unconditional startupmessage_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).APIError4xx and user abort re-thrown as today.Bounds + gate
FUSION_CODE_STREAM_RESUME_ENABLED(default unset = off, byte-identical) — read viaisEnvTruthy, NOTfeature()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)Files
src/services/llm/streamResume.ts—teeCursor(cursor side-channel),resumeStreamFetch(real global fetch, bypasses adapter interceptor),mergeResumedStream(seed-continuation merge),isResumeEligibleError, gate helpers,ResumeRefsWeakMapsrc/services/api/fusion-mlx-stream.ts— optionalseedState?+stateRef?params ontransformMLXStreamToAnthropic(byte-identical when undefined); exportStreamStatesrc/services/api/fusion-mlx-adapter.ts— streaming branch: wrap body withteeCursor, createstateRef, attach refs via WeakMap (off → unchanged)src/services/api/claude.ts— while-loop wrap for-await, resume-eligible branch in catch (off → today's path verbatim)src/__tests__/llm/streamResume.test.ts— 34 tests: teeCursor, seedState continuation, mergeResumedStream, resumeStreamFetch (mock fetch), isResumeEligibleError, gate, ResumeRefs, end-to-end state-continuation mergeVerification
bun run typecheck— 0 errorsbun 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 (nofeature()runtime cast)Defer
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.resume_enabled=true— requires gateway-side env; tracked separately.Co-Authored-By: Claude Fable 5 [email protected]