perf(storage): in-txn window re-anchor supersedes the pre-resolved lookup (#7474, ruling 7439)

e06a2a9fd's window plan (planner-side seq resolution + the delta
option) cannot fire on the measured pf shape: the delta branch's
trustedTailSeqs prefix defense structurally rejects a sliding window
(the plan's tailSeqs ARE the current window, not an extension of the
previous one); the all-hit pre-resolution can never hold because the
window's newest row is new on every HIT turn; the equal-length shape
was missed; and the msg_id-only lookup verified neither bytes nor
tombstones.

Replaced by the in-transaction identity re-anchor (already landed in
the store with 524d1b99b): planIngestReanchor + the store reanchor
branch + the shadow fallback in both twins. Per-row
(session_id, msg_id, identity) probe; existing rows keep their seq,
byte/tombstone checks refuse to the full path, new rows continue
after MAX(seq), ref backfill at first join. Any doubt = the exact
pre-change full path. planIngestDeltaWindow removed as superseded.

tests/window-reanchor-delta.test.ts: the sliding-window repro (refuses
the delta gate, re-anchors, per-row seq stable across slides) + the
refusal set (no session row, tombstoned window row healed by the full
path).

kernel-change: none.
This commit is contained in:
ranxianglei
2026-11-22 12:05:03 +08:00
parent 524d1b99b9
commit fb88bc2af2
4 changed files with 291 additions and 79 deletions
+30 -37
View File
@@ -74,6 +74,13 @@ interface IngestPlan extends IngestSessionInput {
/** Resolved log seqs for pluginSnapshot entries (null when absent). */
pluginSnapshotSeqs: number[] | null;
tailSeqs: number[] | null;
/** Window re-anchor (#7474): every plan row is RESOLVED by indexed
* identity point lookup inside the ingest transaction (existing row
* keeps its seq, new rows continue after max(seq)) instead of the
* full path's O(all rows) identity-map scan. A plan with zero
* resolvable rows (nothing anchored yet) refuses in-txn and falls to
* the full ingest. */
reanchor?: boolean;
}
/** #3133 test instrumentation: per-message JSON serializations performed by
@@ -399,51 +406,37 @@ export function planIngestDelta(
return finishPlan(session, byRawRef, log, pluginSnapshotSeqs, tailSeqs);
}
/** #7439 window re-anchor delta: handles the sliding-window shape where
* tail.length < trustedLen (the pf watermark fast-path HIT turn persists
* only the tail window, not the full history). Instead of the strict-append
* assumption, per-row point-lookup the absolute seq of each window row via
* idx_messages_identity. All rows must hit → tailSeqs = resolved seq list
* (envelope order), new rows append at max(seq)+1, sweep stays off. Any
* row missing → null (caller falls back to full ingest).
*
* @param windowSeqs the resolved absolute seqs for each row in
* `session.lastMessages[0..windowLen)`, in envelope order. Must be the same
* length as `windowLen`. null if any lookup failed.
*/
export function planIngestDeltaWindow(
session: LegacySessionLike,
windowLen: number,
windowSeqs: number[],
boundary: { msgId: string; contentHash: string },
hasRawTail: boolean,
head?: { msgId: string } | null,
): IngestPlan | null {
/** #7474 window re-anchor planner: the pf-window lane persists only the
* tail window (~56 rows), so planIngestDelta's strict-append assumption
* (the tail EXTENDS the trusted prefix) is structurally false — equal /
* sliding / shrinking windows refuse at the gate, and the full ingest
* pays O(all session rows) per HIT turn to re-derive what one indexed
* point lookup per window row can answer (idx_messages_identity):
* existing rows keep their seq, new rows continue after max(seq). Every
* window row is identity-probed inside the transaction — no positional
* assumption rides below the window (the same trust model the full path
* gives window plans; the sampled digest stays the backstop). Any doubt
* (all rows new, a tombstone, changed bytes at a stable identity) refuses
* to the exact full path. */
export function planIngestReanchor(session: LegacySessionLike): IngestPlan | null {
if (session.pluginSnapshot && session.pluginSnapshot.length > 0) return null;
// #3301: import payloads need the full path (sweep + lowest-seq rows).
if (session.decompositionLog && session.decompositionLog.length > 0) return null;
const tail = session.lastMessages;
if (!tail || windowLen <= 0 || windowLen > tail.length || windowSeqs.length !== windowLen) return null;
// Boundary probe: the LAST window row must match the boundary.
const probe = serializeForStore(tail[windowLen - 1]);
ingestSerializations.count++;
if (tail[windowLen - 1].id !== boundary.msgId || splitMediaContent(probe).hash !== boundary.contentHash) return null;
// Head probe: the FIRST window row must match the head.
if (head !== undefined && head !== null && windowLen > 1 && tail[0].id !== head.msgId) return null;
if (!tail || tail.length === 0) return null;
const byRawRef = session.state.messageRefs.byRaw;
const log: LogEntry[] = [];
const appended: number[] = [];
const maxWindowSeq = Math.max(...windowSeqs);
// New rows (beyond the window) append at max(windowSeqs) + 1.
for (let i = windowLen; i < tail.length; i++) {
for (let i = 0; i < tail.length; i++) {
const m = tail[i];
const raw = serializeForStore(m);
ingestSerializations.count++;
const parsed = JSON.parse(raw) as { role: string; contentType?: string };
const split = splitMediaContent(raw);
const seq = maxWindowSeq + 1 + log.length;
appended.push(seq);
// Placeholder seqs in WINDOW ORDER (1..n); the transaction resolves
// each to its absolute seq (existing row's seq or max(seq)+k) and
// remaps tailSeqs + block bounds through the same map.
log.push({
seq,
seq: i + 1,
msgId: m.id,
content: split.content,
hash: split.hash,
@@ -456,9 +449,9 @@ export function planIngestDeltaWindow(
});
}
const pluginSnapshotSeqs = session.pluginSnapshot ? [] : null;
// tailSeqs = resolved window seqs (envelope order) + new row seqs.
const tailSeqs = [...windowSeqs, ...appended];
return finishPlan(session, byRawRef, log, pluginSnapshotSeqs, tailSeqs);
const plan = finishPlan(session, byRawRef, log, pluginSnapshotSeqs, log.map((e) => e.seq));
plan.reanchor = true;
return plan;
}
/** Shared plan tail (everything except the messages log): given the same
+41 -31
View File
@@ -31,7 +31,7 @@
*/
import { log as loggerLog } from "../logger.js";
import { planIngest, planIngestDelta, planIngestDeltaWindow, loadLegacyView, LegacyViewBuilder, appendBlockContents, mergeOrphanBlockContents, completeBlockContents, type LegacySessionLike } from "./ingest.ts";
import { planIngest, planIngestDelta, planIngestReanchor, loadLegacyView, LegacyViewBuilder, appendBlockContents, mergeOrphanBlockContents, completeBlockContents, type LegacySessionLike } from "./ingest.ts";
import type { CcrLedgerRow } from "./slim.ts";
import { splitMediaContent } from "./identity.js";
import type { BlockView } from "../session.js";
@@ -861,38 +861,32 @@ export class UnifiedShadow {
if (headMsgId === null) return false;
head = { msgId: headMsgId };
}
let plan = planIngestDelta(legacy, mark.seq, mark.tailSeqs, { msgId: boundary.msgId, contentHash: boundary.contentHash }, hasRawTail, head);
if (!plan) {
// #7439 window re-anchor delta: the pf watermark fast-path HIT
// turn persists only the tail window (~56 rows), so
// tail.length < trustedLen (shrink) is the structural shape.
// Per-row point-lookup the absolute seq of each window row via
// idx_messages_identity; all hit → window plan, any miss →
// full ingest as before. No invariant loosened.
const tail = legacy.lastMessages;
const trustedLen = mark.tailSeqs.length;
if (tail && trustedLen > 0 && tail.length < trustedLen) {
const windowSeqs: number[] = [];
let allHit = true;
for (let i = 0; i < tail.length; i++) {
const seq = this.sync.lookupSeqByMsgId(legacy.id, tail[i].id);
if (seq === null) { allHit = false; break; }
windowSeqs.push(seq);
}
if (allHit) {
plan = planIngestDeltaWindow(legacy, tail.length, windowSeqs, { msgId: boundary.msgId, contentHash: boundary.contentHash }, hasRawTail, head);
}
const plan = planIngestDelta(legacy, mark.seq, mark.tailSeqs, { msgId: boundary.msgId, contentHash: boundary.contentHash }, hasRawTail, head);
if (plan) {
const applied = this.sync.ingestSession(plan, {
trustedSeq: mark.seq,
boundaryMsgId: boundary.msgId,
boundaryHash: boundary.contentHash,
trustedTailSeqs: mark.tailSeqs,
});
if (applied) this.stats.deltaIngests++;
return applied;
}
// #7474 window re-anchor: envelope (folded-render) shapes that
// violate strict-append — the pf-window lane's sliding tail
// window — resolve per-row by indexed identity instead of the
// O(all rows) full remap. Raw lineage never enters (its delta
// gates stay authoritative there); any in-txn doubt returns the
// caller to the exact full path.
if (!hasRawTail) {
const rp = planIngestReanchor(legacy);
if (rp) {
const applied = this.sync.ingestSession(rp, undefined, undefined, { trustedTailSeqs: mark.tailSeqs });
if (applied) this.stats.deltaIngests++;
return applied;
}
}
if (!plan) return false;
const applied = this.sync.ingestSession(plan, {
trustedSeq: mark.seq,
boundaryMsgId: boundary.msgId,
boundaryHash: boundary.contentHash,
trustedTailSeqs: mark.tailSeqs,
});
if (applied) this.stats.deltaIngests++;
return applied;
return false;
} catch {
return false;
}
@@ -1218,6 +1212,13 @@ export class UnifiedShadow {
return this.sync.snapMsgIdLiveIds(sessionId);
}
/** #7474 P2 (ruling 7439): pin ledger entry — egress op log when the
* session has one, messages rows otherwise (see UnifiedStore.snapPinLiveIds). */
snapPinLiveIds(sessionId: string): string[] {
if (this.sync === null) return [];
return this.sync.snapPinLiveIds(sessionId);
}
/** #7398 seg 3: the sqlite UnifiedStore behind this shadow — the egress
* op-log recorder's narrow seam. Null on network backends (mysql): the
* shadow tables are sqlite-lane only, and the recorder skips the turn
@@ -1480,6 +1481,15 @@ export class UnifiedShadow {
if (plan) {
applied = await backend.ingestSession(plan, { trustedSeq: mark.seq, boundaryMsgId: boundary.msgId, boundaryHash: boundary.contentHash, trustedTailSeqs: mark.tailSeqs });
if (applied) this.stats.deltaIngests++;
} else if (!hasRawTail) {
// #7474 window re-anchor (async twin): sliding
// tail windows resolve per-row by indexed
// identity instead of the O(all rows) remap.
const rp = planIngestReanchor(legacy);
if (rp) {
applied = this.sync?.ingestSession(rp, undefined, undefined, { trustedTailSeqs: mark.tailSeqs }) ?? false;
if (applied) this.stats.deltaIngests++;
}
}
}
}
-11
View File
@@ -2452,17 +2452,6 @@ export class UnifiedStore {
return row ? row.msg_id : null;
}
/** #7439 window re-anchor delta: point-lookup the absolute seq for a
* (session_id, msg_id) pair via idx_messages_msg_id. Returns null when
* the row is missing. O(1) index probe. msg_id is unique within a
* session (kernel invariant), so the identity column is not needed. */
lookupSeqByMsgId(sessionId: string, msgId: string): number | null {
const row = this.db
.prepare("SELECT seq FROM messages WHERE session_id = ? AND msg_id = ?")
.get(sessionId, msgId) as { seq: number } | undefined;
return row ? row.seq : null;
}
/** #3301: message rows for the given ids — EVERY seq row matching an id
* (edits append; callers keep the latest per id) plus, when
* includeNeighbors, the seq±1 rows so split-form rc pairs stay adjacent
+220
View File
@@ -0,0 +1,220 @@
/**
* #7474 window re-anchor delta: the pf-window lane persists only the tail
* WINDOW every HIT turn, so planIngestDelta's strict-append assumption
* (the tail extends the trusted prefix) is structurally false — equal /
* sliding / shrinking windows refuse at the gate and the full ingest paid
* O(all session rows) per HIT turn to re-derive identity→seq. The re-anchor
* path resolves every window row by ONE indexed identity point lookup
* instead: existing rows keep their seq, new rows continue after max(seq),
* tailSeqs become the window's absolute seqs in envelope order —
* byte-identical to what the full path writes for a window plan. This suite
* pins:
* 1. the repro: a sliding window refuses planIngestDelta (pre-fix every
* HIT turn took the full path);
* 2. seq stability across sliding windows (the D4-1 contract — same
* identity keeps its seq, no re-basing);
* 3. new rows land at max(seq)+k with the watermark following the window
* tip;
* 4. every doubt falls to the exact full path (unknown session = no
* anchor; a tombstoned window row = #4390 reactivation territory).
*/
import { test } from "node:test";
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { UnifiedStore } from "../src/storage/store.ts";
import { planIngest, planIngestDelta, planIngestReanchor, type LegacySessionLike } from "../src/storage/ingest.ts";
import type { CoreMessage } from "../kernel/src/types.js";
const hermetic = fs.mkdtempSync(path.join(os.tmpdir(), "bili-reanchor-hermetic-"));
process.env.BILI_CONFIG_FILE = path.join(hermetic, "no-config.json");
process.env.BILI_STORAGE_UNIFIED = "legacy";
function tmpdir(prefix: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
const refToken = (i: number): string => `m${String(i + 1).padStart(5, "0")}`;
function msg(i: number): CoreMessage {
return { id: `h_msg${i}`, role: i % 2 === 0 ? "user" : "assistant", contentType: "text", text: `hello ${i}` } as CoreMessage;
}
/** Envelope (folded-render) presentation of rows [from, to) plus the new
* row `to`: the pf-window shape — lastMessagesFolded, no raw tail. */
function mkWindow(id: string, from: number, toExclusive: number, folded: boolean): LegacySessionLike {
const byRaw: Record<string, string> = {};
const byRef: Record<string, string> = {};
const lastMessages: CoreMessage[] = [];
for (let i = from; i <= toExclusive; i++) {
const ref = refToken(i);
byRaw[`h_msg${i}`] = ref;
byRef[ref] = `h_msg${i}`;
lastMessages.push(msg(i));
}
return {
id,
createdAt: 1_000,
lastSeen: 2_000 + toExclusive,
meta: { protocol: "anthropic" },
stats: { requests: toExclusive + 1 },
metadata: {},
state: {
blocks: [],
messageRefs: { byRaw, byRef },
nextBlockId: 1,
nextRunId: 1,
},
blockContents: new Map(),
lastMessages,
lastMessagesFolded: folded,
contentStore: { version: 1 as const, byHash: {} as Record<string, string>, byRef: {} as Record<string, unknown> },
} as LegacySessionLike;
}
function mkRaw(id: string, count: number): LegacySessionLike {
const byRaw: Record<string, string> = {};
const byRef: Record<string, string> = {};
const lastMessages: CoreMessage[] = [];
for (let i = 0; i < count; i++) {
const ref = refToken(i);
byRaw[`h_msg${i}`] = ref;
byRef[ref] = `h_msg${i}`;
lastMessages.push(msg(i));
}
return {
id,
createdAt: 1_000,
lastSeen: 2_000 + count,
meta: { protocol: "anthropic" },
stats: { requests: count },
metadata: {},
state: {
blocks: [],
messageRefs: { byRaw, byRef },
nextBlockId: 1,
nextRunId: 1,
},
blockContents: new Map(),
lastMessages,
lastMessagesFolded: false,
contentStore: { version: 1 as const, byHash: {} as Record<string, string>, byRef: {} as Record<string, unknown> },
} as LegacySessionLike;
}
interface Row {
seq: number;
msg_id: string;
content_hash: string;
retired_at: number | null;
}
function rows(store: UnifiedStore, sid: string): Row[] {
return (store as unknown as { db: { prepare(q: string): { all(...a: unknown[]): unknown } } }).db
.prepare("SELECT seq, msg_id, content_hash, retired_at FROM messages WHERE session_id = ?")
.all(sid) as Row[];
}
test("#7474: sliding window refuses the delta gate and re-anchors by indexed identity", () => {
const dir = tmpdir("bili-reanchor-");
const store = UnifiedStore.open(path.join(dir, "index.db"));
try {
const sid = "sess-window";
// Turn 1: raw full view of 100 rows establishes the ledger.
const t1 = mkRaw(sid, 100);
assert.ok(store.ingestSession(planIngest(t1), undefined, { completeLog: true }));
const base = rows(store, sid);
assert.equal(base.length, 100);
const seqOf = new Map(base.map((r) => [r.msg_id, r.seq]));
// Turn 2: the HIT-turn window — rows 44..99 slide in PLUS new row
// 100 (57 envelope rows, no raw tail). PRE-FIX repro: the delta
// planner refuses this shape (equal-length / boundary gates), so
// every HIT turn paid the O(all rows) full remap.
const t2 = mkWindow(sid, 44, 100, true);
const mark2 = store.ingestWatermark(sid)!;
const boundary2 = store.probeIngestBoundary(sid, mark2.seq)!;
assert.equal(
planIngestDelta(t2, mark2.seq, mark2.tailSeqs, { msgId: boundary2.msgId, contentHash: boundary2.contentHash }, false),
null,
"sliding window must still refuse strict-append (the repro)",
);
const p2 = planIngestReanchor(t2);
assert.ok(p2, "re-anchor planner accepts the window shape");
assert.ok(
store.ingestSession(p2, undefined, { completeLog: false }, { trustedTailSeqs: mark2.tailSeqs }),
"re-anchor commit",
);
let cur = rows(store, sid);
assert.equal(cur.length, 101, "only the ONE new row lands — no full rewrite");
for (const r of cur) {
if (r.msg_id !== "h_msg100") assert.equal(r.seq, seqOf.get(r.msg_id), `seq stability for ${r.msg_id}`);
}
seqOf.set("h_msg100", 100);
let tail2 = store.tailSeqs(sid)!;
assert.equal(tail2.length, 57, "tailSeqs = the window, in envelope order");
assert.equal(tail2[0], seqOf.get("h_msg44"), "window head keeps its absolute seq");
assert.equal(tail2[56], 100, "new row continues after max(seq)");
assert.equal(store.ingestWatermark(sid)!.seq, 100, "watermark follows the window tip");
// Turn 3: the window slides again (45..100 + new 101) — seqs must
// stay put (D4-1) and the ledger grows by one.
const t3 = mkWindow(sid, 45, 101, true);
const mark3 = store.ingestWatermark(sid)!;
assert.equal(mark3.seq, 100, "tip after the second window");
const boundary3 = store.probeIngestBoundary(sid, mark3.seq)!;
assert.equal(planIngestDelta(t3, mark3.seq, mark3.tailSeqs, { msgId: boundary3.msgId, contentHash: boundary3.contentHash }, false), null);
const p3 = planIngestReanchor(t3)!;
assert.ok(store.ingestSession(p3, undefined, { completeLog: false }, { trustedTailSeqs: mark3.tailSeqs }));
cur = rows(store, sid);
assert.equal(cur.length, 102);
for (const r of cur) {
if (r.msg_id !== "h_msg101") assert.equal(r.seq, seqOf.get(r.msg_id), `seq stability after second slide (${r.msg_id})`);
}
const tail3 = store.tailSeqs(sid)!;
assert.equal(tail3[0], seqOf.get("h_msg45"));
assert.equal(tail3[tail3.length - 1], 101);
assert.equal(store.ingestWatermark(sid)!.seq, 101);
} finally {
store.close();
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* win */ }
}
});
test("#7474: re-anchor refuses with nothing to anchor and with tombstoned window rows", () => {
const dir = tmpdir("bili-reanchor-refuse-");
const store = UnifiedStore.open(path.join(dir, "index.db"));
try {
// Unknown session: every row is new → no anchor → refuse (the full
// path must establish the rows, not the re-anchor). No session row
// yet, so the trusted tail is empty.
const fresh = mkWindow("sess-fresh", 0, 5, true);
const pf = planIngestReanchor(fresh);
assert.ok(pf);
assert.ok(!store.ingestSession(pf, undefined, { completeLog: false }, { trustedTailSeqs: [] }), "no session row → refuse to the full path");
assert.ok(store.ingestSession(planIngest(fresh), undefined, { completeLog: true }));
// Tombstoned window row: #4390 rewind-redo territory — the full
// path reactivates in place; a pointer at a retired seq would drop
// the row from the view.
const sid = "sess-tomb";
const t1 = mkRaw(sid, 10);
assert.ok(store.ingestSession(planIngest(t1), undefined, { completeLog: true }));
(store as unknown as { db: { prepare(q: string): { run(...a: unknown[]): unknown } } }).db
.prepare("UPDATE messages SET retired_at = ? WHERE session_id = ? AND msg_id = ?")
.run(Date.now(), sid, "h_msg8");
const t2 = mkWindow(sid, 5, 10, true);
const mark = store.ingestWatermark(sid)!;
const p2 = planIngestReanchor(t2)!;
assert.ok(!store.ingestSession(p2, undefined, { completeLog: false }, { trustedTailSeqs: mark.tailSeqs }), "tombstone must fall to the full path");
// And the full path still heals (reactivates) it — the COMPLETE raw
// view, so the sweep has nothing legitimate to retire.
assert.ok(store.ingestSession(planIngest(mkRaw(sid, 11)), undefined, { completeLog: true }));
assert.ok(rows(store, sid).every((r) => r.retired_at === null));
} finally {
store.close();
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* win */ }
}
});