From 97039e8df10e423ae7cb8b12e6290fb7c58cbf4e Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 5 Oct 2026 13:16:39 +0800 Subject: [PATCH 1/2] fix: cross-spec compress-failure circuit breaker + stale-generation diagnosis (#2146) --- src/preflight.ts | 3 +- src/stream.ts | 112 ++++++++++++- tests/issue2146-compress-loop-breaker.test.ts | 151 ++++++++++++++++++ .../issue847-compress-failure-guards.test.ts | 5 +- 4 files changed, 262 insertions(+), 9 deletions(-) create mode 100644 tests/issue2146-compress-loop-breaker.test.ts diff --git a/src/preflight.ts b/src/preflight.ts index ef3c501d5b..01f5d54c1f 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -1372,7 +1372,8 @@ export async function preflightCompress(deps: PreflightDeps, messages: CoreMessa log: (msg) => deps.log("info", msg), }; const creditBefore = deps.session.stats.compressCreditTokens; - const applied = applyRanges(parseCompressInput({ content: [{ startId: startRef, endId: endRef, summary, topic: "preflight overflow compress" }] }), ctx); + // #2146: internal lane — must not arm the model-facing loop breaker. + const applied = applyRanges(parseCompressInput({ content: [{ startId: startRef, endId: endRef, summary, topic: "preflight overflow compress" }] }), ctx, { loopTracking: false }); if (applied.outcome === "refused") { deps.log("warn", `[preflight] ${applied.text}`); noteSkip(`${skipKey}: apply failed — ${safePrefix(applied.text.replace(/^\[Compression FAILED[:\s]*/, ""), 200)}`); diff --git a/src/stream.ts b/src/stream.ts index 1a41b6488d..0907b562e0 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -171,6 +171,86 @@ function clearCompressFailures(session: Session): void { } } +// #2146: the exact-spec repeat guard above is defeated by a model that walks +// spec space — one fresh (also failing) range per call. In the incident, +// glm-5.3-flash burned 2h42m on 161 DISTINCT failing specs after a client +// restart left stale-generation refs in its persisted history, never calling +// acp_status despite every receipt asking it to; the #1026/#1029 hints were +// in the receipts and were ignored. A session-level streak of consecutive +// TOTAL failures (any spec) catches that shape: at N failures the receipt +// switches from diagnostic hints to a hard-stop instruction. Hardcoded by +// design (config-surface discipline, cf. DEGENERATE_FOLD_COVERAGE). Disarm is +// success or 10 min of quiet — refs keep advancing DURING the loop (each +// failed round appends messages), so a frontier-based decay would disarm +// mid-loop and be defeated the same way. +const COMPRESS_LOOP_KEY = "compressFailStreak"; +const COMPRESS_LOOP_THRESHOLD = 3; +const COMPRESS_LOOP_DECAY_MS = 10 * 60 * 1000; + +type CompressLoopStreak = { n: number; lastAt: number }; + +function readCompressLoopStreak(session: Session): CompressLoopStreak | undefined { + const v = session.metadata[COMPRESS_LOOP_KEY]; + if (!v || typeof v !== "object") return undefined; + const o = v as Record; + if (typeof o["n"] !== "number" || !Number.isFinite(o["n"]) || typeof o["lastAt"] !== "number") return undefined; + return { n: Math.max(0, Math.floor(o["n"] as number)), lastAt: o["lastAt"] as number }; +} + +function writeCompressLoopStreak(session: Session, s: CompressLoopStreak | undefined): void { + if (s === undefined) delete session.metadata[COMPRESS_LOOP_KEY]; + else session.metadata[COMPRESS_LOOP_KEY] = s; + markDirty(session); +} + +/** #2146: record one total compress failure (any spec) and return "" while + * healthy, or the circuit-breaker paragraph to embed in the receipt once the + * streak arms. The breaker NEVER refuses execution — it only changes what a + * FAILED call tells the model, so a legitimate call can always still succeed + * and reset the streak via clearCompressLoopStreak. */ +export function noteCompressLoopFailure(ctx: RewriteCtx, specLabel: string): string { + const now = Date.now(); + let streak = readCompressLoopStreak(ctx.session); + if (streak && now - streak.lastAt > COMPRESS_LOOP_DECAY_MS) streak = undefined; + const n = (streak?.n ?? 0) + 1; + writeCompressLoopStreak(ctx.session, { n, lastAt: now }); + if (n < COMPRESS_LOOP_THRESHOLD) return ""; + const label = specLabel || "unparseable call"; + if (n === COMPRESS_LOOP_THRESHOLD) { + ctx.log(`[warn: compress-loop] circuit breaker armed after ${n} consecutive compress failures (last spec: ${label}) — receipts now demand a full stop; disarms on success or ${COMPRESS_LOOP_DECAY_MS / 60000} min quiet`); + } else { + ctx.log(`[warn: compress-loop] failure ${n} in armed streak (last spec: ${label})`); + } + return ` [COMPRESS CIRCUIT BREAKER: ${n} consecutive compress failures in this session — every attempt has failed and further attempts will keep failing. STOP calling compress now: do not try other ranges, do not re-issue any previous range, and do not poll acp_status. Continue your actual task without compressing — compression happens again only when there is genuinely new content to fold.]`; +} + +export function clearCompressLoopStreak(session: Session): void { + if (readCompressLoopStreak(session)) writeCompressLoopStreak(session, undefined); +} + +/** #2146: every requested endpoint sits strictly ABOVE the session's highest + * mapped m-ref. Such refs cannot exist in this session (refs are never + * pre-allocated), so the kernel's generic "typo or wrong session" wording + * misleads models into hunting for the typo and re-anchoring on other stale + * artifacts. The deterministic cause is stale-generation refs baked into the + * client's persisted history — name it instead. */ +export function beyondFrontierNote(state: Pick, ranges: Array<{ startRef: string; endRef: string }>): string { + let highest = 0; + for (const ref of Object.keys(state.messageRefs?.byRef ?? {})) { + const m = M_REF_NUM_RE.exec(ref); + if (m) highest = Math.max(highest, Number(m[1])); + } + if (highest <= 0 || ranges.length === 0) return ""; + const allAbove = ranges.every((r) => { + const s = M_REF_NUM_RE.exec(r.startRef.trim()); + const e = M_REF_NUM_RE.exec(r.endRef.trim()); + return !!s && !!e && Number(s[1]) > highest && Number(e[1]) > highest; + }); + if (!allAbove) return ""; + const hi = `m${String(highest).padStart(5, "0")}`; + return ` All requested refs are above this session's highest ref (${hi}) — they cannot exist here (this session allocates no future refs). They are stale artifacts from an earlier session generation left in your visible history; NO superset of them can ever compress. Request only refs ≤ ${hi}, or call acp_status for the live ranges.`; +} + // #1029: after a session-generation change (client restart/fork starts a fresh // session instance whose refs restart at m00001), stale refs from the previous // generation fail resolution. The kernel gate points at acp_status; inline the @@ -310,7 +390,11 @@ function applyErrorNote(r: { errors: string[] }): string { // hosts that want to penalize this shape grep the warn marker below. const DEGENERATE_FOLD_COVERAGE = 0.8; -export function applyRanges(parsed: ReturnType, ctx: RewriteCtx): ProxyToolResult { +export function applyRanges(parsed: ReturnType, ctx: RewriteCtx, opts?: { loopTracking?: boolean }): ProxyToolResult { + // #2146: preflight overflow-compress is bili's OWN internal lane — its + // failures have separate reporting (noteSkip) and must not arm the + // model-facing circuit breaker on attempts the model never made. + const trackLoop = opts?.loopTracking !== false; const { ranges, diagnostics } = parsed; if (ranges.length === 0) { ctx.log("[acp-proxy: compress call had no valid ranges; nothing compressed.]"); @@ -344,23 +428,25 @@ export function applyRanges(parsed: ReturnType, ctx: !isEmptyCall && argLen !== undefined && (diagnostics.kind === "malformed-json" || diagnostics.kind === "truncated"); + const parseKey = `parse:${diagnostics.kind}:${diagnostics.invalidItems}:${rawReasons.slice(0, 3).join("|")}`; const guard = recordCompressFailure( ctx.session, - `parse:${diagnostics.kind}:${diagnostics.invalidItems}:${rawReasons.slice(0, 3).join("|")}`, + parseKey, isEmptyCall ? "An empty call fails identically on every retry — drop it instead of re-issuing." : argCorruption ? "Do not retry the same corrupt byte string — re-issue the call as one well-formed JSON object." : "Fix the argument shape against the format below instead of re-issuing the same malformed call.", ); + const loopGuard = trackLoop ? noteCompressLoopFailure(ctx, parseKey) : ""; if (isEmptyCall) { - return compressResult(`[Compression FAILED: the call carried no content at all (kind=${diagnostics.kind}) — an empty compress() compresses nothing and can never succeed. Do NOT re-issue an empty call; if you meant to compress, put the non-empty 'content' array (elements {startId, endId, summary}) in that SAME single call.${guard}]`, "refused", 0); + return compressResult(`[Compression FAILED: the call carried no content at all (kind=${diagnostics.kind}) — an empty compress() compresses nothing and can never succeed. Do NOT re-issue an empty call; if you meant to compress, put the non-empty 'content' array (elements {startId, endId, summary}) in that SAME single call.${guard}${loopGuard}]`, "refused", 0); } if (argCorruption) { const truncNote = diagnostics.kind === "truncated" ? " (looks truncated)" : ""; - return compressResult(`[Compression FAILED: the call's arguments (${argLen} chars) were not parseable JSON${truncNote} — the intended content was lost and nothing was compressed. Re-issue the compress call as well-formed JSON: a single object with a non-empty 'content' array of {startId, endId, summary} elements.${guard}]`, "refused", 0); + return compressResult(`[Compression FAILED: the call's arguments (${argLen} chars) were not parseable JSON${truncNote} — the intended content was lost and nothing was compressed. Re-issue the compress call as well-formed JSON: a single object with a non-empty 'content' array of {startId, endId, summary} elements.${guard}${loopGuard}]`, "refused", 0); } - return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why} compress requires a non-empty 'content' array where each element is EITHER an object {startId, endId, summary} OR one line-form string whose first line is 'mNNNNN–mNNNNN optional topic' with the summary markdown on the following lines (a separate summary-only element right after a bare header line is also accepted). startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${compressibleSpanHint(ctx.session.state)} Re-issue the compress call with a valid content array.${guard}]`, "refused", 0); + return compressResult(`[Compression FAILED: no valid ranges parsed (kind=${diagnostics.kind}, dropped=${diagnostics.invalidItems}).${why} compress requires a non-empty 'content' array where each element is EITHER an object {startId, endId, summary} OR one line-form string whose first line is 'mNNNNN–mNNNNN optional topic' with the summary markdown on the following lines (a separate summary-only element right after a bare header line is also accepted). startId/endId are mNNNNN message refs from the conversation (call acp_status to see current refs).${compressibleSpanHint(ctx.session.state)} Re-issue the compress call with a valid content array.${guard}${loopGuard}]`, "refused", 0); } // #847: detect reversed refs as SUBMITTED, before #1001 normalization // rewrites them (order matters — normalizeRangeOrder mutates in place). @@ -449,9 +535,20 @@ export function applyRanges(parsed: ReturnType, ctx: ? ` This conversation holds only ${totalChars} char(s) — below the ${minChars}-char minimum, so NO range can succeed yet; do not retry compress or call acp_status/search_context about it — continue answering the user's task.` : ""; const dropped = droppedEntriesNote(diagnostics); - return compressResult(`[Compression FAILED: ${errs}${revNote}${currentRefsSnapshot(ctx)}${recordCompressFailure(ctx.session, normalizedSpecKey(ranges))}${spanHint}${noViableAnywhere}${dropped ? " " + dropped : ""}${applyErrorNote(r)}]`, "refused", 0); + const specKey = normalizedSpecKey(ranges); + const repeatGuard = recordCompressFailure(ctx.session, specKey); + const loopGuard = trackLoop ? noteCompressLoopFailure(ctx, specKey) : ""; + const beyond = beyondFrontierNote(ctx.session.state, ranges); + // #2146: once the breaker arms, the diagnostic hint cluster it used + // to lead with has proven unread by the looping model — swap it for + // the hard-stop paragraph instead of stacking more ignored advice. + const hints = loopGuard === "" + ? `${beyond}${currentRefsSnapshot(ctx)}${repeatGuard}${spanHint}${noViableAnywhere}` + : `${beyond}${loopGuard}`; + return compressResult(`[Compression FAILED: ${errs}${revNote}${hints}${dropped ? " " + dropped : ""}${applyErrorNote(r)}]`, "refused", 0); } clearCompressFailures(ctx.session); + clearCompressLoopStreak(ctx.session); // #189 observability: record the rewrite magnitude + fold point so a // downstream transient rejection (GLM 3007) can be correlated with it. @@ -577,7 +674,8 @@ export function applyRanges(parsed: ReturnType, ctx: return compressResult(msg, dropped !== "" || r.errors.length > 0 ? "partial" : "applied", r.blocksCreated); } catch (err) { ctx.log(`[acp-proxy: compress failed: ${String(err)}]`); - return compressResult(`[Compression FAILED: ${String(err)}${recordCompressFailure(ctx.session, normalizedSpecKey(ranges))}]`, "refused", 0); + const specKey = normalizedSpecKey(ranges); + return compressResult(`[Compression FAILED: ${String(err)}${recordCompressFailure(ctx.session, specKey)}${trackLoop ? noteCompressLoopFailure(ctx, specKey) : ""}]`, "refused", 0); } } diff --git a/tests/issue2146-compress-loop-breaker.test.ts b/tests/issue2146-compress-loop-breaker.test.ts new file mode 100644 index 0000000000..33c18e9c78 --- /dev/null +++ b/tests/issue2146-compress-loop-breaker.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { test } from "node:test"; +import type { Config, CoreMessage } from "acp-kernel"; +import { createCore, createInitialState, assignRefs, emptyRefMap, defaultConfig } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { applyRanges, beyondFrontierNote, type RewriteCtx } from "../src/stream.ts"; +import { parseCompressInput } from "../src/compress-tool.ts"; + +_setStoreForTest(new SessionStore({ enabled: false })); + +const SUMMARY = "summary ".repeat(20); + +function textMsg(id: string, role: "user" | "assistant", text: string): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function makeSession(): Session { + return { + id: `issue2146-${randomUUID()}`, + meta: {}, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 15000, compressCreditTokens: 0, contextTokens: 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, + persisted: false, + pendingRetrievals: [], + }; +} + +function makeCtx(messages: CoreMessage[], config?: Config, logs?: string[]): RewriteCtx & { session: Session; config: Config } { + const session = makeSession(); + const res = assignRefs(messages, { existing: emptyRefMap(), nextIndex: 0 }); + session.state.messageRefs = res.map; + return { core: createCore(), config: config ?? defaultConfig(200000), messages, session, log: logs ? (m) => logs.push(m) : () => {} }; +} + +function compressArgs(startId: string, endId: string) { + return JSON.parse(JSON.stringify({ content: [{ startId, endId, summary: SUMMARY }] })); +} + +// Two sub-gate small messages + six big ones: three DISTINCT failing specs +// (single-message ranges + the pair, all under the 5000-char gate) and one +// guaranteed-success spec (m00003–m00008, 30000 chars). +function fixtureMessages(): CoreMessage[] { + const msgs: CoreMessage[] = [ + textMsg("raw_1", "assistant", "a".repeat(800)), + textMsg("raw_2", "assistant", "b".repeat(800)), + ]; + for (let i = 3; i <= 8; i++) msgs.push(textMsg(`raw_${i}`, "assistant", "x".repeat(5000))); + return msgs; +} + +test("#2146: distinct-spec failure streak arms the circuit breaker at 3", () => { + const logs: string[] = []; + const ctx = makeCtx(fixtureMessages(), undefined, logs); + + const f1 = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; + assert.ok(f1.startsWith("[Compression FAILED:"), `first attempt fails at gate (got: ${f1.slice(0, 120)})`); + assert.ok(!f1.includes("CIRCUIT BREAKER"), "failure 1 carries no breaker"); + + const f2 = applyRanges(parseCompressInput(compressArgs("m00002", "m00002")), ctx).text; + assert.ok(f2.startsWith("[Compression FAILED:"), "failure 2"); + assert.ok(!f2.includes("CIRCUIT BREAKER"), "failure 2 (different spec) still carries no breaker"); + + const f3 = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.ok(f3.startsWith("[Compression FAILED:"), "failure 3"); + assert.match(f3, /COMPRESS CIRCUIT BREAKER: 3 consecutive/, "third consecutive failure on a THIRD distinct spec arms the breaker"); + assert.match(f3, /STOP calling compress/, "breaker demands a full stop"); + + const f4 = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.match(f4, /COMPRESS CIRCUIT BREAKER: 4 consecutive/, "count continues while armed"); + + assert.ok(logs.some((l) => l.includes("[warn: compress-loop] circuit breaker armed after 3 consecutive")), "arm event logged for operator diagnosis"); + assert.ok(logs.some((l) => l.includes("[warn: compress-loop] failure 4 in armed streak")), "subsequent armed failures logged"); +}); + +test("#2146: success clears the streak; later failures start fresh", () => { + const ctx = makeCtx(fixtureMessages()); + applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx); + applyRanges(parseCompressInput(compressArgs("m00002", "m00002")), ctx); + const armed = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.match(armed, /CIRCUIT BREAKER/, "precondition: streak armed"); + + const ok = applyRanges(parseCompressInput(compressArgs("m00003", "m00008")), ctx).text; + assert.ok(ok.startsWith("[Compressed "), `large range compresses (got: ${ok.slice(0, 120)})`); + assert.equal(ctx.session.metadata["compressFailStreak"], undefined, "loop streak cleared on success"); + + const after = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; + assert.ok(after.startsWith("[Compression FAILED:"), "small range still fails after the successful compress"); + assert.ok(!after.includes("CIRCUIT BREAKER"), "post-success failure restarts the streak at 1"); +}); + +test("#2146: streak decays after 10 min quiet but continues within the window", () => { + const ctx = makeCtx(fixtureMessages()); + ctx.session.metadata["compressFailStreak"] = { n: 2, lastAt: Date.now() - 11 * 60 * 1000 }; + const decayed = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; + assert.ok(decayed.startsWith("[Compression FAILED:"), "fails as expected"); + assert.ok(!decayed.includes("CIRCUIT BREAKER"), "11-min-old streak decays — failure counts as #1 again"); + const s1 = ctx.session.metadata["compressFailStreak"] as { n?: number } | undefined; + assert.equal(s1?.n, 1, "metadata restarted at n=1"); + + ctx.session.metadata["compressFailStreak"] = { n: 2, lastAt: Date.now() - 9 * 60 * 1000 }; + const continued = applyRanges(parseCompressInput(compressArgs("m00002", "m00002")), ctx).text; + assert.match(continued, /CIRCUIT BREAKER: 3 consecutive/, "9-min-old streak is still live — arms at 3"); +}); + +test("#2146: all-refs-above-frontier gets the deterministic stale-generation diagnosis", () => { + const msgs: CoreMessage[] = [ + textMsg("raw_1", "assistant", "a".repeat(800)), + textMsg("raw_2", "assistant", "b".repeat(800)), + ]; + const ctx = makeCtx(msgs); + const out = applyRanges(parseCompressInput(compressArgs("m00006", "m00010")), ctx).text; + assert.ok(out.startsWith("[Compression FAILED:"), `unknown refs fail (got: ${out.slice(0, 120)})`); + assert.match(out, /above this session's highest ref \(m00002\)/, "names the frontier"); + assert.match(out, /stale artifacts/, "attributes the cause to stale-generation history"); + + const mixed = applyRanges(parseCompressInput(compressArgs("m00001", "m00010")), ctx).text; + assert.ok(mixed.startsWith("[Compression FAILED:"), "still fails"); + assert.ok(!mixed.includes("above this session's highest ref"), "note suppressed when any endpoint is inside the frontier"); +}); + +test("#2146: beyondFrontierNote unit shapes", () => { + const res = assignRefs([textMsg("r1", "assistant", "abc"), textMsg("r2", "assistant", "def")], { existing: emptyRefMap(), nextIndex: 0 }); + const state = createInitialState(); + state.messageRefs = res.map; + assert.match(beyondFrontierNote(state, [{ startRef: "m00006", endRef: "m00010" }]), /\(m00002\)/); + assert.equal(beyondFrontierNote(state, [{ startRef: "m00001", endRef: "m00006" }]), "", "in-frontier start suppresses"); + assert.equal(beyondFrontierNote(state, [{ startRef: "b1", endRef: "m00010" }]), "", "block-id endpoints have no cross-namespace ordering"); + assert.equal(beyondFrontierNote(state, []), "", "empty range list"); + const emptyState = createInitialState(); + assert.equal(beyondFrontierNote(emptyState, [{ startRef: "m00001", endRef: "m00002" }]), "", "no mapped refs"); +}); + +test("#2146: loopTracking:false (preflight lane) never touches the model-facing streak", () => { + const ctx = makeCtx(fixtureMessages()); + for (let i = 0; i < 5; i++) { + const out = applyRanges(parseCompressInput(compressArgs(i % 2 === 0 ? "m00001" : "m00002", i % 2 === 0 ? "m00001" : "m00002")), ctx, { loopTracking: false }).text; + assert.ok(out.startsWith("[Compression FAILED:"), "internal-lane call still reports its failure"); + assert.ok(!out.includes("CIRCUIT BREAKER"), "internal lane never shows the breaker"); + } + assert.equal(ctx.session.metadata["compressFailStreak"], undefined, "streak untouched across 5 internal failures"); + + const tracked = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; + assert.ok(!tracked.includes("CIRCUIT BREAKER"), "first tracked failure after the internal storm starts fresh"); +}); diff --git a/tests/issue847-compress-failure-guards.test.ts b/tests/issue847-compress-failure-guards.test.ts index 1dadcbc1a7..90d6e3cc25 100644 --- a/tests/issue847-compress-failure-guards.test.ts +++ b/tests/issue847-compress-failure-guards.test.ts @@ -113,7 +113,10 @@ test("#847: repeated identical failing spec escalates; success clears the streak assert.match(second, /acp_status/, "escalation points at acp_status"); const third = applyRanges(parseCompressInput(compressArgs("m00001", "m00002")), ctx).text; - assert.match(third, /3 time\(s\)/, "alternating direction still counts as the same spec"); + // #2146: at 3 consecutive failures (same or distinct specs) the cross-spec + // circuit breaker supersedes the exact-spec repeat text — alternating + // direction still counts as the same spec. + assert.match(third, /COMPRESS CIRCUIT BREAKER: 3 consecutive/, "third consecutive failure upgrades to the loop breaker"); const success = applyRanges(parseCompressInput(compressArgs("m00003", "m00008")), ctx).text; assert.ok(success.startsWith("[Compressed "), `large range compresses (got: ${success.slice(0, 100)})`); From 62bb0c73eecc431a4aac80751f4c561ce0bb77a2 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 5 Oct 2026 16:25:01 +0800 Subject: [PATCH 2/2] fix: stop stale-generation receipts from echoing phantom refs back (#2146) --- src/stream.ts | 20 ++++++++++++++++++- tests/issue2146-compress-loop-breaker.test.ts | 14 +++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/stream.ts b/src/stream.ts index 0907b562e0..173c49e713 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -545,7 +545,25 @@ export function applyRanges(parsed: ReturnType, ctx: const hints = loopGuard === "" ? `${beyond}${currentRefsSnapshot(ctx)}${repeatGuard}${spanHint}${noViableAnywhere}` : `${beyond}${loopGuard}`; - return compressResult(`[Compression FAILED: ${errs}${revNote}${hints}${dropped ? " " + dropped : ""}${applyErrorNote(r)}]`, "refused", 0); + let receipt = `[Compression FAILED: ${errs}${revNote}${hints}${dropped ? " " + dropped : ""}${applyErrorNote(r)}]`; + // #2146: when every requested ref is provably stale-generation, the + // kernel's per-range error text hands those exact phantom numbers + // straight back into the client-persisted history — where the + // looping model reads them as unfinished work and slides further up + // the same ladder (incident log: m29971–m30020 → m30021–m30070 → … + // across hours). Scrub the requested endpoints from the model- + // visible receipt so that echo channel dies; the ctx.log line above + // keeps the real refs for the operator. Live refs are untouched: + // when the note fires, every requested ref exceeds the session's + // highest mapped ref, so no live snapshot number can collide. + if (beyond !== "") { + for (const rg of ranges) { + for (const id of [rg.startRef, rg.endRef]) { + receipt = receipt.split(id).join("[stale-ref]"); + } + } + } + return compressResult(receipt, "refused", 0); } clearCompressFailures(ctx.session); clearCompressLoopStreak(ctx.session); diff --git a/tests/issue2146-compress-loop-breaker.test.ts b/tests/issue2146-compress-loop-breaker.test.ts index 33c18e9c78..bf2f3b9635 100644 --- a/tests/issue2146-compress-loop-breaker.test.ts +++ b/tests/issue2146-compress-loop-breaker.test.ts @@ -149,3 +149,17 @@ test("#2146: loopTracking:false (preflight lane) never touches the model-facing const tracked = applyRanges(parseCompressInput(compressArgs("m00001", "m00001")), ctx).text; assert.ok(!tracked.includes("CIRCUIT BREAKER"), "first tracked failure after the internal storm starts fresh"); }); + +test("#2146: stale-generation receipts scrub the phantom refs; in-frontier failures keep them verbatim", () => { + const ctx = makeCtx(fixtureMessages()); + const stale = applyRanges(parseCompressInput(compressArgs("m00010", "m00014")), ctx).text; + assert.ok(stale.startsWith("[Compression FAILED:"), `unknown refs fail (got: ${stale.slice(0, 120)})`); + assert.match(stale, /above this session's highest ref \(m00008\)/, "frontier diagnosis present"); + assert.doesNotMatch(stale, /m00010|m00014/, "phantom endpoints are NOT echoed back into the client-persisted receipt"); + assert.match(stale, /\[stale-ref\]/, "scrubbed marker takes their place"); + + const mixed = applyRanges(parseCompressInput(compressArgs("m00001", "m00009")), ctx).text; + assert.ok(mixed.startsWith("[Compression FAILED:"), "still fails"); + assert.ok(!mixed.includes("above this session's highest ref"), "note suppressed (start inside frontier)"); + assert.match(mixed, /m00009/, "an in-frontier unknown endpoint stays verbatim — a real typo the model can correct"); +});