Skip to content

Commit 7ea7080

Browse files
fix(file-safety, utils): give each write its own staging name, and stage exclusively at the target's mode
Three shapes in this unit's own delta, each measured against 90bbdad before and after. safeWriteText staged into a fixed directory name, .file-safety-staging, under a path the workspace controls. Two self-staged writes to one file therefore shared one staging place, and an entry left there by a crashed or interrupted writer became a permanent blocker for every later write to that file: mkdirSync could not create it, and the recovery unlink - non-recursive - could not remove a non-empty directory. The staging directory now carries this call's generated name (.file-safety-staging_<ts>_<rand>), the same shape safeWriteJson already uses for its staging file, so cleanup can only ever reach this write's own directory. A caller-supplied tempPath is untouched: that path is the caller's by contract, and the two comments that claimed the fixed name was safe are rewritten to say what the code now guarantees. safeWriteJson streamed the staged payload through fsSync.createWriteStream(targetPath, { encoding }) - an ordinary create-or-truncate open of a generated path inside a directory the workspace controls. It is now opened with openSync(targetPath, "wx", stageMode), where stageMode is the mode of the file being replaced (0o644 when there is no target yet), plus a best-effort fchmodSync so a 0o664 or 0o666 target is not staged as 0o644 under the common umask 022 and lose group write through the commit rename. The descriptor is handed to the write stream, which owns closing it. This is the rule safeWriteText already follows (openSync(tempPath, "w", targetMode) + fchmodSync, at safeWriteText.ts:264-286), and 85 call sites sit behind this writer (McpHub, TaskHistoryStore, caches, FileContextTracker), so target-mode preservation - not a blanket 0o600 - is what can be applied without silently republishing every cached JSON with a new mode. Tests. safeWriteText.spec.ts gains a describe with 3 rows (generated name shape, one directory per concurrent write, caller-supplied tempPath left at the caller's name). safeWriteJson.test.ts gains 4 rows: refusal when the generated staging path is already occupied, mode inheritance from the target, 0o644 default for a fresh target, and a real-link row - junction on win32, directory symlink elsewhere, with a capability probe that records EPERM/ENOSYS/ENOTSUP/EOPNOTSUPP instead of asserting a resolution it never built - which pins the lock on the referent of an operating-system alias rather than a mocked realpath. The backup-deletion row is retitled to what it actually measures and now asserts the committed content, the orphaned backup, and that no staging file was left behind; the comment naming the deliberately-absent guarded-write titles is rewritten to name both json-layer rows and to record that the rollback row is inherited from upstream main, not new here. Red-first then controls, all on pinned node v22.23.4 (.tmp-node22; box node v25.9.0 unused), from the worktree's own junction install: - safeWriteText lane, head baseline 45 passed (45); new rows against unmodified production 3 failed / 45 passed (48); with the fix 48 passed (48). Negative control - staging name swapped back to the fixed name - exits 1 with exactly those 3 rows failing and nothing else; file restored byte-identical (18223 B, sha256 ddd301ba1e7e9b97...) and re-run 48/48. - safeWriteJson lane, head baseline 62 passed (62), 0 skipped (the PR body's "38 passed, 1 skipped" is stale at this head); new rows against unmodified production 3 failed / 63 passed (66); with the fix 66 passed (66). Control A (production helper reverted to the head blob) fails exactly those 3 staging rows. Control B (make the backup-delete catch re-throw) fails 4 rows including the retitled backup-deletion row. Control C (lock keyed on the caller-named path) fails 3 rows including the real-link row. Each control restored byte-identical (safeWriteJson.ts sha256 ffd1d2aa208eb534...). - guardedWrite lane: 1 new row, and its control is the point. PR Zoo-Code-Org#2359 carries an open CodeRabbit row (PRRT_kwDOSK-bwM61HM7S) about a reserved chain promise left unhandled for an event-loop turn; this unit has no reserved promise (enqueue composes with prev.then(fn, fn), guardedWrite.ts:87), so the row pins that and the control injects the reported shape - a rejection with no handler for one macrotask - into the cancellation throw: 1 failed / 40 passed (41), the recorded reason exactly the injected error, and only that row fails. Restored byte-identical (16431 B, sha256 8cda11b309fffff9...) and re-run 41/41. CodeRabbit rows triaged against this head rather than carried over: safeWriteJson.test.ts:829 and :984 are answered by the two retitled/extended rows; safeWriteJson.ts:72 is answered by the wx + target-mode staging above; safeWriteJson.ts:271 (importExport export-failure surfacing) and safeWriteJson.ts:225 (which path the lock key takes) stay open - importExport.ts:350-353 still swallows the export failure for the UI to render and no settings_export* key exists in any of the 18 locale directories, and the lock-key choice is an owner-level contract question with the four other copies of this writer. Gates (worktree wt-s3-1405, node v22.23.4): prettier --check on all five touched files exit 0; tsc --noEmit -p tsconfig.json exit 0 with 0 error lines, sensitivity control (one deliberate type error in src) returns exit 2 with the error and back to 0 on removal; eslint --max-warnings=0 on the five changed files exit 0 with 0 messages each, and the same run over all of src reports 1169 files 0 messages; src/eslint-suppressions.json unchanged in this commit (30910 B, 265 files / 265 rule-entries / 2869 counts, against merge base 73931fe 265 / 265 / 2870), and none of the five files has an entry at the merge base or now, so no count rises.
1 parent 90bbdad commit 7ea7080

5 files changed

Lines changed: 369 additions & 28 deletions

File tree

‎src/core/tools/__tests__/guardedWrite.spec.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,57 @@ describe("guardedWrite (S4a, epic #1375)", () => {
512512
})
513513
})
514514

