--verify keeps a mismatched original until a matching copy replaces it (closes #199)
check / check (push) Waiting to run

With --verify, an original whose hash does not match is no longer removed
before its replacement is downloaded. replaceOriginal, beside placeOriginal
in src/library/content.ts, has the content cache's new fetchOriginal write
the replacement to a temporary file beside the original, hashes it, and
renames it over the original only when it matches; a live photo's image and
video are both hashed before either is renamed. A failed or mismatching
download leaves the old bytes and album links, removes the temporary files,
and lands in failures.json. The replacement is always downloaded, never
copied from the cache. The leftover-file cleanup also takes a live photo's
replacement files, .quak-<pid>-<random>.<ext>.

Model: opus-5-5
This commit was merged in pull request #209.
This commit is contained in:
2026-10-16 06:56:19 +02:00
parent 960a7ce8a6
commit 8583863ec0
7 changed files with 294 additions and 115 deletions
+83 -20
View File
@@ -191,9 +191,12 @@ class HostileClient extends MockClient {
}
// A content source that writes byte buffers of the expected length and can be
// told to fail one fileID's original, to exercise per-file resilience.
// told to fail one fileID's original, as a server error or as a 404, or to
// write other bytes for it, to exercise per-file resilience.
interface StubSource extends ContentSource {
failID?: number;
notFoundID?: number;
otherBytesID?: number;
failThumbID?: number;
originalCalls: number;
}
@@ -204,8 +207,10 @@ const stubSource = (): StubSource => {
original: async ({ file: f, destination }) => {
s.originalCalls++;
if (s.failID === f.id) throw new Error("HTTP 500 from server");
if (s.notFoundID === f.id) throw new Error("HTTP 404 from server");
const size = SIZE_BY_ID[f.id] ?? 10;
writeFileSync(destination, Buffer.alloc(size));
const fill = s.otherBytesID === f.id ? 2 : 0;
writeFileSync(destination, Buffer.alloc(size, fill));
return { bytesWritten: size };
},
thumbnail: async ({ file: f, destination }) => {
@@ -696,17 +701,26 @@ describe("lib.backup", () => {
// A child that has already exited: its process ID is not running.
const exitedPID = spawnSync(process.execPath, ["-e", ""]).pid;
const leftover = `.quak-backup-2026-03-01.100.jpg-${exitedPID}-abc123.tmp`;
// A live photo's image and video downloaded to replace a stored one,
// before they were renamed into place.
const replacement = [
`.quak-${exitedPID}-abc789.heic`,
`.quak-${exitedPID}-abc789.mov`,
];
// This test's own process stands in for a backup running at the same
// time.
const inProgress = `.quak-backup-2026-03-01.101.jpg-${process.pid}-def456.tmp`;
writeFileSync(join(day, leftover), "partial");
writeFileSync(join(day, inProgress), "partial");
for (const name of [leftover, ...replacement, inProgress]) {
writeFileSync(join(day, name), "partial");
}
const lib = await openLibrary(stubSource());
await lib.backup({ downloadDirectory: outDir });
const names = readdirSync(day);
expect(names).not.toContain(leftover);
expect(names).not.toContain(replacement[0]);
expect(names).not.toContain(replacement[1]);
expect(names).toContain(inProgress);
lib.close();
});
@@ -1294,7 +1308,8 @@ describe("image metadata in each file's JSON", () => {
});
// With `verify`, each original already stored is hashed, and one that does not
// match the content hash its metadata records is downloaded again.
// match the content hash its metadata records is downloaded again, and replaced
// only by a download that matches.
describe("backup with verify", () => {
// MockClient's files, each recording the hash of what `stubSource` writes
// for it, except diagram.png (200), which records none.
@@ -1337,6 +1352,12 @@ describe("backup with verify", () => {
const good = Buffer.alloc(SIZE_BY_ID[100]!);
const corrupt = Buffer.alloc(SIZE_BY_ID[100]!, 1);
// The temporary files left in the date folder of the backup in `outDir`.
const tempFiles = (outDir: string): string[] =>
readdirSync(join(outDir, DAY)).filter((name) =>
name.startsWith(".quak-"),
);
it("leaves an original that matches its hash, and one with no hash, as they are", async () => {
const { lib, source, outDir } = await backedUp();
const calls = source.originalCalls;
@@ -1381,13 +1402,16 @@ describe("backup with verify", () => {
expect(log.filter((msg) => msg.startsWith("MISMATCH"))).toEqual([
"MISMATCH original beach.jpg (100): its bytes do not match its content hash",
]);
expect(tempFiles(outDir)).toEqual([]);
await lib.close();
});
it("records a failed download in failures.json, with the original removed", async () => {
// A copy whose hash does not match is still mostly the photo, so the
// backup keeps it until it holds a better one.
it("keeps an original that does not match its hash when its download answers 404", async () => {
const { lib, source, outDir } = await backedUp();
writeFileSync(saved(outDir, "100.jpg"), corrupt);
source.failID = 100;
source.notFoundID = 100;
const result = await lib.backup({
downloadDirectory: outDir,
@@ -1400,18 +1424,18 @@ describe("backup with verify", () => {
failed: 1,
});
expect(Object.keys(readLedger(outDir).files)).toEqual(["100"]);
expect(existsSync(saved(outDir, "100.jpg"))).toBe(false);
expect(readFileSync(saved(outDir, "100.jpg"))).toEqual(corrupt);
expect(
readlinkSync(join(outDir, "collections", "Vacation", "beach.jpg")),
).toBe(linkTo("100.jpg"));
expect(tempFiles(outDir)).toEqual([]);
await lib.close();
});
it("records in failures.json an original the cache puts back with the same bad bytes", async () => {
const lib = await openLibrary(stubSource(), new HashedClient());
const outDir = join(root, "backup");
// The cache holds a bad copy, and a backup copies an original the
// cache holds to its save path.
const cached = await lib.photos.byID({ fileID: 100 })!.original();
writeFileSync(cached.path, corrupt);
await lib.backup({ downloadDirectory: outDir });
it("keeps an original that does not match its hash when its download does not match either", async () => {
const { lib, source, outDir } = await backedUp();
writeFileSync(saved(outDir, "100.jpg"), corrupt);
source.otherBytesID = 100;
const result = await lib.backup({
downloadDirectory: outDir,
@@ -1424,10 +1448,39 @@ describe("backup with verify", () => {
failed: 1,
});
expect(result.errors.map((e) => e.error)).toEqual([
"the original put back does not match its content hash either",
"the downloaded original does not match its content hash either",
]);
expect(Object.keys(readLedger(outDir).files)).toEqual(["100"]);
expect(readFileSync(saved(outDir, "100.jpg"))).toEqual(corrupt);
expect(tempFiles(outDir)).toEqual([]);
await lib.close();
});
// The cache can hold the same bad bytes, as a copy from it is not checked
// as a download is, so the replacement is always downloaded.
it("downloads the replacement even when the cache holds the original", async () => {
const source = stubSource();
const lib = await openLibrary(source, new HashedClient());
const outDir = join(root, "backup");
// The cache holds a bad copy, and a backup copies an original the
// cache holds to its save path.
const cached = await lib.photos.byID({ fileID: 100 })!.original();
writeFileSync(cached.path, corrupt);
await lib.backup({ downloadDirectory: outDir });
const calls = source.originalCalls;
const result = await lib.backup({
downloadDirectory: outDir,
verify: true,
});
expect(result).toMatchObject({
downloaded: 1,
mismatched: 1,
failed: 0,
});
expect(source.originalCalls).toBe(calls + 1);
expect(readFileSync(saved(outDir, "100.jpg"))).toEqual(good);
await lib.close();
});
@@ -1511,6 +1564,9 @@ describe("backup album folders", () => {
writeFileSync(path, `original ${fileID}`);
return { path };
},
fetchOriginal: async () => {
throw new Error("no verify in this stand-in");
},
thumbnail: async () => {
throw new Error("no thumbnails in this stand-in");
},
@@ -2244,11 +2300,12 @@ describe("backup of live photos", () => {
Buffer.from(IMAGE),
);
expect(readFileSync(video)).toEqual(Buffer.from(VIDEO));
expect(readdirSync(join(outDir, DAY)).sort()).toEqual(stored);
expect(tree(outDir)).toEqual(linked);
await lib.close();
});
it("removes both files of a live photo that does not match its hash when downloading it again fails", async () => {
it("keeps both files of a live photo that does not match its hash when downloading it again fails", async () => {
const { file: live, body } = await asLivePhoto(
file(500, 10, "IMG_0500.HEIC"),
);
@@ -2266,8 +2323,14 @@ describe("backup of live photos", () => {
expect(result).toMatchObject({ mismatched: 1, failed: 1 });
expect(Object.keys(readLedger(outDir).files)).toEqual(["500"]);
expect(existsSync(saved(outDir, "500.heic"))).toBe(false);
expect(existsSync(saved(outDir, "500.mov"))).toBe(false);
expect(readFileSync(saved(outDir, "500.heic"))).toEqual(
Buffer.from(IMAGE),
);
expect(readFileSync(saved(outDir, "500.mov"), "utf-8")).toBe(
"another few seconds of video",
);
expect(readdirSync(join(outDir, DAY)).sort()).toEqual(stored);
expect(tree(outDir)).toEqual(linked);
await lib.close();
});