Skip to content

Commit d8c34aa

Browse files
author
easonLiangWorldedtech
committed
fix(tools): stat-match the create placeholder + fail-closed save cleanup (S4b, #1375)
CR incremental review on d037753 raised two findings on the create branch of open() (DiffViewProvider.ts): 1. A placeholder another writer touched between open()'s fs.writeFile() and the observation was recorded as a complete observation of content open() never read (and would let the token-guarded cleanup unlink the writer's file). The create branch now verifies the placeholder with the same S2 stat-matched contract as the modify branch: pre-stat, utf-8 read, post- stat; only a stat-matched empty read records the token as a complete observation. A non-empty read or stat mismatch (or a failed post-stat) records nothing, so the prior observation is untouched and the save fails closed. 2. A rejected save with a collected task threw before the discard-only cleanup, leaking the empty placeholder. The fail-closed throw now sits inside the try block so the task-unavailable rejection flows through the same cleanup as a guard verdict (token-guarded placeholder unlink, dirty discard, diff close). The cleanup token is captured in open() whether or not the task is still live: it is provider state used only for cleanup, while the observation (task state) stays gated on a live task. Specs: the placeholder-observation tests now stat-match (two bigint stats + utf-8 read); the collected-task case expects the cleanup token to be captured with no observation; new cases cover a writer-contested placeholder, a failed post-stat, and a bracketing-stat mismatch. 164/164 affected suites; tsc --noEmit and eslint --max-warnings=0 clean; suppression counts unchanged.
1 parent d037753 commit d8c34aa

2 files changed