515+
// The 2359 lane carries an open CodeRabbit row (PRRT_kwDOSK-bwM61HM7S, guardedWrite.ts:163 at
516+
// 4e1c51c31c) about a reserved chain promise that stays unattached for an event-loop turn, so
517+
// Node can report an unhandled rejection even though the caller handles the write's promise.
518+
// This unit has no reserved promise to leave unattached: enqueue composes with prev.then(fn, fn)
519+
// (src/core/tools/guardedWrite.ts:87) and returns the same link its own bookkeeping handlers
520+
// are attached to. Measured rather than asserted - a real cancellation rejection queued behind
521+
// a gated link, a real macrotask flush, and the process's own unhandled-rejection signal.
522+
it("reports no unhandled rejection for a queued write that rejects behind a pending one", async () => {
523+
const unhandled: unknown[] = []
524+
const onUnhandledRejection = (reason: unknown): void => {
525+
unhandled.push(reason)
526+
}
527+
let releaseFirst: () => void = () => {}
528+
process.on("unhandledRejection", onUnhandledRejection)
529+
try {
530+
const firstGate = new Promise<void>(function (resolve) {
531+
releaseFirst = resolve
532+
})
533+
mockedSafeWriteText.mockImplementationOnce(async () => {
534+
await firstGate
535+
})
536+
// The target is absent, the only state an unobserved "create" may publish into: both
537+
// links' entry probes report ENOENT, so the first reaches the gated publish and the
538+
// second stays queued behind it.
539+
mockedFsAccess.mockRejectedValue(
540+
Object.assign(new Error("ENOENT: no such file or directory, access"), { code: "ENOENT" }),
541+
)
542+
const task = createMockTask()
543+
const first = guardedWrite(task, "unhandled.txt", "first", "create")
544+
const second = guardedWrite(task, "unhandled.txt", "second", "create")
545+
await new Promise(function (resolve) {
546+
setImmediate(resolve)
547+
})
548+
// The second link is still queued behind the gated first one when the task goes away.
549+
task.abort = true
550+
releaseFirst()
551+
await first
552+
await expect(second).rejects.toThrow(/was cancelled/)
553+
// Node decides unhandledness once the microtask queue drains, so one macrotask turn is
554+
// long enough for a rejection nobody attached a handler to in time to be reported.
555+
await new Promise(function (resolve) {
556+
setImmediate(resolve)
557+
})
558+
} finally {
559+
releaseFirst()
560+
process.off("unhandledRejection", onUnhandledRejection)
561+
}
562+
563+
expect(unhandled).toEqual([])
564+
})
565+
515566
it("a write submitted after an earlier one settled still serializes in submission order", async () => {
516567
const reg = new ObservationRegistry()
517568
reg.observe(abs("evict.txt"), "v1")

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,72 @@ describe("safeWriteText", () => {
189189
})
190190
})
191191

