Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions devlog/2026-09-02_acp-loop-truncation-retry/DESIGN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
# DESIGN: acp-loop truncation retry + well-formed Anthropic error stream

## Problem shape

`runCompressLoop` is an `AsyncGenerator<Buffer>`: it reads the upstream SSE
stream, forwards client-facing chunks as it parses them, and only knows the
stream was truncated *after* the parse loop ends without a done event
(`!sawDone`). `fetchWithRetry` cannot see this failure — it inspects
`response.ok` after headers and never reads the body. So recovery has to live
at loop level, where the "did I already commit to the client?" state is known.

## Retry predicate — the zero-side-effect invariant

A truncated round can be transparently replayed **iff** nothing observable
happened. All of these must hold at the end of the parse loop:

- `!sawDone` — the stream actually truncated;
- `!forwardedAny` — no chunk was yielded to the client this attempt. A
per-attempt flag set by `fwd()` wrapping the five yield sites in the parse
loop (raw text, synthetic text, raw reasoning, synthetic reasoning, meta).
Ping-only streams count as forwarded (conservative: the client saw
something, so a retry would duplicate it);
- `calls.length === 0` — no tool call was collected. The `tool_call` /
marker / `emitText` yields happen *after* the parse loop, so they are not
yet covered by `forwardedAny` and need explicit checks:
- `calls.length === 0` rules out tool_call and marker yields (both are
derived from `calls`);
- `!(ctx.textProtocol && assistantText.length > 0)` rules out the
text-protocol `emitText` yield (only emitted when textProtocol and the
round produced text);
- `!signal?.aborted` — the client is still connected;
- `!truncationRetried` — function-level flag: at most ONE retry per request
(the issue says "走一次"). The flag is never reset, so a second truncated
round (round 2+) also fails fast.

Placement: the check runs **after** the parse loop and **before**
`recordUsage`. This matters: a round-2+ `message_start` sets `usage` without
forwarding anything, so recording before the retry check would double-count
the retried attempt's tokens.

