Repository navigation
fix: acp-loop zero-side-effect truncation retry + well-formed anthropic error stream (#413) - #440
Conversation
…ic error stream (#413)
📦 Built Package ArtifactBranch: Option A — Install from npm PR tag (recommended)npm install -g billion-context@pr-440Each push to this PR publishes a new version under the Option B — Download artifact
tar xzf billion-context-pr440.tgz
npm install -g packageThis comment is automatically updated on each push. |
…ponse.failed (#440) The loop-level responses adapter (src/loop/adapter-responses.ts) emitted a response.failed with no preceding response.created when the upstream stream truncated (200 + early EOF) before response.created reached the client. An orphan response.failed crashes strict clients (codex) — the same class as the anthropic message_start gap fixed in #413. Two emit paths were affected, not just emitError: - 0-event/partial EOF routes through emitCompletion's failed branch (the responses parseStream yields a fallback done:failed on truncation, unlike the anthropic adapter), so the common case never hit emitError. - emitError covers HTTP-error / empty-body paths. Both now track whether response.created was forwarded (createdForwarded, set in round 1) and synthesize one before emitting response.failed, reusing the forwarded created id when present so created/failed stay id-consistent. Tests: tests/loop-responses-orphan.test.ts (0-event EOF, truncation-after-created, emitError synthesis). All fail on the pre-fix adapter, pass after.
[bot] 🏷 Reviewed PR #413 (acp-loop zero-side-effect truncation retry + well-formed anthropic error stream). I checked out the branch, re-ran the full pre-flight, and stress-tested the retry invariant. Verdict: solid fix, but one real hole in the zero-side-effect invariant for the OpenAI adapter (round 2+) — trivial to close (2 lines). Details below. Pre-flight — re-verified, all green
What's correct
Finding — the invariant has a hole for OpenAI round-2+ reasoningThe PR's core claim is "retry iff nothing was forwarded." DESIGN.md says
For Anthropic this is harmless: a thinking block is always preceded by its For the OpenAI adapter it is not harmless. In round 2+ the leading role chunk is emitted as Repro (I ran this against the branch): round 1 =
This is a regression vs pre-fix (which had no retry at all) and directly contradicts the "zero-side-effect" invariant the PR is built on. The Responses adapter is unaffected (it emits no Fix (verified): wrap both reasoning yields in if (ev.raw) {
yield fwd(ev.raw);
} else if (round > 1 && ev.delta.length > 0 && adapter.emitReasoning) {
yield fwd(adapter.emitReasoning(ev.delta));
}With that change my repro gives RecommendationThe primary production case (Anthropic 0-event truncation) is handled correctly and the fix is otherwise clean — I'd be comfortable merging. But since the whole PR is about the zero-side-effect invariant, I'd recommend closing the 2-line OpenAI-reasoning gap before merge (it currently lets a side-effecting retry through, and DESIGN.md already asserts it's covered). Happy to add a regression test for the OpenAI round-2+ reasoning-truncation case alongside the fix if you want it. Out-of-scope items (responses |
…end retry to responses-shaped truncation - core.ts: wrap the two reasoning yield sites (ev.raw / emitReasoning) in fwd() — a round-1 truncation after reasoning-only output was treated as zero-side-effect and retried, duplicating reasoning bytes already sent to the client (openai reasoning_content has no preceding meta chunk) - core.ts: ParsedStreamEvent done gains truncated?: boolean; the retry predicate accepts (!sawDone || truncatedDone) so adapters that surface truncation as a synthetic failed done (responses parseStream fallback) also get the zero-side-effect retry — previously the retry never fired for responses streams despite #441's premise - adapter-responses.ts: the !terminalKind fallback done is marked truncated: true (upstream-explicit response.failed stays non-retryable) - tests: loop-truncation-reasoning (red on pre-fix core), orphan T1/T2 stub fetch (retry now fetches), T4 retry-success
…continuation retry) Field data (relay -> GLM via ACP client; 6.5h, 30+ rounds) contributed by the issue reporter in #862: the reasoning-only-prefix shape errored 7x across 5 sessions pre-fix; the visible-text shape (long final reports) had no recovery path at all. - #413 gate relaxed from !forwardedAny to also cover invisible-only prefixes (reasoning/meta): a thinking-then-cut stream now retries instead of erroring. Scoped to the openai wire, whose chunks are stateless. Stateful wires keep the strict nothing-forwarded condition: once anything was forwarded their per-response identity framing is already live (anthropic message_start with open content blocks, responses response.created - #440's single-created invariant), and a re-fetched response would emit it a second time. - New continuation retry for cuts AFTER visible text reached the client: one re-fetch with an ephemeral nudge quoting the forwarded tail (<=800 chars), asking the model to resume seamlessly without repeating; roundBody updated so any later blind re-fetch carries the continuation context. OpenAI wire only, same framing reason. The nudge never enters coreMessages/session state (same ephemerality as #732's). - Two independent one-shot budgets (truncationRetried / continuationRetried) so both cut orderings self-heal; max 2 extra fetches per request, each logged. Rounds with tool-call fragments keep the plain truncation error (fragment semantics only survive a completed stream). Tests: flip tests/loop-truncation-reasoning.test.ts (old strict-gate assertion); add tests/loop-truncation-continuation.test.ts covering both cut orderings, budget exhaustion, tool-call exclusion, failed-retry fallback, and textProtocol exclusion. Existing #413-T3/T4 (anthropic) and #440-T2 (responses) now guard the wire scoping. Pre-flight on 0.1.117: typecheck clean, 1675/1677 pass (2 skipped), build ok. Closes #862
The second truncation gate (continuation nudge) was hardcoded to the openai wire, so an anthropic stream cut after visible text reached the client had no proxy-side self-heal path and fell straight to the error channel. Relax the gate to openai || anthropic; the two anthropic re-fetch hazards are already neutralized by the adapter shipped in #1464 (state-keyed message_start suppression, close-at-resume with block indices continuing upward), and a dead attempt's partial output is never committed to history (commit happens only on proxy-tool rounds), with the #539 unsigned-thinking guard as backstop. responses/google stay excluded (#440 single-created invariant). Regression tests: tests/issue1470-anthropic-nudge.test.ts (recovery with nudge-body/tail verification + exhaustion on the error channel). Full suite green on the #1464 head: 2883 pass / 0 fail / 12 skipped; typecheck clean.
fix: acp-loop zero-side-effect truncation retry + well-formed anthropic error stream (#413)
Root cause (confirmed, all three)
When the upstream returns 200 and the SSE stream ends early (no
message_delta/message_stop), the compress loop only discovers the truncation after the parse loop ends with!sawDone—fetchWithRetryinspectsresponse.okafter headers and never reads the body, so mid-stream EOF is invisible to it. Consequences, each confirmed by code read and by red tests written against the unmodified code:!sawDonebranch fails fast. A round that forwarded nothing (0 text + 0 reasoning + 0 executed tools) is a zero-side-effect retry candidate; instead the upstream flake landed in the host session (3 production events in 3 days, two of them 0+0).emitErroris stateless w.r.t. what was already forwarded — it emitscontent_block_start/delta/stop + message_delta + message_stopdirectly. If the truncation hit beforemessage_startreached the client, the client sees a block sequence with no starting frame (protocol-malformed); openthinkingblocks are never closed. The responses branch already fixed its own copy of this class (src/stream-error.ts); the Anthropic adapter was missed.ctx.log(→log("info", "[sid] ...")) plus a globalloggerLog("error", ...)— both tee to the same sink, so every truncation produced two lines.Changes
src/loop/core.tsfetchWithRetrywrapper and re-parses the same round.!sawDone && !forwardedAny && calls.length === 0 && !(textProtocol && text accumulated) && !signal.aborted && !truncationRetried.forwardedAnyis a per-attempt flag set by the five parse-loop yield sites; the post-looptool_call/marker/emitTextyields are covered by the explicitcalls/text checks. The check runs beforerecordUsageso a retried round's tokens are not double-counted.roundBodytracks the last body actually sent (updated on the re-request path before thecurrentUpstreamswap), so a round-2+ retry re-sends the compressed body, not the original request.ctx.log); the duplicate globalloggerLog("error", ...)line is removed.src/loop/adapter-anthropic.tsmessageStartForwardedandopenBlocks(client indices of forwarded-but-unclosed blocks).emitErroremits, in order: a syntheticmessage_startif none was forwarded (captured id or generated, zero usage),content_block_stopfor every still-open block, the existing error text block, and the existing terminal. The stream is now always well-formed — starting frame first, every block closed, terminal last — regardless of where the truncation hit.tests/loop-truncation.test.ts(new, 6 tests — all failed against the pre-fix code)Pre-flight
npm run typecheck— cleannpm test— 874 pass / 0 fail (868 + 6 new)npm run build— successOut of scope (reported, not fixed)
adapter-responses.tsemitError: aresponse.failedwithout a priorresponse.createdis the same orphan class if the stream truncated before the created event.core.tsalso double-logs (ctx.log+loggerLog("error")) — same pattern; the issue only reported the truncation one.reRequest = true(truncated after a complete proxy tool call, before the done event) is silently swallowed — the loop continues to the next round. Arguably benign; unchanged.Devlog
devlog/2026-09-02_acp-loop-truncation-retry/— REQ.md, WORKLOG.md, DESIGN.md.