Skip to content

Commit 28129e1

Browse files
test(file-safety,fileLock): answer five review threads with pinned behaviour and kill the hop-budget mutants
Five CodeRabbit threads on PR 2383 stay open because the behaviour they ask about is either unpinned or pinned by an upper bound. Each one is answered here with a row that fails without the fix plus negative-control numbers against the behaviour as it stands. The merge of the U4 head ahead of this commit brings the lstat cast fix through the ancestor, which is the earliest-carrier consequence drawn from line 14 of comment 6767513159 and the keep-1914-versions recommendation at line 21 of comment 6739877102; the record does not state that consequence itself. Thread 4525471078 - fileLock.spec.ts cycle test asserted only toBeLessThanOrEqual(64), so a walk that spent a different number of hops and stopped on a different cycle member still passed. It now asserts the exact lock key and the exact hop count: eight frames of eight hops spend the 64-hop budget, 64 mod 3 leaves the cursor on the second member, realpath reports ENOENT to the root, so the key is the lexical second member. Measured against mutants in this worktree: - frame budget 8 to 9 at fileLock.ts:61 -> 1 failed, 6 passed - hop budget not carried to the next frame at fileLock.ts:74 -> 1 failed, 6 passed Both were killed by the new rows; the unmutated tree runs 7 passed in that file. Thread 4525470987 - the crash-safety test named a post-commit backup cleanup failure as swallowed, but the step that makes it pass is step 6 retrying once. The name, the comment and the assertions now say that: the failing attempt and the retry are both counted. Removing the retry (attempt < 2 to attempt < 1 at safeWriteText.ts:796) turns 3 tests red, including this one and its twin, so the assertion is load-bearing. Thread 4525471043 - the failure path after the commit rename removes the backup copy with one unlink whose error is swallowed, while the success path makes two attempts and reports a leftover as OrphanedPublishedBackupError. No source change this round: reporting the leftover would change which error the caller sees. A new top-level describe pins what happens today - one attempt, the durability failure reported, and nothing in it naming the path the failed unlink left beside the target. The desired contract was measured instead of assumed: the same test with toHaveLength(2) fails on this tree with 1 failed, 73 passed, which is the row a source fix would have to make pass. Skipping the unlink at safeWriteText.ts:841 turns 4 tests red, including this pin. Thread 4525471113 - fileLock.ts carried its own copy of the error-code extractor. It now calls getErrorCode from utils/errorCode.ts, which drops 3 counted source lines. The two copies differ only in accepting a non-string code property, and the only use is a comparison against two string literals, so the behaviour is identical and no test had to change: six suites covering fileLock.ts and safeWriteJson.ts run 157 passed, 6 skipped, exit 0. Thread 4525471006 - canonicalKey.spec.ts now pins the divergence the reviewer asked to see, with the two requirements quoted in the comment above it: an ancestor realpath that fails with EACCES makes resolveLockKey reject while withFileLock still locks the lexical path. Swallowing the rethrow at safeWriteText.ts:356 turns that row red with 'promise resolved ... instead of rejecting'. Verification, all of it in worktree wt-r161-1914 at node v22.23.4 (the version in .nvmrc) with a frozen-lockfile install of this tree's own pnpm-lock.yaml: - vitest run over the six affected specs: 6 files passed, 157 passed, 6 skipped, exit 0. - vitest run of the three directly edited specs before the mutants: 3 files passed, 84 tests passed, exit 0. - eslint --prune-suppressions --max-warnings=0 on each of the four touched files: exit 0, no output, and none of the four has an entry in src/eslint-suppressions.json, so each file's count is 0 before and 0 after. Summed over the file the counts read 2,866 before and 2,866 after across 265 file keys; the prune run rewrote the JSON from tab indent to two-space indent (30,910 B to 33,294 B, 0 semantic count diffs) and that churn was reverted, so this commit carries only the four paths in its stat. - tsc --noEmit in src exit 0; tsc -p tsconfig.json --noEmit at the root exit 0. - no --no-verify, no HUSKY=0, no git add -A, no changeset and no CHANGELOG change.
1 parent c2ca88c commit 28129e1

4 files changed

Lines changed: 91 additions & 13 deletions

File tree

‎src/services/file-safety/__tests__/safeWriteText.spec.ts‎

