Skip to content

Commit 8a9d5b7

Browse files
fix(u5b): refuse an exact backup mtime tie instead of trusting readdir order
Recovery picks the newest committed backup with `sort((a, b) => b.mtimeMs - a.mtimeMs)` and renames the head of that list, then unlinks the rest. mtime is the only recency signal there, so when two backups share an exact mtime the sort decides nothing and the winner is whatever order readdir happened to return -- and the loser of that coin flip is deleted. That is the same evidence situation as a backup whose stat throws, which recovery already refuses rather than treating as absent, so a tie now resolves as uncheckable: reject, restore nothing, delete nothing, leave both copies for a human to read. The tie is asserted with utimes rather than raced against the clock, and a differing-mtime row rides beside it so the pair is not just a test that two backups means reject.
1 parent b328ded commit 8a9d5b7

2 files changed

Lines changed: 93 additions & 3 deletions

File tree

‎src/utils/__tests__/jsonFileRecovery.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as path from "path"
44

55
import { acquireFileLock } from "../fileLock"
66
import { setPersistenceTraceSink } from "../../core/task-persistence/persistenceTrace"
7-
import { deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery"
7+
import { recoverInterruptedReplacement, deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery"
88
import { readFileWithMissingRetry } from "../../core/task-persistence/readFileWithMissingRetry"
99

1010
vi.mock("fs/promises", async () => {
@@ -57,6 +57,57 @@ describe("reader recovery", () => {
5757
await expect(fs.readFile(backup)).rejects.toMatchObject({ code: "ENOENT" })
5858
})
5959

60+
// The recency choice is `sort((a, b) => b.mtimeMs - a.mtimeMs)` followed by renaming
61+
// the head of that list. mtime is the only signal recovery has, so an exact tie says
62+
// nothing about which backup holds the committed content - the winner would be readdir
63+
// order, and the loser is unlinked. The tie is set with utimes rather than raced
64+
// against the clock, so the row does not depend on how fast two writes land; the
65+
// second row is the control that keeps this from being a test which merely asserts
66+
// "two backups means reject".
67+
it("refuses an exact mtime tie between two backups instead of picking by directory order", async () => {
68+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
69+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
70+
const shared = new Date(1_700_000_000_000)
71+
await fs.utimes(backup, shared, shared)
72+
await fs.utimes(otherBackup, shared, shared)
73+
74+
const error = await recoverInterruptedReplacement(target).then(
75+
() => undefined,
76+
(reason: unknown) => reason,
77+
)
78+
expect(error).toMatchObject({
79+
name: "AmbiguousBackupRecencyError",
80+
code: "AMBIGUOUS_BACKUP_RECENCY",
81+
mtimeMs: 1_700_000_000_000,
82+
})
83+
// The diagnostic has to name the magnitude it refused to guess about.
84+
expect(String((error as Error).message)).toContain("share mtime 1700000000000")
85+
86+
// Fail closed: nothing restored, nothing deleted, so both copies survive for a
87+
// human to read.
88+
await expect(fs.access(target)).rejects.toMatchObject({ code: "ENOENT" })
89+
expect(JSON.parse(await fs.readFile(backup, "utf8"))).toEqual({ committed: true })
90+
expect(JSON.parse(await fs.readFile(otherBackup, "utf8"))).toEqual({ other: true })
91+
})
92+
93+
it("restores the newer backup when two backups have different mtimes", async () => {
94+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
95+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
96+
const older = new Date(1_700_000_000_000)
97+
const newer = new Date(1_700_000_000_001)
98+
await fs.utimes(otherBackup, older, older)
99+
await fs.utimes(backup, newer, newer)
100+
101+
const recovery = await recoverInterruptedReplacement(target)
102+
103+
expect(recovery.foundLeftovers).toBe(true)
104+
expect(recovery.restoredFrom).toBe(backup)
105+
expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ committed: true })
106+
// The loser of a decided race is still garbage-collected, which is the contract the
107+
// tie row must not break.
108+
await expect(fs.access(otherBackup)).rejects.toMatchObject({ code: "ENOENT" })
109+
})
110+
60111
it("traces reader restoration and lock waiting", async () => {
61112
const sink = vi.fn()
62113
setPersistenceTraceSink(sink)

‎src/utils/jsonFileRecovery.ts‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,32 @@ export async function deleteJsonFile(filePath: string): Promise<void> {
9999
})
100100
}
101101

102+
/**
103+
* Two leftover backups whose mtimes are exactly equal carry no evidence about which
104+
* one is the newer committed state - mtime is the only recency signal recovery has -
105+
* so choosing between them would be the order readdir happened to list them in, and
106+
* the loser of that order is garbage-collected below. Recovery refuses instead, the
107+
* same fail-closed decision it already makes for a backup it cannot stat: nothing is
108+
* restored and nothing is deleted, so both copies stay on disk for a human to read.
109+
*/
110+
class AmbiguousBackupRecencyError extends Error {
111+
readonly code = "AMBIGUOUS_BACKUP_RECENCY"
112+
readonly targetPath: string
113+
readonly mtimeMs: number
114+
readonly firstBackupPath: string
115+
readonly secondBackupPath: string
116+
constructor(targetPath: string, mtimeMs: number, firstBackupPath: string, secondBackupPath: string) {
117+
super(
118+
`Cannot tell which backup of ${targetPath} is the newest committed state: ${firstBackupPath} and ${secondBackupPath} share mtime ${mtimeMs}. Nothing was restored or deleted.`,
119+
)
120+
this.name = "AmbiguousBackupRecencyError"
121+
this.targetPath = targetPath
122+
this.mtimeMs = mtimeMs
123+
this.firstBackupPath = firstBackupPath
124+
this.secondBackupPath = secondBackupPath
125+
}
126+
}
127+
102128
/**
103129
* Heals the canonical path after an interrupted previous write. Must run
104130
* under the advisory lock and before any data is read or written: temp and
@@ -112,8 +138,9 @@ export async function deleteJsonFile(filePath: string): Promise<void> {
112138
* renamed to its backup but before the replacement landed. A process exit
113139
* at that point leaves the canonical path absent, which readers see as a
114140
* permanent ENOENT that no retry can repair, so the newest backup is
115-
* restored first. Leftover replacement and backup files are garbage
116-
* collected afterwards.
141+
* restored first, chosen by mtime. Two backups that share an exact mtime are
142+
* refused rather than split by directory order; see AmbiguousBackupRecencyError.
143+
* Leftover replacement and backup files are garbage collected afterwards.
117144
*
118145
* @returns Whether leftover files were found, and the backup path that was
119146
* restored, if any.
@@ -181,6 +208,18 @@ export async function recoverInterruptedReplacement(
181208
).filter((entry): entry is { backupPath: string; mtimeMs: number } => entry !== null)
182209
if (backupStats.length > 0) {
183210
backupStats.sort((a, b) => b.mtimeMs - a.mtimeMs)
211+
if (backupStats.length > 1 && backupStats[1].mtimeMs === backupStats[0].mtimeMs) {
212+
// mtime is the only recency signal here, and an exact tie carries none: the
213+
// winner would be the order readdir happened to list the two in, and the
214+
// loser is unlinked below. Refuse, as recovery already refuses a backup it
215+
// cannot stat.
216+
throw new AmbiguousBackupRecencyError(
217+
absoluteFilePath,
218+
backupStats[0].mtimeMs,
219+
backupStats[0].backupPath,
220+
backupStats[1].backupPath,
221+
)
222+
}
184223
const newestBackupPath = backupStats[0].backupPath
185224
try {
186225
await fs.rename(newestBackupPath, absoluteFilePath)

0 commit comments

Comments
 (0)