Skip to content

Commit f5de88a

Browse files
committed
feat(tools): guarded write CAS core with per-path FIFO chain (S4a, #1375)
1 parent 588b95f commit f5de88a

2 files changed

Lines changed: 589 additions & 0 deletions

File tree

Lines changed: 370 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,370 @@
1+
/**
2+
* Tests for the guarded-write compare-and-swap core (upstream epic #1375,
3+
* phase A4a).
4+
*
5+
* Covers guard selection through the S2 observation registry, version-token
6+
* CAS, remediation messages, and the per-absolute-path FIFO chain: FIFO
7+
* ordering, exactly-one winner under concurrency, no wedge after a rejected
8+
* link, and independence across paths.
9+
*/
10+
11+
import * as fs from "fs/promises"
12+
import * as path from "path"
13+
14+
import { describe, expect, it, beforeEach, vi } from "vitest"
15+
16+
import { createIfAbsent, guardedWrite, resetChain } from "../guardedWrite"
17+
import { safeWriteText } from "../../../services/file-safety/safeWriteText"
18+
import { computeVersionToken } from "../../../utils/versionToken"
19+
import { ObservationRegistry } from "../../task/observationRegistry"
20+
import type { Task } from "../../task/Task"
21+
22+
// -- Mocks -------------------------------------------------------------------
23+
24+
vi.mock("fs/promises", () => ({
25+
access: vi.fn(),
26+
stat: vi.fn(),
27+
}))
28+
29+
vi.mock("../../../utils/versionToken", () => ({
30+
computeVersionToken: vi.fn(),
31+
}))
32+
33+
vi.mock("../../../services/file-safety/safeWriteText", () => ({
34+
safeWriteText: vi.fn(),
35+
}))
36+
37+
const mockedFsAccess = vi.mocked(fs.access)
38+
const mockedComputeVersionToken = vi.mocked(computeVersionToken)
39+
const mockedSafeWriteText = vi.mocked(safeWriteText)
40+
41+
// -- Fixtures ----------------------------------------------------------------
42+
43+
const WORKSPACE = "/test/workspace"
44+
45+
/** Resolve a fixture path the same way guardedWrite resolves task.cwd-relative paths. */
46+
const abs = (relPath: string): string => path.resolve(WORKSPACE, relPath)
47+
48+
interface MockTaskOptions {
49+
cwd?: string
50+
observationRegistry?: ObservationRegistry
51+
}
52+
53+
/**
54+
* Minimal structural Task: guardedWrite only reads task.cwd and
55+
* task.observationRegistry. The real Task constructor needs the full provider
56+
* machinery, so a single documented double cast stands in for the class.
57+
*/
58+
function createMockTask(options: MockTaskOptions = {}): Task {
59+
const task = {
60+
cwd: options.cwd ?? WORKSPACE,
61+
observationRegistry: options.observationRegistry ?? new ObservationRegistry(),
62+
}
63+
return task as unknown as Task
64+
}
65+
66+
// -- Tests -------------------------------------------------------------------
67+
68+
describe("guardedWrite (S4a, epic #1375)", () => {
69+
beforeEach(() => {
70+
vi.resetAllMocks()
71+
resetChain()
72+
})
73+
74+
describe("unobserved create", () => {
75+
it("succeeds when the file is absent and publishes via safeWriteText", async () => {
76+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
77+
const task = createMockTask()
78+
79+
await guardedWrite(task, "new-file.txt", "hello", "create")
80+
81+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
82+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello")
83+
})
84+
85+
it("fails with the read-first remediation when the file exists - nothing published", async () => {
86+
mockedFsAccess.mockResolvedValue(undefined)
87+
const task = createMockTask()
88+
89+
await expect(guardedWrite(task, "existing.txt", "hello", "create")).rejects.toThrow(
90+
"File already exists at " +
91+
abs("existing.txt") +
92+
" and was not read before this write -- read the file first, then retry.",
93+
)
94+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
95+
})
96+
97+
it("rethrows I/O errors that are not ENOENT verbatim (no guard verdict on access failure)", async () => {
98+
const failures = [{ code: "EACCES" }, null, "volume offline", new Error("EIO-ish failure")]
99+
for (const failure of failures) {
100+
mockedFsAccess.mockRejectedValueOnce(failure)
101+
await expect(createIfAbsent(abs("io-error.txt"), "x")).rejects.toBe(failure)
102+
}
103+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
104+
})
105+
})
106+
107+
describe("unobserved update", () => {
108+
it("succeeds when the file is absent (same create guard)", async () => {
109+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
110+
const task = createMockTask()
111+
112+
await guardedWrite(task, "new-file.txt", "hello", "update")
113+
114+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("new-file.txt"), "hello")
115+
})
116+
117+
it("fails with the read-first remediation when the file exists - nothing published", async () => {
118+
mockedFsAccess.mockResolvedValue(undefined)
119+
const task = createMockTask()
120+
121+
await expect(guardedWrite(task, "existing.txt", "hello", "update")).rejects.toThrow(
122+
"File already exists at " +
123+
abs("existing.txt") +
124+
" and was not read before this write -- read the file first, then retry.",
125+
)
126+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
127+
})
128+
})
129+
130+
describe("observed create", () => {
131+
it("recreates a file that vanished after the read", async () => {
132+
const reg = new ObservationRegistry()
133+
reg.observe(abs("gone.txt"), "v1")
134+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
135+
const task = createMockTask({ observationRegistry: reg })
136+
137+
await guardedWrite(task, "gone.txt", "back", "create")
138+
139+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
140+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("gone.txt"), "back")
141+
})
142+
143+
it("goes through the version guard when the file still exists", async () => {
144+
const reg = new ObservationRegistry()
145+
reg.observe(abs("kept.txt"), "v1")
146+
mockedFsAccess.mockResolvedValue(undefined)
147+
mockedComputeVersionToken.mockResolvedValue("v1")
148+
const task = createMockTask({ observationRegistry: reg })
149+
150+
await guardedWrite(task, "kept.txt", "rewritten", "create")
151+
152+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("kept.txt"), "rewritten")
153+
})
154+
155+
it("fails with the stale remediation suffix when the version moved", async () => {
156+
const reg = new ObservationRegistry()
157+
reg.observe(abs("kept.txt"), "v1")
158+
mockedFsAccess.mockResolvedValue(undefined)
159+
mockedComputeVersionToken.mockResolvedValue("v2")
160+
const task = createMockTask({ observationRegistry: reg })
161+
162+
await expect(guardedWrite(task, "kept.txt", "rewritten", "create")).rejects.toThrow(
163+
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
164+
)
165+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
166+
})
167+
168+
it("defers to the version guard when the access check is denied (not ENOENT)", async () => {
169+
const reg = new ObservationRegistry()
170+
reg.observe(abs("locked.txt"), "v1")
171+
mockedFsAccess.mockRejectedValue({ code: "EACCES" })
172+
mockedComputeVersionToken.mockResolvedValue("v2")
173+
const task = createMockTask({ observationRegistry: reg })
174+
175+
await expect(guardedWrite(task, "locked.txt", "rewritten", "create")).rejects.toThrow(
176+
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
177+
)
178+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
179+
})
180+
})
181+
182+
describe("observed update (version CAS)", () => {
183+
it("publishes when the on-disk version matches the observation", async () => {
184+
const reg = new ObservationRegistry()
185+
reg.observe(abs("doc.txt"), "v1")
186+
mockedComputeVersionToken.mockResolvedValue("v1")
187+
const task = createMockTask({ observationRegistry: reg })
188+
189+
await guardedWrite(task, "doc.txt", "new content", "update")
190+
191+
expect(mockedComputeVersionToken).toHaveBeenCalledWith(abs("doc.txt"))
192+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "new content")
193+
})
194+
195+
it("fails with the stale remediation suffix when the version moved - nothing published", async () => {
196+
const reg = new ObservationRegistry()
197+
reg.observe(abs("doc.txt"), "v1")
198+
mockedComputeVersionToken.mockResolvedValue("v2")
199+
const task = createMockTask({ observationRegistry: reg })
200+
201+
await expect(guardedWrite(task, "doc.txt", "new content", "update")).rejects.toThrow(
202+
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
203+
)
204+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
205+
})
206+
})
207+
208+
describe("edit", () => {
209+
it("fails read-first when the file was never observed - nothing published, no I/O", async () => {
210+
const task = createMockTask()
211+
212+
await expect(guardedWrite(task, "any.txt", "patched", "edit")).rejects.toThrow(
213+
"File not read yet -- read the file, then retry.",
214+
)
215+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
216+
expect(mockedComputeVersionToken).not.toHaveBeenCalled()
217+
expect(mockedFsAccess).not.toHaveBeenCalled()
218+
})
219+
220+
it("publishes when the version matches the observation", async () => {
221+
const reg = new ObservationRegistry()
222+
reg.observe(abs("doc.txt"), "v1")
223+
mockedComputeVersionToken.mockResolvedValue("v1")
224+
const task = createMockTask({ observationRegistry: reg })
225+
226+
await guardedWrite(task, "doc.txt", "patched", "edit")
227+
228+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("doc.txt"), "patched")
229+
})
230+
231+
it("fails with the stale remediation suffix when the version moved", async () => {
232+
const reg = new ObservationRegistry()
233+
reg.observe(abs("doc.txt"), "v1")
234+
mockedComputeVersionToken.mockResolvedValue("v3")
235+
const task = createMockTask({ observationRegistry: reg })
236+
237+
await expect(guardedWrite(task, "doc.txt", "patched", "edit")).rejects.toThrow(
238+
"Stale version -- the file changed since you read it (expected v1, current v3); re-read the file, then retry.",
239+
)
240+
expect(mockedSafeWriteText).not.toHaveBeenCalled()
241+
})
242+
})
243+
244+
describe("concurrency: per-path FIFO chain", () => {
245+
it("two concurrent updates on one path - exactly one publishes, the other fails stale", async () => {
246+
const reg = new ObservationRegistry()
247+
reg.observe(abs("shared.txt"), "v1")
248+
mockedComputeVersionToken.mockResolvedValue("v1")
249+
const task = createMockTask({ observationRegistry: reg })
250+
251+
// The first publish changes the on-disk state (new token).
252+
mockedSafeWriteText.mockImplementation(async () => {
253+
mockedComputeVersionToken.mockResolvedValue("v2")
254+
})
255+
256+
const p1 = guardedWrite(task, "shared.txt", "first", "update")
257+
const p2 = guardedWrite(task, "shared.txt", "second", "update")
258+
const [r1, r2] = await Promise.allSettled([p1, p2])
259+
260+
if (r1.status !== "fulfilled" || r2.status !== "rejected") {
261+
throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status)
262+
}
263+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
264+
expect(r2.reason.message).toBe(
265+
"Stale version -- the file changed since you read it (expected v1, current v2); re-read the file, then retry.",
266+
)
267+
})
268+
269+
it("observed-absent then two concurrent creates - the second fails stale", async () => {
270+
const reg = new ObservationRegistry()
271+
reg.observe(abs("absent.txt"), "v1") // read before, file later vanished
272+
mockedFsAccess.mockRejectedValue({ code: "ENOENT" })
273+
const task = createMockTask({ observationRegistry: reg })
274+
275+
let publishes = 0
276+
mockedSafeWriteText.mockImplementation(async () => {
277+
publishes += 1
278+
if (publishes === 1) {
279+
// After the first publish the file exists again under a new token.
280+
mockedFsAccess.mockResolvedValue(undefined)
281+
mockedComputeVersionToken.mockResolvedValue("v2")
282+
}
283+
})
284+
285+
const p1 = guardedWrite(task, "absent.txt", "first", "create")
286+
const p2 = guardedWrite(task, "absent.txt", "second", "create")
287+
const [r1, r2] = await Promise.allSettled([p1, p2])
288+
289+
if (r1.status !== "fulfilled" || r2.status !== "rejected") {
290+
throw new Error("expected exactly one publish, got " + r1.status + " / " + r2.status)
291+
}
292+
expect(publishes).toBe(1)
293+
expect(r2.reason.message).toContain("Stale version")
294+
expect(r2.reason.message).toContain("re-read the file, then retry.")
295+
})
296+
297+
it("the chain settles after a rejection - a later matching write still runs", async () => {
298+
const reg = new ObservationRegistry()
299+
reg.observe(abs("settle.txt"), "v1")
300+
mockedComputeVersionToken.mockResolvedValue("v2") // already stale at v1
301+
const task = createMockTask({ observationRegistry: reg })
302+
303+
const p1 = guardedWrite(task, "settle.txt", "first", "update")
304+
await expect(p1).rejects.toThrow("Stale version")
305+
306+
// No resetChain: the rejected link must not wedge the chain. The
307+
// caller re-reads the file (observation refreshed to v2) and retries.
308+
reg.observe(abs("settle.txt"), "v2")
309+
const p2 = guardedWrite(task, "settle.txt", "second", "update")
310+
await expect(p2).resolves.toBeUndefined()
311+
312+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
313+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("settle.txt"), "second")
314+
})
315+
316+
it("writes on different paths are independent (no cross-path serialization)", async () => {
317+
const reg = new ObservationRegistry()
318+
reg.observe(abs("a.txt"), "v1")
319+
reg.observe(abs("b.txt"), "v1")
320+
mockedComputeVersionToken.mockResolvedValue("v1")
321+
const task = createMockTask({ observationRegistry: reg })
322+
323+
const p1 = guardedWrite(task, "a.txt", "a", "update")
324+
const p2 = guardedWrite(task, "b.txt", "b", "update")
325+
await Promise.all([p1, p2])
326+
327+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(2)
328+
})
329+
})
330+
331+
describe("path resolution", () => {
332+
it("resolves a relative path against task.cwd", async () => {
333+
const reg = new ObservationRegistry()
334+
reg.observe(abs("sub/dir.txt"), "v1")
335+
mockedComputeVersionToken.mockResolvedValue("v1")
336+
const task = createMockTask({ observationRegistry: reg })
337+
338+
await guardedWrite(task, "sub/dir.txt", "content", "update")
339+
340+
expect(mockedSafeWriteText).toHaveBeenCalledWith(abs("sub/dir.txt"), "content")
341+
})
342+
343+
it("uses an absolute path as-is", async () => {
344+
const absolute = "/other/path/file.txt"
345+
const reg = new ObservationRegistry()
346+
reg.observe(absolute, "v1")
347+
mockedComputeVersionToken.mockResolvedValue("v1")
348+
const task = createMockTask({ observationRegistry: reg })
349+
350+
await guardedWrite(task, absolute, "content", "update")
351+
352+
expect(mockedSafeWriteText).toHaveBeenCalledWith(absolute, "content")
353+
})
354+
})
355+
356+
describe("resetChain", () => {
357+
it("detaches pending links so later writes start a fresh chain", async () => {
358+
const reg = new ObservationRegistry()
359+
reg.observe(abs("x.txt"), "v1")
360+
mockedComputeVersionToken.mockResolvedValue("v1")
361+
const task = createMockTask({ observationRegistry: reg })
362+
363+
await guardedWrite(task, "x.txt", "a", "update")
364+
resetChain()
365+
await guardedWrite(task, "x.txt", "b", "update")
366+
367+
expect(mockedSafeWriteText).toHaveBeenLastCalledWith(abs("x.txt"), "b")
368+
})
369+
})
370+
})

0 commit comments

Comments
 (0)