Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 38 additions & 9 deletions src/storage/ingest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,13 +705,25 @@ interface LegacyView {

type BlockContents = LegacyView["blockContents"];

/** Shared by full-view and resident-field reads; each page is released after parsing. */
export function appendBlockContents(contents: BlockContents, rows: Pick<LegacyViewRows["blocks"][number], "blockId" | "summary" | "one">[]): void {
/** Shared by full-view and resident-field reads; each page is released after parsing.
* #7335: a poisoned summary/one CAS row (stored bytes no longer parse) is skipped and
* reported through `skipped` instead of aborting the whole load — the block's state row
* survives, completeBlockContents falls back to the block's own inline summary for the
* missing text, and the next full ingest re-points the row at the synthesized content. */
export function appendBlockContents(
contents: BlockContents,
rows: Pick<LegacyViewRows["blocks"][number], "blockId" | "summary" | "one">[],
skipped?: { table: "messages" | "blocks"; key: string; error: string }[],
): void {
for (const b of rows) {
contents.set(b.blockId, {
one: b.one === null ? null : (JSON.parse(b.one) as BlockView),
full: JSON.parse(b.summary) as BlockView,
});
try {
contents.set(b.blockId, {
one: b.one === null ? null : (JSON.parse(b.one) as BlockView),
full: JSON.parse(b.summary) as BlockView,
});
} catch (err) {
skipped?.push({ table: "blocks", key: `content:${b.blockId}`, error: String(err) });
}
}
}

Expand Down Expand Up @@ -748,6 +760,11 @@ export class LegacyViewBuilder {
* tell an older build's default from a value written after the rows
* (#7574 rollback). */
private columnKstate: Record<string, unknown> = {};
/** #7335 poison-row isolation: rows whose stored bytes no longer parse as
* JSON are skipped and recorded here instead of aborting the whole load —
* before this, one bad row threw out of finish() and the session was
* rebuilt from scratch (all blocks and refs discarded). */
readonly skippedCorruptRows: { table: "messages" | "blocks"; key: string; error: string }[] = [];

constructor(
private readonly session: LegacyViewRows["session"],
Expand Down Expand Up @@ -835,12 +852,24 @@ export class LegacyViewBuilder {
}

addBlocks(rows: LegacyViewRows["blocks"]): void {
for (const b of rows) this.blocks.push(JSON.parse(b.payloadJson));
appendBlockContents(this.blockContents, rows);
for (const b of rows) {
try {
this.blocks.push(JSON.parse(b.payloadJson));
} catch (err) {
this.skippedCorruptRows.push({ table: "blocks", key: String(b.blockId), error: String(err) });
}
}
appendBlockContents(this.blockContents, rows, this.skippedCorruptRows);
}

addMessages(rows: LegacyViewRows["messages"]): void {
for (const m of rows) this.messagesBySeq.set(m.seq, JSON.parse(m.content) as CoreMessage);
for (const m of rows) {
try {
this.messagesBySeq.set(m.seq, JSON.parse(m.content) as CoreMessage);
} catch (err) {
this.skippedCorruptRows.push({ table: "messages", key: `seq=${m.seq}`, error: String(err) });
}
}
}

/** #6785 step 6: the ccr_entries ledger (CAS content) that backs a slim
Expand Down
10 changes: 9 additions & 1 deletion src/storage/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -667,7 +667,15 @@ export class MysqlBackend implements StorageBackend {
/** Atomic refcount-aware CAS insert-or-bump. */
private async putContent(c: PoolConnection | Pool, content: string, precomputedHash?: string): Promise<string> {
const bytes = Buffer.from(content, "utf8");
const hash = precomputedHash ?? sha256Hex(bytes);
// #7335: verify the caller-supplied digest against the bytes — the CAS
// key is what every reader resolves by, so a mismatched pair poisons
// the store (sqlite twin has the same guard).
const hash = sha256Hex(bytes);
if (precomputedHash !== undefined && precomputedHash !== hash) {
throw new Error(
`content CAS digest mismatch: caller supplied ${precomputedHash} but ${bytes.byteLength} bytes hash to ${hash} — refusing to persist an unverified row`,
);
}
await c.query(
"INSERT INTO content (hash, byte_len, refcount, algo, bytes) VALUES (?, ?, 1, 'sha256', ?) " +
"ON DUPLICATE KEY UPDATE refcount = refcount + 1",
Expand Down
62 changes: 57 additions & 5 deletions src/storage/shadow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import { sqliteCorruptionDetail } from "./sqlite-errors.ts";
import { recordSidecarInstance, recordSidecarOpenFailure } from "./runtime-status.ts";
import type { SqliteEngineName, SqliteEngineSource } from "./driver.ts";
import type { MessageRow, BlockRow, SessionRow, RefRow, MessageRefContentRow, MessageIdContentRow } from "./store.js";
import type { CoreMessage, MessageContentStore } from "acp-kernel";
import type { CompressionBlock, CoreMessage, MessageContentStore } from "acp-kernel";

// True once quick_check proved this process's index corrupt. such a boot is
// alarm-only by design (files stay put; the operator repairs/moves them by
Expand Down Expand Up @@ -928,6 +928,7 @@ export class UnifiedShadow {
// getOrphanViews also unions any legacy column entries.
builder.addOrphanViews(store.getOrphanViews(id) ?? {});
builder.addStateFields(store.getStateFields(id) ?? {});
warnCorruptSkips(id, builder);
// The builder preserves every MERGE_STATE_FIELDS key; its
// generic state declaration only needs widening here.
const view = builder.finish();
Expand Down Expand Up @@ -968,12 +969,16 @@ export class UnifiedShadow {
}
if (fields.blockContents) {
const contents: NonNullable<ResidentFields["blockContents"]> = new Map();
const corruptSkips: { table: "messages" | "blocks"; key: string; error: string }[] = [];
for (let offset = 0; ; offset += VIEW_READ_BATCH_SIZE) {
const page = store.getBlockContents(id, { limit: VIEW_READ_BATCH_SIZE, offset });
const blocks = Array.isArray(page) ? page : [];
appendBlockContents(contents, blocks);
appendBlockContents(contents, blocks, corruptSkips);
if (blocks.length < VIEW_READ_BATCH_SIZE) break;
}
if (corruptSkips.length > 0) {
loggerLog("warn", `[storage] resident block contents degraded for ${id}: ${corruptSkips.length} unparseable row(s) skipped (${corruptSkips.map((s) => s.key).join(", ")})`);
}
mergeOrphanBlockContents(contents, JSON.stringify(store.getOrphanViews(id) ?? {}));
result.blockContents = contents;
}
Expand Down Expand Up @@ -1600,6 +1605,7 @@ export class UnifiedShadow {
// #6785 step 7: same orphan-journal union on the async leg.
builder.addOrphanViews(await reader.getOrphanViews(id) ?? {});
builder.addStateFields(await reader.getStateFields(id) ?? {});
warnCorruptSkips(id, builder);
return builder.finish() as LegacySessionLike;
});
if (!loaded) return null;
Expand Down Expand Up @@ -1827,6 +1833,25 @@ function warnTailGaps(id: string, view: { tailGaps?: number }): void {
}
}

/** #7335: poison-row isolation report — unparseable rows the builder skipped
* so a single corrupt row cannot abort the whole load (previously one bad
* row threw out of finish(), the session was rebuilt from scratch and every
* block and ref was discarded). */
function warnCorruptSkips(
id: string,
builder: { skippedCorruptRows: { table: string; key: string; error: string }[] },
): void {
const rows = builder.skippedCorruptRows;
if (rows.length > 0) {
loggerLog(
"warn",
`[storage] unified view degraded for ${id}: ${rows.length} unparseable row(s) skipped (${rows
.map((r) => `${r.table} ${r.key}: ${r.error}`)
.join("; ")}); the session loaded without them (#7335)`,
);
}
}

function shadowDigest(view: unknown): string {
return canonicalDigest(view);
}
Expand Down Expand Up @@ -1898,19 +1923,46 @@ class BatchedViewVerification {

addBlocks(rows: BlockRow[]): void {
for (const row of rows) {
const payload = JSON.parse(row.payloadJson);
let payload: CompressionBlock;
try {
payload = JSON.parse(row.payloadJson);
} catch {
// #7335: a poisoned block row must not abort the whole save —
// mark drift so the comparison surfaces it loudly, and keep
// positional alignment for the slots that follow.
this.changed("state");
this.blockCount++;
continue;
}
if (payload?.active === true) this.activeBlocks++;
if (this.blockCount >= this.legacy.state.blocks.length || shadowDigest(payload) !== shadowDigest(this.legacy.state.blocks[this.blockCount])) this.changed("state");
this.blockCount++;
this.compareContents(row.blockId, { one: row.one === null ? null : JSON.parse(row.one), full: JSON.parse(row.summary) });
try {
this.compareContents(row.blockId, { one: row.one === null ? null : JSON.parse(row.one), full: JSON.parse(row.summary) });
} catch {
// #7335: poisoned summary/one CAS row — the block slot above
// already compared; the unreadable text is drift, not a crash.
this.changed("blockContents");
this.remainingContents.delete(row.blockId);
}
// A current block wins over an identically named journal entry.
this.orphans.delete(row.blockId);
}
}

addMessages(rows: MessageRow[]): void {
for (const row of rows) {
const raw = JSON.parse(row.content);
let raw: unknown;
try {
raw = JSON.parse(row.content);
} catch {
// #7335: a poisoned row must not abort the whole save — the
// verify-sample throw retried on every subsequent save until
// the store was cleaned. Skip it and mark drift so the
// comparison surfaces the disagreement loudly instead.
this.changed("messages");
continue;
}
this.messages.set(row.seq, { sig: messageSignature(raw), raw });
}
}
Expand Down
16 changes: 11 additions & 5 deletions src/storage/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1033,11 +1033,17 @@ export class UnifiedStore {
/** Content CAS: insert-if-absent + refcount bump; returns hash. */
private putContent(content: string | Buffer, precomputedHash?: string): string {
const bytes = typeof content === "string" ? Buffer.from(content, "utf8") : content;
// #3133: planner-produced rows carry the digest from their intern or
// delta pass — skip the per-message re-hash here (same value: sha256
// over the same utf8 bytes). Only direct callers without a planner
// pay the hash at this layer.
const hash = precomputedHash ?? sha256Hex(bytes);
// #3133 kept the planner digest as the CAS key to skip the per-message
// re-hash; #7335 turns the same digest into a VERIFIED one — the CAS
// key is what every reader resolves by, so a caller-supplied hash that
// does not match its bytes silently poisons the store (observed: 26
// mismatched rows from an older dev build killed an entire session).
const hash = sha256Hex(bytes);
if (precomputedHash !== undefined && precomputedHash !== hash) {
throw new Error(
`content CAS digest mismatch: caller supplied ${precomputedHash} but ${bytes.byteLength} bytes hash to ${hash} — refusing to persist an unverified row`,
);
}
const existing = this.db.prepare("SELECT refcount FROM content WHERE hash = ?").get(hash) as
| { refcount: number }
| undefined;
Expand Down
Loading
Loading