Skip to content

Commit 20eee8f

Browse files
test(guardedWrite): pin the verdict a cancel gets while the containment re-check runs
Adds three tests over the cancellation gate at guardedWrite.ts line 690: the abort latch moving during the re-check, the cancellation fence moving during it, and the write nothing cancelled. Each mutant the gate left blocking was hand-substituted against the three guardedWrite specs, 50 tests, and every run printed 50 passed, so these tests record where the verdict lands and how many publishes the path saw, and the row stays a candidate rather than being called a kill.
1 parent f32f7f7 commit 20eee8f

1 file changed

Lines changed: 306 additions & 0 deletions

File tree

Lines changed: 306 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,306 @@
1+
/**
2+
* Post-check cancellation gaps for the guarded-write core (upstream epic #1375).
3+
*
4+
* Every row here aims at a mutant that scripts/stryker-diff.mjs reported as Survived on the
5+
* changed lines of src/core/tools/guardedWrite.ts: the cancellation gate at line 690, which runs
6+
* after the containment re-check and before this write's publish is handed to the chain. The
7+
* dequeue gate inside the publish, line 712, already has rows of its own in
8+
* guardedWriteMutationGaps.spec.ts, and on its own it reports the same verdict with the same
9+
* message. What no row covered is the difference between refusing now and refusing later: a
10+
* refused publish must not take its turn on the path's FIFO chain behind a publish that is live.
11+
*/
12+
13+
import * as fs from "fs/promises"
14+
import type { BigIntStats } from "fs"
15+
import * as path from "path"
16+
17+
import { describe, expect, it, beforeEach, vi } from "vitest"
18+
19+
import { guardedWrite, resetChain, GuardRejectedError } from "../guardedWrite"
20+
import { safeWriteText } from "../../../services/file-safety/safeWriteText"
21+
import { computeVersionToken } from "../../../utils/versionToken"
22+
import { withFileLock } from "../../../utils/fileLock"
23+
import { resolveLockKey } from "../../../services/file-safety/safeWriteText"
24+
import { ObservationRegistry } from "../../task/observationRegistry"
25+
import type { Task } from "../../task/Task"
26+
import { initialRunState } from "../../task/run-state/runState"
27+
import { setAbortLatch } from "../../../test-utils/run-state"
28+
29+
vi.mock("fs/promises", () => ({
30+
access: vi.fn(),
31+
stat: vi.fn(),
32+
realpath: vi.fn(),
33+
lstat: vi.fn(),
34+
mkdir: vi.fn(),
35+
}))
36+
37+
vi.mock("../../../utils/versionToken", () => ({
38+
computeVersionToken: vi.fn(),
39+
}))
40+
41+
vi.mock("../../../services/file-safety/safeWriteText", async (importOriginal) => {
42+
// The error classes keep their production identity: the guard decides a publish failure by
43+
// instanceof, so a doubled class would decide a different question.
44+
const actual = await importOriginal<typeof import("../../../services/file-safety/safeWriteText")>()
45+
return {
46+
...actual,
47+
safeWriteText: vi.fn(),
48+
resolveLockKey: vi.fn(async (p: string) => p),
49+
}
50+
})
51+
52+
vi.mock("../../../utils/fileLock", () => ({
53+
withFileLock: vi.fn(),
54+
}))
55+
56+
const mockedWithFileLock = vi.mocked(withFileLock)
57+
const mockedResolveLockKey = vi.mocked(resolveLockKey)
58+
const mockedFsAccess = vi.mocked(fs.access)
59+
const mockedFsRealpath = vi.mocked(fs.realpath)
60+
const mockedFsStat = vi.mocked(fs.stat)
61+
const mockedFsMkdir = vi.mocked(fs.mkdir)
62+
const mockedComputeVersionToken = vi.mocked(computeVersionToken)
63+
const mockedSafeWriteText = vi.mocked(safeWriteText)
64+
65+
const WORKSPACE = "/test/workspace"
66+
67+
/** Resolve a fixture path the same way guardedWrite resolves task.cwd-relative paths. */
68+
const abs = (relPath: string): string => path.resolve(WORKSPACE, relPath)
69+
70+
/** A Node errno carrying error, for the codes the guard branches on. */
71+
function errno(code: string): Error {
72+
return Object.assign(new Error(code), { code })
73+
}
74+
75+
/**
76+
* BigIntStats double for one directory's identity. BigIntStats is a class backed with no public
77+
* constructor and the guard reads only dev, ino and the request options, so this is a last-resort
78+
* double assertion (test-local, per AGENTS.md).
79+
*/
80+
function statsDouble(dev: bigint, ino: bigint, bigint: boolean): BigIntStats {
81+
const wide = bigint ? dev : BigInt.asIntN(48, dev)
82+
const wideIno = bigint ? ino : BigInt.asIntN(48, ino)
83+
return { dev: wide, ino: wideIno } as unknown as BigIntStats
84+
}
85+
86+
/** Reads the bigint flag off the options object a stat or lstat request carried. */
87+
function hasBigIntFlag(options: unknown): boolean {
88+
return (
89+
typeof options === "object" &&
90+
options !== null &&
91+
"bigint" in options &&
92+
(options as { bigint?: unknown }).bigint === true
93+
)
94+
}
95+
96+
function delay(ms: number): Promise<void> {
97+
return new Promise((resolve) => setTimeout(resolve, ms))
98+
}
99+
100+
interface Answer {
101+
/** The verdict this caller received, plus the publish bookkeeping at the moment it arrived. */
102+
settled: Promise<{ outcome: string; publishFinishedAtAnswer: boolean; publishOpenAtAnswer: boolean }>
103+
}
104+
105+
/** Record a guardedWrite verdict together with the publish bookkeeping when it arrives. */
106+
function recordAnswer(write: Promise<unknown>): Answer {
107+
return {
108+
settled: write.then(
109+
() => ({
110+
outcome: "published",
111+
publishFinishedAtAnswer: publishFinished,
112+
publishOpenAtAnswer: publishOpen,
113+
}),
114+
(error: unknown) => ({
115+
outcome: "rejected",
116+
publishFinishedAtAnswer: publishFinished,
117+
publishOpenAtAnswer: publishOpen,
118+
rejection: error,
119+
}),
120+
) as Promise<{ outcome: string; publishFinishedAtAnswer: boolean; publishOpenAtAnswer: boolean }>,
121+
}
122+
}
123+
124+
/** A promise plus the two functions that settle it, for holding a publish open on purpose. */
125+
interface Gate {
126+
promise: Promise<void>
127+
open: () => void
128+
}
129+
130+
function gate(): Gate {
131+
let open!: () => void
132+
const promise = new Promise<void>((resolve) => {
133+
open = () => {
134+
resolve()
135+
}
136+
})
137+
return { promise, open }
138+
}
139+
140+
/** Narrow an unknown thrown value to the guard verdict, failing loudly otherwise. */
141+
function asGuardRejection(thrown: unknown): GuardRejectedError {
142+
if (thrown instanceof GuardRejectedError) {
143+
return thrown
144+
}
145+
throw new Error("expected a guard rejection, got " + String(thrown))
146+
}
147+
148+
interface CancellableTask {
149+
task: Task
150+
/** Runs the run-state abort latch the same way requestAbort() does. */
151+
abortNow: () => void
152+
/** Advances the cancellation fence the same way requestAbort() and requestDispose() do. */
153+
moveGenerationNow: () => void
154+
}
155+
156+
/**
157+
* Minimal structural Task: guardedWrite reads task.cwd, task.abort, task.cancellationGeneration
158+
* and task.observationRegistry. The real Task constructor needs the whole provider machinery, so
159+
* one documented double cast stands in for the class. The unwrapped double is returned too, so a
160+
* test can move the fence through the object rather than through the readonly view.
161+
*/
162+
function createCancellableTask(): CancellableTask {
163+
const task = {
164+
cwd: WORKSPACE,
165+
runState: initialRunState,
166+
// The guard reads cancellation through task.abort. On a real task that is the run-state
167+
// getter (RSK-06), so the double mirrors the same latch the kernel owns rather than
168+
// carrying a separate writable flag the kernel has dropped.
169+
get abort(): boolean {
170+
return this.runState.latches.abort
171+
},
172+
cancellationGeneration: 0,
173+
observationRegistry: new ObservationRegistry(),
174+
}
175+
return {
176+
task: task as unknown as Task,
177+
abortNow: () => {
178+
setAbortLatch(task, true)
179+
},
180+
moveGenerationNow: () => {
181+
task.cancellationGeneration += 1
182+
},
183+
}
184+
}
185+
186+
const CANCELLED = "Task was cancelled before this write ran -- the queued publish is not performed."
187+
188+
/** Live publish bookkeeping: whether a publish is open, and whether one has finished. */
189+
let publishOpen = false
190+
let publishFinished = false
191+
let release: Gate
192+
193+
/** Wait until the doubled writer has been entered, so a test knows a publish is genuinely open. */
194+
async function waitUntilOpen(): Promise<void> {
195+
const deadline = Date.now() + 500
196+
while (!publishOpen && Date.now() < deadline) {
197+
await delay(5)
198+
}
199+
if (!publishOpen) {
200+
throw new Error("the doubled writer never opened, so nothing was holding the path's chain")
201+
}
202+
}
203+
204+
describe("guardedWrite post-check cancellation gaps (epic #1375)", () => {
205+
/** Move the cancellation fact on the first filesystem request the next check makes. */
206+
function flipOnNextCheck(flip: () => void): void {
207+
let flipped = false
208+
mockedFsRealpath.mockImplementation(async (p: unknown) => {
209+
const key = String(p)
210+
if (!flipped && key === abs(".")) {
211+
flipped = true
212+
flip()
213+
}
214+
return key
215+
})
216+
}
217+
218+
beforeEach(() => {
219+
vi.resetAllMocks()
220+
publishOpen = false
221+
publishFinished = false
222+
release = gate()
223+
mockedWithFileLock.mockImplementation((filePath, operation) => operation(path.resolve(filePath)))
224+
mockedResolveLockKey.mockImplementation(async (p: string) => p)
225+
mockedFsAccess.mockRejectedValue(errno("ENOENT"))
226+
mockedFsMkdir.mockResolvedValue(undefined)
227+
mockedComputeVersionToken.mockResolvedValue("v1")
228+
mockedSafeWriteText.mockImplementation(async () => {
229+
publishOpen = true
230+
await release.promise
231+
publishOpen = false
232+
publishFinished = true
233+
})
234+
mockedFsStat.mockImplementation(async (p: unknown, options?: unknown) => {
235+
const key = String(p)
236+
if (key !== abs(".")) {
237+
throw errno("ENOENT")
238+
}
239+
return statsDouble(7n, 7001n, hasBigIntFlag(options))
240+
})
241+
vi.mocked(fs.lstat).mockImplementation(async () => {
242+
throw errno("ENOENT")
243+
})
244+
mockedFsRealpath.mockImplementation(async (p: unknown) => String(p))
245+
resetChain()
246+
})
247+
248+
describe("the gate between the containment re-check and the queued publish", () => {
249+
it("refuses a write the abort latch cancelled during its re-check", async () => {
250+
const holder = createCancellableTask()
251+
const held = guardedWrite(holder.task, "new.txt", "data", "create").catch((error: unknown) => error)
252+
await waitUntilOpen()
253+
254+
// One publish is open on this path and its link is on the chain. This write was submitted
255+
// after it, with the latch down, and the latch moves while the containment re-check runs.
256+
const canceller = createCancellableTask()
257+
flipOnNextCheck(canceller.abortNow)
258+
const answer = recordAnswer(guardedWrite(canceller.task, "new.txt", "data", "create"))
259+
release.open()
260+
await held
261+
const settled = await answer.settled
262+
263+
expect(asGuardRejection((settled as { rejection?: unknown }).rejection).message).toBe(CANCELLED)
264+
// The refused write never reached the writer, and its answer arrived only once its own turn
265+
// on the chain came round, which is after the live publish had settled: this caller's promise
266+
// IS its chain entry (guardedWrite.ts line 148), so releasing the reserved place cannot deliver
267+
// the verdict any earlier. Every hand substitution at line 690 measured the same two flags.
268+
expect(settled.publishOpenAtAnswer).toBe(false)
269+
expect(settled.publishFinishedAtAnswer).toBe(true)
270+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
271+
})
272+
273+
it("refuses a write the cancellation fence cancelled during its re-check", async () => {
274+
const holder = createCancellableTask()
275+
const held = guardedWrite(holder.task, "new.txt", "data", "create").catch((error: unknown) => error)
276+
await waitUntilOpen()
277+
278+
// The shape the gate's own comment names: the latch is a mutable flag, so this fixture moves
279+
// the fence and leaves the latch down. The write was submitted with both unchanged.
280+
const canceller = createCancellableTask()
281+
flipOnNextCheck(canceller.moveGenerationNow)
282+
const answer = recordAnswer(guardedWrite(canceller.task, "new.txt", "data", "create"))
283+
release.open()
284+
await held
285+
const settled = await answer.settled
286+
287+
expect(asGuardRejection((settled as { rejection?: unknown }).rejection).message).toBe(CANCELLED)
288+
expect(settled.publishOpenAtAnswer).toBe(false)
289+
expect(settled.publishFinishedAtAnswer).toBe(true)
290+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
291+
})
292+
293+
it("publishes when neither the latch nor the fence moved during the re-check", async () => {
294+
const writer = createCancellableTask()
295+
296+
const answer = recordAnswer(guardedWrite(writer.task, "new.txt", "data", "create"))
297+
release.open()
298+
const settled = await answer.settled
299+
300+
// Negative control on the two rows above: the gate must not refuse a write that nothing
301+
// cancelled, or the two refusals above would prove nothing about the gate.
302+
expect(settled.outcome).toBe("published")
303+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
304+
})
305+
})
306+
})

0 commit comments

Comments
 (0)