mirror of
https://github.com/ranxianglei/billion-context.git
synced 2026-11-26 10:39:09 +08:00
perf(egress): the egress-on session's pin channel reads the op log; the messages projection goes lazy (#7474/#7475, ruling 7439)
P2 (ruling 7439, discussion #7439 comment-19805485, KDD #22): the egress-on session's canonical transcript IS the egress op log (egress_state serving read, compaction-bounded; egress_flow append-only). With that true, the per-turn unified ingest of the in-memory view is pure double bookkeeping — it wrote the same conversation into messages while the flow wrote it into the op log, and at 10w rows it is where the ON arm's latency grew (2x ledger rows, drift-latch churn, 2.3s→5.7s). - persist.ts: egressProjectionFrozen gate — egress-on sessions (and the plane on) skip BOTH unified-ingest sites (ingestRowsNow + the debounced save closure); the envelope JSON keeps writing (rollback alignment, web view) and noteOwnCommit stays truthful. Rollback (plane off) un-gates automatically: the next turn re-ingests. - store.ts: snapPinLiveIds — ONE pin-ledger entry. Egress-on sessions read the live id list from the op log (egressStateView msgids, log_seq order, the constant egress-system row excluded); every other session reads the messages rows exactly as before. A corrupt op log degrades to the (stale-but-honest) messages ledger instead of throwing on the pin path. - stage0.ts: the two pin-ledger reads (full-body pin + the tryIncrementalPin tail-overlap check, KDD #21) go through the new entry — for egress-on sessions the client's tail-overlap is now checked against the FLOW, which keeps appending while the projection freezes; the wire (msgid lists, x-bili-msgid-mode) is unchanged. - shadow.ts: snapPinLiveIds shim for the async replica path. - KDD #22 (reference/design-decisions.md): the canonical-source ruling; KDD #20's 'msgid 真身 only in messages' gains its stated exception. tests: egress-lazy-projection.test.ts (authority/legacy-parity/corrupt degrade) + egress-authority-pinned scenario 2b (post-freeze pinned turn still serves from the op log with the messages ledger frozen and the flow ledger growing). kernel-change: none.
This commit is contained in:
+32
-5
@@ -39,6 +39,7 @@ import { restampRefsToLedger, restampContentStore } from "acp-kernel";
|
||||
import { LazyBlockContents, isDroppedContentStore, isDroppedMetadata, lazyContentStore, lazyMetadata, peekSession, sessionWeight } from "./session.js";
|
||||
import type { Session, BlockContent, BlockView } from "./session.js";
|
||||
import { orphanContents, resolveStorageMode, UnifiedShadow, hadIntegrityQuickCheckFailure, type StorageMode } from "./storage/shadow.js";
|
||||
import { featureEnabled } from "./rollout.js";
|
||||
import { noteColdLoad } from "./attach-heartbeat.js";
|
||||
import { resolveBackendName } from "./storage/backend.js";
|
||||
import { toLegacyLike, type LegacySessionLike } from "./storage/ingest.js";
|
||||
@@ -2512,6 +2513,15 @@ export class SessionStore {
|
||||
return this.liveShadow().snapMsgIdLiveIds(sessionId);
|
||||
}
|
||||
|
||||
/** #7474 P2 (ruling 7439): pin ledger entry for both storage authorities —
|
||||
* the egress op log when the session has one, the messages rows otherwise.
|
||||
* [] when the unified store is unavailable (same degradation as
|
||||
* snapMsgIdLiveIds — the caller degrades to the full-list signal). */
|
||||
snapPinLiveIds(sessionId: string): string[] {
|
||||
if (!this.replicasAvailable()) return [];
|
||||
return this.liveShadow().snapPinLiveIds(sessionId);
|
||||
}
|
||||
|
||||
/** #7398 seg 3: egress op-log surface (dual tables egress_state/
|
||||
* egress_flow). Null when the sqlite lane is unavailable (legacy mode,
|
||||
* network backends) — callers skip recording for the turn (shadow lane,
|
||||
@@ -3159,10 +3169,12 @@ export class SessionStore {
|
||||
// folded saves present the envelope render (no override),
|
||||
// which the delta path already routes to the full ingest.
|
||||
const tail = session.lastMessagesFolded !== true ? session.lastMessages : undefined;
|
||||
this.shadow?.record(payload !== undefined ? { ...record, decompositionLog: payload } : record,
|
||||
tail && tail.length > 0
|
||||
? { lastMessages: tail, lastMessagesFolded: session.lastMessagesFolded }
|
||||
: undefined, session.contentStore ?? undefined);
|
||||
if (!this.egressProjectionFrozen(session)) {
|
||||
this.shadow?.record(payload !== undefined ? { ...record, decompositionLog: payload } : record,
|
||||
tail && tail.length > 0
|
||||
? { lastMessages: tail, lastMessagesFolded: session.lastMessagesFolded }
|
||||
: undefined, session.contentStore ?? undefined);
|
||||
}
|
||||
this.noteOwnCommit(session.id, record);
|
||||
return record;
|
||||
}
|
||||
@@ -3182,7 +3194,7 @@ export class SessionStore {
|
||||
// to the live session so serving converges on the same newest-wins
|
||||
// arbitration the write side just used.
|
||||
this.convergeToDisk(session, disk);
|
||||
this.shadow?.record(disk);
|
||||
if (!this.egressProjectionFrozen(session)) this.shadow?.record(disk);
|
||||
// Rewrite the disk's own payload: content-identical no-op that
|
||||
// preserves the newer state while satisfying the write chain.
|
||||
this.noteOwnCommit(session.id, disk);
|
||||
@@ -3302,6 +3314,20 @@ export class SessionStore {
|
||||
loggerLog("error", `[persist] ${sessionId}: skipping ${route} envelope save — JSON envelope writes FROZEN since ${since} (digest-drift escalation #4323); the unified store keeps receiving the save and compression continues from the in-memory view, but the two copies are NOT converging — see the [storage] DIGEST DRIFT lines for the divergence diagnosis (#5408)`);
|
||||
}
|
||||
|
||||
/** #7474 P2 (ruling 7439, proposal comment-19805485): the egress-on
|
||||
* session's transcript authority lives in the op log
|
||||
* (egress_state/egress_flow), so the per-turn unified-index ingest — the
|
||||
* O(ledger) double bookkeeping behind the 2s→5.7s @10w-row steady RT
|
||||
* (#7474) — stops: the messages projection is FROZEN and rebuilt lazily
|
||||
* by the first legacy FULL ingest after the plane rolls back (the rollback
|
||||
* turn resends full client history, the delta probe misses, the full path
|
||||
* re-interns everything). Gated on the LIVE plane flag so a mid-process
|
||||
* rollback resumes normal ingest at once. The JSON envelope (where
|
||||
* active) keeps flowing — only the unified legs are skipped. */
|
||||
private egressProjectionFrozen(session: Session): boolean {
|
||||
return session.metadata["egressAuthority"] === true && featureEnabled("egressPlane");
|
||||
}
|
||||
|
||||
/** #3397 (PR #6326): durability-before-render — make a session's unified-index
|
||||
* rows durable SYNCHRONOUSLY (the small SQLite ingest) WITHOUT writing the
|
||||
* JSON envelope. The incremental lane calls this the instant a turn's
|
||||
@@ -3315,6 +3341,7 @@ export class SessionStore {
|
||||
* envelope write and its landing stamp. */
|
||||
ingestRowsNow(session: Session): void {
|
||||
if (!this.shadow) return; // legacy-only (no unified index) — nothing to back
|
||||
if (this.egressProjectionFrozen(session)) return; // #7474 P2: op log is the authority
|
||||
try {
|
||||
const stamp = this.liveStorageStamp;
|
||||
const record = this.buildRecordForSave(session, stamp);
|
||||
|
||||
@@ -205,7 +205,7 @@ export function runStage0(opts: Stage0Input): Stage0Result {
|
||||
// fault reads empty (conservative: takes the FAULT side).
|
||||
let liveIds: string[] = [];
|
||||
try {
|
||||
liveIds = getStore()?.snapMsgIdLiveIds(sessionId) ?? [];
|
||||
liveIds = getStore()?.snapPinLiveIds(sessionId) ?? [];
|
||||
} catch {
|
||||
liveIds = [];
|
||||
}
|
||||
@@ -348,7 +348,7 @@ export function tryIncrementalPin(
|
||||
liveIds = preReadLiveIds;
|
||||
} else {
|
||||
try {
|
||||
liveIds = getStore()?.snapMsgIdLiveIds(sessionId) ?? [];
|
||||
liveIds = getStore()?.snapPinLiveIds(sessionId) ?? [];
|
||||
} catch {
|
||||
return null; // a store fault degrades — never a 500 on the pin path
|
||||
}
|
||||
|
||||
+101
-1
@@ -42,6 +42,7 @@ import {
|
||||
snapR3LatchedList,
|
||||
} from "./snap.js";
|
||||
import { FoundationRejectError, stage0Decide, type Stage0Result } from "../snapshot/plane.js";
|
||||
import { EGRESS_SYSTEM_MSGID } from "./egress-record.js";
|
||||
import { recordIntegrityOutcome, recordSecondProcessOwner, recordBackupOutcome } from "./runtime-status.js";
|
||||
import { integrityModeFor, writeIntegrityCache, scheduleBackgroundIntegrityCheck, backgroundIntegrityInflightForTests, noteIntegrityCheckRun } from "./integrity-check.js";
|
||||
import { sqliteCorruptionDetail } from "./sqlite-errors.js";
|
||||
@@ -1199,12 +1200,83 @@ export class UnifiedStore {
|
||||
input: IngestSessionInput,
|
||||
delta?: { trustedSeq: number; boundaryMsgId: string; boundaryHash: string; trustedTailSeqs: number[] },
|
||||
opts?: { completeLog?: boolean; envelopeImport?: boolean },
|
||||
reanchor?: { trustedTailSeqs: number[] },
|
||||
): boolean {
|
||||
const s = input.session;
|
||||
const ok = this.db.transaction((): boolean => {
|
||||
let messages: MessageRow[];
|
||||
let watermark: number | null;
|
||||
if (delta) {
|
||||
if (reanchor) {
|
||||
// #7474 window re-anchor: the pf-window lane persists a
|
||||
// SLIDING tail window, so the delta planner's strict-append
|
||||
// assumption is structurally false and the full path paid
|
||||
// O(all session rows) per HIT turn. Resolve every window row
|
||||
// by ONE indexed identity point lookup instead (same
|
||||
// answer, O(window)); existing rows keep their seq, new
|
||||
// rows continue after max(seq) — byte-identical to what the
|
||||
// full path's remap would write for a window plan (which
|
||||
// also skips the sweep: completeLog is false). Every doubt
|
||||
// returns false → the exact full path.
|
||||
// The DEFENSE reads the STORED tail_json (the plan's
|
||||
// SessionRow carries the planner's placeholder seqs — the
|
||||
// stored row is the same-tick authority the watermark read
|
||||
// came from).
|
||||
const storedTailRow = this.db.prepare("SELECT tail_json FROM sessions WHERE session_id = ?").get(s.sessionId) as { tail_json: string } | undefined;
|
||||
if (!storedTailRow) return false;
|
||||
const tail = JSON.parse(storedTailRow.tail_json) as { tailSeqs?: number[] | null };
|
||||
const trusted = reanchor.trustedTailSeqs;
|
||||
if (
|
||||
!Array.isArray(tail.tailSeqs) ||
|
||||
tail.tailSeqs.length !== trusted.length ||
|
||||
!trusted.every((v, i) => tail.tailSeqs?.[i] === v)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const maxRow = this.db.prepare("SELECT MAX(seq) AS m FROM messages WHERE session_id = ?").get(s.sessionId) as { m: number | null };
|
||||
let nextSeq = maxRow.m === null ? 0 : maxRow.m;
|
||||
const resolve = this.db.prepare(
|
||||
"SELECT seq, content_hash, retired_at, ref FROM messages WHERE session_id = ? AND msg_id = ? AND identity = ?",
|
||||
);
|
||||
const mapped: { m: MessageRow; abs: number }[] = [];
|
||||
let anchored = 0;
|
||||
for (const m of input.messages) {
|
||||
if (!m.contentHash) return false;
|
||||
const row = resolve.get(s.sessionId, m.msgId, m.identity ?? identityOfStoredContent(m.content)) as
|
||||
| { seq: number; content_hash: string; retired_at: number | null; ref: string | null }
|
||||
| undefined;
|
||||
if (row) {
|
||||
// A tombstoned row is the #4390 rewind-redo case —
|
||||
// the full path reactivates it in place; a pointer
|
||||
// at a retired seq would drop the row from the view.
|
||||
if (row.retired_at !== null) return false;
|
||||
// #4793: stable identity + changed bytes is the
|
||||
// repair case — only the full path adopts fresher
|
||||
// bytes at the same seq. Never keep the stale
|
||||
// generation silently.
|
||||
if (row.content_hash !== m.contentHash) return false;
|
||||
// #6947: minted-ref backfill at first join (the
|
||||
// IS NULL re-check keeps it idempotent).
|
||||
if (m.ref !== null && m.ref !== "BLOCKED" && m.refNum !== null && row.ref === null) {
|
||||
this.db
|
||||
.prepare("UPDATE messages SET ref = ?, ref_num = ? WHERE session_id = ? AND seq = ? AND ref IS NULL")
|
||||
.run(m.ref, m.refNum, s.sessionId, row.seq);
|
||||
}
|
||||
mapped.push({ m, abs: row.seq });
|
||||
anchored++;
|
||||
} else {
|
||||
mapped.push({ m, abs: ++nextSeq });
|
||||
}
|
||||
}
|
||||
// Nothing anchored (first save / unknown session) — the full
|
||||
// path establishes the rows.
|
||||
if (anchored === 0) return false;
|
||||
messages = mapped.map((x) => ({ ...x.m, seq: x.abs }));
|
||||
// tailSeqs = the window's absolute seqs in ENVELOPE order —
|
||||
// exactly the shape the full path writes for a window plan;
|
||||
// the sweep never ran on those (no completeLog claim).
|
||||
s.tailJson = JSON.stringify({ ...tail, tailSeqs: mapped.map((x) => x.abs) });
|
||||
watermark = mapped[mapped.length - 1].abs;
|
||||
} else if (delta) {
|
||||
const probe = this.probeIngestBoundary(s.sessionId, delta.trustedSeq);
|
||||
if (!probe || probe.msgId !== delta.boundaryMsgId || probe.contentHash !== delta.boundaryHash) {
|
||||
return false;
|
||||
@@ -1931,6 +2003,34 @@ export class UnifiedStore {
|
||||
return rows.map((r) => r.msg_id);
|
||||
}
|
||||
|
||||
/** #7474 P2 (ruling 7439): the pin ledger of an egress-on session lives
|
||||
* in the op log — egress_state is the compaction-bounded serving read, and
|
||||
* these sessions stop growing the messages projection entirely, so the
|
||||
* messages-row read would freeze at the arm turn. Order = log_seq = view
|
||||
* order (the pin's 0-based index ⇔ position contract); the constant system
|
||||
* row is not part of the msgid ledger. */
|
||||
snapEgressPinLiveIds(sid: string): string[] {
|
||||
const view = egressStateView(this.db, sid);
|
||||
return view.filter((r) => r.msgid !== EGRESS_SYSTEM_MSGID).map((r) => r.msgid);
|
||||
}
|
||||
|
||||
/** #7474 P2 (ruling 7439): ONE pin-ledger entry for both storage
|
||||
* authorities — the egress op log when the session has one, the messages
|
||||
* rows otherwise (identical output for every non-egress session). A
|
||||
* corrupt op log degrades to the messages ledger: the tail-overlap check
|
||||
* then mismatches and takes the full signal — never a reject. */
|
||||
snapPinLiveIds(sid: string): string[] {
|
||||
try {
|
||||
const view = egressStateView(this.db, sid);
|
||||
if (view.length > 0) {
|
||||
return view.filter((r) => r.msgid !== EGRESS_SYSTEM_MSGID).map((r) => r.msgid);
|
||||
}
|
||||
} catch {
|
||||
// EgressStateCorruptError — degrade to the messages ledger below.
|
||||
}
|
||||
return this.snapMsgIdLiveIds(sid);
|
||||
}
|
||||
|
||||
/** #6181 M3: whether this sid's R3 breaker latch PERSISTED from a
|
||||
* previous process (a restart must not re-arm a misbehaving host and
|
||||
* re-400 the same broken envelope). */
|
||||
|
||||
@@ -155,6 +155,31 @@ test("pinned lane: bootstrap, steady serve, unpinned control, hard-fail (#7439-5
|
||||
await settle("conv-armed");
|
||||
assert.ok(flowRows("conv-armed") > flowAfterBootstrap, "the flow keeps appending (the view is not frozen)");
|
||||
|
||||
// 2b. #7474 P2 (ruling 7439): with the projection frozen the PIN
|
||||
// ledger moves to the op log. The messages rows stop growing at
|
||||
// bootstrap while the flow keeps every turn — and the NEXT pinned
|
||||
// turn still resolves incrementally (its tail-overlap check runs
|
||||
// against the FLOW, not the frozen messages ledger).
|
||||
const msgsLedgerAfterT2 = store!.snapMsgIdLiveIds("conv-armed").length;
|
||||
const flowLedgerAfterT2 = store!.snapPinLiveIds("conv-armed");
|
||||
assert.ok(flowLedgerAfterT2.length >= 4, `the flow ledger carries the pinned ids (got ${flowLedgerAfterT2.length})`);
|
||||
assert.ok(!flowLedgerAfterT2.includes("egress-system"), "the constant system row is not part of the pin ledger");
|
||||
const seed3 = [...seed2, msg("user", 4)];
|
||||
logs.length = 0;
|
||||
const r2b = await post("conv-armed", seed3, seed3.map((_, i) => hostId(i)));
|
||||
assert.equal(r2b.status, 200, `the post-freeze pinned turn must succeed (got ${r2b.status}: ${r2b.body.slice(0, 200)})`);
|
||||
assert.ok(
|
||||
logs.some((l) => l.includes("conv-armed") && l.includes("existing row(s) served from the op-log")),
|
||||
"the post-freeze turn still serves from the op-log",
|
||||
);
|
||||
await settle("conv-armed");
|
||||
assert.equal(
|
||||
store!.snapMsgIdLiveIds("conv-armed").length,
|
||||
msgsLedgerAfterT2,
|
||||
"the messages projection is FROZEN for the egress-on session (no per-turn ingest)",
|
||||
);
|
||||
assert.ok(store!.snapPinLiveIds("conv-armed").length > flowLedgerAfterT2.length, "the flow ledger kept growing while the projection froze");
|
||||
|
||||
// 3. Unpinned control: the seam never logs egress-authority.
|
||||
const r3 = await post("conv-plain", [msg("user", 0)], undefined);
|
||||
assert.equal(r3.status, 200);
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* #7474 P2 (ruling 7439): the egress-on session's pin ledger lives in the
|
||||
* op log. `snapPinLiveIds` is the ONE read entry: egress_state (the
|
||||
* compaction-bounded serving read) when the session has an op log, the
|
||||
* messages rows otherwise — so a non-egress session sees exactly the old
|
||||
* output, and a corrupt op log degrades to the (stale-but-honest) messages
|
||||
* ledger instead of throwing on the pin path.
|
||||
*/
|
||||
|
||||
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 { openSqliteDatabase } from "../src/storage/driver.ts";
|
||||
import { migrateSchema } from "../src/storage/schema.ts";
|
||||
import { egressStateAppend, egressStateView } from "../src/storage/egress-state.ts";
|
||||
import { recordEgressTurn, type EgressOpLogStore } from "../src/storage/egress-record.ts";
|
||||
import { planIngest } from "../src/storage/ingest.ts";
|
||||
import type { BiliMessage } from "acp-kernel/wire";
|
||||
|
||||
const M = (id: string, text: string, role: BiliMessage["role"] = "user"): BiliMessage =>
|
||||
({ id, role, contentType: "text", text });
|
||||
|
||||
function tmpdir(prefix: string): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||||
}
|
||||
|
||||
function openStore(): { store: UnifiedStore; adapter: EgressOpLogStore; db: ReturnType<typeof openSqliteDatabase>["db"]; dir: string } {
|
||||
const dir = tmpdir("bili-egress-projection-");
|
||||
const { db } = openSqliteDatabase(path.join(dir, "index.db"));
|
||||
migrateSchema(db);
|
||||
const store = UnifiedStore.open(path.join(dir, "index.db"));
|
||||
const adapter: EgressOpLogStore = {
|
||||
egressStateAppendOps: (sid, ops, nowMs) => egressStateAppend(db, sid, ops, nowMs),
|
||||
egressStateView: (sid) => egressStateView(db, sid),
|
||||
egressStateCompactView: () => 0,
|
||||
egressStateViewAt: (sid, seq) => {
|
||||
const rows = db
|
||||
.prepare("SELECT op_seq, log_seq, row_type, msgid, payload, bytes FROM egress_flow WHERE session_id = ? AND op_seq <= ? ORDER BY op_seq ASC")
|
||||
.all(sid, seq) as unknown as { op_seq: number; log_seq: number | null; row_type: "B" | "I" | "D" | "U"; msgid: string | null; payload: string; bytes: string | null }[];
|
||||
void rows;
|
||||
throw new Error("unused in this suite");
|
||||
},
|
||||
egressStateMaxSeq: (sid) => {
|
||||
void egressStateView(db, sid);
|
||||
return (db.prepare("SELECT COALESCE(MAX(log_seq), 0) AS mx FROM egress_flow WHERE session_id = ?").get(sid) as { mx: number }).mx;
|
||||
},
|
||||
egressStateTruncateAfter: (sid, seq) => {
|
||||
const a = db.prepare("DELETE FROM egress_state WHERE session_id = ? AND op_seq > ?").run(sid, seq);
|
||||
const b = db.prepare("DELETE FROM egress_flow WHERE session_id = ? AND op_seq > ?").run(sid, seq);
|
||||
return Number(a.changes) + Number(b.changes);
|
||||
},
|
||||
};
|
||||
return { store, adapter, db, dir };
|
||||
}
|
||||
|
||||
test("snapPinLiveIds: op-log authority, system row excluded, order = log_seq", () => {
|
||||
const H = openStore();
|
||||
try {
|
||||
let view = recordEgressTurn({ store: H.adapter, sessionId: "s1", prev: undefined, conversation: [M("m1", "alpha")], systemText: "sys", nowMs: 1 });
|
||||
view = recordEgressTurn({ store: H.adapter, sessionId: "s1", prev: view, conversation: [M("m1", "alpha"), M("m2", "beta")], systemText: "sys", nowMs: 2 });
|
||||
assert.deepEqual(H.store.snapPinLiveIds("s1"), ["m1", "m2"]);
|
||||
assert.deepEqual(H.store.snapMsgIdLiveIds("s1"), [], "the messages projection is untouched by egress recording");
|
||||
} finally {
|
||||
fs.rmSync(H.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("snapPinLiveIds: a session without an op log reads the messages ledger unchanged", () => {
|
||||
const H = openStore();
|
||||
try {
|
||||
const core = {
|
||||
id: "plain-sess",
|
||||
createdAt: 1_000,
|
||||
lastSeen: 2_000,
|
||||
meta: { protocol: "anthropic" },
|
||||
stats: { requests: 2 },
|
||||
metadata: {},
|
||||
state: {
|
||||
blocks: [],
|
||||
messageRefs: { byRaw: { h1: "m00001", h2: "m00002" }, byRef: { m00001: "h1", m00002: "h2" } },
|
||||
nextBlockId: 1,
|
||||
nextRunId: 1,
|
||||
},
|
||||
blockContents: new Map(),
|
||||
lastMessages: [
|
||||
{ id: "h1", role: "user", contentType: "text", text: "one" } as never,
|
||||
{ id: "h2", role: "assistant", contentType: "text", text: "two" } as never,
|
||||
],
|
||||
contentStore: { version: 1 as const, byHash: {} as Record<string, string>, byRef: {} as Record<string, unknown> },
|
||||
} as never;
|
||||
assert.ok(H.store.ingestSession(planIngest(core), undefined, { completeLog: true }));
|
||||
const fromMessages = H.store.snapMsgIdLiveIds("plain-sess");
|
||||
assert.ok(fromMessages.length >= 2, `messages ledger populated (got ${fromMessages.length})`);
|
||||
assert.deepEqual(H.store.snapPinLiveIds("plain-sess"), fromMessages, "no op log → byte-identical to the legacy read");
|
||||
} finally {
|
||||
fs.rmSync(H.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("snapPinLiveIds: a corrupt op log degrades to the messages ledger, never throws", () => {
|
||||
const H = openStore();
|
||||
try {
|
||||
let view = recordEgressTurn({ store: H.adapter, sessionId: "s3", prev: undefined, conversation: [M("m1", "alpha")], systemText: "sys", nowMs: 1 });
|
||||
view = recordEgressTurn({ store: H.adapter, sessionId: "s3", prev: view, conversation: [M("m1", "alpha"), M("m2", "beta")], systemText: "sys", nowMs: 2 });
|
||||
// A +U whose target msgid does not exist in the view: the replay
|
||||
// must reject (EgressStateCorruptError) — the pin read then falls
|
||||
// back to the messages ledger instead of throwing.
|
||||
const bad = dbMaxOpSeq(H.db, "s3") + 1;
|
||||
H.db
|
||||
.prepare("INSERT INTO egress_state (session_id, op_seq, log_seq, row_type, msgid, payload, bytes, created_at) VALUES (?, ?, NULL, 'U', ?, ?, ?, ?)")
|
||||
.run("s3", bad, "ghost", JSON.stringify({ role: "user" }), "corrupt-bytes", 3);
|
||||
assert.throws(() => H.adapter.egressStateView("s3"), /corrupt|egress-state/i);
|
||||
assert.deepEqual(H.store.snapPinLiveIds("s3"), H.store.snapMsgIdLiveIds("s3"), "corrupt op log → messages ledger (stale-but-honest, never a pin-path throw)");
|
||||
} finally {
|
||||
fs.rmSync(H.dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function dbMaxOpSeq(db: ReturnType<typeof openSqliteDatabase>["db"], sid: string): number {
|
||||
return (db.prepare("SELECT COALESCE(MAX(op_seq), 0) AS mx FROM egress_state WHERE session_id = ?").get(sid) as { mx: number }).mx;
|
||||
}
|
||||
Reference in New Issue
Block a user