Skip to content

Commit 7cd0106

Browse files
Zoo-Code-Org#1912 review rows: resolve-or-refuse lock key, re-verify at the commit
Eleven review rows were open on Zoo-Code-Org#1912 at 085fbf8. Every production change below carries a row that fails without it, and that claim was tested rather than asserted: the two source files were read out of 085fbf8 with 'git show', written into this worktree unchanged, and the three affected spec files were run against them. 15 of this unit's rows failed - 5 in services/file-safety/__tests__/safeWriteText.spec, 9 in utils/__tests__/safeWriteJson.test, 1 in utils/__tests__/safeWriteJson.lockKey.spec - while every pre-existing row in those files stayed green. safeWriteJson.interruption.test (12) and safeWriteText.integration.spec (7) were green in both states. safeWriteText.ts - the lock key is resolved or refused, never guessed canonicalDirKey now walks upward only while the lookup answers ENOENT: it collects the missing names, retries the parent, and rethrows any other code, so a directory that exists but cannot be read is no longer treated as absent. resolveLockKey bounds the link walk at 8 links and throws instead of returning whichever link the bound stopped on; it reads a relative referent against the link's real parent rather than the spelled one; and it accepts only ENOENT and EINVAL from readlink as 'not a link' - measured on this box, those are the two answers a real readlink gives (EINVAL for a plain file, ENOENT for a missing path) - so any other code propagates instead of being read as a verdict about the path. Rows: refuses a lock key when an ancestor exists but cannot be canonicalized; keys a relative referent through the link's real parent, not the spelled one; propagates a readlink failure that says nothing about whether the path is a link; and the existing cycle row, retitled to terminates on a link cycle and refuses rather than naming whichever link the bound stopped on. The last of those is a contract change, not an addition: at 085fbf8 the same fixture returned the 8th link's spelling and the old row asserted the return, so the row now asserts the rejection and keeps the eight-call evidence. Before the commit rename, safeWriteText compares the staging name against the identity it just fsynced (fstatSync with bigint stats, then lstat at the rename, nlink compared against 1n because every bigint field is a bigint and 1n !== 1 is always true) and refuses with StagingPathError when a different file sits there; the cleanup gate skips the unlink in that case, because the name now belongs to another file's write. Rows: refuses the commit rename when a different file sits at the staging name after the fsync (rename not called, unlink not called) and keeps the commit when the staged name still holds the file that was fsynced. The second row is a control and passes at 085fbf8 as well, which is what a control is for. Two pre-existing rows needed better doubles rather than a looser product: rows whose subject is target resolution mocked fs.lstat to reject ENOENT for every path, and the staging check reads the same mock, so those doubles are now path-aware; and the lock-key spec's two 'not a link' doubles threw a bare Error with no code, which the new taxonomy cannot treat as 'not a link', so they now carry EINVAL. safeWriteJson.ts - the confinement decision is pinned and re-checked at the rename The confinement root resolved before the lock is captured once (confinedScopeRoot) and every later check uses it, so a peer that replaces the scope directory's name while the writer waits for the lock can no longer move the publish outside the scope the write was authorised for. Recovery now runs after the confinement check rather than before it, against the same pinned root, and is keyed to the lock key - the referent's directory - so an interrupted EPERM fallback is found by the next writer that arrives through a differently named alias. _assertConfinementStillHolds compares the re-resolved target with the pinned target and re-checks each pinned directory's identity and its resolved path, and it runs both before the staged write and immediately before the commit rename, so an ancestor swapped while the JSON was streaming cannot publish outside the scope. ENOENT and ENOTDIR from those lookups mean the directory is gone or is no longer a directory; every other code propagates, so a transient EACCES is no longer reported as an ancestor replacement. TargetMovedError now names the target the caller authorised and the target it resolves to now, which are different things. _streamDataToFile creates the staged file with mode 0o600, and _copyTargetMode fails closed: a stat or chmod failure aborts the publish instead of logging past it and publishing a world-readable replacement for a private target. Rows: refuses the commit when an ancestor is swapped while the staged write is in flight; refuses the commit when a moved ancestor's old name is replaced by a link back to it; propagates a transient ancestor lookup failure instead of reporting a replaced ancestor; reports what the target resolves to now when it no longer resolves to the pinned target; holds the confined scope to the directory named before the lock when a peer replaces that name; does not recover an interrupted write through an ancestor that was replaced while the lock was waited for; creates the staged JSON private and puts the target's own mode on it before publishing; aborts the publish when the staged file cannot take the target's mode; aborts the publish when the target's mode cannot be read; and, in the lock-key spec, recovers an interrupted write beside the referent the lock key names, not beside the spelling the caller arrived with. The post-commit directory-fsync row was strengthened in place instead of added beside itself. It used to assert only that the warning mentions fsync, which the warning also satisfies when the directory cannot be opened at all, so no fsync ever ran. It now records the fsyncSync descriptors and the openSync calls for the published file's directory and requires a fsync on one of those handles after the commit rename. The vacuity was demonstrated in three runs of that one row: the old assertion plus a mocked openSync failure passed (1 passed, 61 skipped), the new assertions plus the same mocked failure failed, and the new assertions on the unmodified run passed. Two harness facts shaped the row: reading a spy's calls after mockRestore is vacuous because restoring clears the call history, and createWriteStream opens the file lazily, so the staged file's own mode is read on the stream's open event. Gates, this worktree, node 22.23.4 win32, cwd src unless noted: eslint --max-warnings=0 --no-warn-ignored --no-cache, the five delta files: exit 0, no output. prettier --check, the same five: exit 0 (All matched files use Prettier code style). tsc --noEmit -p tsconfig.json: exit 2, one line - activate/registerCommands.ts(88,102): error TS2739 - the same pre-existing error the parent reports; nothing else. src/eslint-suppressions.json: 0 bytes of diff; no suppressed count moved. safeWriteText.spec 94 passed (103 rows at parent, 109 now); safeWriteText.integration.spec 7 passed; safeWriteJson.test 62 passed (46 rows at parent, 55 now, 1 row strengthened); safeWriteJson.lockKey.spec 6 passed (5 at parent); safeWriteJson.interruption.test 12 passed. Lanes, run one at a time: misc 2119 passed 13 skipped; core 4247 passed 9 skipped; services 1704 passed 11 failed; api 4069 passed 1 failed. Coverage with those specs: safeWriteText.ts 96.93 statements 91.23 branch 96.75 lines; safeWriteJson.ts 94.94 statements 82 branch 94.94 lines (misc lane, exit 0). The services and api failures are local and pre-existing: with the parent's two source files restored the same specs give the same 11 and 1 (marketplace 4, rules 5, parser 2 - TelemetryService not initialized through the junction'd donor telemetry package, and EPERM on fs.symlink; and api/providers/__tests__/poe.spec.ts expecting maxTokens 8192 and receiving 128000). poe.spec fails alone as well, so it is not lane contention. knip and knip:production could not run here at all: both stop with 'Cannot find module @roo-code/config-eslint/base' while loading apps/cli/eslint.config.mjs, and scripts/knip-policy.test.mjs reports 7 pass 1 fail with this unit's changes stashed, the same numbers it reports unstashed. knip's arm was green at the parent and this delta exports nothing new, so the local inability to run it is recorded as a gap in this checkout's install, not as evidence. No changeset and no CHANGELOG entry, per AGENTS.md. Delta: 5 files, 858 insertions, 86 deletions, of which 603 insertions are test rows.
1 parent 085fbf8 commit 7cd0106