Lines changed: 59 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -364,23 +364,35 @@ describe("safeWriteText", () => {
364364
expect(fs.rename).toHaveBeenCalledTimes(1)
365365
})
366366

367-
it("a post-commit backup cleanup failure is non-fatal: the target stays committed and no temp is left behind", async () => {
367+
it("a post-commit backup cleanup failure is retried: the target stays committed and the retry clears", async () => {
368368
const targetPath = "/tmp/test-dir/target.txt"
369369
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
370370
vi.mocked(fsSync.openSync).mockReturnValue(1)
371-
// The post-commit backup unlink (SUT step 6) fails — the write must
372-
// still succeed; an orphaned backup is the documented acceptable
373-
// outcome, so the failure is swallowed instead of rolling back.
374-
vi.mocked(fs.unlink).mockRejectedValueOnce(new Error("EPERM"))
371+
const backupUnlinks: string[] = []
372+
// The post-commit backup unlink (SUT step 6) fails on its first attempt. What makes
373+
// the write still succeed is that step 6 retries once, so the retry is asserted here
374+
// instead of being described as a swallow - the swallow is the success path at the
375+
// failure-path unlink, which the failure-path describe pins separately.
376+
vi.mocked(fs.unlink).mockImplementation(async (candidate: unknown) => {
377+
const asString = String(candidate)
378+
if (asString.includes("safeWriteText.bak_")) {
379+
backupUnlinks.push(asString)
380+
if (backupUnlinks.length === 1) {
381+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" })
382+
}
383+
}
384+
})
375385

376386
await safeWriteText(targetPath, "data", { backup: true, platform: "linux" })
377387

378388
// the commit rename (temp -> target) still happened; it is the only rename
379389
expect(fs.rename).toHaveBeenCalledTimes(1)
380390
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath)
381391

382-
// the failing cleanup was the post-commit backup unlink
392+
// the failing cleanup was the post-commit backup unlink, attempted twice: attempt
393+
// one hit EPERM and attempt two is the retry that cleared it
383394
expect(fs.unlink).toHaveBeenCalledWith(expect.stringContaining("safeWriteText.bak_"))
395+
expect(backupUnlinks).toHaveLength(2)
384396

385397
// the staging temp was already committed by the rename; nothing
386398
// temp-shaped is unlinked afterwards
@@ -1598,6 +1610,47 @@ describe("cleanup before a rollback failure is reported", () => {
15981610
})
15991611
})
16001612

1613+
describe("backup removal on the failure path", () => {
1614+
beforeEach(() => mockDefaults())
1615+
// Thread 4525471043 on the CodeRabbit review of PR 2383. After the commit rename the
1616+
// failure path removes the backup copy with one unlink whose error is swallowed, while
1617+
// step 6 on the success path makes two attempts and reports a leftover as
1618+
// OrphanedPublishedBackupError. This test pins what the failure path does today and
1619+
// names the gap instead of fixing it: reporting the leftover would change which error
1620+
// the caller sees, and this round changes no source on this path.
1621+
it("makes one unlink attempt and reports the durability failure, not the leftover backup path", async () => {
1622+
const targetPath = "/tmp/test-dir/target.txt"
1623+
const dirPath = path.dirname(targetPath)
1624+
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
1625+
// The file fd opens normally; the parent-directory open after the commit rename
1626+
// fails, which is the post-commit durability failure that routes here.
1627+
vi.mocked(fsSync.openSync).mockImplementation((target) => {
1628+
if (String(target) === dirPath) {
1629+
throw new Error("EBADF")
1630+
}
1631+
return 1
1632+
})
1633+
const backupUnlinks: string[] = []
1634+
vi.mocked(fs.unlink).mockImplementation(async (candidate: unknown) => {
1635+
const asString = String(candidate)
1636+
if (asString.includes("safeWriteText.bak_")) {
1637+
backupUnlinks.push(asString)
1638+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" })
1639+
}
1640+
})
1641+
1642+
const error = await safeWriteText(targetPath, "data", { backup: true, platform: "linux" }).catch(
1643+
(thrown: unknown) => thrown,
1644+
)
1645+
expect(error).toBeInstanceOf(PostCommitDurabilityError)
1646+
// The durability failure is what the caller learns, and nothing in it names the copy
1647+
// this path failed to remove.
1648+
expect((error as Error).message).not.toContain("safeWriteText.bak_")
1649+
expect(backupUnlinks).toHaveLength(1)
1650+
expect(backupUnlinks[0]).toContain("safeWriteText.bak_")
1651+
})
1652+
})
1653+
16011654
describe("resolvePublishTarget", () => {
16021655
beforeEach(() => mockDefaults())
16031656

‎src/utils/__tests__/fileLock.canonicalKey.spec.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,4 +68,25 @@ describe("withFileLock lock-key canonicalization", () => {
6868
})
6969
expect(seen).toEqual([alias])
7070
})
71+
it("pins the deliberate divergence: an ancestor realpath failure rejects the key but not the lock", async () => {
72+
// Requirement quoted from comment 4525695084 on the CodeRabbit review of PR 2383,
73+
// ASCII-normalised (the original uses typographic apostrophes and a bullet list):
74+
// 1. make an ancestor realpath fail with EACCES, and
75+
// 2. assert that resolveLockKey(target) rejects while withFileLock still takes the
76+
// lock at the lexical path.
77+
// The divergence is the contract, not an accident: resolveLockKey canonicalizes the
78+
// parent through canonicalDirKey, which rethrows a non-ENOENT realpath failure so a
79+
// read-modify-write never guesses which lock it is on, while canonicalLockPath returns
80+
// the lexical path on the same failure so task-history deletion still serialises on
81+
// something. This test is the pin: if either half changes, the divergence has to be
82+
// re-decided on purpose instead of discovered in review.
83+
vi.mocked(mockedRealpath).mockImplementation(async (_target) => {
84+
throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })
85+
})
86+
87+
await expect(resolveLockKey(alias)).rejects.toThrow("EACCES")
88+
await withFileLock(alias, async () => undefined)
89+
expect(mockedLock).toHaveBeenCalledTimes(1)
90+
expect(mockedLock.mock.calls[0][0]).toBe(alias)
91+
})
7192
})