192+
// The staging directory's name is the chain's single shape for this directory (tracking issue 1991
193+
// section 6): it is generated per write, the way the temp file inside it is generated, so no path the
194+
// user's workspace already controls can become the directory this primitive mkdirs, chmods and rmdirs.
195+
describe("per-write staging directory name", () => {
196+
// The generated shape: the fixed prefix plus the same Date.now + random suffix the temp file gets,
197+
// end-anchored so a suffix-less or hand-named path fails.
198+
const _isPerWriteStagingName = (name: string): boolean => /^\.file-safety-staging_\d+_[a-z0-9]+$/.test(name)
199+
200+
it("names the staging directory of the generated shape", async () => {
201+
const targetPath = "/tmp/test-dir/target.txt"
202+
vi.mocked(fsSync.openSync).mockReturnValue(1)
203+
204+
await safeWriteText(targetPath, "hello", { targetPathIsResolved: true, platform: "linux" })
205+
206+
const staged = vi.mocked(fsSync.mkdirSync).mock.calls.map((call) => String(call[0]))
207+
expect(staged).toHaveLength(1)
208+
expect(_isPerWriteStagingName(path.basename(staged[0]))).toBe(true)
209+
// Staged beside the directory the publish targets, not somewhere else.
210+
expect(path.resolve(path.dirname(staged[0]))).toBe(path.resolve(_dirPath(targetPath)))
211+
})
212+
213+
it("gives each self-staged write its own staging directory", async () => {
214+
const dir = "/tmp/test-dir"
215+
const targetA = path.join(dir, "target-a.txt")
216+
const targetB = path.join(dir, "target-b.txt")
217+
vi.mocked(fsSync.openSync).mockReturnValue(1)
218+
219+
await Promise.all([
220+
safeWriteText(targetA, "A", { targetPathIsResolved: true, platform: "linux" }),
221+
safeWriteText(targetB, "B", { targetPathIsResolved: true, platform: "linux" }),
222+
])
223+
224+
// Two writes into one directory must not stage into one shared directory: with a shared name
225+
// each write's cleanup rmdir runs while the other write still has a temp open in it, so a
226+
// release either fails or removes a directory another write is about to publish from.
227+
const staged = vi.mocked(fsSync.mkdirSync).mock.calls.map((call) => String(call[0]))
228+
expect(staged).toHaveLength(2)
229+
expect(new Set(staged).size).toBe(2)
230+
for (const stagedDir of staged) {
231+
expect(_isPerWriteStagingName(path.basename(stagedDir))).toBe(true)
232+
}
233+
})
234+
235+
it("leaves a path the workspace controls at the fixed shared name untouched", async () => {
236+
const targetPath = "/tmp/test-dir/target.txt"
237+
// The name the shared-name shape mkdir-ed, chmod-ed and rmdir-ed. A workspace can commit a
238+
// symlink or a directory at exactly this path, and mkdirSync with recursive:true accepts the
239+
// existing entry without creating anything, so the chmod would repair a directory outside the
240+
// target directory and the staged file would land in it.
241+
const sharedName = path.basename(_stagingDir(_dirPath(targetPath)))
242+
vi.mocked(fsSync.openSync).mockReturnValue(1)
243+
244+
await safeWriteText(targetPath, "hello", { targetPathIsResolved: true, platform: "linux" })
245+
246+
const mkdirNames = vi.mocked(fsSync.mkdirSync).mock.calls.map((call) => path.basename(String(call[0])))
247+
expect(mkdirNames).not.toContain(sharedName)
248+
const chmodNames = vi
249+
.mocked(fsSync.chmodSync)
250+
.mock.calls.filter((call) => call[1] === 0o700)
251+
.map((call) => path.basename(String(call[0])))
252+
expect(chmodNames).not.toContain(sharedName)
253+
const rmdirNames = vi.mocked(fsSync.rmdirSync).mock.calls.map((call) => path.basename(String(call[0])))
254+
expect(rmdirNames).not.toContain(sharedName)
255+
})
256+
})
257+
192258
// ── Test 2: fsync ordering ───────────────────────────────────────────────
193259

