Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
92 changes: 81 additions & 11 deletions src/persist.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createHash, randomUUID } from "node:crypto";
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
import { readdir, readFile, rm } from "node:fs/promises";
import * as path from "node:path";
const { join } = path;
Expand Down Expand Up @@ -341,6 +341,61 @@ export function fileNameMatchesId(base: string, id: string, protocol?: string, u
return false;
}

/** #5779: forensic retention cap for `.corrupt-<ts>` quarantine copies per base
* file, counting the just-created copy. The newest copy carries the forensics;
* older copies of the same base are redundant history of an already-fresh-
* started session. */
export const CORRUPT_SIBLING_CAP = 1;

/** #5779: bound `.corrupt-<ts>` quarantine copies so a hot session can no
* longer accumulate unbounded forensic weight on disk (issue #5779: 273 ×
* ~0.6 GiB in one tree). Keeps at most CORRUPT_SIBLING_CAP siblings of
* `baseFile` in total — `keepPath` (the just-created copy) always survives
* even under clock skew; older ones are deleted. Best-effort: an unreadable
* dir or a locked file (Windows AV) skips the entry and the next quarantine
* retries the sweep. Returns removal counts for log lines; never throws. */
export function pruneCorruptSiblings(baseFile: string, keepPath?: string): { removed: number; locked: number } {
const dir = path.dirname(baseFile);
const prefix = `${path.basename(baseFile)}.corrupt-`;
const keepName = keepPath ? path.basename(keepPath) : undefined;
let names: string[];
try {
names = readdirSync(dir);
} catch {
return { removed: 0, locked: 0 };
}
const stampOf = (name: string): number => {
const n = Number(name.slice(prefix.length));
return Number.isFinite(n) ? n : 0;
};
const others = names.filter((n) => n.startsWith(prefix) && n !== keepName).sort((a, b) => stampOf(b) - stampOf(a));
let removed = 0;
let locked = 0;
for (const name of others.slice(Math.max(0, CORRUPT_SIBLING_CAP - 1))) {
try {
unlinkSync(path.join(dir, name));
removed++;
} catch {
locked++;
}
}
return { removed, locked };
}

/** #5779: true when a decode failure is resource exhaustion — V8 reports both
* allocation families ("Array buffer allocation failed", "JavaScript heap out
* of memory") as RangeError. Such a file must NOT be quarantined: the bytes
* are fine, the process just could not afford them this round. The
* "Maximum call stack size exceeded" RangeError is structural pathology
* (genuinely pathological payload depth) and stays on the corruption side. */
export function isAllocationFailureError(error: unknown): boolean {
return error instanceof RangeError && /allocation failed|heap out of memory/i.test(error.message);
}

function errText(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}

