diff --git a/src/storage-maintenance.ts b/src/storage-maintenance.ts index 24afcf896f..268a2d96a1 100644 --- a/src/storage-maintenance.ts +++ b/src/storage-maintenance.ts @@ -287,7 +287,8 @@ async function runForeignBlocks(store: SessionStore, json: boolean, apply: boole const result = applyForeignBlockSweep(store, plan); if (!result) return fail("foreign-block sweep failed mid-run (see log)", json, data); data.result = result; - if (json) return { code: 0, text: `${JSON.stringify(data, null, 2)}\n` }; + const code = result.failed.length > 0 ? 1 : 0; + if (json) return { code, text: `${JSON.stringify(data, null, 2)}\n` }; text += `\nexecuted:\n archived blocks: ${result.archived.length}`; for (const f of result.archived) text += `\n ${f.sessionId} / ${f.blockId} (tier ${f.tier}, covered ${f.coveredCount})`; if (result.failed.length > 0) { @@ -295,7 +296,7 @@ async function runForeignBlocks(store: SessionStore, json: boolean, apply: boole for (const f of result.failed) text += `\n ${f.finding.sessionId} / ${f.finding.blockId}: ${f.reason ?? "unknown"}`; } text += "\nnote: takes effect on next session load/restart — a running host keeps its in-memory copy until reload"; - return { code: 0, text: `${text}\n` }; + return { code, text: `${text}\n` }; } export async function runSessionsCommand(opts: { diff --git a/tests/e2e/e2e-update-state.test.ts b/tests/e2e/e2e-update-state.test.ts index 03f2b1db22..e31baf7659 100644 --- a/tests/e2e/e2e-update-state.test.ts +++ b/tests/e2e/e2e-update-state.test.ts @@ -299,6 +299,11 @@ test("self-update keeps live compression state: folds survive the OLD→NEW hop envBase.BILI_UPDATE_POLICY_URL = "http://127.0.0.1:1/no-policy.json"; envBase.BILI_PERSIST_DEBOUNCE_MS = "200"; envBase.BILI_SESSIONS_DIR = sessionsDir; + // Pure-sqlite default (5a80e2b8e, #6480) turns the JSON envelope + // writer OFF, but this lane asserts on the on-disk .json session file + // (state survival across the update). Pin the writer ON so the + // envelope this test was written for is still produced. + envBase.BILI_STORAGE_JSON_WRITER = "on"; const port = await freePort(); proxy = spawnProxy(installDir, port, envBase); diff --git a/tests/foreign-block-sweep-exit.test.ts b/tests/foreign-block-sweep-exit.test.ts new file mode 100644 index 0000000000..4e3d101fd6 --- /dev/null +++ b/tests/foreign-block-sweep-exit.test.ts @@ -0,0 +1,81 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runSessionsCommand } from "../src/storage-maintenance.ts"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { planIngest, type LegacySessionLike } from "../src/storage/ingest.ts"; + +process.env.BILI_PERSIST_ZSTD = "0"; +process.env.BILI_STORAGE_UNIFIED = "full"; + +function seed(dir: string): void { + const store = UnifiedStore.open(join(dir, "index.db")); + try { + store.ingestSession(planIngest({ + id: "parent", createdAt: 1000, lastSeen: 2000, + meta: { protocol: "openai" }, stats: {}, metadata: {}, + state: { + nextBlockId: 4, nextRunId: 4, messageRefs: { byRaw: {}, byRef: {} }, + blocks: ["healthy", "foreign-a", "foreign-b"].map((blockId, i) => ({ + blockId, runId: i + 1, createdAt: 1000, tier: 1, active: true, + summary: `summary of ${blockId}`, kind: "fold", reason: "test", + effectiveMessageIds: [i === 0 ? "own-message" : `other-${i}`], directMessageIds: [], + })), + }, + blockContents: new Map(), + lastMessages: [{ id: "own-message", role: "user", contentType: "text", text: "parent history" }], + lastMessagesFolded: false, pluginSnapshot: undefined, contentStore: undefined, + } as unknown as LegacySessionLike)); + } finally { store.close(); } +} + +function blockIds(dir: string): string[] { + const store = UnifiedStore.open(join(dir, "index.db")); + try { return store.getBlocks("parent").map((b) => b.blockId).sort(); } + finally { store.close(); } +} + +for (const json of [false, true]) { + test(`foreign-blocks reports archive write failure and remains retryable (${json ? "JSON" : "text"})`, async () => { + const dir = mkdtempSync(join(tmpdir(), "bili-sweep-exit-")); + try { + seed(dir); + const obstruction = join(dir, "archive", UnifiedStore.BLOCK_ARCHIVE_LOG_NAME); + mkdirSync(obstruction, { recursive: true }); + const failed = await runSessionsCommand({ sub: "foreign-blocks", apply: true, json, dir }); + if (json) { + const report = JSON.parse(failed.text); + assert.equal(report.result.archived.length, 0); + assert.equal(report.result.failed.length, 2); + assert.deepEqual(report.result.failed.map((f: { finding: { blockId: string } }) => f.finding.blockId).sort(), ["foreign-a", "foreign-b"]); + } else { + assert.match(failed.text, /failed:\s+2/); + assert.match(failed.text, /foreign-a/); + assert.match(failed.text, /foreign-b/); + } + assert.deepEqual(blockIds(dir), ["foreign-a", "foreign-b", "healthy"]); + assert.equal(failed.code, 1, "an unsuccessful archive sweep must not signal success"); + + rmSync(obstruction, { recursive: true }); + const retried = await runSessionsCommand({ sub: "foreign-blocks", apply: true, json, dir }); + assert.equal(retried.code, 0); + assert.deepEqual(blockIds(dir), ["healthy"]); + assert.equal((await runSessionsCommand({ sub: "foreign-blocks", apply: true, json, dir })).code, 0); + } finally { rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } + }); +} + +test("foreign-blocks dry-run remains successful and does not touch the archive", async () => { + const dir = mkdtempSync(join(tmpdir(), "bili-sweep-dry-exit-")); + try { + seed(dir); + mkdirSync(join(dir, "archive", UnifiedStore.BLOCK_ARCHIVE_LOG_NAME), { recursive: true }); + for (const json of [false, true]) { + const result = await runSessionsCommand({ sub: "foreign-blocks", json, dir }); + assert.equal(result.code, 0); + } + assert.deepEqual(blockIds(dir), ["foreign-a", "foreign-b", "healthy"]); + } finally { rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } +});