Skip to content

Commit 312713d

Browse files
author
Zoo (VP)
committed
fix(b08): atomic write safety, type fixes, rebase onto main
1 parent 2644a0b commit 312713d

4 files changed

Lines changed: 110 additions & 226 deletions

File tree

‎src/core/task-persistence/TaskOrganizationStore.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -840,12 +840,18 @@ export class TaskOrganizationStore {
840840
}
841841

842842
this.getTasksDir()
843-
.then((tasksDir) => {
843+
.then(async (tasksDir) => {
844844
if (this.disposed) {
845845
return
846846
}
847847

848848
try {
849+
// Ensure the tasks directory exists before watching it.
850+
// fs.watch throws ENOENT when the watched path does not
851+
// exist, which happens on first run before any task is
852+
// persisted.
853+
await fs.mkdir(tasksDir, { recursive: true })
854+
849855
this.fsWatcher = fsSync.watch(tasksDir, { recursive: false }, (_eventType, filename) => {
850856
if (this.disposed) {
851857
return

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

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ describe("safeUpdateJson", () => {
8888
test("creates a new file when allowCreate is true and the file does not exist", async () => {
8989
const updated = await safeUpdateJson(
9090
currentTestFilePath,
91-
(current) => ({ ...(current ?? {}), created: true }),
91+
(current: { created?: boolean } | undefined) => ({ ...(current ?? {}), created: true }),
9292
{ allowCreate: true },
9393
)
9494

@@ -99,7 +99,7 @@ describe("safeUpdateJson", () => {
9999

100100
test("throws when the file does not exist and allowCreate is false", async () => {
101101
await expect(
102-
safeUpdateJson(currentTestFilePath, (current) => ({ ...(current ?? {}), nope: true })),
102+
safeUpdateJson(currentTestFilePath, (current: { nope?: boolean } | undefined) => ({ ...(current ?? {}), nope: true })),
103103
).rejects.toThrow("safeUpdateJson: file does not exist and allowCreate is false")
104104

105105
// The file must not have been created.
@@ -109,10 +109,13 @@ describe("safeUpdateJson", () => {
109109
test("reads the current content and writes the updater result back", async () => {
110110
await fs.writeFile(currentTestFilePath, JSON.stringify({ counter: 1 }))
111111

112-
const updated = await safeUpdateJson(currentTestFilePath, (current) => ({
113-
...current,
114-
counter: (current?.counter ?? 0) + 1,
115-
}))
112+
const updated = await safeUpdateJson(
113+
currentTestFilePath,
114+
(current: { counter: number } | undefined) => ({
115+
...current,
116+
counter: (current?.counter ?? 0) + 1,
117+
}),
118+
)
116119

117120
expect(updated).toEqual({ counter: 2 })
118121
const content = await readFileContent(currentTestFilePath)
@@ -122,7 +125,11 @@ describe("safeUpdateJson", () => {
122125
test("supports prettyPrint output", async () => {
123126
await fs.writeFile(currentTestFilePath, JSON.stringify({ a: 1 }))
124127

125-
await safeUpdateJson(currentTestFilePath, (current) => ({ ...current, b: 2 }), { prettyPrint: true })
128+
await safeUpdateJson(
129+
currentTestFilePath,
130+
(current: { a?: number; b?: number } | undefined) => ({ ...current, b: 2 }),
131+
{ prettyPrint: true },
132+
)
126133

127134
const raw = await fs.readFile(currentTestFilePath, "utf8")
128135
expect(raw).toContain("\n\t")
@@ -132,7 +139,11 @@ describe("safeUpdateJson", () => {
132139
test("creates parent directories when they do not exist", async () => {
133140
const deepPath = path.join(tempDir, "level1", "level2", "deep.json")
134141

135-
await safeUpdateJson(deepPath, (current) => ({ ...(current ?? {}), deep: true }), { allowCreate: true })
142+
await safeUpdateJson(
143+
deepPath,
144+
(current: { deep?: boolean } | undefined) => ({ ...(current ?? {}), deep: true }),
145+
{ allowCreate: true },
146+
)
136147

137148
expect(await readFileContent(deepPath)).toEqual({ deep: true })
138149
})
@@ -165,32 +176,23 @@ describe("safeUpdateJson", () => {
165176

166177
// ────────────────────────────── Failure & rollback scenarios ──────────────────────────────
167178

168-
test("rolls back to the original file when the final rename fails", async () => {
179+
test("leaves the original file unchanged when the final rename fails", async () => {
169180
const initialData = { message: "Initial content, should be restored" }
170181
await fs.writeFile(currentTestFilePath, JSON.stringify(initialData))
171182

172183
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
173-
let renameCallCount = 0
174-
vi.mocked(fs.rename).mockImplementation(async (oldPath, newPath) => {
175-
renameCallCount++
176-
if (renameCallCount === 1) {
177-
// First call: filePath -> tempBackupFilePath (should succeed)
178-
return fsPromisesActuals.rename!(oldPath, newPath)
179-
} else if (renameCallCount === 2) {
180-
// Second call: tempNewFilePath -> filePath (should fail)
181-
throw new Error("Rename from temp to final failed")
182-
} else if (renameCallCount === 3) {
183-
// Third call: tempBackupFilePath -> filePath (rollback, should succeed)
184-
return fsPromisesActuals.rename!(oldPath, newPath)
185-
}
186-
return fsPromisesActuals.rename!(oldPath, newPath)
184+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
185+
throw new Error("Rename from temp to final failed")
187186
})
188187

189188
await expect(
190-
safeUpdateJson(currentTestFilePath, (current) => ({ ...current, changed: true })),
189+
safeUpdateJson(
190+
currentTestFilePath,
191+
(current: { message?: string; changed?: boolean } | undefined) => ({ ...current, changed: true }),
192+
),
191193
).rejects.toThrow("Rename from temp to final failed")
192194

193-
// The file was restored to its initial content.
195+
// The file was never moved, so its initial content is intact.
194196
expect(await readFileContent(currentTestFilePath)).toEqual(initialData)
195197
})
196198

@@ -213,13 +215,19 @@ describe("safeUpdateJson", () => {
213215
vi.mocked(fsSyncActual.createWriteStream).mockImplementationOnce((_path, _options) => errorStream)
214216

215217
await expect(
216-
safeUpdateJson(currentTestFilePath, (current) => ({ ...current, changed: true })),
218+
safeUpdateJson(
219+
currentTestFilePath,
220+
(current: { initial?: string; changed?: boolean } | undefined) => ({ ...current, changed: true }),
221+
),
217222
).rejects.toThrow("Stream write error")
218223

219224
// If the lock wasn't released, this second attempt would fail with a lock error.
220225
// Instead, it should succeed (proving the lock was released).
221226
await expect(
222-
safeUpdateJson(currentTestFilePath, (current) => ({ ...current, second: true })),
227+
safeUpdateJson(
228+
currentTestFilePath,
229+
(current: { initial?: string; second?: boolean } | undefined) => ({ ...current, second: true }),
230+
),
223231
).resolves.toEqual({ initial: "content", second: true })
224232
})
225233

@@ -238,7 +246,7 @@ describe("safeUpdateJson", () => {
238246
const { safeUpdateJson: mockedSafeUpdateJson } = await import("../safeWriteJson")
239247

240248
await expect(
241-
mockedSafeUpdateJson(lockTestFilePath, (current) => ({ ...(current ?? {}), changed: true })),
249+
mockedSafeUpdateJson(lockTestFilePath, (current: { changed?: boolean } | undefined) => ({ ...(current ?? {}), changed: true })),
242250
).rejects.toThrow("Failed to get lock.")
243251

244252
// Clean up

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

Lines changed: 47 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ describe("safeWriteJson", () => {
158158
expect(content).toEqual({ initial: "content" })
159159
})
160160

161-
test("should handle failure when renaming filePath to tempBackupFilePath (filePath exists)", async () => {
161+
test("should handle failure when renaming the temp file to the target (filePath exists)", async () => {
162162
const initialData = { message: "Initial content, should remain" }
163163
const newData = { message: "New content, should not be written" }
164164

@@ -167,46 +167,31 @@ describe("safeWriteJson", () => {
167167

168168
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
169169
vi.mocked(fs.rename).mockImplementationOnce(async () => {
170-
throw new Error("Rename to backup failed")
170+
throw new Error("Rename to final failed")
171171
})
172172

173-
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename to backup failed")
173+
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename to final failed")
174174

175-
// Verify the original file still exists with initial content
175+
// The atomic rename never happened, so the original file is untouched.
176176
const content = await readFileContent(currentTestFilePath)
177177
expect(content).toEqual(initialData)
178178
})
179179

180-
test("should handle failure when renaming tempNewFilePath to filePath (filePath exists, backup succeeded)", async () => {
180+
test("should leave the original file unchanged when the atomic rename fails", async () => {
181181
const initialData = { message: "Initial content, should be restored" }
182182
const newData = { message: "New content" }
183183

184184
// Overwrite the pre-created file with specific initial data
185185
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify(initialData))
186186

187-
// Track rename calls
188-
let renameCallCount = 0
189-
190187
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
191-
vi.mocked(fs.rename).mockImplementation(async (oldPath, newPath) => {
192-
renameCallCount++
193-
if (renameCallCount === 1) {
194-
// First call: filePath -> tempBackupFilePath (should succeed)
195-
return fsPromisesActuals.rename!(oldPath, newPath)
196-
} else if (renameCallCount === 2) {
197-
// Second call: tempNewFilePath -> filePath (should fail)
198-
throw new Error("Rename from temp to final failed")
199-
} else if (renameCallCount === 3) {
200-
// Third call: tempBackupFilePath -> filePath (rollback, should succeed)
201-
return fsPromisesActuals.rename!(oldPath, newPath)
202-
}
203-
// Default: use original implementation
204-
return fsPromisesActuals.rename!(oldPath, newPath)
188+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
189+
throw new Error("Rename from temp to final failed")
205190
})
206191

207192
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename from temp to final failed")
208193

209-
// Verify the file was restored to initial content
194+
// The file was never moved, so its initial content is intact.
210195
const content = await readFileContent(currentTestFilePath)
211196
expect(content).toEqual(initialData)
212197
})
@@ -292,28 +277,28 @@ describe("safeWriteJson", () => {
292277
expect(content).toEqual(data)
293278
})
294279

295-
test("should handle failure when deleting tempBackupFilePath (filePath exists, all renames succeed)", async () => {
280+
test("should clean up the temp file when the atomic rename fails", async () => {
296281
const initialData = { message: "Initial content" }
297-
const newData = { message: "Successfully written new content" }
282+
const newData = { message: "New content" }
298283

299284
// Overwrite the pre-created file with specific initial data
300285
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify(initialData))
301286

302-
// fs.unlink is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
303-
vi.mocked(fs.unlink).mockImplementationOnce(async () => {
304-
throw new Error("Failed to delete backup file")
287+
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
288+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
289+
throw new Error("Rename from temp to final failed")
305290
})
306291

307-
// The write should succeed even if backup deletion fails
308-
await safeWriteJson(currentTestFilePath, newData)
292+
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename from temp to final failed")
309293

310-
// Verify the new content was written successfully
311-
const content = await readFileContent(currentTestFilePath)
312-
expect(content).toEqual(newData)
294+
// The temp file must be cleaned up and the original file left intact.
295+
const dirEntries = await fs.readdir(tempDir)
296+
expect(dirEntries.filter((entry) => entry.includes(".new_"))).toHaveLength(0)
297+
expect(await readFileContent(currentTestFilePath)).toEqual(initialData)
313298
})
314299

315-
// Test for console error suppression during backup deletion
316-
test("should suppress console.error when backup deletion fails", async () => {
300+
// Test for console error suppression during temp file cleanup
301+
test("should suppress console.error when temp file cleanup fails", async () => {
317302
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) // Suppress console.error
318303
const initialData = { message: "Initial" }
319304
const newData = { message: "New" }
@@ -322,44 +307,41 @@ describe("safeWriteJson", () => {
322307

323308
// fs.unlink is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
324309
vi.mocked(fs.unlink).mockImplementation(async (filePath: any) => {
325-
if (filePath.toString().includes(".bak_")) {
326-
throw new Error("Backup deletion failed")
310+
if (filePath.toString().includes(".new_")) {
311+
throw new Error("Temp file cleanup failed")
327312
}
328313
return fsPromisesActuals.unlink!(filePath)
329314
})
330315

331-
await safeWriteJson(currentTestFilePath, newData)
316+
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
317+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
318+
throw new Error("Rename from temp to final failed")
319+
})
320+
321+
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename from temp to final failed")
332322

333323
// Verify console.error was called with the expected message
334-
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("Successfully wrote"), expect.any(Error))
324+
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to clean up temporary new file"), expect.any(Error))
335325

336326
consoleErrorSpy.mockRestore()
337327
vi.mocked(fs.unlink).mockRestore()
338328
})
339329

340-
// The expected error message might need to change if the mock behaves differently.
341-
test("should handle failure when renaming tempNewFilePath to filePath (filePath initially exists)", async () => {
330+
test("should handle failure when renaming the temp file to the target (filePath initially exists)", async () => {
342331
// currentTestFilePath exists due to beforeEach.
343332
const initialData = { message: "Initial content" }
344333
const newData = { message: "New content" }
345334

346335
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify(initialData))
347336

348337
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
349-
let renameCallCount = 0
350-
vi.mocked(fs.rename).mockImplementation(async (oldPath, newPath) => {
351-
renameCallCount++
352-
if (renameCallCount === 2) {
353-
// Second call: tempNewFilePath -> filePath (should fail)
354-
throw new Error("Rename failed")
355-
}
356-
// For all other calls, use the original implementation
357-
return fsPromisesActuals.rename!(oldPath, newPath)
338+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
339+
throw new Error("Rename failed")
358340
})
359341

360342
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Rename failed")
361343

362-
// The file should be restored to its initial content
344+
// The file was never moved, so its initial content is intact.
363345
const content = await readFileContent(currentTestFilePath)
364346
expect(content).toEqual(initialData)
365347
})
@@ -434,36 +416,32 @@ describe("safeWriteJson", () => {
434416
expect(vi.mocked(fs.access)).toHaveBeenCalled()
435417
})
436418

437-
// Test for rollback failure scenario
438-
test("should log error and re-throw original if rollback fails", async () => {
439-
const initialData = { message: "Initial, should be lost if rollback fails" }
419+
// Test for temp file cleanup failure scenario
420+
test("should log error and re-throw original if temp file cleanup fails", async () => {
421+
const initialData = { message: "Initial, should remain" }
440422
const newData = { message: "New content" }
441423

442424
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify(initialData))
443425

444426
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) // Suppress console.error
445427

446428
// fs.rename is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
447-
let renameCallCount = 0
448-
vi.mocked(fs.rename).mockImplementation(async (oldPath, newPath) => {
449-
renameCallCount++
450-
if (renameCallCount === 2) {
451-
// Second call: tempNewFilePath -> filePath (fail)
452-
throw new Error("Primary rename failed")
453-
} else if (renameCallCount === 3) {
454-
// Third call: tempBackupFilePath -> filePath (rollback, also fail)
455-
throw new Error("Rollback rename failed")
456-
}
457-
return fsPromisesActuals.rename!(oldPath, newPath)
429+
vi.mocked(fs.rename).mockImplementationOnce(async () => {
430+
throw new Error("Primary rename failed")
431+
})
432+
433+
// fs.unlink is already vi.fn() — use vi.mocked to avoid double-wrapping via vi.spyOn
434+
vi.mocked(fs.unlink).mockImplementationOnce(async () => {
435+
throw new Error("Temp cleanup failed")
458436
})
459437

460-
// Should throw the original error, not the rollback error
438+
// Should throw the original error, not the cleanup error
461439
await expect(safeWriteJson(currentTestFilePath, newData)).rejects.toThrow("Primary rename failed")
462440

463-
// Verify console.error was called for the rollback failure
441+
// Verify console.error was called for the cleanup failure
464442
expect(consoleErrorSpy).toHaveBeenCalledWith(
465-
expect.stringContaining("Failed to restore backup"),
466-
expect.objectContaining({ message: "Rollback rename failed" }),
443+
expect.stringContaining("Failed to clean up temporary new file"),
444+
expect.objectContaining({ message: "Temp cleanup failed" }),
467445
)
468446

469447
consoleErrorSpy.mockRestore()

0 commit comments

Comments
 (0)