/** Session persistence policy over the kernel StateStore mechanism. The
* public API predates the extraction and is kept stable for session.ts /
* server.ts / export.ts. */
Expand Down Expand Up @@ -1153,14 +1208,24 @@ export class SessionStore {
}
let raw: unknown;
try { raw = JSON.parse(bytes.toString("utf8")); }
catch {
catch (plainTextError) {
try { raw = JSON.parse(this.readCodec.decode(bytes)); }
catch (decodeError) {
// #3157 self-heal: a size-correct but undecodable file (a VDL=0
// zero file left by a crash between write and rename — now
// prevented by the fsync fix) used to throw here on every load,
// 502-ing the whole lane until a human deleted the file. Isolate
// it beside the original and start this session fresh instead.
// torn write — now prevented by #3157's fsync; pre-fix files can
// still surface) used to throw here on every load, 502-ing the
// whole lane until a human deleted the file. Isolate it beside
// the original and start this session fresh instead.
// #5779: allocation failure = resource exhaustion, not corruption —
// quarantining destroyed a healthy envelope and its fold state, and
// the eviction/cold-load loop rebuilt + re-quarantined it (~0.6 GiB
// of forensic copies per failure). Classify BOTH errors: an OOM in
// the first attempt leaves this catch holding only the codec's own
// format error. Leave the file in place; the next load retries.
if (isAllocationFailureError(plainTextError) || isAllocationFailureError(decodeError)) {
this.log("error", `[persist] session state ${path.basename(file)} unreadable this round — decode ran out of memory, NOT corruption; file left in place for retry (${errText(plainTextError)} / ${errText(decodeError)})`);
return null;
}
this.quarantineCorruptState(file, id, decodeError);
return null;
}
Expand All @@ -1181,16 +1246,21 @@ export class SessionStore {
* (plugin.ts). Best-effort: if the rename fails (Windows AV/indexer lock),
* the caller still treats the file as a miss — the session starts fresh and
* the next boot retries the isolation. The `.corrupt-<ts>` suffix does not
* end in `.json`, so the directory walkers skip it next boot (it stays for
* forensics; sweepStaleTemps only removes `.tmp-*` orphans). */
* end in `.json`, so the directory walkers skip it next boot. Retention is
* bounded (#5779): pruneCorruptSiblings keeps only the newest
* CORRUPT_SIBLING_CAP copy per base file — the forensic value lives in the
* latest failure, and unbounded copies once filled user disks (~0.6 GiB
* each, hundreds per tree). */
private quarantineCorruptState(file: string, id: string, cause: unknown): void {
const causeText = cause instanceof Error ? cause.message : String(cause);
const causeText = errText(cause);
const quarantinePath = `${file}.corrupt-${Date.now()}`;
try {
renameSync(file, quarantinePath);
this.log("warn", `[persist] quarantined undecodable session state ${path.basename(file)} → ${path.basename(quarantinePath)}; starting ${id} fresh (${causeText})`);
const pruned = pruneCorruptSiblings(file, quarantinePath);
const capNote = pruned.removed > 0 ? `; removed ${pruned.removed} older forensic cop${pruned.removed === 1 ? "y" : "ies"} (cap ${CORRUPT_SIBLING_CAP})` : "";
this.log("warn", `[persist] quarantined undecodable session state ${path.basename(file)} → ${path.basename(quarantinePath)}; starting ${id} fresh (${causeText})${capNote}`);
} catch (renameErr) {
this.log("error", `[persist] failed to quarantine corrupt session state ${path.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${renameErr instanceof Error ? renameErr.message : String(renameErr)})`);
this.log("error", `[persist] failed to quarantine corrupt session state ${path.basename(file)}; resuming ${id} empty this load (${causeText}; rename: ${errText(renameErr)})`);
}
}

Expand Down
11 changes: 8 additions & 3 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { ServerResponse } from "node:http";
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { getStore, storageStatusLabel } from "./persist.js";
import { CORRUPT_SIBLING_CAP, getStore, pruneCorruptSiblings, storageStatusLabel } from "./persist.js";
import { cloneStoreForRefs } from "./store.js";
import { acquireInFlight, createSession, getSessionAsync, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, noteAbortedTurn, peekSession, releaseInFlight, statusInputBaseline, withSessionLock, type Session } from "./session.js";
import { clientConversationHeader } from "./session-id.js";
Expand Down Expand Up @@ -379,10 +379,15 @@ export function loadConversations(): void {
} catch {
// #406: preserve the corrupt bytes for forensics instead of
// silently zeroing every route on the next debounced write.
// #5779: bound the forensic retention like the session store does.
let removedCopies = 0;
try {
fs.renameSync(conversationsFile(), `${conversationsFile()}.corrupt-${Date.now()}`);
const backup = `${conversationsFile()}.corrupt-${Date.now()}`;
fs.renameSync(conversationsFile(), backup);
removedCopies = pruneCorruptSiblings(conversationsFile(), backup).removed;
} catch {}
loggerLog("warn", "[plugin] plugin-conversations.json is corrupt — backed up beside the original, starting an empty routing table");
const capNote = removedCopies > 0 ? `; removed ${removedCopies} older forensic cop${removedCopies === 1 ? "y" : "ies"} (cap ${CORRUPT_SIBLING_CAP})` : "";
loggerLog("warn", `[plugin] plugin-conversations.json is corrupt — backed up beside the original, starting an empty routing table${capNote}`);
}
conversationsDirty = false;
}
Expand Down
183 changes: 183 additions & 0 deletions tests/issue5779-corrupt-quarantine-cap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { tmpdir } from "node:os";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readdirSync, statSync, writeFileSync } from "node:fs";
import * as path from "node:path";
const { join } = path;
import { CORRUPT_SIBLING_CAP, SessionStore, isAllocationFailureError } from "../src/persist.ts";
import type { StateStoreCodec } from "acp-kernel/persist";
import type { Session } from "../src/session.ts";
import { createInitialState } from "acp-kernel";
import { loadConversations } from "../src/plugin.ts";
import { setLogCapture } from "../src/logger.ts";
import { rmrf } from "./tmp-rm.ts";

/** #5779: the .corrupt-<ts> quarantine copies (#3157 self-heal) accumulated
* without bound — one ~0.6 GiB forensic copy per failed load of a hot
* session (273 copies / ~157 GiB in a single user tree). Two defects:
* nothing ever pruned the copies, and an out-of-memory decode failure was
* misclassified as corruption, quarantining a HEALTHY envelope and burning
* its fold state so the eviction/cold-load loop rebuilt and re-quarantined
* it. This file pins both halves: retention capped at the newest copy per
* base file, and allocation failures leaving the file in place for retry.
*
* The quarantine path is legacy-file behavior: under unified-full reads are
* served from index.db and a corrupt JSON envelope is never even probed, so
* pin the same tier the CI non-storage corpus baseline uses
* (tests/preload-storage-baseline.mjs). */
process.env.BILI_STORAGE_UNIFIED = "legacy";

type LogLine = { level: string; msg: string };

function makeSession(id: string): Session {
return {
id,
meta: { protocol: "openai", upstreamOrigin: "http://upstream" },
stats: { requests: 0, tokensSaved: 0, inputTokens: 0, cachedTokens: 0, outputTokens: 0, cacheSamples: 0, lastInputTokens: 0, contextTokens: 0, compressCreditTokens: 0, retrieveCalls: 0, retrieveHits: 0, retrieveMisses: 0, storedBytes: 0, storeBytesSaved: 0, rangeRestores: 0 },
metadata: {},
state: createInitialState(),
createdAt: Date.now(),
lastSeen: Date.now(),
blockContents: new Map(),
inFlight: 0,
persisted: false,
pendingRetrievals: [],
};
}

function filePath(dir: string, id: string): string {
return join(dir, "openai", "upstream_" + createHash("sha256").update(id, "utf8").digest("hex").slice(0, 24) + ".json");
}

const META = { protocol: "openai", upstreamOrigin: "http://upstream" };

function corruptZeroFill(file: string): number {
const size = statSync(file).size;
assert.ok(size > 0, "state file has content before corruption");
writeFileSync(file, Buffer.alloc(size));
return size;
}

function corruptSiblingsOf(file: string): string[] {
return readdirSync(path.dirname(file)).filter((n) => n.startsWith(path.basename(file) + ".corrupt-")).sort();
}

test("#5779: pre-existing older .corrupt-* copies are pruned to the cap on quarantine", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-5779-"));
const logs: LogLine[] = [];
try {
const store = new SessionStore({ dir, debounceMs: 0, enabled: true, log: (level, msg) => logs.push({ level, msg }) });
const file = filePath(dir, "s-cap");
await store.writeNow(makeSession("s-cap"));
// Simulate the historical accumulation: older forensic copies already
// sitting beside the live file (the user had 273 of these).
const base = path.basename(file);
writeFileSync(join(dir, "openai", `${base}.corrupt-1000000`), "old forensic copy A");
writeFileSync(join(dir, "openai", `${base}.corrupt-2000000`), "old forensic copy B");
const size = corruptZeroFill(file);

assert.equal(store.loadSync("s-cap", META), null, "undecodable file yields a fresh start");
const siblings = corruptSiblingsOf(file);
assert.equal(siblings.length, CORRUPT_SIBLING_CAP, "only the newest forensic copy survives the sweep");
assert.equal(statSync(join(dir, "openai", siblings[0])).size, size, "the survivor is the just-created quarantine copy, not a stale one");
assert.ok(logs.some((l) => l.level === "warn" && l.msg.includes("quarantined") && l.msg.includes("removed 2 older forensic copies")), "warn log reports the sweep");
} finally {
rmrf(dir);
}
});

test("#5779: repeated quarantine rounds never accumulate copies", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-5779-"));
try {
const store = new SessionStore({ dir, debounceMs: 0, enabled: true, log: () => {} });
const file = filePath(dir, "s-loop");
for (let round = 0; round < 3; round++) {
await store.writeNow(makeSession("s-loop"));
corruptZeroFill(file);
assert.equal(store.loadSync("s-loop", META), null, `round ${round}: undecodable file yields a fresh start`);
const count = corruptSiblingsOf(file).length;
assert.equal(count, CORRUPT_SIBLING_CAP, `round ${round}: retention stays at the cap`);
}
} finally {
rmrf(dir);
}
});

test("#5779: an allocation failure during decode does NOT quarantine the file", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-5779-"));
const logs: LogLine[] = [];
try {
const store = new SessionStore({ dir, debounceMs: 0, enabled: true, log: (level, msg) => logs.push({ level, msg }) });
const file = filePath(dir, "s-oom");
await store.writeNow(makeSession("s-oom"));
corruptZeroFill(file);
// The plaintext attempt fails first (NUL bytes), then the codec
// attempt runs out of memory allocating the decoded payload.
(store as unknown as { readCodec: StateStoreCodec }).readCodec = {
encode: (d: string) => d,
decode: () => { throw new RangeError("Array buffer allocation failed"); },
};

assert.equal(store.loadSync("s-oom", META), null, "load yields a fresh start this round");
assert.ok(existsSync(file), "healthy-bytes file left in place for retry");
assert.equal(corruptSiblingsOf(file).length, 0, "no forensic copy created for an OOM failure");
assert.ok(logs.some((l) => l.level === "error" && l.msg.includes("out of memory")), "error log explains the non-corruption verdict");
} finally {
rmrf(dir);
}
});

test("#5779: a genuine decode error still quarantines (gate negative direction)", async () => {
const dir = mkdtempSync(join(tmpdir(), "bili-5779-"));
try {
const store = new SessionStore({ dir, debounceMs: 0, enabled: true, log: () => {} });
const file = filePath(dir, "s-synerr");
await store.writeNow(makeSession("s-synerr"));
corruptZeroFill(file);
(store as unknown as { readCodec: StateStoreCodec }).readCodec = {
encode: (d: string) => d,
decode: () => { throw new SyntaxError("Unexpected end of JSON input"); },
};

assert.equal(store.loadSync("s-synerr", META), null);
assert.ok(!existsSync(file), "genuine decode failure still moves the file out of the way");
assert.equal(corruptSiblingsOf(file).length, CORRUPT_SIBLING_CAP, "exactly one forensic copy kept");
} finally {
rmrf(dir);
}
});