5 files changed

Lines changed: 858 additions & 86 deletions

File tree

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

Lines changed: 145 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1447,10 +1447,15 @@ describe("safeWriteText", () => {
14471447

14481448
it("when realpath reports ENOENT (target absent), uses the given path as-is", async () => {
14491449
const targetPath = "/tmp/test-dir/target.txt"
1450-
vi.mocked(fs.realpath).mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" }))
1451-
// lstat reports the path itself as absent, so this is a new target and
1452-
// the fallback is allowed.
1453-
vi.mocked(fs.lstat).mockRejectedValue(Object.assign(new Error("ENOENT"), { code: "ENOENT" }))
1450+
const enoent = Object.assign(new Error("ENOENT"), { code: "ENOENT" })
1451+
vi.mocked(fs.realpath).mockRejectedValue(enoent)
1452+
// lstat reports the target path itself as absent, so this is a new target and
1453+
// the fallback is allowed. The staging name is answered apart: the commit
1454+
// re-verifies the staged file before renaming it, and the file this write just
1455+
// created and fsynced is present there.
1456+
vi.mocked(fs.lstat).mockImplementation(async (target) =>
1457+
String(target).includes("safeWriteText_") ? _fileStats(false) : Promise.reject(enoent),
1458+
)
14541459
vi.mocked(fsSync.openSync).mockReturnValue(1)
14551460

14561461
await safeWriteText(targetPath, "data", { platform: "linux" })
@@ -1653,9 +1658,16 @@ describe("resolveLockKey", () => {
16531658
const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
16541659
vi.mocked(fs.realpath).mockRejectedValue(enoent)
16551660
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(true))
1656-
// Only the link path is read, so a single answer is enough and keeps the mock's
1657-
// return type matching fs.promises.readlink.
1658-
vi.mocked(fs.readlink).mockResolvedValue("referent.json")
1661+
// The link answers with its referent; the referent itself is the file that is
1662+
// missing, so readlink answers ENOENT there and the walk stops. Those are the two
1663+
// answers a real readlink gives - measured with node 22.23.4 on win32, a missing
1664+
// path reports ENOENT and a path that is not a link reports EINVAL - and the walk
1665+
// ends on both and on no other code.
1666+
// Matched by basename because the walk hands readlink the spelling it is holding,
1667+
// which is the caller's spelling for the first hop and the joined referent after it.
1668+
vi.mocked(fs.readlink).mockImplementation(async (target) =>
1669+
path.basename(String(target)) === "file.json" ? "referent.json" : Promise.reject(enoent),
1670+
)
16591671

16601672
// Mid-commit a peer writer renames the referent away and back, so the key
16611673
// must still be computable while the link dangles.
@@ -1664,19 +1676,134 @@ describe("resolveLockKey", () => {
16641676
)
16651677
})
16661678

1667-
it("terminates on a two-link cycle instead of walking forever", async () => {
1679+
it("terminates on a link cycle and refuses rather than naming whichever link the bound stopped on", async () => {
16681680
const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
16691681
vi.mocked(fs.realpath).mockRejectedValue(enoent)
16701682
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(true))
16711683
// Every readlink answers with the same link, so an unbounded walk would
1672-
// never end; the bounded walk returns the key it actually reached.
1684+
// never end. Returning the intermediate link was not a safe answer either: a
1685+
// writer that entered the same chain from the other end stops at a different
1686+
// link, and the two writers then hold two locks for one file. The walk is
1687+
// bounded and the caller is told that no key could be resolved.
16731688
vi.mocked(fs.readlink).mockImplementation(async () => "a.json")
16741689

1675-
await expect(resolveLockKey("/tmp/linkdir/a.json")).resolves.toBe(
1676-
path.resolve(path.join("/tmp/linkdir", "a.json")),
1677-
)
1690+
await expect(resolveLockKey("/tmp/linkdir/a.json")).rejects.toThrow(/symlink chain is deeper than 8 links/)
1691+
// The bound is still what terminates the walk: eight reads, no more.
16781692
expect(fs.readlink).toHaveBeenCalledTimes(8)
16791693
})
1694+
1695+
it("refuses a lock key when an ancestor exists but cannot be canonicalized", async () => {
1696+
// The file itself is absent, so the key is computed from the directory. The directory
1697+
// is there but its parent component is a regular file, so realpath answers ENOTDIR:
1698+
// the canonical location of that directory is unknown. Returning the spelled path
1699+
// would key this writer apart from every writer that did canonicalize the same file,
1700+
// which is the two-locks-for-one-file loss this function exists to prevent, so only
1701+
// the ENOENT answer may be walked over.
1702+
const enotdir = Object.assign(new Error("ENOTDIR: not a directory"), { code: "ENOTDIR" })
1703+
vi.mocked(fs.realpath).mockImplementation(async (target) => {
1704+
if (path.resolve(String(target)) === path.resolve("/tmp/dir/package/sub")) throw enotdir
1705+
return String(target)
1706+
})
1707+
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(false))
1708+
1709+
await expect(resolveLockKey("/tmp/dir/package/sub/file.json")).rejects.toBe(enotdir)
1710+
})
1711+
1712+
it("keys a relative referent through the link's real parent, not the spelled one", async () => {
1713+
// `..` in a referent names the directory the link lives in. Under a symlinked
1714+
// directory that is not the directory the caller spelled, so joining the referent
1715+
// onto the spelled parent keys a different file: the writer that arrives through the
1716+
// alias and the writer that arrives through the referent then stop excluding each
1717+
// other. The link here hangs in /tmp/alias/notes, which resolves to /real/notes, and
1718+
// its referent is ../other/b.json, which lives in /real/other.
1719+
const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1720+
vi.mocked(fs.realpath).mockImplementation(async (target) => {
1721+
const key = path.resolve(String(target))
1722+
if (key === path.resolve("/tmp/alias/notes/a.json")) throw enoent
1723+
if (key === path.resolve("/tmp/alias/notes")) return path.resolve("/real/notes")
1724+
if (key === path.resolve("/real/other")) return path.resolve("/real/other")
1725+
return String(target)
1726+
})
1727+
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(true))
1728+
vi.mocked(fs.readlink).mockImplementation(async (target) =>
1729+
path.basename(String(target)) === "a.json"
1730+
? "../other/b.json"
1731+
: Promise.reject(Object.assign(new Error("EINVAL: invalid argument"), { code: "EINVAL" })),
1732+
)
1733+
1734+
await expect(resolveLockKey("/tmp/alias/notes/a.json")).resolves.toBe(
1735+
path.join(path.resolve("/real/other"), "b.json"),
1736+
)
1737+
})
1738+
1739+
it("propagates a readlink failure that says nothing about whether the path is a link", async () => {
1740+
// ENOENT and EINVAL are the two answers that end the walk, because each says the
1741+
// path is not a chain to follow. EACCES says nothing of the kind: the path may or
1742+
// may not be a link, and guessing that it is not keys this writer to the alias while
1743+
// a writer that reached the referent keys the referent.
1744+
const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
1745+
const eacces = Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" })
1746+
vi.mocked(fs.realpath).mockRejectedValue(enoent)
1747+
vi.mocked(fs.lstat).mockResolvedValue(_fileStats(true))
1748+
vi.mocked(fs.readlink).mockRejectedValue(eacces)
1749+
1750+
await expect(resolveLockKey("/tmp/linkdir/file.json")).rejects.toBe(eacces)
1751+
})
1752+
})
1753+
1754+
describe("staged file identity at the commit rename", () => {
1755+
beforeEach(() => mockDefaults())
1756+
1757+
it("refuses the commit rename when a different file sits at the staging name after the fsync", async () => {
1758+
const targetPath = "/tmp/test-dir/target.txt"
1759+
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
1760+
vi.mocked(fsSync.openSync).mockReturnValue(1)
1761+
// The file this write opened, wrote and fsynced: a single-named regular file with
1762+
// identity (dev 7, ino 4242). lstat with { bigint: true } reports every numeric field
1763+
// as a bigint, so the staging-side doubles carry nlink as one too.
1764+
const fsynced = _fileStatsWithIdentity(4242n, 7n)
1765+
fsynced.nlink = 1n
1766+
vi.mocked(fsSync.fstatSync).mockReturnValue(fsynced)
1767+
// After this write closed the descriptor, a process that can write the staging
1768+
// directory moved this write's file aside and named another file after it. The commit
1769+
// rename takes the name, so it would publish bytes this write never wrote or flushed.
1770+
const foreign = _fileStatsWithIdentity(9999n, 7n)
1771+
foreign.nlink = 1n
1772+
vi.mocked(fs.lstat).mockImplementation(async (target) =>
1773+
String(target).includes("safeWriteText_") ? foreign : _fileStats(false),
1774+
)
1775+
1776+
const error = await safeWriteText(targetPath, "hello", { platform: "linux" }).then(
1777+
() => undefined,
1778+
(commitError: unknown) => commitError,
1779+
)
1780+
1781+
expect(error).toBeInstanceOf(StagingPathError)
1782+
expect((error as StagingPathError).message).toContain("between the fsync and the commit rename")
1783+
// The rename is the statement that publishes, and it never ran.
1784+
expect(fs.rename).not.toHaveBeenCalled()
1785+
// The file at the staging name belongs to someone else: the failure cleanup must not
1786+
// delete the file that took this write's name.
1787+
expect(fs.unlink).not.toHaveBeenCalled()
1788+
})
1789+
1790+
it("keeps the commit when the staged name still holds the file that was fsynced", async () => {
1791+
const targetPath = "/tmp/test-dir/target.txt"
1792+
vi.mocked(fs.realpath).mockResolvedValue(targetPath)
1793+
vi.mocked(fsSync.openSync).mockReturnValue(1)
1794+
// The staging name resolves to the same identity the descriptor carried, so the
1795+
// guard above must not fire on an ordinary write.
1796+
const fsynced = _fileStatsWithIdentity(4242n, 7n)
1797+
fsynced.nlink = 1n
1798+
vi.mocked(fsSync.fstatSync).mockReturnValue(fsynced)
1799+
vi.mocked(fs.lstat).mockImplementation(async (target) =>
1800+
String(target).includes("safeWriteText_") ? fsynced : _fileStats(false),
1801+
)
1802+
1803+
await safeWriteText(targetPath, "hello", { platform: "linux" })
1804+
1805+
expect(fs.rename).toHaveBeenCalledWith(expect.stringContaining("safeWriteText_"), targetPath)
1806+
})
16801807
})
16811808

16821809
describe("caller-supplied staging path", () => {
@@ -1945,7 +2072,12 @@ describe("resolvePublishTarget", () => {
19452072
const targetPath = "/tmp/test-dir/target.txt"
19462073
const enoent = Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
19472074
vi.mocked(fs.realpath).mockRejectedValue(enoent)
1948-
vi.mocked(fs.lstat).mockRejectedValue(enoent)
2075+
// The target is absent, which is what the fallback is about. The staging name is
2076+
// answered separately: the commit re-verifies the staged file before renaming it,
2077+
// and this write created and fsynced that file itself.
2078+
vi.mocked(fs.lstat).mockImplementation(async (target) =>
2079+
String(target).includes("safeWriteText_") ? _fileStats(false) : Promise.reject(enoent),
2080+
)
19492081
vi.mocked(fsSync.openSync).mockReturnValue(1)
19502082

19512083
await safeWriteText(targetPath, "data", { platform: "linux" })

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

Lines changed: 111 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -348,12 +348,37 @@ function errorCode(error: unknown): string | undefined {
348348
* Windows 8.3 short name, so a lock key must be canonical even when the file
349349
* itself is not there yet -- otherwise the key for one file depends on whether
350350
* the file exists when the key is computed, and two writers take two locks.
351+
* Components that are not there yet are walked over and re-joined onto the nearest
352+
* ancestor that is: the writer that arrives before this file's parent directory is
353+
* created has to take the lock of the writer that arrives after it. Only a missing
354+
* component may be walked over. An ancestor that exists but cannot be canonicalized
355+
* (ENOTDIR under a regular-file component, EACCES, EIO, ELOOP) means the canonical
356+
* key is unknown, and handing back the literal spelling would key this writer apart
357+
* from every writer that did canonicalize the same file.
351358
*/
352359

353360
async function canonicalDirKey(absoluteFilePath: string): Promise<string> {
354-
const dirPath = path.dirname(absoluteFilePath)
355-
const canonicalDir = await fs.realpath(dirPath).catch(() => dirPath)
356-
return path.join(canonicalDir, path.basename(absoluteFilePath))
361+
const basename = path.basename(absoluteFilePath)
362+
const missing: string[] = []
363+
let cursor = path.dirname(absoluteFilePath)
364+
for (;;) {
365+
try {
366+
const canonicalDir = await fs.realpath(cursor)
367+
return path.join(canonicalDir, ...missing.reverse(), basename)
368+
} catch (error: unknown) {
369+
if (errorCode(error) !== "ENOENT") {
370+
throw error
371+
}
372+
const parent = path.dirname(cursor)
373+
if (parent === cursor) {
374+
// The root of this path was reached with components still missing: no ancestor
375+
// is left to canonicalize, so this spelling is the only answer available.
376+
return path.join(cursor, ...missing.reverse(), basename)
377+
}
378+
missing.push(path.basename(cursor))
379+
cursor = parent
380+
}
381+
}
357382
}
358383

359384
/**
@@ -362,8 +387,10 @@ async function canonicalDirKey(absoluteFilePath: string): Promise<string> {
362387
* tolerates a dangling link, because the lock key has to be computable while a
363388
* peer writer is mid-commit (a publish renames the staged file onto the referent,
364389
* and backup mode keeps a copy beside it).
365-
* The walk is bounded so a two-link cycle terminates, and every key it returns is
366-
* canonicalized through canonicalDirKey.
390+
* The walk is bounded, and a chain the bound cannot resolve rejects rather than naming
391+
* an arbitrary intermediate link: two writers that enter the same chain from different
392+
* ends would otherwise key one file with two different locks. Every key it does return
393+
* is canonicalized through canonicalDirKey.
367394
*/
368395
export async function resolveLockKey(absoluteFilePath: string): Promise<string> {
369396
try {
@@ -376,16 +403,37 @@ export async function resolveLockKey(absoluteFilePath: string): Promise<string>
376403
if (errorCode(error) !== "ENOENT") {
377404
throw error
378405
}
379-
// A real readlink throws for anything that is not a link, so a normal chain
380-
// ends the walk. Two links that point at each other never would, so the
381-
// walk is bounded and callers use the key they actually reached.
406+
// A real readlink reports "this is not a link" by throwing: EINVAL on the
407+
// platforms this file runs on (measured with node 22.23.4 on win32, and EINVAL
408+
// on linux), and ENOENT when the path itself is gone. Those two answers end the
409+
// walk. Any other failure - EACCES, EIO, ELOOP - says nothing about whether this
410+
// path is a link, so it propagates: keying this writer to the alias while a
411+
// writer that reached the referent keys the referent is the two-locks-for-one-file
412+
// loss this function exists to prevent, and guessing it is how that loss arrives.
413+
const linkWalkLimit = 8
382414
let key = absoluteFilePath
383-
for (let depth = 0; depth < 8; depth++) {
384-
const target = await fs.readlink(key).catch(() => undefined)
415+
for (let depth = 0; depth < linkWalkLimit; depth++) {
416+
const target = await fs.readlink(key).catch((linkError: unknown) => {
417+
const code = errorCode(linkError)
418+
if (code === "ENOENT" || code === "EINVAL") return undefined
419+
throw linkError
420+
})
385421
if (target === undefined) return await canonicalDirKey(key)
386-
key = await canonicalDirKey(path.resolve(path.dirname(key), target))
422+
// A relative referent is relative to the link's REAL parent, not to the spelling the
423+
// caller arrived with: under a symlinked directory `..` names the referent's parent,
424+
// so a lexical join keys a different file and the writer through the alias stops
425+
// excluding the writer through the referent. When the link's own parent cannot be
426+
// canonicalized - a dangling chain - the lexical join is the only answer available.
427+
const referentParent = path.isAbsolute(target)
428+
? undefined
429+
: await fs.realpath(path.dirname(key)).catch(() => undefined)
430+
key = await canonicalDirKey(path.resolve(referentParent ?? path.dirname(key), target))
387431
}
388-
return await canonicalDirKey(key)
432+
// The bound only exists to terminate a cycle. Past it the chain names no file, so
433+
// the caller is told instead of handed whichever link the walk stopped on.
434+
throw new Error(
435+
`safeWriteText: could not resolve a lock key for ${absoluteFilePath}: the symlink chain is deeper than ${linkWalkLimit} links`,
436+
)
389437
}
390438
}
391439

@@ -531,6 +579,15 @@ export async function safeWriteText(
531579

532580
let backupPath: string | null = null
533581
let releaseBackupOnSuccess = false
582+
// Identity of the staged file as this write last held it open, captured from the descriptor
583+
// that was fsynced. The commit rename below takes a NAME, and between the fsync (which
584+
// releases the descriptor) and that rename a process that can write the staging directory can
585+
// move this write's file aside and put another file at the same name; the rename would then
586+
// publish content this write never wrote and never flushed.
587+
let stagedIdentity: fsSync.BigIntStats | null = null
588+
// Set when the pre-commit comparison finds a different file at the staging name: the name no
589+
// longer belongs to this write, so the failure cleanup must not unlink somebody else's file.
590+
let stagedPathIsForeign = false
534591
// Non-null only when the win32 step-2 block saved a successful DACL dump:
535592
// it gates the step-5 restore and is tracked for the cleanup unlinks.
536593
let daclDumpPath: string | null = null
@@ -599,6 +656,7 @@ export async function safeWriteText(
599656
offset += fsSync.writeSync(fd, buffer, offset, buffer.length - offset)
600657
}
601658
_fsyncFile(fd)
659+
stagedIdentity = fsSync.fstatSync(fd, { bigint: true })
602660
} finally {
603661
fsSync.closeSync(fd)
604662
}
@@ -637,6 +695,7 @@ export async function safeWriteText(
637695
fsSync.fchmodSync(fd, targetMode)
638696
}
639697
_fsyncFile(fd)
698+
stagedIdentity = fsSync.fstatSync(fd, { bigint: true })
640699
} finally {
641700
fsSync.closeSync(fd)
642701
}
@@ -805,6 +864,42 @@ export async function safeWriteText(
805864
)
806865
}
807866

867+
// The staging path is a name, not the file. Everything above released the descriptor,
868+
// and a process that can write the staging directory has had the whole window since the
869+
// fsync to move this write's file aside and name another file after it. The rename below
870+
// follows the name, so compare the name against the descriptor this write fsynced and
871+
// refuse rather than publish bytes that were never flushed here. A move preserves dev+ino,
872+
// and a hard link leaves nlink above 1, so both are caught the same way the open above is.
873+
if (stagedIdentity) {
874+
const nowStaged = await fs.lstat(tempPath, { bigint: true }).catch((error: unknown) => {
875+
if (errorCode(error) === "ENOENT") {
876+
throw new StagingPathError(
877+
`Staging file disappeared before the commit rename: ${tempPath}`,
878+
tempPath,
879+
)
880+
}
881+
throw error
882+
})
883+
if (
884+
typeof nowStaged.ino === "bigint" &&
885+
typeof stagedIdentity.ino === "bigint" &&
886+
(!nowStaged.isFile() ||
887+
nowStaged.ino !== stagedIdentity.ino ||
888+
nowStaged.dev !== stagedIdentity.dev ||
889+
// bigint against bigint: lstat with { bigint: true } reports nlink as a bigint,
890+
// so comparing it with the number 1 would never be equal.
891+
nowStaged.nlink !== 1n)
892+
) {
893+
// The name now belongs to a different file: unlinking it here would delete the
894+
// file that took its place, which this write has no claim on.
895+
stagedPathIsForeign = true
896+
throw new StagingPathError(
897+
`Staging file changed between the fsync and the commit rename: ${tempPath}`,
898+
tempPath,
899+
)
900+
}
901+
}
902+
808903
await fs.rename(tempPath, targetPath)
809904
committed = true
810905

@@ -939,7 +1034,10 @@ export async function safeWriteText(
9391034
// Only a write that never committed has a staged file to remove. After the commit
9401035
// rename there is nothing at tempPath but the published target, and unlinking it here
9411036
// would un-commit the write the caller is being told about.
942-
if (!committed) {
1037+
// The pre-commit comparison above found a foreign file at the staging name: this write's own
1038+
// file is gone from that name, and removing what took its place would destroy a file the
1039+
// caller never handed over.
1040+
if (!committed && !stagedPathIsForeign) {
9431041
let cleanupError: unknown = null
9441042
for (let attempt = 0; attempt < 2; attempt++) {
9451043
try {

0 commit comments

Comments
 (0)