Skip to content

Commit 3caf4db

Browse files
test(file-safety,fileLock): carry the four pinned rows from PR 1914 across to this re-port
The reviewer verified these fixes on PR 1914 and then said, on threads 4525470987, 4525471078 and 4525471113, that this PR still contains the original test and the inline extractor at src/utils/fileLock.ts:82, and asked that the change be brought here if this PR proceeds. It does proceed, so the change comes here. The four paths are carried as the same blobs as commit 28129e1 on PR 1914: git hash-object of each staged file equals the blob id recorded in that commit (7d16823 fileLock.ts, ceb1388 fileLock.spec.ts, f5725de fileLock.canonicalKey.spec.ts, 68fc6e6 safeWriteText.spec.ts). That is deliberate: if PR 1914 merges first, the later rebase of this branch onto it drops this copy with no content change, because both sides hold byte-identical blobs for the same paths. No reader has to infer that from the diff. What lands, with line numbers taken from the blobs this commit records: - src/utils/fileLock.ts:5 imports getErrorCode from src/utils/errorCode.ts and line 83 calls it, so the inline extractor at the old line 82 is gone and three counted executable lines come off the diff. The two copies differed only on a non-string code property, and the sole use compares against the string literals "ENOENT" and "ENOTDIR", so behaviour is unchanged. - src/utils/__tests__/fileLock.spec.ts:171-172 pin the cycle walk exactly - the lock lands on the lexical second member and the walk spends 64 link hops - instead of asserting toBeLessThanOrEqual(64). - src/services/file-safety/__tests__/safeWriteText.spec.ts:367-395 rename and re-comment the post-commit backup cleanup case to say what makes it pass, a retried unlink, and count the attempts with expect(backupUnlinks).toHaveLength(2). The same file also carries the failure-path pin at line 1613. - src/utils/__tests__/fileLock.canonicalKey.spec.ts:71 pins the deliberate divergence - an ancestor realpath failure with EACCES rejects resolveLockKey but not the lock - and the BigIntStats cast fix for the lstat double arrives with the same blob. Verification, all of it in worktree wt-r164-2383 at node v22.23.4 (the version in .nvmrc) on a frozen-lockfile install of this tree's own pnpm-lock.yaml (37.9 s, husky installed by its prepare): - vitest run of the six affected specs (fileLock.spec, fileLock.canonicalKey.spec, fileLock.test, safeWriteText.spec, safeWriteJson.test, safeWriteJson.interruption.test): exit 0, 6 files passed, 139 tests passed. The kill evidence for these rows lives with PR 1914, where each mutant was run in the same content: frame budget 8 to 9 killed 1 of 7, hop budget not carried killed 1 of 7, the retry narrowed from two attempts to one killed 3 of 74, the skipped unlink killed 4 of 74, and swallowing the canonicalDirKey rethrow killed 1 of 3. - eslint --prune-suppressions --max-warnings=0 on each of the four touched files exits 0 with no output, and none of the four has an entry in src/eslint-suppressions.json, so each count is 0 before and 0 after; summed over that file the counts read 2,868 before and 2,868 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. - no --no-verify, no HUSKY=0, no git add -A, no changeset and no CHANGELOG change, and no label change.
1 parent 1f656e3 commit 3caf4db

4 files changed

Lines changed: 96 additions & 14 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: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,11 @@ beforeEach(() => {
3333
mockedLock.mockReset()
3434
// alias.json is a symlink to item.json; everything else resolves to itself.
3535
mockedRealpath.mockImplementation(async (target) => (target === alias ? referent : String(target)))
36-
mockedLstat.mockImplementation(async () => ({ isSymbolicLink: () => false }) as unknown as BigIntStats)
36+
// fs/promises types lstat as returning BigIntStats and this mock only ever needs
37+
// isSymbolicLink(), so the assertion is single-step and names the subset the double
38+
// actually fakes. AGENTS.md asks for a reason next to a cast a typed API cannot
39+
// express: no test in this file reads a bigint field, so no bigint field is faked.
40+
mockedLstat.mockImplementation(async () => ({ isSymbolicLink: () => false }) as BigIntStats)
3741
mockedReadlink.mockRejectedValue(Object.assign(new Error("not a link"), { code: "EINVAL" }))
3842
})
3943

@@ -64,4 +68,25 @@ describe("withFileLock lock-key canonicalization", () => {
6468
})
6569
expect(seen).toEqual([alias])
6670
})
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+
})
6792
})

‎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)