Skip to content

Commit 6e95600

Browse files
committed
fix(doctor): stream restore archive hashing
1 parent 673f77f commit 6e95600

2 files changed

Lines changed: 93 additions & 13 deletions

File tree

‎src/commands/doctor-session-sqlite-migration-run.ts‎

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export type ActiveSessionSqliteMigrationRun = {
7171

7272
const SESSION_SQLITE_MIGRATION_RUNS_DIR = "session-sqlite-migration-runs";
7373
const COMPLETED_MIGRATION_RUN_RETENTION = 50;
74+
const RESTORE_ARCHIVE_HASH_CHUNK_BYTES = 64 * 1024;
7475
const AbsolutePathSchema = z
7576
.string()
7677
.min(1)
@@ -548,6 +549,21 @@ type RestoreArchiveInspection =
548549
| { state: "invalid"; reason: string }
549550
| { state: "missing" };
550551

552+
function hashRestoreArchive(fd: number, size: number): string {
553+
const hash = createHash("sha256");
554+
const buffer = Buffer.allocUnsafe(RESTORE_ARCHIVE_HASH_CHUNK_BYTES);
555+
let offset = 0;
556+
while (offset < size) {
557+
const read = fs.readSync(fd, buffer, 0, Math.min(buffer.length, size - offset), offset);
558+
if (read === 0) {
559+
throw new Error("archive changed while it was inspected");
560+
}
561+
hash.update(buffer.subarray(0, read));
562+
offset += read;
563+
}
564+
return hash.digest("hex");
565+
}
566+
551567
function inspectRestoreArchive(move: SessionSqliteMigrationMove): RestoreArchiveInspection {
552568
if (hasSymbolicLinkInDirectoryPath(path.dirname(move.archivePath))) {
553569
return { state: "invalid", reason: "archive parent is a symbolic link; refusing restore" };
@@ -583,20 +599,11 @@ function inspectRestoreArchive(move: SessionSqliteMigrationMove): RestoreArchive
583599
reason: "archive changed while it was inspected; refusing restore",
584600
};
585601
}
586-
const content = readFileDescriptorBoundedSync(fd, descriptorStat.size);
587-
const finalPathStat = fs.lstatSync(move.archivePath);
588-
if (
589-
finalPathStat.dev !== descriptorStat.dev ||
590-
finalPathStat.ino !== descriptorStat.ino ||
591-
finalPathStat.size !== descriptorStat.size
592-
) {
593-
return {
594-
state: "invalid",
595-
reason: "archive changed while it was inspected; refusing restore",
596-
};
597-
}
602+
let digest: string;
598603
let legacyEntryCount: number | undefined;
599604
if (move.kind === "legacy-store") {
605+
const content = readFileDescriptorBoundedSync(fd, descriptorStat.size);
606+
digest = createHash("sha256").update(content).digest("hex");
600607
let parsed: unknown;
601608
try {
602609
parsed = JSON.parse(content.toString("utf-8"));
@@ -613,11 +620,26 @@ function inspectRestoreArchive(move: SessionSqliteMigrationMove): RestoreArchive
613620
};
614621
}
615622
legacyEntryCount = Object.keys(parsed).length;
623+
} else {
624+
// Transcript-like archives can be arbitrarily large. Hash them incrementally so duplicate
625+
// planning cannot turn a Doctor restore into a synchronous whole-file allocation.
626+
digest = hashRestoreArchive(fd, descriptorStat.size);
627+
}
628+
const finalPathStat = fs.lstatSync(move.archivePath);
629+
if (
630+
finalPathStat.dev !== descriptorStat.dev ||
631+
finalPathStat.ino !== descriptorStat.ino ||
632+
finalPathStat.size !== descriptorStat.size
633+
) {
634+
return {
635+
state: "invalid",
636+
reason: "archive changed while it was inspected; refusing restore",
637+
};
616638
}
617639
return {
618640
state: "available",
619641
snapshot: {
620-
digest: createHash("sha256").update(content).digest("hex"),
642+
digest,
621643
...(legacyEntryCount === undefined ? {} : { legacyEntryCount }),
622644
size: descriptorStat.size,
623645
},

‎src/commands/doctor-session-sqlite.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,6 +1357,64 @@ describe("runDoctorSessionSqlite", () => {
13571357
}
13581358
});
13591359

1360+
it("streams duplicate large transcript archives while selecting an identical restore", async () => {
1361+
const store = createLegacyStore();
1362+
const importReport = await runDoctorSessionSqlite({
1363+
env: store.env,
1364+
mode: "import",
1365+
store: store.storePath,
1366+
});
1367+
const firstManifestPath = requireMigrationManifestPath(importReport.migrationRun?.manifestPath);
1368+
const firstManifest = readMigrationManifest(firstManifestPath);
1369+
const firstTarget = expectDefined(firstManifest.targets[0], "first migration target");
1370+
const transcriptMove = expectDefined(
1371+
firstTarget.plannedMoves.find((move) => move.kind === "transcript"),
1372+
"transcript archive move",
1373+
);
1374+
const largeTranscript = `${JSON.stringify({
1375+
payload: "x".repeat(4 * 1024 * 1024),
1376+
type: "event",
1377+
})}\n`;
1378+
fs.writeFileSync(transcriptMove.archivePath, largeTranscript, { mode: 0o600 });
1379+
1380+
const secondArchivePath = `${transcriptMove.archivePath}.duplicate`;
1381+
fs.copyFileSync(transcriptMove.archivePath, secondArchivePath);
1382+
const duplicateManifest = structuredClone(firstManifest);
1383+
duplicateManifest.runId = `${firstManifest.runId}-duplicate`;
1384+
duplicateManifest.startedAt = new Date(Date.parse(firstManifest.startedAt) + 1).toISOString();
1385+
duplicateManifest.targets = [
1386+
{
1387+
...firstTarget,
1388+
completedMoves: [{ ...transcriptMove, archivePath: secondArchivePath }],
1389+
plannedMoves: [{ ...transcriptMove, archivePath: secondArchivePath }],
1390+
},
1391+
];
1392+
const duplicateManifestPath = path.join(
1393+
path.dirname(firstManifestPath),
1394+
`${duplicateManifest.runId}.json`,
1395+
);
1396+
fs.writeFileSync(duplicateManifestPath, `${JSON.stringify(duplicateManifest, null, 2)}\n`, {
1397+
mode: 0o600,
1398+
});
1399+
1400+
const restore = await runDoctorSessionSqlite({
1401+
allAgents: true,
1402+
cfg: {},
1403+
env: store.env,
1404+
mode: "restore",
1405+
});
1406+
1407+
const restoreReport = expectDefined(
1408+
restore.targets.find((target) => target.restore)?.restore,
1409+
"aggregate restore report",
1410+
);
1411+
expect(restoreReport.conflicts).toEqual([]);
1412+
expect(restore.totals.issues).toBe(0);
1413+
expect(fs.statSync(store.transcriptPath).size).toBe(Buffer.byteLength(largeTranscript));
1414+
expect(fs.readFileSync(store.transcriptPath, "utf-8")).toBe(largeTranscript);
1415+
expect([transcriptMove.archivePath, secondArchivePath].filter(fs.existsSync)).toHaveLength(1);
1416+
});
1417+
13601418
it("fails closed when several manifests contain distinct nonempty session indexes", async () => {
13611419
const store = createLegacyStore();
13621420
const preMigrationIndex = fs.readFileSync(store.storePath, "utf-8");

0 commit comments

Comments
 (0)