Lines changed: 147 additions & 32 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 48 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -165,26 +165,44 @@ export class DiffViewProvider {
165165
// Make sure the file exists before we open it.
166166
if (!fileExists) {
167167
await fs.writeFile(absolutePath, "")
168-
// S4b follow-up (#44): the empty placeholder is fully known (empty),
169-
// so observe the just-written on-disk version as complete; the accepted
170-
// save then publishes through the guard's version check. Unlike the
171-
// modify branch above, this is recorded even when the task already has
172-
// an observation for the path: that observation describes a file that
173-
// no longer exists, and keeping it would make the accept-time CAS
174-
// (the placeholder token on disk vs. the vanished file's token) fail
175-
// every time, so recreating the file would always fail and the
176-
// placeholder would leak. The placeholder token is the correct baseline
177-
// for the new file: an external change to the placeholder before the
178-
// accept still moves the on-disk token and fails the CAS.
179-
const displayTask = this.taskRef.deref()
180-
if (displayTask) {
181-
const placeholderStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
182-
if (placeholderStats) {
183-
const placeholderVersion = versionTokenOfStat(placeholderStats)
184-
displayTask.observationRegistry.observe(absolutePath, placeholderVersion, true)
168+
// S4b follow-up (#44 / epic #1375): the empty placeholder is fully
169+
// known (empty), but verify it with the same S2 stat-matched contract
170+
// as the modify branch above: a stat-mismatched or non-empty read
171+
// means another writer touched the placeholder in the window after
172+
// open() wrote it, and that writer's token must not be observed as
173+
// complete (observing it would claim we saw content we never read, and
174+
// the token-guarded cleanup would unlink their file) - nothing is
175+
// recorded and the save fails closed instead. When the placeholder is
176+
// verified empty, its token replaces any prior observation for the
177+
// path: a prior observation describes a file that no longer exists, and
178+
// keeping it would make the accept-time CAS (the placeholder token on
179+
// disk vs. the vanished file's token) fail every time, so recreating
180+
// the file would always fail. The placeholder token is the correct
181+
// baseline for the new file: an external change to the placeholder
182+
// before the accept moves the on-disk token and fails the CAS. The
183+
// cleanup token is captured whether or not the task is still live:
184+
// a rejected save must not leave the placeholder behind even when the
185+
// owning task has been collected.
186+
const placeholderPreStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
187+
if (placeholderPreStats) {
188+
const placeholderContent = await fs.readFile(absolutePath, "utf-8").catch(() => undefined)
189+
const placeholderPostStats = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
190+
const placeholderToken = versionTokenOfStat(placeholderPreStats)
191+
// Stat-matched (S2): the read is trusted only while the bracketing
192+
// stats agree and the content is exactly the empty placeholder.
193+
if (
194+
placeholderPostStats &&
195+
placeholderToken === versionTokenOfStat(placeholderPostStats) &&
196+
placeholderContent === ""
197+
) {
185198
// Remember the placeholder token so a rejected save can remove
186-
// the placeholder only while it is still the exact file we wrote.
187-
this.placeholderVersion = placeholderVersion
199+
// the placeholder only while it is still the exact file open()
200+
// wrote.
201+
this.placeholderVersion = placeholderToken
202+
const displayTask = this.taskRef.deref()
203+
if (displayTask) {
204+
displayTask.observationRegistry.observe(absolutePath, placeholderToken, true)
205+
}
188206
}
189207
}
190208
}
@@ -401,18 +419,21 @@ export class DiffViewProvider {
401419
// changed after the preview or the target was never observed, with the
402420
// standard re-read-then-retry remediation.
403421
const saveTask = this.taskRef.deref()
404-
if (!saveTask) {
405-
// Fail closed: without the owning task the observation registry is
406-
// unreachable and the save cannot be guarded.
407-
throw new Error("Cannot guard the write: the owning task is no longer available")
408-
}
409422
try {
423+
if (!saveTask) {
424+
// Fail closed: without the owning task the observation registry is
425+
// unreachable and the save cannot be guarded. The rejection flows
426+
// through the same discard-only cleanup as a guard verdict, so a
427+
// dead task cannot leave the empty placeholder behind either.
428+
throw new Error("Cannot guard the write: the owning task is no longer available")
429+
}
410430
// Stryker disable next-line StringLiteral: "" is semantically identical to "update" in guardedWrite (only "edit" and "create" take distinct branches), so the StringLiteral mutant is equivalent at this sole production call site.
411431
await guardedWrite(saveTask, this.relPath, editedContent, "update")
412432
} catch (error) {
413-
// Discard-only failure cleanup. The guard rejected the publish
414-
// (stale version, unobserved target, or a partial-read observation),
415-
// so the on-disk content is the newer source of truth. Reload it
433+
// Discard-only failure cleanup. The publish was rejected (stale
434+
// version, unobserved target, a partial-read observation, or an
435+
// unavailable task), so the on-disk content is the newer source of
436+
// truth. Reload it
416437
// into the buffer (discarding the rejected edit), remove the empty
417438
// new-file placeholder while it is still exactly the file open()
418439
// wrote, and close the diff views. Never use revertChanges() here:

‎src/integrations/editor/__tests__/DiffViewProvider.spec.ts‎

Lines changed: 99 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,7 @@ describe("DiffViewProvider", () => {
10511051
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
10521052
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
10531053
vi.mocked(fs.stat).mockResolvedValue(previewStats)
1054+
vi.mocked(fs.readFile).mockResolvedValue("")
10541055
diffViewProvider.editType = "create"
10551056
mockTask.observationRegistry.clear()
10561057

@@ -1060,10 +1061,13 @@ describe("DiffViewProvider", () => {
10601061
expect(obs).toBeDefined()
10611062
expect(obs!.version).toBe(versionTokenOfStat(previewStats))
10621063
expect(obs!.complete).toBe(true)
1063-
// The create path stats exactly once (the placeholder), so the single
1064-
// call carries the bigint requirement.
1064+
// The create path stat-matches the placeholder (pre + post read), so
1065+
// both calls carry the bigint requirement, and the verification read
1066+
// uses utf-8.
10651067
expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(1, `${mockCwd}/brand-new.ts`, { bigint: true })
1066-
expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(1)
1068+
expect(vi.mocked(fs.stat)).toHaveBeenNthCalledWith(2, `${mockCwd}/brand-new.ts`, { bigint: true })
1069+
expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(2)
1070+
expect(vi.mocked(fs.readFile)).toHaveBeenCalledWith(`${mockCwd}/brand-new.ts`, "utf-8")
10671071
})
10681072

10691073
it("open() leaves the target unobserved when the pre/post stat mismatch (mid-preview mutation)", async () => {
@@ -1231,6 +1235,7 @@ describe("DiffViewProvider", () => {
12311235
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
12321236
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
12331237
vi.mocked(fs.stat).mockResolvedValue(previewStats)
1238+
vi.mocked(fs.readFile).mockResolvedValue("")
12341239
diffViewProvider.editType = "create"
12351240
mockTask.observationRegistry.clear()
12361241
mockTask.observationRegistry.observe(`${mockCwd}/t3-create.ts`, "model-token", true)
@@ -1241,7 +1246,7 @@ describe("DiffViewProvider", () => {
12411246
// the placeholder is written, stat-matched, observed (replacing the
12421247
// vanished file's stale token), and remembered for cleanup
12431248
expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/t3-create.ts`, "")
1244-
expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(1)
1249+
expect(vi.mocked(fs.stat)).toHaveBeenCalledTimes(2)
12451250
expect(mockTask.observationRegistry.get(`${mockCwd}/t3-create.ts`)?.version).toBe(placeholderToken)
12461251
expect(diffViewProvider["placeholderVersion"]).toBe(placeholderToken)
12471252
})
@@ -1260,15 +1265,103 @@ describe("DiffViewProvider", () => {
12601265
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
12611266
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
12621267
vi.mocked(fs.stat).mockResolvedValue(previewStats)
1268+
vi.mocked(fs.readFile).mockResolvedValue("")
12631269
diffViewProvider.editType = "create"
12641270
mockTask.observationRegistry.clear()
12651271
diffViewProvider["taskRef"] = { deref: () => undefined } as unknown as WeakRef<Task>
12661272

12671273
await diffViewProvider.open("t3-dead-task.ts")
12681274

12691275
expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/t3-dead-task.ts`, "")
1270-
// no live task: nothing observed, nothing remembered for cleanup
1276+
// no live task: nothing observed, but the cleanup token is still
1277+
// captured (provider state) so the fail-closed save rejection can
1278+
// remove the placeholder instead of leaking it
12711279
expect(mockTask.observationRegistry.get(`${mockCwd}/t3-dead-task.ts`)).toBeUndefined()
1280+
expect(diffViewProvider["placeholderVersion"]).toBe(versionTokenOfStat(previewStats))
1281+
})
1282+
1283+
it("open() does not record a placeholder another writer touched after the write", async () => {
1284+
// CR d037753 finding: a writer that touched the placeholder between
1285+
// open()'s fs.writeFile() and the observation would have its token
1286+
// recorded as a complete observation of content open() never read.
1287+
// The stat-matched verification must reject it: no observation (the
1288+
// prior observation stays untouched), no cleanup token (so a rejected
1289+
// save cannot unlink the writer's file), and the save fails closed.
1290+
const mockEditor = mockTextEditor(`${mockCwd}/contested.ts`)
1291+
vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined)
1292+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
1293+
setTimeout(() => callback(mockTextDocument(`${mockCwd}/contested.ts`)), 0)
1294+
return { dispose: vi.fn() }
1295+
})
1296+
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
1297+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
1298+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
1299+
vi.mocked(fs.readFile).mockResolvedValue("external content")
1300+
diffViewProvider.editType = "create"
1301+
mockTask.observationRegistry.clear()
1302+
mockTask.observationRegistry.observe(`${mockCwd}/contested.ts`, "model-token", true)
1303+
1304+
await diffViewProvider.open("contested.ts")
1305+
1306+
expect(vi.mocked(fs.writeFile)).toHaveBeenCalledWith(`${mockCwd}/contested.ts`, "")
1307+
// nothing recorded, and the vanished file's prior observation was
1308+
// not replaced with the writer's token
1309+
expect(mockTask.observationRegistry.get(`${mockCwd}/contested.ts`)?.version).toBe("model-token")
1310+
expect(diffViewProvider["placeholderVersion"]).toBeUndefined()
1311+
})
1312+
1313+
it("open() does not record the placeholder when the post-stat fails after the write", async () => {
1314+
// The bracketing stats must both succeed: a failed post-stat means
1315+
// the read is not trustworthy, so nothing is recorded.
1316+
const mockEditor = mockTextEditor(`${mockCwd}/statfail.ts`)
1317+
vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined)
1318+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
1319+
setTimeout(() => callback(mockTextDocument(`${mockCwd}/statfail.ts`)), 0)
1320+
return { dispose: vi.fn() }
1321+
})
1322+
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
1323+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
1324+
vi.mocked(fs.stat)
1325+
.mockResolvedValueOnce(previewStats)
1326+
.mockRejectedValueOnce(Object.assign(new Error("ENOENT: no such file"), { code: "ENOENT" }))
1327+
vi.mocked(fs.readFile).mockResolvedValue("")
1328+
diffViewProvider.editType = "create"
1329+
mockTask.observationRegistry.clear()
1330+
1331+
await diffViewProvider.open("statfail.ts")
1332+
1333+
expect(mockTask.observationRegistry.get(`${mockCwd}/statfail.ts`)).toBeUndefined()
1334+
expect(diffViewProvider["placeholderVersion"]).toBeUndefined()
1335+
})
1336+
1337+
it("open() does not record the placeholder when the bracketing stats disagree (mid-preview mutation)", async () => {
1338+
// A token change between the bracketing stats means the placeholder
1339+
// was replaced or rewritten while open() was reading it - same S2
1340+
// rule as the modify branch: nothing is recorded.
1341+
const mutatedStats = {
1342+
isDirectory: () => false,
1343+
dev: BigInt(1),
1344+
ino: BigInt(2),
1345+
size: BigInt(301),
1346+
mtimeNs: BigInt(4_000_000_001n),
1347+
ctimeNs: BigInt(5_000_000_000n),
1348+
} as unknown as BigIntStats
1349+
const mockEditor = mockTextEditor(`${mockCwd}/mutated-new.ts`)
1350+
vi.mocked(vscode.commands.executeCommand).mockResolvedValue(undefined)
1351+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
1352+
setTimeout(() => callback(mockTextDocument(`${mockCwd}/mutated-new.ts`)), 0)
1353+
return { dispose: vi.fn() }
1354+
})
1355+
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
1356+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
1357+
vi.mocked(fs.stat).mockResolvedValueOnce(previewStats).mockResolvedValueOnce(mutatedStats)
1358+
vi.mocked(fs.readFile).mockResolvedValue("")
1359+
diffViewProvider.editType = "create"
1360+
mockTask.observationRegistry.clear()
1361+
1362+
await diffViewProvider.open("mutated-new.ts")
1363+
1364+
expect(mockTask.observationRegistry.get(`${mockCwd}/mutated-new.ts`)).toBeUndefined()
12721365
expect(diffViewProvider["placeholderVersion"]).toBeUndefined()
12731366
})
12741367

@@ -1286,6 +1379,7 @@ describe("DiffViewProvider", () => {
12861379
vi.mocked(vscode.window).visibleTextEditors = [mockEditor]
12871380
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor)
12881381
vi.mocked(fs.stat).mockResolvedValue(previewStats)
1382+
vi.mocked(fs.readFile).mockResolvedValue("")
12891383
diffViewProvider.editType = "create"
12901384
// prior read observation (the file has since vanished)
12911385
expect(mockTask.observationRegistry.get(`${mockCwd}/test.ts`)?.version).toBe("v1")

0 commit comments

Comments
 (0)