test("#5779: isAllocationFailureError classifies only V8 allocation failures", () => {
assert.equal(isAllocationFailureError(new RangeError("Array buffer allocation failed")), true, "buffer allocation failure");
assert.equal(isAllocationFailureError(new RangeError("JavaScript heap out of memory")), true, "heap exhaustion");
assert.equal(isAllocationFailureError(new RangeError("Maximum call stack size exceeded")), false, "stack overflow is structural pathology, stays corruption-side");
assert.equal(isAllocationFailureError(new SyntaxError("Unexpected token")), false, "syntax errors stay corruption-side");
assert.equal(isAllocationFailureError(new Error("boom")), false, "plain errors stay corruption-side");
assert.equal(isAllocationFailureError("RangeError-ish string"), false, "non-Error values stay corruption-side");
});

test("#5779: plugin-conversations.json quarantine copies are capped too", () => {
const dir = mkdtempSync(join(tmpdir(), "bili-5779-"));
const logged: string[] = [];
const prev = process.env.XDG_STATE_HOME;
process.env.XDG_STATE_HOME = dir;
setLogCapture((_level, msg) => logged.push(msg));
try {
const stateDir = join(dir, "billion-context");
mkdirSync(stateDir, { recursive: true });
const file = join(stateDir, "plugin-conversations.json");
for (let round = 0; round < 2; round++) {
writeFileSync(file, "{corrupt-bytes");
loadConversations();
const backups = readdirSync(join(dir, "billion-context")).filter((f) => f.startsWith("plugin-conversations.json.corrupt-"));
assert.equal(backups.length, CORRUPT_SIBLING_CAP, `round ${round}: exactly one backup kept`);
}
assert.ok(logged.some((m) => m.includes("plugin-conversations.json is corrupt")));
} finally {
setLogCapture(null);
if (prev === undefined) delete process.env.XDG_STATE_HOME;
else process.env.XDG_STATE_HOME = prev;
rmrf(dir);
}
});
Loading