‎src/utils/__tests__/fileLock.spec.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,16 @@ test("terminates on a three-link cycle instead of recursing forever", async () =
160160

161161
const releaseLock = await acquireFileLock(a)
162162

163-
// Terminated with exactly one lock acquisition on a cycle member, and the
164-
// total hop budget held across all frames.
163+
// Terminated with exactly one lock acquisition, and the hop accounting is pinned to an
164+
// exact number instead of an upper bound: eight frames of eight hops spend the 64-hop
165+
// budget, 64 mod 3 leaves the cursor on the second cycle member, and realpath reports
166+
// ENOENT all the way to the root, so the lock lands on the lexical second member.
167+
// An upper bound accepts any walk that stopped early, which is how the per-frame bound
168+
// mutant and the budget-carry mutant survived: they also terminate, just after a
169+
// different number of hops and on a different member.
165170
expect(lockfile.lock).toHaveBeenCalledTimes(1)
166-
expect(vi.mocked(fsPromises.readlink).mock.calls.length).toBeLessThanOrEqual(64)
171+
expect(lockfile.lock).toHaveBeenCalledWith(b, expect.objectContaining({ realpath: false }))
172+
expect(vi.mocked(fsPromises.readlink).mock.calls.length).toBe(64)
167173

168174
await releaseLock()
169175
})

‎src/utils/fileLock.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as path from "path"
22
import { tracePersistenceEvent } from "../core/task-persistence/persistenceTrace"
33
import * as lockfile from "proper-lockfile"
44
import * as fs from "fs/promises"
5+
import { getErrorCode } from "./errorCode"
56

67
/**
78
* Shared staleness window for per-file advisory locks. This module owns the
@@ -79,10 +80,7 @@ async function canonicalLockPath(filePath: string, remainingLinkHops = MAX_TOTAL
7980
const realPath = await fs.realpath(cursor)
8081
return missing.length > 0 ? path.join(realPath, ...missing.reverse()) : realPath
8182
} catch (error) {
82-
const code =
83-
typeof error === "object" && error !== null && "code" in error
84-
? (error as { code?: string }).code
85-
: undefined
83+
const code = getErrorCode(error)
8684
if (code !== "ENOENT" && code !== "ENOTDIR") return absoluteFilePath
8785
const parent = path.dirname(cursor)
8886
if (parent === cursor) return absoluteFilePath

0 commit comments

Comments
 (0)