Mechanics: the parse loop is wrapped in an inner `for (;;)` attempt loop.
On a qualifying truncation the loop calls `fetchUpstream(roundBody)` (the
hoisted `fetchWithRetry` wrapper — same backoff, same `BILI_REPLAY_RETRY_*`
env knobs, same #189 rejection logging) and `continue`s; the outer round
number is unchanged, so a round-1 retry re-parses as round 1 and its
`message_start` is forwarded exactly once (attempt 1 forwarded nothing).
Per-attempt state (text/reasoning/calls/usage/finishReason/sawDone/
suppressCompletion/forwardedAny) is reset at the top of the attempt loop.

`roundBody` (new): the re-request path replaces the body each round
(`compressMessages`); the old code re-fetched with `requestOptions` + a local
`newBody`. The retry must re-send **the body that produced the truncated
stream** — on round 1 that is the original `requestBody`, on round N it is
the compressed body. `roundBody` is updated right before the
`currentUpstream` swap, so it always holds the last body actually sent.

Failure of the retry itself falls through to the existing truncation error
path (empty body on the retry response is converted to
`UpstreamHttpError` so it is caught by the same handler).

## Adapter: tracking what was forwarded

The Anthropic adapter closure gains two pieces of state:

- `messageStartForwarded: boolean` — set where the round-1 `message_start`
is forwarded (always forwarded in round 1, so the flag is set there);
- `openBlocks: number[]` — client indices of blocks whose
`content_block_start` was forwarded but whose `content_block_stop` was not.
Pushed in the non-tool `content_block_start` branch (forwarded in all
rounds); removed in the `content_block_stop` branches via an `indexOf`
guard (tool_use blocks are never pushed — they are buffered in `pending`
and emitted as a whole later).

`emitError(message)` now emits, in order:

1. synthetic `message_start` (if `!messageStartForwarded`) —
`buildSyntheticMessageStart()`: the captured `messageId` if any, else a
generated `msg_acp_error_<ts>` id; empty `content`, null stop reason,
zero usage, the request model if known. Zero usage is honest: nothing
completed.
2. `content_block_stop` for every index in `openBlocks` (drained);
3. the existing error text block (`[acp-proxy: <message>]`);
4. the existing terminal (`message_delta` + `message_stop`).

Result: the stream is always well-formed — starting frame first, every block
closed, terminal last — regardless of where the truncation hit (before
`message_start`, mid-thinking-block, mid-text-block, or after everything).

On the retry path the adapter state is all-initial at re-parse time
(`messageId` undefined, `clientIndex` 0, flag false, no open blocks), so the
re-parsed stream is shaped exactly like a fresh first parse — consistent.

## Logging

The truncation path keeps `ctx.log` (session-prefixed `info` line, which is
what session-level dashboards key on) and drops the global
`loggerLog("error", ...)` duplicate. One event, one line. (The upstream-HTTP
failure path on re-request still double-logs — same pattern, out of scope,
reported in the PR.)

## What is NOT retried (and why)

- Anything that forwarded a single byte to the client (retry would emit a
duplicate/partial stream the client cannot reconcile);
- Any round that collected a tool call or ran a proxy tool (side effects);
- Text-protocol rounds that accumulated text (the post-loop `emitText` yield
would double it);
- Aborted requests;
- Second and later truncations within one request (one retry, per the issue).
57 changes: 57 additions & 0 deletions devlog/2026-09-02_acp-loop-truncation-retry/REQ.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# REQ: acp-loop upstream truncation — zero-side-effect retry, well-formed Anthropic error stream, single-point logging

Issue #413: when the upstream LLM returns 200 but the SSE stream ends early
(no `message_delta`/`message_stop`), the compress loop (`src/loop/core.ts`)
fails fast with `emitError` and no recovery. Three concrete defects, all
confirmed by code read + red tests before the fix:

1. **No retry for zero-side-effect truncation.** `fetchWithRetry` only wraps
the re-request fetches (it inspects `response.ok` after headers and never
reads the body — mid-stream EOF is only observable at loop level via the
missing done event). A round that forwarded nothing to the client
(`0 text + 0 reasoning + 0 executed tools`, nothing yielded) is a
zero-side-effect retry candidate; the loop instead surfaced the upstream
flake to the host session. Production evidence: 3 truncation events in
3 days, two of them 0+0 (2026-08-31T00:35:24Z, 2026-08-31T06:03:43Z).
2. **Orphan Anthropic stream on first-round truncation.** 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 stream truncated before `message_start` reached the client, the
client sees a `content_block_*` sequence with no starting frame —
malformed per the Anthropic stream protocol. Open `thinking` blocks left
by the truncation are never closed either. The responses branch already
fixed the same class (see `src/stream-error.ts` comment); the Anthropic
adapter was missed.
3. **Double logging.** Every truncation event was logged twice: `ctx.log`
(→ `log("info", "[sid] ...")`) plus a global `loggerLog("error", ...)` —
both tee to the same file + stderr.

## Acceptance criteria (from the issue)

- Stub upstream: headers then 0-event EOF → exactly 1 retry observed; after
the failed retry the client stream passes "SSE start frame before
content_block" schema validation.
- Truncation fixture with open blocks: every `content_block_start` has a
matching `content_block_stop` before stream end.
- Each single truncation produces exactly 1 log line.

## Constraints

- The retry must be provably side-effect-free: nothing forwarded to the
client, no tool calls executed, no usage recorded, no state mutation.
- At most ONE retry per request (the issue says "走一次").
- No new dependencies; `fetchWithRetry` reuse (same backoff/env knobs).
- The re-request path's behavior (degraded retry, #189 rejection logging)
is unchanged; only its `fetchUpstream` definition is hoisted.

## Non-goals (reported in the PR, 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.
- `core.ts` upstream-error path (HTTP failure on re-request) 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.
58 changes: 58 additions & 0 deletions devlog/2026-09-02_acp-loop-truncation-retry/WORKLOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# WORKLOG: acp-loop upstream truncation — zero-side-effect retry, well-formed Anthropic error stream, single-point logging

- Task ID: `2026-09-02_acp-loop-truncation-retry`
- Home Repo: `billion-context`
- Status: Done
- Updated: 2026-09-02

## 1. Summary

- **What was done**: (1) the compress loop now retries once when an upstream
stream truncates (200 + early EOF) after forwarding nothing to the client;
(2) the Anthropic adapter's `emitError` now synthesizes a `message_start`
if none was forwarded and closes every block still open at error time;
(3) the truncation event is logged once (via `ctx.log`) instead of twice.
- **Why**: zero-side-effect truncations are the most common recoverable
upstream flake (3 in 3 days in production, two of them 0+0); failing fast
lands the flake in the host session. The orphan stream shape violates the
Anthropic stream protocol and can crash strict clients (the responses
branch already fixed its own copy of this class). Double logging makes
incident triage count events wrong.
- **Behavior / compatibility changes**: Yes, three —
1. A first-round (or any-round) truncation that forwarded nothing and
executed no tool calls now triggers exactly one retry through
`fetchWithRetry` before the error is surfaced. Clients see either a
clean successful stream or the error stream — never a partial one.
2. The Anthropic error stream is now always well-formed: starts with
`message_start`, every `content_block_start` has a matching
`content_block_stop`, ends with `message_delta` + `message_stop`.
3. Truncation is logged once at `info` (session-prefixed) instead of twice
(`info` + `error`).
- **Risk level**: Low. The retry is gated on a strict zero-side-effect
predicate (nothing forwarded, no tool calls, nothing accumulated for the
host, not aborted, not already retried); the adapter change only adds
frames that strict clients require; logging change is cosmetic.

## 2. Change Log

### Commits

| Commit | Description |
|--------|-------------|
| `<sha>` | fix: acp-loop zero-side-effect truncation retry + well-formed anthropic error stream (#413) |

### Key Files

- `src/loop/core.ts` — retry loop around the per-round parse; hoisted
`fetchUpstream`; dropped the second (global error) log line on truncation;
`roundBody` tracks the last body actually sent so a retry re-sends the
compressed round body, not the original request.
- `src/loop/adapter-anthropic.ts` — `messageStartForwarded` / `openBlocks`
tracking in the adapter closure; `buildSyntheticMessageStart()`;
`emitError` closes open blocks and backfills the starting frame.
- `tests/loop-truncation.test.ts` — new; 6 tests covering all three
acceptance criteria plus retry-body tracking and the once-per-request cap.

## 3. Design & Implementation Notes

See `DESIGN.md` for the dataflow and the safety invariants.
46 changes: 44 additions & 2 deletions src/loop/adapter-anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,35 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
const model = (requestBody.model as string) ?? undefined;
let messageId: string | undefined;
let clientIndex = 0;
let messageStartForwarded = false;
const openBlocks: number[] = [];

const removeOpenBlock = (index: number): void => {
const i = openBlocks.indexOf(index);
if (i >= 0) openBlocks.splice(i, 1);
};

// #413: emitError must terminate a well-formed stream even when the
// upstream died before sending message_start — synthesize the start frame
// so content blocks are never orphaned (strict clients reject them).
const buildSyntheticMessageStart = (): Buffer => {
const extra: Record<string, unknown> = {};
if (model) extra.model = model;
const msg: Record<string, unknown> = {
id: messageId ?? `msg_acp_error_${Date.now()}`,
type: "message",
role: "assistant",
content: [],
stop_reason: null,
stop_sequence: null,
usage: { input_tokens: 0, output_tokens: 0 },
...extra,
};
return Buffer.from(
`event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: msg })}\n\n`,
"utf8",
);
};

const buildTextBlock = (index: number, text: string): Buffer =>
Buffer.from(
Expand Down Expand Up @@ -206,6 +235,7 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
if (typeof u.input_tokens === "number") roundInput = u.input_tokens;
if (typeof u.cache_read_input_tokens === "number") roundCached = u.cache_read_input_tokens;
if (round === 1) {
messageStartForwarded = true;
yield { kind: "meta", chunk: rawBuf, firstRoundOnly: true } as ParsedStreamEvent;
}
} else if (type === "ping") {
Expand All @@ -221,6 +251,7 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
if (block.type === "thinking" || block.type === "redacted_thinking") thinkingIndexes.add(upstreamIndex);
const ci = clientIndex++;
indexMap.set(upstreamIndex, ci);
openBlocks.push(ci);
yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci), firstRoundOnly: round === 1 } as ParsedStreamEvent;
}
} else if (type === "content_block_delta") {
Expand Down Expand Up @@ -272,10 +303,12 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
// Seal the current thinking segment so interleaved thinking
// blocks each keep their own signature on rebuild.
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
removeOpenBlock(ci);
yield { kind: "meta", chunk: remapIndexInEvent(eventStr, ci), firstRoundOnly: false } as ParsedStreamEvent;
yield { kind: "reasoning", delta: "", blockEnd: true } as ParsedStreamEvent;
} else {
const ci = indexMap.get(upstreamIndex) ?? upstreamIndex;
removeOpenBlock(ci);
if (lastTextIndex !== null) {
const tail = tagFilter.flush();
if (tail.length > 0) {
Expand Down Expand Up @@ -385,8 +418,17 @@ export function createAnthropicAdapter(requestBody: Record<string, unknown>, ori
},

emitError(message) {
const errBlock = buildTextBlock(clientIndex++, `\n[acp-proxy: ${message}]\n`);
return Buffer.concat([errBlock, buildTerminal("end_turn", 0, 0, 0)]);
const parts: Buffer[] = [];
if (!messageStartForwarded) {
parts.push(buildSyntheticMessageStart());
messageStartForwarded = true;
}
for (const index of openBlocks.splice(0)) {
parts.push(Buffer.from(`event: content_block_stop\ndata: ${JSON.stringify({ type: "content_block_stop", index })}\n\n`, "utf8"));
}
parts.push(buildTextBlock(clientIndex++, `\n[acp-proxy: ${message}]\n`));
parts.push(buildTerminal("end_turn", 0, 0, 0));
return Buffer.concat(parts);
},
};
}
Loading
Loading