194260
describe("fsync ordering", () => {

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

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,21 @@ function _tempName(dir: string, prefix: string): string {
6969
return path.join(dir, "." + prefix + "_" + Date.now() + "_" + Math.random().toString(36).substring(2) + ".tmp")
7070
}
7171

72-
/** Create a private staging sub-directory inside *dir* so that multiple
73-
* concurrent writes never collide on their temp names. */
72+
/** Create a private per-write staging sub-directory inside *dir*. The name is
73+
* generated here, the way the temp file inside it is named, so concurrent writes
74+
* never collide on their temp names and never share a directory whose release one
75+
* write would have to decide about while another write is still staging in it. */
7476
function _stagingDir(dir: string): string {
75-
const sd = path.join(dir, ".file-safety-staging")
77+
// A shared fixed name is a path the workspace controls: mkdirSync with
78+
// recursive:true accepts an existing entry of that name without creating
79+
// anything, so a committed .file-safety-staging symlink would have the chmod
80+
// below repair the permissions of a directory outside the target directory and
81+
// put the staged file in it. A name this call generated cannot be pre-planted.
82+
const sd = path.join(dir, ".file-safety-staging_" + Date.now() + "_" + Math.random().toString(36).substring(2))
7683
// mode:0o700 protects a freshly created staging dir; the best-effort chmod
77-
// repairs a pre-existing one (mkdirSync with recursive:true never chmods an
78-
// existing directory), so staged temp files are never group/world readable.
84+
// covers the case where an entry already sits at the generated name (mkdirSync
85+
// with recursive:true never chmods an existing directory), so staged temp files
86+
// are never group/world readable.
7987
fsSync.mkdirSync(sd, { recursive: true, mode: 0o700 })
8088
try {
8189
fsSync.chmodSync(sd, 0o700)
@@ -86,16 +94,17 @@ function _stagingDir(dir: string): string {
8694
return sd
8795
}
8896

89-
/** Remove the staging sub-directory when nothing is staged in it any more.
90-
* rmdirSync fails on a non-empty directory (a concurrent write is still using it)
91-
* and on a directory that is already gone, so the last write to finish cleans up
92-
* and the others leave it to that writer - no shared bookkeeping is needed, and a
93-
* persistent hidden directory is never left in the user's workspace. */
97+
/** Remove this write's staging sub-directory when nothing is staged in it any
98+
* more. rmdirSync fails on a non-empty directory (this write's temp unlink did not
99+
* land) and on a directory that is already gone; both are tolerated. The name is
100+
* this call's, so the rmdir never has to decide about a directory another write is
101+
* still staging in, and a persistent hidden directory is never left in the user's
102+
* workspace. */
94103
function _removeStagingDirIfEmpty(dir: string): void {
95104
try {
96105
fsSync.rmdirSync(dir)
97106
} catch {
98-
// non-empty (a concurrent write is still staging there) or already removed
107+
// non-empty (the temp unlink did not land) or already removed
99108
}
100109
}
101110

@@ -233,7 +242,8 @@ export async function safeWriteText(filePath: string, content: string, options?:
233242

234243
// Create the staging directory only when we generate the temp file there;
235244
// callers supplying their own tempPath (e.g. safeWriteJson) must not be left
236-
// with an empty .file-safety-staging directory behind.
245+
// with an empty staging directory behind, and a directory named here is this
246+
// call's own, never a path the workspace already controls.
237247
let stagingDirPath: string | null = null
238248
let tempPath: string
239249
if (options?.tempPath) {
@@ -399,8 +409,8 @@ export async function safeWriteText(filePath: string, content: string, options?:
399409
}
400410
}
401411

402-
// tempPath is now the committed file; no cleanup needed. Remove the staging
403-
// directory when this write was the last one using it.
412+
// tempPath is now the committed file; no cleanup needed. The staging directory
413+
// carries this call's generated name, so removing it cannot reach another write.
404414
if (stagingDirPath !== null) {
405415
_removeStagingDirIfEmpty(stagingDirPath)
406416
}
@@ -426,8 +436,9 @@ export async function safeWriteText(filePath: string, content: string, options?:
426436
// cleanup failure is non-fatal
427437
}
428438

429-
// The temp is gone, so the staging directory is ours to remove when no other
430-
// write is staging in it; a non-empty rmdir leaves it for that writer.
439+
// The temp is gone, so this write's staging directory is empty and can go. A
440+
// non-empty rmdir means the unlink above did not land; the directory is this
441+
// call's own, so a concurrent write never loses its staging place here.
431442
if (stagingDirPath !== null) {
432443
_removeStagingDirIfEmpty(stagingDirPath)
433444
}

0 commit comments

Comments
 (0)