From a6583ddf02ba8f41abf30f6e56302d6ff1fd37d8 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 30 Oct 2026 13:49:14 +0800 Subject: [PATCH 1/4] fix(#5179): map the loop's early "length" finish onto Anthropic's max_tokens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The loop ends a turn early in two places (failed-only compress round #156/#4186, and the round limit), both with finishReason "length" — OpenAI's word. The Anthropic wire has no such stop reason, and Claude Code treats an unknown one as a normal end of turn, so the agent stopped mid-task and waited for the user. Translate to max_tokens at the adapter boundary: Claude Code auto-resumes a max_tokens turn, which is what an early end of an unfinished turn wants. Upstream's own stop reasons pass through unchanged. --- src/loop/adapter-anthropic.ts | 11 +- ...ue5179-anthropic-early-stop-reason.test.ts | 103 ++++++++++++++++++ 2 files changed, 112 insertions(+), 2 deletions(-) create mode 100644 tests/issue5179-anthropic-early-stop-reason.test.ts diff --git a/src/loop/adapter-anthropic.ts b/src/loop/adapter-anthropic.ts index 18f0fcbaae..20b030ea68 100644 --- a/src/loop/adapter-anthropic.ts +++ b/src/loop/adapter-anthropic.ts @@ -152,6 +152,14 @@ function rewriteTextDeltaEvent(eventStr: string, newIndex: number, newText: stri return Buffer.from(rebuilt.join("\n") + "\n\n", "utf8"); } +// The loop's own early ends say "length", OpenAI's word; Anthropic has no +// such stop reason, and Claude Code stops mid-task on one it does not know. +// "max_tokens" makes it resume the turn instead (#5179). +function anthropicStopReason(reason: string | undefined): string { + if (!reason) return "end_turn"; + return reason === "length" ? "max_tokens" : reason; +} + function buildTextDeltaEvent(index: number, text: string): Buffer { return Buffer.from( `event: content_block_delta\n` + @@ -738,9 +746,8 @@ export function createAnthropicAdapter(requestBody: Record, ori }, emitCompletion(opts?: EmitCompletionOpts) { - const stopReason = opts?.finishReason ?? "end_turn"; return buildTerminal( - stopReason, + anthropicStopReason(opts?.finishReason), opts?.usage?.outputTokens ?? 0, opts?.usage?.inputTokens ?? 0, opts?.usage?.cachedTokens ?? 0, diff --git a/tests/issue5179-anthropic-early-stop-reason.test.ts b/tests/issue5179-anthropic-early-stop-reason.test.ts new file mode 100644 index 0000000000..4376be851d --- /dev/null +++ b/tests/issue5179-anthropic-early-stop-reason.test.ts @@ -0,0 +1,103 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { Config } from "acp-kernel"; +import { createCore, createInitialState } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { runCompressLoop, createAnthropicAdapter, MAX_LOOP_ROUNDS } from "../src/loop/index.ts"; +import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; + +// #5179: the loop ends a turn early in two places — a failed-only compress +// round (#156/#4186) and the round limit — both with finishReason "length", +// OpenAI's word. The Anthropic wire has no such stop reason, and Claude Code +// reads an unknown one as a plain end of turn, stopping the task mid-flight. +// The adapter must translate to "max_tokens", which Claude Code auto-resumes. + +function sse(type: string, data: unknown): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +function makeSession(): Session { + return { + id: "anthropic-early-stop-test", + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, contextTokens: 0, compressCreditTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + pendingRetrievals: [], + persisted: false, + }; +} + +function toolRound(name: string, input: unknown): string { + return [ + sse("message_start", { type: "message_start", message: { id: "msg_r", usage: { input_tokens: 100 } } }), + sse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "tool_use", id: `toolu_${name}`, name, input: {} } }), + sse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "input_json_delta", partial_json: JSON.stringify(input) } }), + sse("content_block_stop", { type: "content_block_stop", index: 0 }), + sse("message_delta", { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 7 } }), + sse("message_stop", { type: "message_stop" }), + ].join(""); +} + +async function runAnthropicLoop(round: string): Promise<{ out: string; reRequests: number }> { + const body = { model: "claude-opus-5-5", stream: true, messages: [{ role: "user", content: "go on" }] }; + let reRequests = 0; + const orig = globalThis.fetch; + globalThis.fetch = (async () => { + reRequests++; + return new Response(round, { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + let out = ""; + try { + const ctx = { + core: createCore(), + config: { modelContextLimit: 200000 } as Config, + messages: [], + session: makeSession(), + log: () => {}, + }; + for await (const c of runCompressLoop(new Response(round, { status: 200 }).body!, ctx, body, { url: "http://mock", headers: {} }, createAnthropicAdapter(body), buildCompressSystemPrompt())) { + out += c.toString("utf8"); + } + } finally { + globalThis.fetch = orig; + } + return { out, reRequests }; +} + +function stopReasons(out: string): unknown[] { + return out + .split("\n") + .filter((l) => l.startsWith("data: ")) + .map((l) => JSON.parse(l.slice(6)) as { type?: string; delta?: { stop_reason?: unknown } }) + .filter((e) => e.type === "message_delta") + .map((e) => e.delta?.stop_reason); +} + +test("a failed-only compress round ends the Anthropic turn with stop_reason max_tokens, so Claude Code resumes", async () => { + const { out, reRequests } = await runAnthropicLoop( + toolRound("compress", { content: [{ startId: "m00001", endId: "m00002", summary: "s" }] }), + ); + assert.equal(reRequests, 0, "the #156/#4186 early end still holds: the failed frame never reaches upstream"); + assert.ok(out.includes("❌"), "the failure receipt still reaches the client"); + assert.deepEqual(stopReasons(out), ["max_tokens"]); +}); + +test("the round limit ends the Anthropic turn with stop_reason max_tokens", async () => { + const { out, reRequests } = await runAnthropicLoop(toolRound("acp_status", {})); + assert.equal(reRequests, MAX_LOOP_ROUNDS - 1, "ran to the loop limit"); + assert.deepEqual(stopReasons(out), ["max_tokens"]); +}); + +test("upstream's own stop reasons reach the client unchanged", () => { + for (const reason of ["end_turn", "tool_use", "max_tokens", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded", "a_future_reason"]) { + const frame = createAnthropicAdapter({ model: "claude-opus-5-5" }).emitCompletion({ finishReason: reason }).toString("utf8"); + assert.deepEqual(stopReasons(frame), [reason], reason); + } + const none = createAnthropicAdapter({ model: "claude-opus-5-5" }).emitCompletion().toString("utf8"); + assert.deepEqual(stopReasons(none), ["end_turn"], "no reason given reads as a normal end"); +}); From 92548e1342c7cbd91d73fb5f6b439e88fce1a077 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Fri, 30 Oct 2026 18:13:57 +0800 Subject: [PATCH 2/4] fix(loop): a failed compress feeds the model a recovery receipt and re-requests instead of ending the turn with "length" (#5220) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #4186 ended the turn on the first failed-only mutating round so that round's ephemeral failure frames could never reach upstream. On OpenAI-protocol clients (and on the Anthropic wire before #5202's revert) the synthetic finish_reason "length" is not resumed by anyone, so a single malformed compress call silently killed the user's task — from v0.1.209 onward. Contract change: when every failing call in a failed-only round had its failure receipt streamed to THIS client (visibility markers on, regular non-thread lane), the ephemeral tool frames are dropped from the rebuild body, an assistant message carrying byte-for-byte the same receipt lines the client saw is appended, and the loop's normal re-request fires. The client then re-sends those exact bytes on its next request, so the upstream prefix is never touched and the model reads back its own failed attempt plus why it failed and continues the task. The turn still ends when an identical (name, args) signature fails again (the restored #156 signature breaker), in threadContinue sessions, or on marker-off surfaces — anywhere the client cannot be handed the receipt bytes. Tests: new gate suite issue5220-failed-compress-receipt (receipt shape + natural end, signature breaker cap, unbounded distinct failures run to MAX_LOOP_ROUNDS, marker-off fallback); contract updates in loop-core, loop-compress, compress-credit, ccr-v2, issue1195-overflow-refold, issue1502-raw-args-salvage; issue5179 keeps asserting max_tokens only on a natural length-end round. --- src/loop/core.ts | 106 ++++++-- src/loop/index.ts | 2 +- tests/ccr-v2.test.ts | 12 +- tests/compress-credit.test.ts | 10 +- tests/issue1195-overflow-refold.test.ts | 21 +- tests/issue1502-raw-args-salvage.test.ts | 9 +- ...ue5179-anthropic-early-stop-reason.test.ts | 17 +- .../issue5220-failed-compress-receipt.test.ts | 235 ++++++++++++++++++ tests/loop-compress.test.ts | 28 ++- tests/loop-core.test.ts | 31 ++- 10 files changed, 406 insertions(+), 65 deletions(-) create mode 100644 tests/issue5220-failed-compress-receipt.test.ts diff --git a/src/loop/core.ts b/src/loop/core.ts index c103051f24..d9bc4af146 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -51,6 +51,30 @@ import { safePrefix, safeSuffix, scrubLoneSurrogatesOnWire } from "../text-safe. export const MAX_LOOP_ROUNDS = 10; +/** #5220: canonical signature of a failed proxy call — sorted-key JSON so + * argument-order noise doesn't defeat the repeat-detection set. Unparseable + * arguments fall back to the raw string (byte equality still catches the + * pathological identical-resubmit ping-pong the original #156 guard existed + * for). Takes the RAW model argument bytes (pr.arguments, per #3661/#156). + */ +export function failedCallSignature(name: string, argsJson: string): string { + let norm = argsJson; + try { + const obj = JSON.parse(argsJson); + if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) { + norm = JSON.stringify( + Object.keys(obj as Record).sort().reduce>((acc, k) => { + acc[k] = (obj as Record)[k]; + return acc; + }, {}), + ); + } + } catch { + /* keep raw */ + } + return `${name}:${norm}`; +} + export function buildVisibilityMarker(toolName: string, result: string): string { const lines = result.split("\n").map((l) => l.trim()).filter((l) => l.length > 0); const failed = lines.some((l) => @@ -597,11 +621,19 @@ export async function* runCompressLoop( // #3302 (Ask 6): probe-family observability — a model failing compress with // one endpoint fixed and the other varying is enumerating a sparse ref - // space; every attempt carries different args, so the failed-only breaker - // below ends such turns without ever flagging them. Log it once as an - // operator signal; the failure receipts carry the live range table. + // space; every attempt carries different args, so the repeat-signature + // breaker below lets such turns run (bounded by MAX_LOOP_ROUNDS) without + // ever flagging them. Log it once as an operator signal; the failure + // receipts carry the live range table. const probeFailures = new Map>(); let probeWarned = false; + // #5220: canonical signatures of compress/decompress calls already FAILED + // in an earlier round of this request. A failed-only round whose signatures + // are ALL previously seen is pure ping-pong (the original #156 guard, + // restored in narrow form): breaking there costs nothing the model could + // have learned from. First-time failures feed the model a recovery + // receipt instead (see the failed-only handler below). + const failedSigs = new Set(); // #762,#1479: strict-echo origin for re-request normalization (the learned // flag rides on ctx.session.metadata; mirrors prepareOpenai's static gate). @@ -1191,6 +1223,13 @@ export async function* runCompressLoop( let realCalls = 0; const realToolCalls: ToolCallEmit[] = []; const proxyResults: { name: string; callId: string; result: string; arguments: string; wireArguments: string; signature?: string; image?: { base64: string; mediaType: string } }[] = []; + // #5220: the marker lines ACTUALLY streamed to the client this round + // (deduped, same order as the stream). On a failed-only round this IS + // the recovery receipt the retry body must carry — reconstructing it + // afterwards from seenMarkers would be impossible (the set no longer + // remembers which entries are new) and would drift from what the + // client saw. + const streamedMarkers: string[] = []; for (const call of allCalls) { if (call.name.length === 0) { @@ -1222,6 +1261,7 @@ export async function* runCompressLoop( } else { seenMarkers.add(markerKey); yield adapter.emitMarker(call.name, result.text); + streamedMarkers.push(buildVisibilityMarker(call.name, result.text)); } } } else { @@ -1481,14 +1521,26 @@ export async function* runCompressLoop( return; } - // #156/#4186: if this round is only failed compress/decompress, stop - // here instead of re-requesting. The failed frames spliced into the - // retry body above are ephemeral (#1548): never persisted, never seen - // by the client. Letting them reach upstream and then vanish from the - // next request rewrites the provider's frozen prefix mid-history — - // an unsanctioned cache seam. Breaking keeps them off the wire; the - // receipt already streamed to the client carries why it failed, and a - // later turn can retry with a different range. + // Failed-only-round contract — history #156/#4186/#4217, current #5220: + // a round whose proxy results are ALL failed compress/decompress used + // to end the turn here with a fabricated "length" finish. Cache-clean + // (the ephemeral failure frames never reach upstream, #1548) but fatal + // to the user: no client on any wire auto-continues "length" (OpenAI: + // no such convention; Anthropic: not even a legal stop reason), so one + // bad compress call killed a running task mid-work (#5220 report; + // #5179 Anthropic field case). #5220 flips the default: feed the + // failure to the MODEL and let IT decide. The retry body carries ONE + // plain assistant receipt whose bytes are exactly the visibility + // markers already streamed to the client, so the client's transcript + // carries the same bytes into its next request and the provider's + // frozen prefix never diverges — no ephemeral frames, no seam, fuzz + // stays green. Bounded twice over: the narrow #156 breaker (every + // signature in the round already failed before → ping-pong → break) + // and MAX_LOOP_ROUNDS above. Threads-continue turns and + // visibilityMarkers=false requests keep the old contract: their client/ + // delta view lacks the marker bytes, so a receipt-only body would + // carry server-invisible bytes upstream — exactly the seam #4186 + // forbids. const failedMutating = proxyResults.filter( (pr) => (pr.name === "compress" || pr.name === "decompress") && pr.result.includes("FAILED"), ); @@ -1503,10 +1555,34 @@ export async function* runCompressLoop( } if (reRequest && failedMutating.length > 0 && failedMutating.length === proxyResults.length) { - ctx.log(`[acp-loop] round ${round}: failed-only mutating round; completing after ${round} round(s) instead of re-requesting (#156/#4186)`); - loggerLog("warn", `[acp-loop] failed compress/decompress round at round ${round}; breaking early (#156/#4186)`); - yield adapter.emitCompletion({ finishReason: "length", usage, terminalExtra }); - return; + const sigs = failedMutating.map((pr) => failedCallSignature(pr.name, pr.arguments)); + const stuck = sigs.every((s) => failedSigs.has(s)); + const receiptable = !stuck && ctx.visibilityMarkers !== false && !threadContinue; + if (!receiptable) { + const why = stuck + ? "every failing signature already failed in an earlier round" + : "receipt channel unavailable (" + ([threadContinue ? "threads-delta" : null, ctx.visibilityMarkers === false ? "visibility markers off" : null].filter(Boolean).join(", ")) + ")"; + ctx.log(`[acp-loop] round ${round}: failed-only mutating round (${why}); completing after ${round} round(s) instead of re-requesting (#156/#4186/#5220)`); + loggerLog("warn", `[acp-loop] failed compress/decompress round at round ${round}; breaking early (${why}) (#156/#4186/#5220)`); + yield adapter.emitCompletion({ finishReason: "length", usage, terminalExtra }); + return; + } + sigs.forEach((s) => failedSigs.add(s)); + // Splice the retry body: strip THIS round's ephemeral failure + // frames (they must never reach upstream — #1548/#4186) and + // append the recovery receipt as a plain assistant message — + // bytes identical to what emitMarker already streamed to the + // client this round (same order, same dedup: seenMarkers holds + // exactly what went out). Falls through to the normal + // re-request path below. + const dropIds = new Set(); + for (const pr of failedMutating) { + dropIds.add(`acp_loop_r${round}_asst_tc_${pr.callId}`); + dropIds.add(`acp_loop_r${round}_tool_${pr.callId}`); + } + coreMessages.splice(0, coreMessages.length, ...coreMessages.filter((m) => !dropIds.has(m.id))); + ctx.log(`[acp-loop] round ${round}: failed-only mutating round; feeding the model a recovery receipt (${streamedMarkers.length} marker line(s)) and re-requesting (#5220)`); + coreMessages.push({ id: `acp_loop_r${round}_rcpt`, role: "assistant", contentType: "text", text: streamedMarkers.join("") }); } ctx.log(`[acp-loop] round ${round}: proxy tool executed; re-requesting so the model sees the result`); diff --git a/src/loop/index.ts b/src/loop/index.ts index 5f5ca938c3..8ce0f95d27 100644 --- a/src/loop/index.ts +++ b/src/loop/index.ts @@ -1,4 +1,4 @@ -export { runCompressLoop, executeProxyTool, MAX_LOOP_ROUNDS } from "./core.js"; +export { runCompressLoop, executeProxyTool, MAX_LOOP_ROUNDS, failedCallSignature } from "./core.js"; export type { LoopCtx, RequestOptions, diff --git a/tests/ccr-v2.test.ts b/tests/ccr-v2.test.ts index f490cf1201..828b998358 100644 --- a/tests/ccr-v2.test.ts +++ b/tests/ccr-v2.test.ts @@ -401,11 +401,13 @@ test("e2e CCR v2 opt-in: no ccr config at any level leaves the session unarmed }); const sse = await res.text(); assert.ok(res.ok, `client turn failed: HTTP ${res.status}: ${sse}`); - // The refused decompress is a failed-only round: under #156/#4186 its - // ephemeral frame never reaches upstream again, so the turn ends after - // the compress re-request and the refusal surfaces to the client as the - // failure receipt instead of riding a third request. - assert.equal(captured.length, 2, "initial + compress re-request only; refused decompress is never re-requested"); + // The refused decompress is a failed-only round: under #5220 it gets + // ONE recovery-receipt re-request (the third captured forward), which + // resubmits the identical refusal — where the restored #156 signature + // breaker ends the turn. Its ephemeral frame never rides that re- + // request upstream; the refusal surfaces to the client as the failure + // receipt. + assert.equal(captured.length, 3, "initial + compress re-request + one recovery-receipt re-request for the refused decompress (#5220)"); assert.match(captured[1]!, /Early history: messages 1-7 covered initial setup\./, "compress fold landed before the decompress attempt"); // [#1207 owner decision] CCR is opt-in on every lane: with no ccr key // at any level the session never arms, so the range restore ack is the diff --git a/tests/compress-credit.test.ts b/tests/compress-credit.test.ts index b9268268ed..15f76be254 100644 --- a/tests/compress-credit.test.ts +++ b/tests/compress-credit.test.ts @@ -118,11 +118,11 @@ test("#252: post-compress re-request usage is netted by the compress credit", as test("#252: failed compress accrues no credit", async () => { const ctx = makeCompressibleCtx(); - // Sub-viability range (kernel minCompressRange) → compress FAILS. + // Sub-viability range (kernel minCompressRange) → compress FAILS. Under #5220 +// such a round re-requests with a recovery receipt (round 2 below carries no +// usage report) — and the point still stands: NO credit may be netted off the +// turn's only real usage figure. const badArgs = JSON.stringify({ content: [{ startId: "m00007", endId: "m00007", summary: "s" }] }); - // Usage rides the round-1 completion: the failed-only breaker (#156/#4186) - // ends the turn before any re-request, so this is the only usage report of - // the turn — it must still land raw (no credit netting). const round1 = [ sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), fcEvents(0, "call_c", "compress", badArgs), @@ -138,7 +138,7 @@ test("#252: failed compress accrues no credit", async () => { { model: "gpt-4o", input: [], stream: true }, { url: "http://mock", headers: {} }, ); - assert.equal(fetchCalls, 0, "failed-only round breaks before any re-request (#4186)"); + assert.equal(fetchCalls, 1, "first-time failure re-requests once via recovery receipt (#5220)"); assert.equal(ctx.session.stats.compressCreditTokens, 0, "no credit on failed compress"); assert.equal(ctx.session.stats.lastInputTokens, 50000, "usage lands raw when nothing was compressed"); } finally { diff --git a/tests/issue1195-overflow-refold.test.ts b/tests/issue1195-overflow-refold.test.ts index 0dd554b245..1d4faca825 100644 --- a/tests/issue1195-overflow-refold.test.ts +++ b/tests/issue1195-overflow-refold.test.ts @@ -263,12 +263,15 @@ test("#2777: a failed compress after an accepted overflow fold keeps the fold fo assert.equal(response.status, 200); const stream = await response.text(); const forwards = () => upstream.bodies.filter((raw) => (JSON.parse(raw) as { stream?: boolean }).stream !== false); - // #4186: the failed-only compress round ends the turn — there is no internal - // continuation re-request, and its ephemeral failure frame never reaches - // the upstream (old contract asserted three forwards here). - assert.equal(forwards().length, 2, "original overflow + accepted folded retry only"); + // #4186→#5220: the failed-only compress round no longer ends the turn — + // the receipt re-request is the third forward. It must carry the streamed + // ❌ receipt (client-visible bytes) and NONE of this round's ephemeral + // failure frames (#1548/#4186 seam invariant). + assert.equal(forwards().length, 3, "original overflow + accepted folded retry + recovery-receipt re-request (#5220)"); assert.ok(forwards()[0].includes("MARKER_1_"), "original request contains early history"); assert.ok(forwards()[1].includes(SUMMARY_TEXT) && !forwards()[1].includes("MARKER_1_"), "accepted retry folded early history"); + assert.ok(forwards()[2].includes("Compression FAILED"), "receipt re-request carries the ❌ receipt as assistant text"); + assert.ok(!forwards()[2].includes("tool_result"), "ephemeral failure frames stay off the wire (#1548/#4186)"); assert.match(stream, /Compression FAILED/, "the invalid-range receipt reaches the client"); // #2777 core property under the new contract: the accepted fold survives // the failed compress into the NEXT turn's rebuild. @@ -279,11 +282,11 @@ test("#2777: a failed compress after an accepted overflow fold keeps the fold fo }); assert.equal(r2.status, 200); const f = forwards(); - assert.equal(f.length, 3, "next turn hits the upstream once more"); - assert.ok(f[2].includes(SUMMARY_TEXT), "next-turn rebuild retains the accepted summary"); - assert.ok(!f[2].includes("MARKER_1_"), "next-turn rebuild does not resurrect folded early history"); - assert.ok(f[2].includes("MARKER_11_"), "next-turn rebuild preserves the recent tail"); - assert.ok(f[2].length < f[0].length, "rebuild stays smaller than the rejected original"); + assert.equal(f.length, 4, "next turn hits the upstream once more"); + assert.ok(f[3].includes(SUMMARY_TEXT), "next-turn rebuild retains the accepted summary"); + assert.ok(!f[3].includes("MARKER_1_"), "next-turn rebuild does not resurrect folded early history"); + assert.ok(f[3].includes("MARKER_11_"), "next-turn rebuild preserves the recent tail"); + assert.ok(f[3].length < f[0].length, "rebuild stays smaller than the rejected original"); }); test("e2e #1195 C: when the folded retry is ALSO rejected, the client sees the RETRY's verdict, not the stale first 400 — and the arm stays for the next turn", async (t) => { diff --git a/tests/issue1502-raw-args-salvage.test.ts b/tests/issue1502-raw-args-salvage.test.ts index b1cfa66ccf..4fcdac0bee 100644 --- a/tests/issue1502-raw-args-salvage.test.ts +++ b/tests/issue1502-raw-args-salvage.test.ts @@ -206,10 +206,11 @@ test("#1502 loop: garbage args log head+tail and yield the corruption marker, no assert.doesNotMatch(output, /executing with \{\}/, "old degradation wording gone"); assert.match(output, /were not parseable JSON/, "corruption marker streamed to client"); assert.doesNotMatch(output, /carried no content at all/, "not mislabeled as empty"); - // #4186: a failed-only round ends the turn — the corruption receipt is - // surfaced to the client above and NO re-request carries the ephemeral - // failure frame upstream (old contract asserted refetches === 1). - assert.equal(refetches, 0, "failed-only compress round ends the turn without a re-request"); + // #4186→#5220: the corruption receipt is surfaced to the client above; + // the turn no longer ends there — ONE recovery-receipt re-request fires + // (this mock answers it with plain "ok" text). The ephemeral failure + // frame itself never rides that re-request upstream. + assert.equal(refetches, 1, "failed-only round re-requests once via recovery receipt (#5220)"); } finally { globalThis.fetch = originalFetch; } diff --git a/tests/issue5179-anthropic-early-stop-reason.test.ts b/tests/issue5179-anthropic-early-stop-reason.test.ts index 4376be851d..f121614bd5 100644 --- a/tests/issue5179-anthropic-early-stop-reason.test.ts +++ b/tests/issue5179-anthropic-early-stop-reason.test.ts @@ -6,11 +6,10 @@ import type { Session } from "../src/session.ts"; import { runCompressLoop, createAnthropicAdapter, MAX_LOOP_ROUNDS } from "../src/loop/index.ts"; import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; -// #5179: the loop ends a turn early in two places — a failed-only compress -// round (#156/#4186) and the round limit — both with finishReason "length", -// OpenAI's word. The Anthropic wire has no such stop reason, and Claude Code -// reads an unknown one as a plain end of turn, stopping the task mid-flight. -// The adapter must translate to "max_tokens", which Claude Code auto-resumes. +// #5179: early turn-ends emit finishReason "length" (OpenAI's word); the +// Anthropic wire has no such stop reason, and Claude Code reads an unknown one +// as a plain end of turn, stopping the task mid-flight. The adapter must +// translate to "max_tokens", which Claude Code auto-resumes. function sse(type: string, data: unknown): string { return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; @@ -78,11 +77,15 @@ function stopReasons(out: string): unknown[] { .map((e) => e.delta?.stop_reason); } -test("a failed-only compress round ends the Anthropic turn with stop_reason max_tokens, so Claude Code resumes", async () => { +// #5220 contract: the FIRST failed-only compress round feeds the model a +// recovery receipt and re-requests; this fixture resubmits the identical +// failing call on round 2, where the restored #156 signature breaker ends the +// turn — and whatever the reason, it arrives as "max_tokens", never "length". +test("a failed-only compress round that resubmits its failure ends the Anthropic turn with stop_reason max_tokens, so Claude Code resumes", async () => { const { out, reRequests } = await runAnthropicLoop( toolRound("compress", { content: [{ startId: "m00001", endId: "m00002", summary: "s" }] }), ); - assert.equal(reRequests, 0, "the #156/#4186 early end still holds: the failed frame never reaches upstream"); + assert.equal(reRequests, 1, "first-time failure re-requests once (recovery receipt, #5220); the identical round-2 resubmit trips the #156 signature breaker"); assert.ok(out.includes("❌"), "the failure receipt still reaches the client"); assert.deepEqual(stopReasons(out), ["max_tokens"]); }); diff --git a/tests/issue5220-failed-compress-receipt.test.ts b/tests/issue5220-failed-compress-receipt.test.ts new file mode 100644 index 0000000000..7da198c7cd --- /dev/null +++ b/tests/issue5220-failed-compress-receipt.test.ts @@ -0,0 +1,235 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { Config } from "acp-kernel"; +import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { runCompressLoop, createResponsesAdapter, failedCallSignature, MAX_LOOP_ROUNDS } from "../src/loop/index.ts"; +import { buildCompressSystemPrompt } from "../src/compress-tool.ts"; +import type { CoreMessage } from "acp-kernel"; + +// #5220: a failed compress/decompress call must NEVER end the user's turn. +// Old contract (#156/#4186): ANY failed-only mutating round broke early with a +// fabricated "length" finish — cache-clean (#1548) but fatal: no client on any +// wire auto-continues "length" (OpenAI: no such convention; Anthropic: not even +// a legal stop reason), so one bad compress killed a running task mid-work +// (#5220 field report; #5179 is the same family's Anthropic symptom). +// +// New contract under test here (Responses wire): +// 1. first-time failure → ONE re-request carrying a plain assistant recovery +// receipt whose bytes equal the ❌ marker already streamed to the client; +// this round's ephemeral tool frames are stripped first, so they never +// reach upstream (#1548/#4186 seam invariant preserved); +// 2. the model then DECIDES — this fixture ends the turn naturally; +// 3. resubmitting the identical failing call trips the restored #156 +// signature breaker (ping-pong → break); different args each round run to +// MAX_LOOP_ROUNDS (the #3302 probe family keeps working, bounded); +// 4. fallback: requests with visibility markers OFF have no client-visible +// bytes to anchor the receipt, so they keep the old contract (break with +// no re-request) — otherwise the receipt would be server-invisible bytes +// upstream, exactly the seam #4186 forbids. +// 5. failedCallSignature: argument order must not defeat repeat detection. + +function sse(type: string, data: unknown): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +function fcEvents(outputIndex: number, callId: string, name: string, args: string): string { + return [ + sse("response.output_item.added", { item: { type: "function_call", id: `fc_${callId}`, call_id: callId, name }, output_index: outputIndex }), + sse("response.function_call_arguments.delta", { item_id: `fc_${callId}`, delta: args }), + sse("response.output_item.done", { item: { type: "function_call", id: `fc_${callId}`, call_id: callId, name, arguments: args }, output_index: outputIndex }), + ].join(""); +} + +const COMPLETED = sse("response.completed", { response: { id: "resp_done", status: "completed", output: [] } }); + +const SYS_PROMPT = buildCompressSystemPrompt(); + +function makeCtx(messages: CoreMessage[] = []): { + core: ReturnType; + config: Config; + messages: CoreMessage[]; + session: Session; + log: (m: string) => void; + visibilityMarkers?: boolean; +} { + return { + core: createCore(), + config: defaultConfig(200000), + messages, + session: { + id: "issue5220-test", + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, contextTokens: 0 , compressCreditTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + pendingRetrievals: [], + metadata: {}, + state: createInitialState(), + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + }, + log: () => {}, + }; +} + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function withRefs(ctx: ReturnType): ReturnType { + const res = assignRefs(ctx.messages, { existing: emptyRefMap(), nextIndex: 0 }); + ctx.session.state.messageRefs = res.map; + return ctx; +} + +async function drain( + stream: ReadableStream, + ctx: ReturnType, + requestBody: Record, + requestOptions: { url: string; headers: Record }, +): Promise { + const chunks: Buffer[] = []; + for await (const chunk of runCompressLoop(stream, ctx, requestBody, requestOptions, createResponsesAdapter(), SYS_PROMPT)) { + chunks.push(chunk); + } + return Buffer.concat(chunks).toString("utf8"); +} + +// A round where the model answers plain text and completes naturally — what +// round 2 looks like once the recovery receipt has told the model what failed. +const NATURAL_END_ROUND = [ + sse("response.created", { response: { id: "resp_2", status: "in_progress" } }), + sse("response.output_item.added", { item: { type: "message", id: "msg_2", role: "assistant", status: "in_progress", content: [] }, output_index: 0 }), + sse("response.content_part.added", { item_id: "msg_2", output_index: 0, content_index: 0, part: { type: "output_text", text: "" } }), + sse("response.output_text.delta", { item_id: "msg_2", output_index: 0, content_index: 0, delta: "DONE-NATURAL-5220" }), + sse("response.output_text.done", { item_id: "msg_2", output_index: 0, text: "DONE-NATURAL-5220" }), + sse("response.output_item.done", { item: { type: "message", id: "msg_2", role: "assistant", status: "completed", content: [{ type: "output_text", text: "DONE-NATURAL-5220" }] }, output_index: 0 }), + COMPLETED, +].join(""); + +// A failed-only compress round. seq=constant → every round resubmits the SAME +// failing call (T3, signature breaker); seq=round number → a fresh signature +// each round (T4, probe family). Invalid refs guarantee applyRanges FAILED. +function failingRound(seq: number): string { + return [ + sse("response.created", { response: { id: `resp_${seq}`, status: "in_progress" } }), + fcEvents(0, `call_seq${seq}`, "compress", JSON.stringify({ content: [{ startId: "b99", endId: "b99", summary: `${seq}${"x".repeat(50)}` }] })), + COMPLETED, + ].join(""); +} + +test("#5220 failedCallSignature: key order normalized, unknown names kept, raw fallback on bad JSON", () => { + const a = failedCallSignature("compress", JSON.stringify({ startId: "m001", endId: "m002", summary: "s" })); + const b = failedCallSignature("compress", JSON.stringify({ summary: "s", endId: "m002", startId: "m001" })); + assert.equal(a, b, "argument key order does not defeat repeat detection"); + assert.notEqual(failedCallSignature("decompress", JSON.stringify({ x: 1 })), a, "tool name is part of the signature"); + const raw = "{not json"; + assert.equal(failedCallSignature("compress", raw), `compress:${raw}`, "unparseable arguments fall back to byte equality"); +}); + +test("#5220 T1: first-time failed compress → exactly one recovery-receipt re-request; the model decides (natural end)", async () => { + let n = 0; + const bodies: string[] = []; + const orig = globalThis.fetch; + globalThis.fetch = (async (_u: unknown, init?: RequestInit) => { + n++; + if (init?.body) bodies.push(String(init.body)); + return new Response(NATURAL_END_ROUND, { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + try { + const ctx = withRefs(makeCtx([ + textMsg("u1", "user", "do the task"), + textMsg("a1", "assistant", "working on it"), + ])); + // invalid refs → applyRanges returns FAILED, no block created + const round1 = [ + sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), + fcEvents(0, "call_c5220", "compress", JSON.stringify({ content: [{ startId: "b99", endId: "b99", summary: "x".repeat(60) }] })), + COMPLETED, + ].join(""); + const out = await drain( + new Response(round1, { status: 200 }).body!, + ctx, + { model: "gpt-4o", input: [], stream: true }, + { url: "http://mock", headers: {} }, + ); + assert.equal(n, 1, "first-time failure re-requests ONCE — no fabricated length end, no runaway loop"); + assert.ok(out.includes("❌"), "failure marker still streamed to the client"); + assert.ok(out.includes("DONE-NATURAL-5220"), "the MODEL's natural end-of-turn reached the client (the turn was NOT killed)"); + const body = bodies[0]!; + assert.ok(body.includes("❌"), "retry body carries the recovery receipt as assistant text"); + assert.ok(!body.includes("function_call"), "this round's failed tool-call frame stays off the wire (#1548/#4186)"); + assert.ok(!body.includes("call_c5220"), "no call id from the stripped frames rides upstream"); + assert.ok(!body.includes("\"b99\""), "failing arguments ride upstream only inside the receiptless frame we stripped"); + } finally { + globalThis.fetch = orig; + } +}); + +test("#5220 T3: identical failing call resubmitted → #156 signature breaker stops at round 2", async () => { + let n = 0; + const orig = globalThis.fetch; + globalThis.fetch = (async () => { + n++; + return new Response(failingRound(0), { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + try { + const ctx = withRefs(makeCtx([textMsg("u1", "user", "task")])); + const out = await drain( + new Response(failingRound(0), { status: 200 }).body!, + ctx, + { model: "gpt-4o", input: [], stream: true }, + { url: "http://mock", headers: {} }, + ); + assert.equal(n, 1, "round 2 repeats the EXACT failing signature → breaker ends the turn after one re-request"); + assert.ok(/event: response\.completed/.test(out), "graceful completion (not degenerate empty)"); + assert.ok(out.includes("❌"), "receipt surfaced"); + } finally { + globalThis.fetch = orig; + } +}); + +test("#5220 T4: DIFFERENT failing args every round → no breaker, runs to MAX_LOOP_ROUNDS (probe family survives, bounded)", async () => { + let n = 0; + const orig = globalThis.fetch; + globalThis.fetch = (async () => { + n++; + return new Response(failingRound(n), { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + try { + const ctx = withRefs(makeCtx([textMsg("u1", "user", "task")])); + const out = await drain( + new Response(failingRound(0), { status: 200 }).body!, + ctx, + { model: "gpt-4o", input: [], stream: true }, + { url: "http://mock", headers: {} }, + ); + assert.equal(n, MAX_LOOP_ROUNDS - 1, "every round carries a first-seen signature; only the round limit bounds the turn"); + assert.ok(/event: response\.completed/.test(out), "graceful completion at the limit (not degenerate empty)"); + } finally { + globalThis.fetch = orig; + } +}); + +test("#5220 T5 fallback: visibilityMarkers=false keeps the old contract — break, zero re-requests (no client-visible bytes to anchor the receipt)", async () => { + let n = 0; + const orig = globalThis.fetch; + globalThis.fetch = (async () => { n++; return new Response(COMPLETED, { status: 200, headers: { "content-type": "text/event-stream" } }); }) as typeof fetch; + try { + const ctx = withRefs(makeCtx([textMsg("u1", "user", "task")])); + ctx.visibilityMarkers = false; + const out = await drain( + new Response(failingRound(0), { status: 200 }).body!, + ctx, + { model: "gpt-4o", input: [], stream: true }, + { url: "http://mock", headers: {} }, + ); + assert.equal(n, 0, "markers off → the receipt would be server-invisible bytes upstream (#4186 seam) → old break contract"); + assert.ok(!out.includes("❌"), "no marker was ever surfaced in this mode"); + assert.ok(/event: response\.completed/.test(out), "graceful completion present"); + } finally { + globalThis.fetch = orig; + } +}); diff --git a/tests/loop-compress.test.ts b/tests/loop-compress.test.ts index 2ef8abf27a..9920f4fa5c 100644 --- a/tests/loop-compress.test.ts +++ b/tests/loop-compress.test.ts @@ -112,8 +112,9 @@ function reFetchProbe(): { calls: () => number; bodies: () => string[]; restore: test("loop #3: proxy-tool round → re-request fires (model continues with result), marker shown", async () => { // acp_status drives the re-request deterministically: a bare-session - // compress fails kernel validation and ends the turn under the failed-only - // breaker (#156/#4186), which would un-test this path. + // compress fails kernel validation and enters the #5220 recovery-receipt + // path (receipt re-request with stripped frames), which would muddy this + // plain re-request assertion. const round1 = [ sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), fcEvents(0, "call_s", "acp_status", "{}"), @@ -608,12 +609,14 @@ test("loop #422a: successful compress → re-request carries the refreshed fold } }); -// Scope guard: a FAILED compress changes no state — no refresh. Under the -// failed-only breaker (#156/#4186) such a round ends the turn before any -// re-request: the ephemeral failure frame never reaches upstream (it would -// vanish from the next client request — an unsanctioned mid-history seam), -// and the ❌ receipt streamed to the client carries the reason forward. -test("loop #422b: failed compress → no fold refresh, no re-request (turn ends, receipt surfaced)", async () => { +// Scope guard: a FAILED compress changes no state — no refresh (#422b scope +// unchanged). #5220 contract: such a round no longer ends the turn — the retry +// body carries ONE plain assistant recovery receipt whose bytes equal the ❌ +// marker already streamed to the client; this round's ephemeral tool frames +// are stripped first so they never reach upstream (#1548/#4186 seam). The +// fixture resubmits the identical failing call on round 2 → the #156 +// signature breaker stops exactly one re-request. +test("loop #422b/#5220: failed compress → no fold refresh; recovery-receipt re-request; identical resubmit breaks", async () => { const ctx = withRefs( makeCtx([ textMsg("m00001", "user", "hello"), @@ -628,8 +631,10 @@ test("loop #422b: failed compress → no fold refresh, no re-request (turn ends, COMPLETED, ].join(""); const probe = reFetchProbe(); + let refreshCalls = 0; try { ctx.refreshFolded = () => { + refreshCalls++; throw new Error("refreshFolded must NOT be called for a failed compress"); }; const out = await drain( @@ -638,7 +643,12 @@ test("loop #422b: failed compress → no fold refresh, no re-request (turn ends, { model: "gpt-4o", input: [], stream: true }, { url: "http://mock", headers: {} }, ); - assert.equal(probe.calls(), 0, "failed-only round breaks before any re-request — the failure frame never reaches upstream (#4186)"); + assert.equal(refreshCalls, 0, "no fold refresh for a failed compress"); + assert.equal(probe.calls(), 1, "recovery-receipt re-request fired once; the identical round-2 resubmit hits the #156 signature breaker"); + const body = probe.bodies()[0]!; + assert.ok(body.includes("❌") && body.includes("FAILED"), "retry body carries the recovery receipt as assistant text"); + assert.ok(!body.includes("function_call") && !body.includes("call_id"), "ephemeral failed frames stay off the wire (#1548/#4186) — receipt only"); + assert.ok(!body.includes(compressArgs), "the failing arguments did NOT ride upstream inside an ephemeral frame (receipt carries marker text only)"); assert.ok(out.includes("Compression FAILED"), "failure receipt surfaced to the client so the reason survives the turn"); assert.ok(/event: response\.completed/.test(out), "graceful completion (not degenerate empty)"); } finally { diff --git a/tests/loop-core.test.ts b/tests/loop-core.test.ts index 1d56d9fc41..e8bc5679d4 100644 --- a/tests/loop-core.test.ts +++ b/tests/loop-core.test.ts @@ -264,22 +264,30 @@ test("loop #5: limit-hit graceful — 10 re-request rounds never degenerate empt } }); -// #156/#4186: a failed-only mutating round completes immediately. The failed -// frames are ephemeral (#1548): never persisted, never seen by the client. -// Re-requesting after them lets the frames reach upstream once and then vanish -// from the next client request — an unsanctioned mid-history rewrite of the -// provider's frozen prefix (the seam #4186 measured in 7/17 fuzz seeds). -// Breaking on the FIRST failed-only round keeps them off the wire entirely; -// the streamed ❌ receipt carries the reason into the client's next turn. -test("loop #156/#4186: failed-only compress round → completes after round 1 with ZERO re-requests", async () => { +// #5220 (history #156/#4186): a failed-only mutating round NO LONGER ends the +// turn. The failure is fed back to the model as a plain assistant recovery +// receipt — bytes identical to the ❌ marker already streamed to the client — +// so the model decides what to do next instead of a fabricated "length" +// finish silently killing a running task (no client on any wire auto- +// continues "length"). The retry body must NOT carry this round's ephemeral +// tool frames (#1548/#4186 seam): receipt only. Bounded by the restored #156 +// narrow breaker: re-submitting the IDENTICAL failing call (same signature) +// is pure ping-pong and still breaks — that is exactly what this fixture +// produces on round 2, so it runs ONE re-request then completes. +test("loop #5220: failed-only compress round → recovery-receipt re-request, identical resubmit breaks", async () => { const failingRound = [ sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), fcEvents(0, "call_c", "compress", JSON.stringify({ content: [{ startId: "m00001", endId: "m00002", summary: "s" }] })), COMPLETED, ].join(""); let fetchCalls = 0; + const bodies: string[] = []; const orig = globalThis.fetch; - globalThis.fetch = (async () => { fetchCalls++; return new Response(failingRound, { status: 200 }); }) as typeof fetch; + globalThis.fetch = (async (_url: string, init?: RequestInit) => { + fetchCalls++; + if (init?.body !== undefined) bodies.push(String(init.body)); + return new Response(failingRound, { status: 200 }); + }) as typeof fetch; try { const out = await drain( new Response(failingRound, { status: 200 }).body!, @@ -287,9 +295,12 @@ test("loop #156/#4186: failed-only compress round → completes after round 1 wi { model: "gpt-4o", input: [], stream: true }, { url: "http://mock", headers: {} }, ); - assert.equal(fetchCalls, 0, "the failed frame NEVER reached upstream — no re-request was sent at all"); + assert.equal(fetchCalls, 1, "first-time failure re-requests ONCE (recovery receipt); the identical round-2 resubmit hits the #156 signature breaker"); assert.ok(/response\.completed/.test(out), "graceful completion present (not degenerate empty)"); assert.ok(out.includes("❌"), "failure receipt surfaced to the client so the reason survives the turn"); + const body = bodies[0]!; + assert.ok(body.includes("❌"), "retry body carries the recovery receipt as assistant text"); + assert.ok(!body.includes("function_call") && !body.includes("call_c"), "ephemeral failed frames stay off the wire (#1548/#4186) — receipt only"); } finally { globalThis.fetch = orig; } From ce27617cac7d6409e9d8f7446626944ccb550fb1 Mon Sep 17 00:00:00 2001 From: ci-sync Date: Fri, 30 Oct 2026 22:44:30 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(test):=20pin=20the=20#5140=20cold-resto?= =?UTF-8?q?re=20snapshot=20test=20to=20unified-full=20=E2=80=94=20under=20?= =?UTF-8?q?the=20global=20legacy=20test=20baseline=20its=20sidecar=20never?= =?UTF-8?q?=20opens=20and=20the=20index=20reconstruction=20gate=20can=20ne?= =?UTF-8?q?ver=20pass?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/plugin-fork.test.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 96d9dfeb0f..f07ad30158 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -1477,6 +1477,12 @@ test("HTTP a mid-history rewrite replaces the snapshot wholesale with an exact b }); test("HTTP a cold-restored non-retained parent serves its intact raw tail immediately (#5140)", { timeout: 60_000 }, async () => { + // The reconstruction path reads the unified index, so this test must run + // under unified-full — the global test baseline pins BILI_STORAGE_UNIFIED= + // "legacy" for non-storage suites, under which the sidecar never opens and + // replicasAvailable() is structurally false (a bare sidecar-missing 409). + const oldMode = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "full"; const h = await harness(true); try { const parent = resolveConversation("parent").session!; @@ -1495,7 +1501,10 @@ test("HTTP a cold-restored non-retained parent serves its intact raw tail immedi await sendModel(h, "parent", h.messages); assert.equal((await h.request("/__bili/plugin/snapshot?conversationId=parent")).status, 200); assert.equal(resolveConversation("parent").session!.pluginSnapshot!.length, 3); - } finally { await h.close(); } + } finally { + await h.close(); + if (oldMode === undefined) delete process.env.BILI_STORAGE_UNIFIED; else process.env.BILI_STORAGE_UNIFIED = oldMode; + } }); test("fork protocol v2: snapshot serves the light revision, a stale v1 whole-store revision is still accepted (#2671 Phase 2b)", { timeout: 60_000 }, async () => { From b5f2e2132f3d3fac7cb47ac26b253c5126b701fd Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 31 Oct 2026 02:06:00 +0800 Subject: [PATCH 4/4] fix(loop): a deduped failed-only round must not push an empty receipt upstream (#5220 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the #5220 receipt-retry path found one degenerate state: when EVERY failure marker of a failed-only round was already streamed in an earlier round (seenMarkers dedup — identical failure text, different args, e.g. two equal-size ranges both failing "Total compressible content too small"), streamedMarkers is empty and the code pushed a zero-byte assistant message into the re-request body. On strict wires (Anthropic) an empty text block is an illegal frame; on every wire it is a meaningless zero-byte turn. Reproduced deterministically: session with two 4-char messages, compress m00001..m00001 then m00003..m00003 → round-2 marker deduped → empty assistant item observed in the second re-request body. Skip the receipt push when there are no new marker bytes: the body degrades to history + this round's prose, stays cache-clean (nothing server-invisible rides upstream), and the restored signature breaker / MAX_LOOP_ROUNDS bound any resulting ping-pong. Tests: T6 in tests/issue5220-failed-compress-receipt.test.ts pins the edge (negative control verified — fails on the pre-fix head with exactly the zero-byte assertion); new threads-continue fallback test in tests/issue5179-anthropic-early-stop-reason.test.ts covers the last untested receiptable-guard branch (break without re-request, still max_tokens). --- src/loop/core.ts | 14 +++- ...ue5179-anthropic-early-stop-reason.test.ts | 31 ++++++++ .../issue5220-failed-compress-receipt.test.ts | 75 +++++++++++++++++++ 3 files changed, 118 insertions(+), 2 deletions(-) diff --git a/src/loop/core.ts b/src/loop/core.ts index d9bc4af146..c1279f39a2 100644 --- a/src/loop/core.ts +++ b/src/loop/core.ts @@ -1581,8 +1581,18 @@ export async function* runCompressLoop( dropIds.add(`acp_loop_r${round}_tool_${pr.callId}`); } coreMessages.splice(0, coreMessages.length, ...coreMessages.filter((m) => !dropIds.has(m.id))); - ctx.log(`[acp-loop] round ${round}: failed-only mutating round; feeding the model a recovery receipt (${streamedMarkers.length} marker line(s)) and re-requesting (#5220)`); - coreMessages.push({ id: `acp_loop_r${round}_rcpt`, role: "assistant", contentType: "text", text: streamedMarkers.join("") }); + if (streamedMarkers.length > 0) { + ctx.log(`[acp-loop] round ${round}: failed-only mutating round; feeding the model a recovery receipt (${streamedMarkers.length} marker line(s)) and re-requesting (#5220)`); + coreMessages.push({ id: `acp_loop_r${round}_rcpt`, role: "assistant", contentType: "text", text: streamedMarkers.join("") }); + } else { + // Every failure marker of this round was deduped against an + // earlier round — the client saw nothing new, so a receipt + // would be a zero-byte assistant frame (strict wires reject + // empty text blocks). Skip it: the body degrades to history + + // prose, stays cache-clean, and the signature breaker / + // MAX_LOOP_ROUNDS bound any resulting ping-pong. + ctx.log(`[acp-loop] round ${round}: failed-only mutating round; all markers deduped (nothing new reached the client), re-requesting without a receipt (#5220)`); + } } ctx.log(`[acp-loop] round ${round}: proxy tool executed; re-requesting so the model sees the result`); diff --git a/tests/issue5179-anthropic-early-stop-reason.test.ts b/tests/issue5179-anthropic-early-stop-reason.test.ts index f121614bd5..0baad11e62 100644 --- a/tests/issue5179-anthropic-early-stop-reason.test.ts +++ b/tests/issue5179-anthropic-early-stop-reason.test.ts @@ -96,6 +96,37 @@ test("the round limit ends the Anthropic turn with stop_reason max_tokens", asyn assert.deepEqual(stopReasons(out), ["max_tokens"]); }); +// #5220 guard-branch: on a threads-continue turn the server-side thread delta +// structurally excludes visibility markers (client-side noise, #2701), so a +// receipt could never ride it — such turns keep the old break contract, and +// the break still arrives as max_tokens. +test("a failed-only compress round on a threads-continue turn breaks WITHOUT re-requesting, ending max_tokens", async () => { + const body = { model: "claude-opus-5-5", stream: true, messages: [{ role: "user", content: "go on" }], thread: { type: "continue" } }; + let reRequests = 0; + const orig = globalThis.fetch; + globalThis.fetch = (async () => { reRequests++; return new Response(toolRound("compress", {}), { status: 200, headers: { "content-type": "text/event-stream" } }); }) as typeof fetch; + let out = ""; + try { + const ctx = { + core: createCore(), + config: { modelContextLimit: 200000 } as Config, + messages: [], + session: makeSession(), + log: () => {}, + protocol: "anthropic" as const, + }; + const round = toolRound("compress", { content: [{ startId: "m00001", endId: "m00002", summary: "s" }] }); + for await (const c of runCompressLoop(new Response(round, { status: 200 }).body!, ctx, body, { url: "http://mock", headers: {} }, createAnthropicAdapter(body), buildCompressSystemPrompt())) { + out += c.toString("utf8"); + } + } finally { + globalThis.fetch = orig; + } + assert.equal(reRequests, 0, "threads-delta cannot carry the receipt → old break contract, zero re-requests"); + assert.ok(out.includes("❌"), "the failure receipt still reaches the client"); + assert.deepEqual(stopReasons(out), ["max_tokens"]); +}); + test("upstream's own stop reasons reach the client unchanged", () => { for (const reason of ["end_turn", "tool_use", "max_tokens", "stop_sequence", "pause_turn", "refusal", "model_context_window_exceeded", "a_future_reason"]) { const frame = createAnthropicAdapter({ model: "claude-opus-5-5" }).emitCompletion({ finishReason: reason }).toString("utf8"); diff --git a/tests/issue5220-failed-compress-receipt.test.ts b/tests/issue5220-failed-compress-receipt.test.ts index 7da198c7cd..68ff2cccf2 100644 --- a/tests/issue5220-failed-compress-receipt.test.ts +++ b/tests/issue5220-failed-compress-receipt.test.ts @@ -28,6 +28,11 @@ import type { CoreMessage } from "acp-kernel"; // no re-request) — otherwise the receipt would be server-invisible bytes // upstream, exactly the seam #4186 forbids. // 5. failedCallSignature: argument order must not defeat repeat detection. +// 6. deduped-marker edge: when EVERY failure marker of a failed-only round was +// already streamed in an earlier round (identical failure text, different +// args), the receipt would be a zero-byte assistant message — strict wires +// reject empty text blocks, so the re-request goes out WITHOUT a receipt +// instead (still cache-clean; bounded by breaker / MAX_LOOP_ROUNDS). function sse(type: string, data: unknown): string { return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; @@ -233,3 +238,73 @@ test("#5220 T5 fallback: visibilityMarkers=false keeps the old contract — brea globalThis.fetch = orig; } }); + +function partText(p: unknown): string { + if (typeof p === "object" && p !== null && "text" in p) { + const t = (p as { text: unknown }).text; + return typeof t === "string" ? t : ""; + } + return ""; +} + +function assistantTexts(body: string): string[] { + const parsed = JSON.parse(body) as { input?: Array<{ type?: string; role?: string; content?: unknown }> }; + return (parsed.input ?? []) + .filter((it) => it.type === "message" && it.role === "assistant") + .map((it) => { + const c = it.content; + if (Array.isArray(c)) return c.map(partText).join(""); + return typeof c === "string" ? c : ""; + }); +} + +// m00001 ("task") and m00003 ("done") are both 4 chars, so compressing either +// alone fails with byte-identical text ("Total compressible content too small +// (4 chars across 1 range(s)…)") while carrying DIFFERENT signatures (different +// refs + summaries). Round 2's marker is therefore deduped against round 1's — +// exactly the shape where the receipt would be empty. +test("#5220 T6: deduped markers → re-request WITHOUT an empty assistant frame (strict wires reject zero-byte turns)", async () => { + let n = 0; + const bodies: string[] = []; + const orig = globalThis.fetch; + // round 2: same-size single-ref range (m00003), different summary → fresh + // signature, byte-identical failure text → marker deduped, receipt empty. + const round2 = [ + sse("response.created", { response: { id: "resp_2f", status: "in_progress" } }), + fcEvents(0, "call_r2", "compress", JSON.stringify({ content: [{ startId: "m00003", endId: "m00003", summary: "2".padEnd(51, "x") }] })), + COMPLETED, + ].join(""); + globalThis.fetch = (async (_u: unknown, init?: RequestInit) => { + n++; + if (init?.body) bodies.push(String(init.body)); + return new Response(n === 1 ? round2 : NATURAL_END_ROUND, { status: 200, headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + try { + const ctx = withRefs(makeCtx([ + textMsg("u1", "user", "task"), + textMsg("a1", "assistant", "ok working"), + textMsg("u2", "user", "done"), + ])); + const round1 = [ + sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), + fcEvents(0, "call_r1", "compress", JSON.stringify({ content: [{ startId: "m00001", endId: "m00001", summary: "1".padEnd(51, "x") }] })), + COMPLETED, + ].join(""); + const out = await drain( + new Response(round1, { status: 200 }).body!, + ctx, + { model: "gpt-4o", input: [], stream: true }, + { url: "http://mock", headers: {} }, + ); + assert.equal(n, 2, "round 2's failure has a fresh signature → not stuck → re-requested again; round 3 ends naturally"); + assert.ok(out.includes("DONE-NATURAL-5220"), "the turn survived the deduped-failure round"); + const r1Texts = assistantTexts(bodies[0]!); + assert.ok(r1Texts.some((t) => t.includes("❌")), "round 1's receipt still rides upstream (stable prefix)"); + for (let i = 0; i < bodies.length; i++) { + const texts = assistantTexts(bodies[i]!); + assert.ok(!texts.some((t) => t.trim().length === 0), `re-request ${i + 1}: no zero-byte assistant frame rides upstream (empty text blocks are illegal on strict wires)`); + } + } finally { + globalThis.fetch = orig; + } +});