Skip to content

fix: acp-loop zero-side-effect truncation retry + well-formed anthropic error stream (#413) - #440

Merged
ranxianglei merged 6 commits into
masterfrom
2026-09-02_acp-loop-truncation-retry
Sep 3, 2026
Merged

ranxianglei merged 6 commits into
masterfrom
2026-09-02_acp-loop-truncation-retry

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

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 — fetchWithRetry inspects response.ok after 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:

  1. No retry. The !sawDone branch 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).
  2. Orphan Anthropic stream. The adapter's emitError is stateless w.r.t. what was already forwarded — it emits content_block_start/delta/stop + message_delta + message_stop directly. If the truncation hit before message_start reached the client, the client sees a block sequence with no starting frame (protocol-malformed); open thinking blocks are never closed. The responses branch already fixed its own copy of this class (src/stream-error.ts); the Anthropic adapter was missed.
  3. Double logging. ctx.log (→ log("info", "[sid] ...")) plus a global loggerLog("error", ...) — both tee to the same sink, so every truncation produced two lines.

Changes

src/loop/core.ts

  • The per-round parse loop is wrapped in an inner attempt loop. On a qualifying truncation it retries once through the (hoisted) fetchWithRetry wrapper and re-parses the same round.
  • Retry predicate — the zero-side-effect invariant: !sawDone && !forwardedAny && calls.length === 0 && !(textProtocol && text accumulated) && !signal.aborted && !truncationRetried. forwardedAny is a per-attempt flag set by the five parse-loop yield sites; the post-loop tool_call/marker/emitText yields are covered by the explicit calls/text checks. The check runs before recordUsage so a retried round's tokens are not double-counted.
  • roundBody tracks the last body actually sent (updated on the re-request path before the currentUpstream swap), so a round-2+ retry re-sends the compressed body, not the original request.
  • Truncation is logged once (via ctx.log); the duplicate global loggerLog("error", ...) line is removed.

src/loop/adapter-anthropic.ts

  • The adapter closure now tracks messageStartForwarded and openBlocks (client indices of forwarded-but-unclosed blocks).
  • emitError emits, in order: a synthetic message_start if none was forwarded (captured id or generated, zero usage), content_block_stop for 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)

  • T1: 0-event EOF + failed retry → exactly 1 fetch, schema-valid error stream, exactly 1 log line (acceptance criteria 1 + 3)
  • T2: 0-event EOF + successful retry → one clean stream, no error surfaced
  • T3/T4: truncation with an open thinking / text block → block closed before the error block, no retry (content already forwarded) (acceptance criterion 2)
  • T5: the retry itself truncates → no second retry (one per request)
  • T6: round-2 truncation after a proxy tool call → retry re-sends the round-2 body

Pre-flight

  • npm run typecheck — clean
  • npm test — 874 pass / 0 fail (868 + 6 new)
  • npm run build — success

Out of scope (reported, not fixed)

  • adapter-responses.ts emitError: a response.failed without a prior response.created is the same orphan class if the stream truncated before the created event.
  • The re-request HTTP-failure path in core.ts also double-logs (ctx.log + loggerLog("error")) — same pattern; the issue only reported the truncation one.
  • Truncation with 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.

@github-actions

github-actions Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-02_acp-loop-truncation-retry (bac23c3)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-440

Each push to this PR publishes a new version under the pr-440 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr440.tgz
npm install -g package

This 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.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 ework agent · qwen3.8-27b

[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

  • npm run typecheck — clean
  • npm test — 874 pass / 0 fail (868 + 6 new)
  • npm run build — success
  • Tests are not vacuous: ran the 6 new tests/loop-truncation.test.ts against the merge-base (pre-fix) code → 0/6 pass; against the fix → 6/6 pass. Good red→green.
  • Branch is 19 commits behind master, but I dry-ran a merge: no conflicts on src/loop/core.ts / src/loop/adapter-anthropic.ts (master hasn't touched them since the merge-base). Clean to merge as-is.

What's correct

  • Retry predicate & placement (src/loop/core.ts): check runs after the parse loop, before recordUsage, so a retried round's tokens aren't double-counted. Per-attempt state reset is complete. roundBody correctly tracks the last-sent body (round-1 original, round-N compressed), so a round-2+ retry re-sends the right body — T6 confirms.
  • emitError well-formedness (src/loop/adapter-anthropic.ts): synthetic message_start only if none forwarded, content_block_stop for every still-open block, then error block + terminal. Correct for all four truncation positions (pre-start / mid-thinking / mid-text / post-content). openBlocks push/pop is right (tool_use never pushed — buffered in pending).
  • Double-logging fix: the truncation path now logs once via ctx.log; the global loggerLog("error") duplicate is removed. The re-request HTTP-error path's double-log is correctly left out of scope (documented).
  • Both compression modes: the retry is protocol-neutral (0-event truncation is safe to replay in plugin and proxy mode alike) and the emitError fix applies to both. No mode-specific breakage.

Finding — the invariant has a hole for OpenAI round-2+ reasoning

The PR's core claim is "retry iff nothing was forwarded." DESIGN.md says forwardedAny is "set by fwd() wrapping the five yield sites ... (raw text, synthetic text, raw reasoning, synthetic reasoning, meta)." But only 3 of the 5 are actually wrapped — the two reasoning sites are not:

  • src/loop/core.ts:279 → yield ev.raw; (reasoning raw) — not fwd()
  • src/loop/core.ts:281 → yield adapter.emitReasoning(ev.delta); — not fwd()

For Anthropic this is harmless: a thinking block is always preceded by its content_block_start, which is forwarded via fwd() (round 1 by round===1, round 2+ by !firstRoundOnly), so forwardedAny is already true before any reasoning delta.

For the OpenAI adapter it is not harmless. In round 2+ the leading role chunk is emitted as meta with firstRoundOnly: true → not forwarded (adapter-openai.ts:368), and reasoning_content is forwarded via raw (adapter-openai.ts:328) → hits the unwrapped yield ev.raw. So a round-2 response that starts with reasoning and then truncates (no finish_reason/[DONE]) leaves forwardedAny === false even though bytes already reached the client.

Repro (I ran this against the branch): round 1 = acp_status proxy tool call (→ re-request), round 2 = role chunk + reasoning_content:"let me think" + EOF. Result on current code:

  • fetch calls = 2 (the re-request plus a spurious truncation retry)
  • "let me think" appears 2× in the client stream — the already-forwarded reasoning is duplicated to the client

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 reasoning events, only text/meta).

Fix (verified): wrap both reasoning yields in fwd():

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 fetch calls = 1, reasoning appears 1×, and the full suite stays green (874/0). It also makes the code match DESIGN.md's "five yield sites" claim.

Recommendation

The 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 emitError orphan, re-request double-log, reRequest=true silent swallow) are correctly scoped and documented — no action needed here.

…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
@ranxianglei
ranxianglei merged commit 135f832 into master Sep 3, 2026
6 checks passed
ranxianglei pushed a commit that referenced this pull request Sep 17, 2026
…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
ranxianglei pushed a commit that referenced this pull request Sep 27, 2026
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.
@ranxianglei ranxianglei mentioned this pull request Sep 27, 2026
@ranxianglei
ranxianglei deleted the 2026-09-02_acp-loop-truncation-retry branch October 15, 2026 05:32
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