diff --git a/reference/ref-keyed-surfaces.md b/reference/ref-keyed-surfaces.md index fa7be9a7ef..9cdd506dea 100644 --- a/reference/ref-keyed-surfaces.md +++ b/reference/ref-keyed-surfaces.md @@ -33,9 +33,9 @@ Losing it re-arms the restamp every turn; the re-stamp is a numbering no-op afte `restampRefsToLedger` vacates an old number and records it in `superseded` — but the SAME pass hands vacated numbers to other messages as `seq+1` targets. Post-pass, a number can be **simultaneously live (byRaw/byRef) and a superseded key**. Any consumer that consults `superseded` before the live map misclassifies live refs. -**Contract (enforced by kernel post-pass prune + host guard priority):** -1. Kernel: after the pass, drop `superseded` entries whose key resolves in the final live map. -2. Host guard (`supersededRefRejection`, src/stream.ts): a ref that resolves LIVE is never superseded — liveness first; only genuinely-dead numbers consult the map; translation `oldRef→rawId→live ref` is identity-preserving and mandatory for model-cited pre-restamp refs (the model may cite any number it has ever seen — kernel contract). +**Contract:** +1. Kernel: after the pass, drop `superseded` entries whose key resolves in the final live map. **DRAFTED in #4807, then REVERTED** (storage-engine shadow-digest constraint — see 暂缓 section): until it lands, dual-identity numbers exist on EVERY restamped session (#5199). +2. Host guard (`supersededRefRejection`, src/stream.ts): a ref that resolves LIVE is never superseded — liveness first; only genuinely-dead numbers consult the map; translation `oldRef→rawId→live ref` is identity-preserving and mandatory for model-cited pre-restamp refs (the model may cite any number it has ever seen — kernel contract). Cited numbers that are BOTH live and superseded resolve to the current owner and are logged prominently by callers (#5199). ## Inbound/outbound ref surfaces (verified all-live 2026-10-26, phase C audit) @@ -55,4 +55,4 @@ Outbound emitters all derive from live `state.messageRefs` via the kernel render ## 已评估、暂缓(需要 storage 影子层配合,单独立项) -- **kernel superseded 活键剪枝 + block startRef/endRef / deadRefs 迁移**:实现过并验证过单测,但 storage-engine 的重启不可见契约(wire-parity proofs + 影子摘要对比)依赖重排结果的确定性形状——迁移后影子层报 `DIGEST DRIFT [diverged: state]`,full 模式回退 legacy 信封,wire 漂移 4 项红。正确落地需要影子层把「对齐态」纳入摘要口径;在此之前 host 活表优先已消除其全部用户可见危害。剪枝与迁移的完整实现见 PR 历史(revert 前的 kernel/src/refs.ts)。 +- **kernel superseded 活键剪枝 + block startRef/endRef / deadRefs 迁移**:实现过并验证过单测,但 storage-engine 的重启不可见契约(wire-parity proofs + 影子摘要对比)依赖重排结果的确定性形状——迁移后影子层报 `DIGEST DRIFT [diverged: state]`,full 模式回退 legacy 信封,wire 漂移 4 项红。正确落地需要影子层把「对齐态」纳入摘要口径;⚠️ **2026-10-30 更正(#5199)**:此前「host 活表优先已消除其全部用户可见危害」不成立——隔离 fixture 复现了最坏形态:重启前引用被静默应用到新持有者(成功返回、块只覆盖错误消息)。活表优先只消除了 #4797 死循环;双身份应用现已有醒目日志(host 侧,tests/issue5199-dual-identity-log.test.ts),方向裁决(接受+文档化 vs kernel 不复用已发放号)见 decision request #5204。剪枝与迁移的完整实现见 PR 历史(revert 前的 kernel/src/refs.ts)。 diff --git a/src/stream.ts b/src/stream.ts index 502acda0af..68f5a1b2a1 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -914,18 +914,26 @@ export function findVisibleStubResubmissions(ctx: RewriteCtx, ranges: ParsedRang * Refusal only when an endpoint is a superseded key whose translation * dead-ends (the message lost its mapping entirely — an honest stale cite). * - * Transitional honesty: sessions whose restamp predates kernel #5196's - * slot-retirement may still carry an ambiguity — a number restamped over a - * live occupant, so case 1 can in principle swallow a resent pre-restart - * call's intent. #4807 (#4797) traded that seconds-long replay window - * against a permanent deadlock; live-first keeps that trade. Kernels from - * #5196 onward retire every seat a mover vacates into its own seq+1, so no - * freshly stamped number ever names two messages and case 1 can never - * mis-engage on such data. */ + * Residual hazard (#5199): kernels from #5196 onward retire every seat a + * mover vacates into its own seq+1 (slot retirement), so no FRESHLY stamped + * number ever names two messages. Sessions whose restamp PREDATES #5196, + * however, still carry the ambiguity in their persisted superseded map — a + * number that is live for one message yet the recorded old label of another. + * For those, case 1 applies a resent pre-restart call to the CURRENT owner + * while the model meant the old one, returning success. Live-first stays the + * accepted resolution (rejecting dead-loops like #4797; translating to the + * old owner would mistranslate legitimate post-restamp cites). Until such + * legacy sessions are re-aligned the application is no longer silent: + * dualIdentity below names every such ref so callers log it. */ interface SupersededResolution { rejection: string | null; translatedRanges: T[]; translated: number; + /** #5199: refs that are LIVE for one message while still the recorded old + * label of ANOTHER (the restamp re-issued an already-issued number). The + * live-first resolution applies to the current owner — callers log these + * so a replayed pre-restart citation is diagnosable instead of silent. */ + dualIdentity: string[]; } export function supersededRefRejection( @@ -933,7 +941,7 @@ export function supersededRefRejection { const superseded = session.restampSuperseded; - const out: SupersededResolution = { rejection: null, translatedRanges: [], translated: 0 }; + const out: SupersededResolution = { rejection: null, translatedRanges: [], translated: 0, dualIdentity: [] }; if (!superseded || superseded.size === 0) { out.translatedRanges = ranges.map((r) => ({ ...r })); return out; @@ -941,8 +949,17 @@ export function supersededRefRejection(); const resolveEndpoint = (ref: string): string => { - if (byRef[ref] !== undefined) return ref; + const liveOwner = byRef[ref]; + if (liveOwner !== undefined) { + // #5199: live AND still the recorded old label of another message — + // the restamp issued this number twice. Live-first wins (the + // accepted trade); record it so the caller can log the application. + const oldOwner = superseded.get(ref); + if (oldOwner !== undefined && oldOwner !== liveOwner) dualIdentity.add(ref); + return ref; + } const rawId = superseded.get(ref); if (rawId === undefined) return ref; const next = byRaw[rawId]; @@ -958,6 +975,7 @@ export function supersededRefRejection 5 ? ` (+${dead.length - 5} more)` : ""; @@ -1223,6 +1241,21 @@ export function applyRanges(parsed: ReturnType, ctx: return compressResult(`[Compression REFUSED: out-of-bounds compression is disabled on this route (compress.requireRecommendation) — span(s) ${listed} contain content bili does not currently recommend folding. Call acp_status for the current compressible ranges and stay within them: subdividing a listed span into smaller chunks is fine, and re-folding an already-compressed block to update its summary is fine.]`, "refused", 0, "out-of-recommendation"); } } + if (supersededRes.dualIdentity.length > 0) { + // #5199: cited number(s) that are live for their CURRENT owner while + // still the recorded pre-restamp label of a DIFFERENT message. A + // replayed pre-restart call may have meant the old owner — the fold + // proceeds against the current one (the live-first trade), but the + // application must be visible. Salted ids only (#1454 pattern). + const detail = supersededRes.dualIdentity.map((ref) => { + const owners = [ctx.session.state.messageRefs?.byRef?.[ref], ctx.session.restampSuperseded?.get(ref)] + .filter((o): o is string => typeof o === "string") + .map((o) => saltedMsgIdForLog(o)) + .join("/"); + return `${ref}=${owners}`; + }).join(", "); + ctx.log(`[acp-proxy: ⚠️ compress applied onto reused ref number(s): ${detail} — each is live for its current owner yet was issued to a different message before the ledger alignment; a replayed pre-restart citation may have intended the old owner (#5199; direction decision #5204)]`); + } if (ctx.messages.length > 0) { const ids = ctx.messages.slice(0, 10).map((m) => `${saltedMsgIdForLog(m.id)}(${(m.text ?? "").length}c)`).join(", "); ctx.log(`[acp-proxy: first msg ids: ${ids}]`); diff --git a/tests/issue4797-superseded-deadlock.test.ts b/tests/issue4797-superseded-deadlock.test.ts index 9595d11d72..88bca48b10 100644 --- a/tests/issue4797-superseded-deadlock.test.ts +++ b/tests/issue4797-superseded-deadlock.test.ts @@ -26,7 +26,9 @@ import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/str // Post-restamp (#5196 slot-retirement): b→m2, e→m5; f's target m6 was retired // by e's move within the same pass, so f parks on a fresh number (m8, above // the pre-pass cursor) instead of re-occupying it. Superseded: {m3→b, m6→e, -// m7→f} — no number is live for one message and an alias of another. +// m7→f} — no number is live for one message and an alias of another. The +// pre-#5196 dual-identity shape (a number live for one msg yet another's old +// label) is pinned separately in tests/issue5199-dual-identity-log.test.ts. function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMessage[] } { const state: CompressionState = createInitialState(); const map = emptyRefMap(); diff --git a/tests/issue5199-dual-identity-log.test.ts b/tests/issue5199-dual-identity-log.test.ts new file mode 100644 index 0000000000..8c434f6571 --- /dev/null +++ b/tests/issue5199-dual-identity-log.test.ts @@ -0,0 +1,152 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { createCore, defaultConfig, createInitialState, emptyRefMap, type CoreMessage, type CompressionState } from "acp-kernel"; +import { applyRanges, supersededRefRejection, type RewriteCtx } from "../src/stream.ts"; + +// #5199: after a restart, the cold-load ledger restamp can hand a pre-restart +// ref to ANOTHER message (a vacated number re-issued as someone else's seq+1 +// target in the same pass). The host guard resolves endpoints live-first, so +// a replayed pre-restart compress call citing the OLD number applies to the +// NEW owner and returns success — silently folding the wrong message. The +// live-first resolution is the accepted trade (rejecting dead-loops like +// #4797; translating to the old owner would mistranslate legitimate +// post-restamp cites); what was missing was visibility. This file pins: +// T1 dual-identity application — citing m00006 (live for f, e's old label) +// folds f, NOT e, returns success, and the prominent warning fires; +// T2 negative control — an ordinary live cite produces NO warning; +// T3 resolution contract — dualIdentity dedupes singleton endpoints, clean +// ranges stay empty, the no-map fast path carries an empty list; +// T4 translation path intact — a genuinely-vacated cite still translates +// onto the same message with no dual-identity entry. + +// Pre-#5196 restamped-session shape, built DIRECTLY rather than via +// restampRefsToLedger: #5196 slot-retirement changed the kernel so a fresh +// restamp no longer re-issues a vacated number (in this shape f would park on +// m8 instead of taking e's vacated m6), so the restamp path can no longer +// reproduce the fixture. Sessions restamped BEFORE #5196 still carry exactly +// this persisted shape, which we build verbatim so the host-guard pin stays +// independent of the kernel's current restamp algorithm: +// LIVE: a=m1 b=m2 d=m4 e=m5 f=m6 ; superseded {m3→b, m6→e, m7→f}. +// m6 is therefore dual-identity: live for f AND still e's recorded old label. +function restampedSession(): { session: RewriteCtx["session"]; messages: CoreMessage[] } { + const state: CompressionState = createInitialState(); + const map = emptyRefMap(); + map.byRaw.a = "m00001"; map.byRef.m00001 = "a"; + map.byRaw.b = "m00002"; map.byRef.m00002 = "b"; + map.byRaw.c = "BLOCKED"; + map.byRaw.d = "m00004"; map.byRef.m00004 = "d"; + map.byRaw.e = "m00005"; map.byRef.m00005 = "e"; + map.byRaw.f = "m00006"; map.byRef.m00006 = "f"; + state.messageRefs = map; + // The persisted superseded map such a legacy session carries: each vacated + // number mapped to its pre-restamp owner. m6→e is the dual-identity entry + // (m6 is live for f yet still recorded as e's old label). + const superseded = new Map([ + ["m00003", "b"], + ["m00006", "e"], + ["m00007", "f"], + ]); + const messages: CoreMessage[] = [ + { id: "a", role: "user", contentType: "text", text: "message a body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "b", role: "assistant", contentType: "text", text: "message b body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "d", role: "user", contentType: "text", text: "message d body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "e", role: "assistant", contentType: "text", text: "message e body " + "with enough substance to be worth folding someday. ".repeat(120) }, + { id: "f", role: "user", contentType: "text", text: "message f body " + "with enough substance to be worth folding someday. ".repeat(120) }, + ]; + const session = { + id: "issue5199", + meta: { protocol: "anthropic" }, + stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, compressCreditTokens: 0, contextTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 }, + metadata: {}, + state, + restampSuperseded: superseded, + createdAt: Date.now(), + lastSeen: Date.now(), + blockContents: new Map(), + inFlight: 0, + persisted: false, + pendingRetrievals: [], + } as never as RewriteCtx["session"]; + return { session, messages }; +} + +function makeCtx(): { ctx: RewriteCtx; logs: string[] } { + const logs: string[] = []; + const { session, messages } = restampedSession(); + const ctx = { + core: createCore(), + config: defaultConfig(100_000, { preserveRecentMessages: 0, preserveRecentTokens: 0 }), + messages, + compressMessages: messages, + session, + log: (m: string) => { logs.push(m); }, + } as never as RewriteCtx; + return { ctx, logs }; +} + +const SUMMARY = "Folded span covering the debugging arc with decisions, files touched, and outcomes preserved for later recall.".slice(0, 500); + +function spec(startRef: string, endRef: string): { ranges: { startRef: string; endRef: string; summary: string }[]; diagnostics: unknown } { + return { ranges: [{ startRef, endRef, summary: SUMMARY.repeat(2) }], diagnostics: [] }; +} + +test("T1: citing a dual-identity ref (live for f, e's pre-restamp label) folds f, succeeds, and logs the reused-number warning", () => { + const { ctx, logs } = makeCtx(); + // Fixture precondition: m00006 is live for f while still recorded as e's + // old label — the exact shape #5199 reproduces in production. + const byRef = ctx.session.state.messageRefs?.byRef ?? {}; + assert.equal(byRef["m00006"], "f"); + assert.equal(ctx.session.restampSuperseded?.get("m00006"), "e"); + const res = applyRanges(spec("m00006", "m00006") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `dual-identity cite must not be refused (live-first trade); got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("f"), "fold covers the CURRENT owner f"); + assert.ok(!covered.includes("e"), "the intended-but-old owner e is NOT folded"); + const warn = logs.find((l) => l.includes("reused ref number")); + assert.ok(warn !== undefined, `prominent warning must fire; logs: ${logs.join(" | ")}`); + assert.ok(warn!.includes("m00006"), "warning names the reused ref"); +}); + +test("T2: an ordinary live cite (no dual identity) folds cleanly with NO warning", () => { + const { ctx, logs } = makeCtx(); + const res = applyRanges(spec("m00004", "m00004") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `clean live cite must not be refused; got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("d"), "fold covers d"); + assert.ok(!logs.some((l) => l.includes("reused ref number")), "no warning for non-dual identities"); +}); + +test("T3: resolution contract — singleton dedupe, clean ranges empty, no-map fast path empty", () => { + const { session } = restampedSession(); + // Singleton range: both endpoints hit the same dual-identity ref once. + const res = supersededRefRejection([{ startRef: "m00006", endRef: "m00006" }], session); + assert.equal(res.rejection, null); + assert.deepEqual(res.dualIdentity, ["m00006"]); + // Clean live range: nothing flagged. + const clean = supersededRefRejection([{ startRef: "m00004", endRef: "m00005" }], session); + assert.equal(clean.rejection, null); + assert.deepEqual(clean.dualIdentity, []); + // No-map fast path: field present and empty. + (session as { restampSuperseded?: Map }).restampSuperseded = undefined; + const bare = supersededRefRejection([{ startRef: "m00004", endRef: "m00005" }], session); + assert.deepEqual(bare.dualIdentity, []); +}); + +test("T4: genuinely-vacated cites still translate onto the same message, with no dual-identity entry", () => { + const { ctx, logs } = makeCtx(); + // m00003 is b's pre-restamp label; b now holds m00002. Translation must + // fold b — and flag nothing (the number is vacated, not re-issued). + const res = applyRanges(spec("m00003", "m00003") as never, ctx); + const text = typeof (res as { text?: string }).text === "string" ? (res as { text?: string }).text! : ""; + assert.ok(!text.includes("REFUSED"), `translatable old cite must not be refused; got: ${text.slice(0, 200)}`); + const covered = ctx.session.state.blocks.flatMap((b) => (b.active ? b.effectiveMessageIds : [])); + assert.ok(covered.includes("b"), "translated fold covers the cited message b"); + assert.ok(!covered.includes("a"), "neighbor a untouched"); + assert.ok(logs.some((l) => l.includes("translated") && l.includes("superseded")), "translation still logged"); + assert.ok(!logs.some((l) => l.includes("reused ref number")), "vacated (non-re-issued) numbers are not dual-identity"); +});