From bff3206cad8dbb60e807165240466d69fa78cf71 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 1 Dec 2026 10:49:44 +0800 Subject: [PATCH 1/2] fix(snapshot): converge the legacy incremental pin across a namespace jump (#7981) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The positional (legacy) incremental pin deadlocks when the wire id space moves away from content hashes: every overlap row drifts (host uuid vs ledger h_), the pin degrades to the full signal on every turn, the prefix re-mints as h_ each time, and fold blocks recorded under the churn re-anchor onto churned bytes every turn (the double cache cold per fold the issue reports). The egress ledger answers the identical situation with REANCHOR_NOW and never nulls; the legacy path now gets the same answer under a conservative per-row fingerprint: an overlap-row drift is tolerated (jump) only when EVERY drifted row is a content-hash ledger row (h_<16hex>) carrying a valid client id that is FOREIGN to the whole ledger — i.e. the wire namespace moved to a fresh space and the ledger is the old one. Any other drift row is shared-namespace drift and keeps the legacy null degrade (the issue5874-2x2-p3 I2/I3 contract, verified unmodified and green). The pin converges in one round: the prefix re-stamps from the ledger's write-once rows, the new core takes the declared host ids, the first RAW (miss) turn's ingest sweep aligns the ledger tail to the declared namespace, and every later turn pins on the ordinary positional path. One bounded per-session warn makes the previously silent branch auditable (the reporter's pain was the silence). No version bump (content commit on a feature branch). tests: issue7981-legacy-ns-jump.test.ts (J1..J6 — the jump shape, the post-sweep convergence, mixed-ledger transients, and the three shared- namespace drift cases that must keep degrading); issue5874-2x2-p3.test.ts stays green unmodified (the I2/I3 contract). --- src/snapshot/stage0.ts | 69 +++++- tests/issue7981-legacy-ns-jump.test.ts | 281 +++++++++++++++++++++++++ 2 files changed, 347 insertions(+), 3 deletions(-) create mode 100644 tests/issue7981-legacy-ns-jump.test.ts diff --git a/src/snapshot/stage0.ts b/src/snapshot/stage0.ts index e525037b28..1c2119c6ee 100644 --- a/src/snapshot/stage0.ts +++ b/src/snapshot/stage0.ts @@ -42,6 +42,19 @@ import { egressPlaneGateOn } from "../knobs.js"; import { EGRESS_SYSTEM_MSGID } from "../storage/egress-state.js"; import { checkR3Identity, FoundationRejectError, r3FaultTracker } from "./plane.js"; +// #7981: the kernel's content-hash mint shape (deriveMessageId: "h_" + 16 +// lowercase hex, optional within-pass cluster suffix "_k" — the ledger row +// for a reminted cluster; fastpath.ts carries the same pattern). Used ONLY +// for the namespace-jump fingerprint in tryIncrementalPin below: a drifted +// overlap row whose LEDGER side is server-minted content is a namespace +// jump, not a shared-namespace drift. +const MINTED_ROW_RE = /^h_[0-9a-f]{16}(?:_\d+)?$/; +// #7981: bounded once-per-session warn guard for the namespace-jump notice +// (a session on hit-turn-only flow can fire the jump branch every turn — +// the warn stays once, the debug line lands per turn). Cleared whole when +// the cap is exceeded: the set only gates log noise, never pin semantics. +const jumpWarnedSids = new Set(); + export interface Stage0Input { sessionId: string; /** Lane name for log prefixes only ("openai" | "responses"). */ @@ -374,7 +387,12 @@ export function runStage0(opts: Stage0Input): Stage0Result { // body list on carrier-off turns: the overlap then spans hundreds–2047 // rows and the pin PROVES MORE, not less — so a degraded "full" turn can // still pin and re-upgrade the client; the full list is never a -// requirement any client must be able to produce. Exported: the anthropic +// requirement any client must be able to produce. The ONE tolerated +// exception is the #7981 namespace jump (host-uuid wire space over an +// all-content-hash ledger — see the drift loop below): there the +// row-by-row match deadlocks forever, and the egress ledger already +// answers the identical situation with REANCHOR_NOW (never null). +// Exported: the anthropic // lane's inline pin reuses it (two-form rule). export function tryIncrementalPin( sessionId: string, @@ -440,12 +458,57 @@ export function tryIncrementalPin( // >2048 sessions can only ever send their retained tail) carries up to // the client's window of overlap rows and proves MORE. ANY drift row // degrades to the full signal — D1: never a reject. + // + // #7981 exception — the NAMESPACE JUMP. When the wire id space moves + // from content hashes to host ids (the dsh 0.1.217 client upgrade: + // every message gets a stable host uuid), the ledger — write-once per + // position (INSERT OR IGNORE) — keeps its h_ rows while EVERY + // client-declared id is a fresh uuid: every overlap row drifts + // (uuid vs h_) and the row-by-row match deadlocks the pin forever. Each + // null turn re-mints the whole prefix as h_, and fold blocks recorded + // under the churn re-anchor onto "churned bytes" every turn → the + // double cache cold per fold the issue reports. The egress ledger hits + // the identical jump and answers it with REANCHOR_NOW (never null); + // the legacy positional pin gets the same answer under a conservative + // fingerprint: EVERY drifted row must be a content-hash LEDGER row + // carrying a VALID client id that is FOREIGN to the whole ledger. A + // drift row whose ledger side already holds a host id (or whose client + // id appears somewhere in the ledger) = shared namespace = ordinary + // drift = the legacy null degrade (I2/I3). A "?" client slot proves no + // namespace and degrades. Why the tolerant branch is safe: a ledger + // whose rows are all content mints has NEVER held the client's ids, so + // no position is being rewritten IN ITS OWN namespace — stamping the + // declared ids converges in one round (miss turns ingest RAW: the + // sweep retires the un-presented h_ rows and appends the host ids, + // #3285/#4390) instead of oscillating forever. The stamped view + // ({h_ prefix restamped from the ledger, host-uuid tail}) is stable + // across turns, so fold coverage stops churning after it. const overlapEnd = L - n; // first slot that is a NEW core (>= C) + const ledgerRows = new Set(liveIds); + let jump = false; for (let j = 0; j < overlapEnd; j++) { - if (tailIds[j] !== ledgerEl[T - L + j]) { - log("info", `[${sessionId}] [2x2:${lane}] incremental tail drift at overlap row ${T - L + j} (got=${tailIds[j]}, ledger=${ledgerEl[T - L + j]}) — full signal (reanchor next turn)`); + if (tailIds[j] === ledgerEl[T - L + j]) continue; + const ledgerRow = ledgerEl[T - L + j]!; + const declared = tailIds[j]!; + const jumpRow = + declared !== "?" && + MINTED_ROW_RE.test(ledgerRow) && + !ledgerRows.has(declared); + if (!jumpRow) { + log("info", `[${sessionId}] [2x2:${lane}] incremental tail drift at overlap row ${T - L + j} (got=${declared}, ledger=${ledgerRow}) — full signal (reanchor next turn)`); return null; } + if (!jump) { + jump = true; + if (!jumpWarnedSids.has(sessionId)) { + if (jumpWarnedSids.size > 4096) jumpWarnedSids.clear(); + jumpWarnedSids.add(sessionId); + log("warn", `[${sessionId}] [2x2:${lane}] namespace jump: every drifted overlap row is a content-hash ledger row carrying a client id the ledger has never recorded (host-uuid wire space over an h_ ledger) — pinning onto the declared ids, one round (#7981)`); + } + } + } + if (jump) { + log("debug", `[${sessionId}] [2x2:${lane}] namespace-jump pin applied (overlap rows=${overlapEnd}, new cores=${n}, view=${T}, ledger=${C}) — prefix restamps from the ledger, new cores take the declared ids`); } // Entry screening on the NEW cores (same rules as msgid-pin // validateMsgIds — a bad id must never reach the ledger's unique index). diff --git a/tests/issue7981-legacy-ns-jump.test.ts b/tests/issue7981-legacy-ns-jump.test.ts new file mode 100644 index 0000000000..20797629d4 --- /dev/null +++ b/tests/issue7981-legacy-ns-jump.test.ts @@ -0,0 +1,281 @@ +/** + * #7981 — the legacy (positional) incremental pin deadlocks on the NAMESPACE + * JUMP: the wire id space moves from content hashes to host ids (the dsh + * 0.1.217 client upgrade: every message gets a stable host uuid), the ledger + * is write-once per position (INSERT OR IGNORE) and keeps its h_ rows, so + * EVERY overlap row drifts (uuid vs h_) and the pin degrades to the full + * signal forever. Each null turn re-mints the prefix as h_; fold blocks + * recorded under the churn re-anchor onto "churned bytes" every turn → the + * double cache cold per fold the issue reports (the egress ledger answers + * the identical situation with REANCHOR_NOW, never null — see + * tryEgressPin; the legacy path now gets the same answer under a + * conservative fingerprint). + * + * Fix under test (src/snapshot/stage0.ts tryIncrementalPin): an overlap-row + * drift is TOLERATED (jump) only when every drifted row is a content-hash + * ledger row carrying a valid client id that is FOREIGN to the whole ledger. + * Any other drift row = shared namespace = ordinary drift = the legacy null + * degrade (the issue5874-2x2-p3 I2/I3 contract stays intact — that suite + * must keep passing unmodified). + * + * Scenarios (J*): + * J1 the issue's shape — all-h_ ledger, host-uuid tail → pin (was null): + * prefix re-stamped from the ledger, the new core takes the declared id, + * one warn per session, signal "incremental". + * J2 post-sweep convergence — the ledger now ends in host ids; the + * ordinary positional path pins again WITHOUT the jump branch. + * J3 mixed-ledger transient (hit turns keep the sweep off) — a partial + * match pins on the ordinary path; a drift inside the mixed region + * still converges via the jump branch instead of nulling. + * J4 real drift over a HOST-ID ledger (shared namespace) → null, as before. + * J5 a "?" slot in the overlap proves no namespace → null. + * J6 a drifted client id that EXISTS elsewhere in the ledger → null + * (foreign-id check — the fingerprint is per-row, not list-wide). + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs, { mkdtempSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import type { BiliMessage } from "acp-kernel/wire"; +import { openaiToCore } from "acp-kernel/wire"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { runStage0 } from "../src/snapshot/stage0.ts"; +import { _setStoreForTest } from "../src/persist.ts"; +import type { DbLike } from "../src/storage/snap.ts"; + +process.env.BILI_PERSIST_ZSTD = "0"; +// KDD #25: this suite exercises the LEGACY stage-0 machinery — force the +// full table set so a host rollout that enables the egress plane cannot make +// UnifiedStore.open skip the legacy group (the jump branch must be reached). +process.env.BILI_TEST_FORCE_FULL_DDL = "1"; +const hermetic = fs.mkdtempSync(path.join(os.tmpdir(), "bili-7981-jump-")); +const configPath = path.join(hermetic, "config.json"); +fs.writeFileSync(configPath, "{}"); + +// --------------------------------------------------------------------------- +// Fixtures (same scaffolding as tests/issue5874-2x2-p3.test.ts) +// --------------------------------------------------------------------------- + +function harness(t: test.TestContext) { + const dir = mkdtempSync(path.join(os.tmpdir(), "bili-7981-d23-")); + const prevEnv: Record = {}; + for (const k of ["BILI_STORAGE_UNIFIED", "BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY", "BILI_ROLLOUT_PLUGIN_MSG_ID_INCREMENTAL", "XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) { + prevEnv[k] = process.env[k]; + process.env[k] = k.startsWith("XDG") ? dir : (k === "BILI_STORAGE_UNIFIED" ? "full" : "1"); + } + const store = UnifiedStore.open(path.join(dir, "index.db")); + // runStage0 talks to the store through the SessionStore seam — give it + // the snap delegates, delegating to the real UnifiedStore. + _setStoreForTest({ + setSessionCommitListener() { /* the seam only needs the snap delegates */ }, + snapStage0: (sid: string, ids: string[], opts?: { seqs?: number[] | null }) => store.snapStage0(sid, ids, opts), + snapConvBound: (sid: string) => store.snapConvBound(sid), + snapMsgIdLiveIds: (sid: string) => store.snapMsgIdLiveIds(sid), + snapPinLiveIds: (sid: string) => store.snapPinLiveIds(sid), + snapR3Latched: (sid: string) => store.snapR3Latched(sid), + } as unknown as Parameters[0]); + t.after(() => { + for (const [k, v] of Object.entries(prevEnv)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); + return { dir, store }; +} + +function dMsgs(n: number): BiliMessage[] { + const arr: { role: string, content: string }[] = [{ role: "system", content: "sys" }]; + for (let i = 1; i <= n; i++) arr.push({ role: i % 2 ? "user" : "assistant", content: `c${i}` }); + return (openaiToCore({ messages: arr } as never)).msgs; +} + +function seedLedger(db: DbLike, sid: string, ids: string[]): void { + ids.forEach((id, seq) => { + const hash = `h-7981-${sid}-${seq}`; + db.prepare("INSERT OR IGNORE INTO content (hash, byte_len, refcount, algo, bytes) VALUES (?, 1, 0, 'sha256', x'00')").run(hash); + db.prepare("INSERT OR IGNORE INTO messages (session_id, seq, msg_id, ref, ref_num, role, kind, content_hash, identity, retired_at) VALUES (?, ?, ?, NULL, ?, 'user', 'message', ?, '', NULL)").run(sid, seq, id, seq + 1, hash); + }); +} + +/** A kernel content-hash row (the mint shape MINTED_ROW_RE matches). */ +const H = (i: number): string => `h_${i.toString(16).padStart(16, "0")}`; + +type DLog = { level: string, msg: string }; +function captureLog(): { logs: DLog[], log: (level: string, msg: string) => void } { + const logs: DLog[] = []; + return { logs, log: (level, msg) => logs.push({ level, msg }) }; +} +const jumpWarns = (logs: DLog[]): DLog[] => + logs.filter((l) => l.level === "warn" && l.msg.includes("namespace jump")); + +// --------------------------------------------------------------------------- +// J1 — the issue's shape: an all-h_ ledger meets the host-uuid tail. +// --------------------------------------------------------------------------- + +test("#7981 J1: all-h_ ledger + host-uuid tail pins (was the null deadlock) — prefix from the ledger, new core from the declared ids, one warn", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j1-sid"; + // The poisoned ledger: every row is a server-minted content hash + // (the pre-upgrade wire space), 5 live rows. + const h5 = [H(1), H(2), H(3), H(4), H(5)]; + seedLedger(db, sid, h5); + // Steady-state tail: anchor (the ledger frontier, NOW a host uuid — it + // used to be h_<5>) + one new core. + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-u05", "host-u06"], pluginMode: true, log, + }); + assert.notEqual(r.pinned, null, "the jump is tolerated — the pin applies (pre-fix: null, full signal, forever)"); + assert.equal(r.pinMode, "incremental", "a successful pin ⇒ the client stays incremental (no full-resend churn)"); + assert.deepEqual(r.pinned!.map((m) => m.id).slice(0, 5), h5, "the prefix re-stamps from the LEDGER (its h_ rows are the canonical kernel reference space — write-once)"); + assert.equal(r.pinned![5].id, "host-u06", "the new core takes the declared host id"); + const warns = jumpWarns(logs); + assert.equal(warns.length, 1, "exactly one namespace-jump warn for the session"); + // A second jump turn (the ledger not yet swept) re-fires the branch but + // does NOT re-warn (once-per-session guard). + const r2 = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-u05", "host-u06b"], pluginMode: true, log, + }); + assert.notEqual(r2.pinned, null, "idempotent — the jump branch is stable across turns"); + assert.equal(jumpWarns(logs).length, 1, "the warn stays once per session"); +}); + +// --------------------------------------------------------------------------- +// J2 — after the first RAW (miss) turn the sweep has converged the ledger's +// tail to host ids; the ORDINARY positional path pins again, no jump. +// --------------------------------------------------------------------------- + +test("#7981 J2: post-sweep converged ledger (h_ prefix + host-id tail) pins on the ordinary path — no jump branch, no warn", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j2-sid"; + // J1's ledger after the sweep retires nothing new and appends the + // declared id: [h_1..h_5, host-u06]. + seedLedger(db, sid, [H(1), H(2), H(3), H(4), H(5), "host-u06"]); + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(7), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-u06", "host-u07"], pluginMode: true, log, + }); + assert.notEqual(r.pinned, null, "the anchor now MATCHES the ledger (host id) — ordinary positional pin"); + assert.equal(r.pinMode, "incremental"); + assert.equal(r.pinned![5].id, "host-u06", "the converged row keeps its host id"); + assert.equal(r.pinned![6].id, "host-u07", "the new core pins as before"); + assert.equal(jumpWarns(logs).length, 0, "no namespace jump — the fingerprint must not fire on a shared namespace"); +}); + +// --------------------------------------------------------------------------- +// J3 — mixed-ledger transients (hit turns keep the sweep off, #7366). +// --------------------------------------------------------------------------- + +test("#7981 J3a: a PARTIALLY converged ledger (anchor already a host id, rest h_) pins on the ordinary path", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j3a-sid"; + seedLedger(db, sid, [H(1), H(2), H(3), H(4), "host-u05"]); + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-u05", "host-u06"], pluginMode: true, log, + }); + assert.notEqual(r.pinned, null, "the single overlap row matches — the ordinary path handles it"); + assert.equal(jumpWarns(logs).length, 0, "a matching anchor is NOT a namespace jump"); +}); + +test("#7981 J3b: a drift INSIDE a mixed ledger (h_ row under a host uuid, the rest converged) still converges — no null oscillation", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j3b-sid"; + // One straggler h_ row (the sweep was off on hit turns) with the rest + // already converged: the overlap row drifts (host uuid vs h_) while a + // later overlap row would match — per-row fingerprint, not list-wide. + seedLedger(db, sid, [H(1), H(2), H(3), H(4), "host-u05"]); + // Anchor at row 4 is host-u05 (matches); the drifted row is NOT + // reachable in a 1-overlap steady tail, so use a longer (truncated-form) + // list that reaches back to row 3, which still carries an h_. + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-u04", "host-u05", "host-u06"], pluginMode: true, log, + }); + assert.notEqual(r.pinned, null, "drift row (h_4 vs host-u04) is a jump row; match row (host-u05) is shared — the mixed case converges"); + assert.equal(r.pinned![3].id, H(4), "the straggler position keeps its ledger id (canonical, write-once)"); + assert.equal(r.pinned![4].id, "host-u05", "the converged row keeps its host id"); + assert.equal(r.pinned![5].id, "host-u06", "the new core takes the declared id"); + assert.equal(jumpWarns(logs).length, 1, "the jump branch fired exactly once"); +}); + +// --------------------------------------------------------------------------- +// J4 — real drift over a HOST-ID ledger (a shared namespace) still nulls. +// --------------------------------------------------------------------------- + +test("#7981 J4: drift over a host-id ledger (shared namespace, e.g. a rolled-back or rewritten history) keeps the legacy null degrade", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j4-sid"; + // Fully converged ledger: every row is a host id (no h_ mint anywhere). + seedLedger(db, sid, ["host-a01", "host-a02", "host-a03", "host-a04", "host-a05"]); + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["host-999", "host-a06"], pluginMode: true, log, + }); + assert.equal(r.pinned, null, "the drifted ledger row is a HOST id — not a namespace jump, ordinary drift"); + assert.equal(r.pinMode, "full", "the full signal re-converges next turn (the legacy contract)"); + assert.equal(jumpWarns(logs).length, 0, "no jump warn for a shared-namespace drift"); +}); + +// --------------------------------------------------------------------------- +// J5 — a "?" slot proves no namespace. +// --------------------------------------------------------------------------- + +test("#7981 J5: a '?' slot in the overlap position degrades (a content-derived slot proves no namespace)", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j5-sid"; + seedLedger(db, sid, [H(1), H(2), H(3), H(4), H(5)]); + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: ["?", "host-u06"], pluginMode: true, log, + }); + assert.equal(r.pinned, null, "'?' at a drift row is NOT a jump row — conservative degrade"); + assert.equal(r.pinMode, "full"); + assert.equal(jumpWarns(logs).length, 0); +}); + +// --------------------------------------------------------------------------- +// J6 — the foreign-id check is per ROW: a drifted id that exists elsewhere +// in the ledger is shared-namespace drift, not a jump. +// --------------------------------------------------------------------------- + +test("#7981 J6: a drifted client id that exists ELSEWHERE in the ledger degrades (the fingerprint is per-row, not list-wide)", (t: test.TestContext) => { + const { store } = harness(t); + const db = (store as unknown as { db: DbLike }).db; + const { logs, log } = captureLog(); + const sid = "j6-sid"; + seedLedger(db, sid, [H(1), H(2), H(3), H(4), H(5)]); + // H(2) is a ledger row — sending it at the anchor position means the + // client's namespace SHARES ids with the ledger (reordered/rewritten + // history), not a clean jump. + const r = runStage0({ + sessionId: sid, lane: "openai", msgs: dMsgs(6), + incomingMsgIds: undefined, incomingSeqs: null, + incomingTailIds: [H(2), "host-u06"], pluginMode: true, log, + }); + assert.equal(r.pinned, null, "a shared (non-foreign) id at a drift row keeps the legacy null degrade"); + assert.equal(r.pinMode, "full"); + assert.equal(jumpWarns(logs).length, 0); +}); From 9ca769420bdc47c344247f832ea62bd655521c6c Mon Sep 17 00:00:00 2001 From: ci-check Date: Tue, 1 Dec 2026 11:43:59 +0800 Subject: [PATCH 2/2] ci: re-trigger close-object-guard after adding 'Fixes #7981' to PR body (#7973)