Skip to content

Commit 096abc2

Browse files
fix(diff-view): bind every rollback publish to a version pair
The rollback still had unguarded paths: when the session had no baseline (a guarded publish whose token read failed) or the disk reported no version, it fell back to updatedDocument.save() - an unguarded publish that overwrites any peer write landing in that window with originalContent. The create branch unlinked whenever its token check was inconclusive: a create that recorded only a placeholder identity could delete a peer replacement it never saw. The existing-file rollback now requires both sides of the version comparison - the token this session left and the version the disk reports - and publishes the original bytes through replaceIfVersion in all cases. Without either side it preserves the disk state and raises RollbackConflictError naming what it found, instead of saving. The create rollback unlinks only on a proven token match: unknown ownership (placeholder token unavailable) or a mismatch preserves the path and the created directories and reports the conflict. Tests: missing-baseline and missing-disk-evidence rollbacks assert the conflict and the preserved disk; an identity-only create asserts the peer replacement and directories survive; the tab-close and rollback- ordering tests now observe the revert reconcile. Negative controls: removing the evidence gate reddens the two baseline-conflict tests, relaxing the create ownership check reddens exactly the identity-only test, and reverting the reconcile to a save reddens the four tests that pin it. 177/177 green.
1 parent 4e4cf7f commit 096abc2

2 files changed

Lines changed: 216 additions & 44 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 43 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1257,9 +1257,19 @@ export class DiffViewProvider {
12571257
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
12581258
const diskToken = diskStat === undefined ? undefined : versionTokenOfStat(diskStat)
12591259
const oursToken = this.lastWrittenToken ?? this.placeholderVersion
1260-
if (diskToken !== undefined && oursToken !== undefined && diskToken !== oursToken) {
1260+
if (oursToken === undefined || diskToken === undefined || diskToken !== oursToken) {
1261+
// Ownership is unknown - this session recorded no token (an
1262+
// identity-only or failed stat-bracketed create), or the disk
1263+
// reports none - or mismatched (a peer replaced the placeholder).
1264+
// In every one of those cases the unlink would delete bytes this
1265+
// rollback cannot prove it owns: preserve the path and report the
1266+
// conflict explicitly instead.
12611267
await this.closeAllDiffViews()
1262-
throw new RollbackConflictError(absolutePath, oursToken, diskToken)
1268+
throw new RollbackConflictError(
1269+
absolutePath,
1270+
oursToken ?? "<no-session-version>",
1271+
diskToken ?? "<absent>",
1272+
)
12631273
}
12641274
// No save before the delete: saving the diff buffer would publish the
12651275
// cancelled edit's content to disk immediately before deleting it -
@@ -1298,25 +1308,33 @@ export class DiffViewProvider {
12981308
// eligibility - replaceIfVersion re-reads the version under the lock,
12991309
// and that read is the authoritative check the publish is bound to.
13001310
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
1301-
let casPublished = false
1302-
if (expectedToken !== undefined && diskStat !== undefined) {
1303-
try {
1304-
await replaceIfVersion(absolutePath, expectedToken, originalBytes, displayRelPath)
1305-
casPublished = true
1306-
} catch (error: unknown) {
1307-
if (error instanceof GuardRejectedError) {
1308-
// The CAS rejected: the peer's bytes are preserved. Report the
1309-
// conflict with the disk token the rejection is about.
1310-
const conflictStat = await fs
1311-
.stat(absolutePath, { bigint: true })
1312-
.catch(() => undefined)
1313-
const diskToken =
1314-
conflictStat === undefined ? "<absent>" : versionTokenOfStat(conflictStat)
1315-
await this.closeAllDiffViews()
1316-
throw new RollbackConflictError(absolutePath, expectedToken, diskToken)
1317-
}
1318-
throw error
1311+
if (expectedToken === undefined || diskStat === undefined) {
1312+
// One side of the comparison has no version: the session never
1313+
// recorded what it left (a publish whose token read failed), or the
1314+
// disk reports no version at all. There is nothing to bind a publish
1315+
// to, and an unguarded save here could overwrite a peer's bytes with
1316+
// originalContent - the exact loss the CAS exists to prevent. Preserve
1317+
// the disk state and report the conflict explicitly instead.
1318+
const diskToken = diskStat === undefined ? "<absent>" : versionTokenOfStat(diskStat)
1319+
await this.closeAllDiffViews()
1320+
throw new RollbackConflictError(
1321+
absolutePath,
1322+
expectedToken ?? "<no-session-version>",
1323+
diskToken,
1324+
)
1325+
}
1326+
try {
1327+
await replaceIfVersion(absolutePath, expectedToken, originalBytes, displayRelPath)
1328+
} catch (error: unknown) {
1329+
if (error instanceof GuardRejectedError) {
1330+
// The CAS rejected: the peer's bytes are preserved. Report the
1331+
// conflict with the disk token the rejection is about.
1332+
const conflictStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
1333+
const diskToken = conflictStat === undefined ? "<absent>" : versionTokenOfStat(conflictStat)
1334+
await this.closeAllDiffViews()
1335+
throw new RollbackConflictError(absolutePath, expectedToken, diskToken)
13191336
}
1337+
throw error
13201338
}
13211339

13221340
// Restore the buffer to the original content.
@@ -1330,20 +1348,11 @@ export class DiffViewProvider {
13301348
edit.replace(updatedDocument.uri, fullRange, originalBytes)
13311349
await vscode.workspace.applyEdit(edit)
13321350

1333-
if (casPublished) {
1334-
// The CAS published the original bytes outside VS Code's save path:
1335-
// reconcile the buffer with the disk - reverting reloads the published
1336-
// bytes and clears the dirty flag - instead of saving the buffer back
1337-
// over the disk through the unguarded path this rollback replaced.
1338-
await this.revertDocument(updatedDocument)
1339-
} else {
1340-
// No CAS: either this session never published to the path (no expected
1341-
// version exists) or the disk reported no version to compare against
1342-
// (absent or unreadable). Saving the restored buffer rewrites the
1343-
// bytes this session last knew, as it did before the guarded rollback
1344-
// existed; there was no version to bind the publish to.
1345-
await updatedDocument.save()
1346-
}
1351+
// The CAS published the original bytes outside VS Code's save path:
1352+
// reconcile the buffer with the disk - reverting reloads the published
1353+
// bytes and clears the dirty flag - instead of saving the buffer back
1354+
// over the disk through the unguarded path this rollback replaced.
1355+
await this.revertDocument(updatedDocument)
13471356

13481357
await this.closeAllDiffViews()
13491358

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

Lines changed: 173 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3404,6 +3404,115 @@ describe("DiffViewProvider", () => {
34043404
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
34053405
})
34063406

3407+
it("revertChanges() preserves the disk when the session has no rollback baseline", async () => {
3408+
// A guarded publish whose token read failed leaves the session without a
3409+
// version to bind the restore to. The old fallback saved originalContent
3410+
// unguarded - over any peer write landing in that window. The rollback
3411+
// now preserves the disk state and reports the conflict explicitly.
3412+
const cleanEditor = {
3413+
document: {
3414+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
3415+
getText: vi.fn().mockReturnValue("new content"),
3416+
lineCount: 0,
3417+
encoding: "utf8",
3418+
isDirty: false,
3419+
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
3420+
save: vi.fn().mockResolvedValue(undefined),
3421+
},
3422+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3423+
edit: vi.fn().mockResolvedValue(true),
3424+
revealRange: vi.fn(),
3425+
} as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface.
3426+
diffViewProvider["activeDiffEditor"] = cleanEditor
3427+
diffViewProvider["relPath"] = "test.ts"
3428+
diffViewProvider.editType = "modify"
3429+
diffViewProvider["originalContent"] = "original"
3430+
diffViewProvider["lastWrittenToken"] = undefined
3431+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
3432+
3433+
await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({
3434+
name: "RollbackConflictError",
3435+
oursToken: "<no-session-version>",
3436+
diskToken: versionTokenOfStat(previewStats),
3437+
})
3438+
// The disk was preserved: no publish of originalContent, no buffer write.
3439+
expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original")
3440+
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
3441+
})
3442+
3443+
it("revertChanges() preserves the disk when the disk reports no version", async () => {
3444+
// The mirror case: the session recorded a token but the disk reports no
3445+
// version to compare against (absent or unreadable). Saving here would
3446+
// recreate or clobber a path whose state this session cannot prove.
3447+
const cleanEditor = {
3448+
document: {
3449+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
3450+
getText: vi.fn().mockReturnValue("new content"),
3451+
lineCount: 0,
3452+
encoding: "utf8",
3453+
isDirty: false,
3454+
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
3455+
save: vi.fn().mockResolvedValue(undefined),
3456+
},
3457+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3458+
edit: vi.fn().mockResolvedValue(true),
3459+
revealRange: vi.fn(),
3460+
} as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface.
3461+
diffViewProvider["activeDiffEditor"] = cleanEditor
3462+
diffViewProvider["relPath"] = "test.ts"
3463+
diffViewProvider.editType = "modify"
3464+
diffViewProvider["originalContent"] = "original"
3465+
diffViewProvider["lastWrittenToken"] = versionTokenOfStat(previewStats)
3466+
vi.mocked(fs.stat).mockResolvedValue(undefined as unknown as Awaited<ReturnType<typeof fs.stat>>) // No stat evidence.
3467+
3468+
await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({
3469+
name: "RollbackConflictError",
3470+
oursToken: versionTokenOfStat(previewStats),
3471+
diskToken: "<absent>",
3472+
})
3473+
expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original")
3474+
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
3475+
})
3476+
3477+
it("revertChanges() keeps a peer replacement when the create recorded an identity only", async () => {
3478+
// A create whose placeholder token is unavailable (identity-only or failed
3479+
// stat-bracketed open) cannot prove ownership of the path it is about to
3480+
// unlink: a peer replacement landing in that window would be deleted by a
3481+
// rollback that never saw it. The unlink runs only on a proven token match;
3482+
// an unknown owner keeps the path and the created directories.
3483+
const cleanEditor = {
3484+
document: {
3485+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
3486+
getText: vi.fn().mockReturnValue("placeholder content"),
3487+
lineCount: 0,
3488+
encoding: "utf8",
3489+
isDirty: false,
3490+
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
3491+
save: vi.fn().mockResolvedValue(undefined),
3492+
},
3493+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3494+
edit: vi.fn().mockResolvedValue(true),
3495+
revealRange: vi.fn(),
3496+
} as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface.
3497+
diffViewProvider["activeDiffEditor"] = cleanEditor
3498+
diffViewProvider["relPath"] = "test.ts"
3499+
diffViewProvider.editType = "create"
3500+
diffViewProvider["lastWrittenToken"] = undefined
3501+
diffViewProvider["placeholderVersion"] = undefined
3502+
diffViewProvider["placeholderIdentity"] = { dev: BigInt(1), ino: BigInt(2) }
3503+
diffViewProvider["createdDirs"] = [`${mockCwd}/newdir`]
3504+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
3505+
3506+
await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({
3507+
name: "RollbackConflictError",
3508+
oursToken: "<no-session-version>",
3509+
diskToken: versionTokenOfStat(previewStats),
3510+
})
3511+
// Ownership unknown: neither the unlink nor the directory cleanup ran.
3512+
expect(fs.unlink).not.toHaveBeenCalled()
3513+
expect(fs.rmdir).not.toHaveBeenCalled()
3514+
})
3515+
34073516
it("reports a peer publish that landed after a real successful save as a rollback conflict", async () => {
34083517
// The rollback baseline must come from this session's own publish: a real
34093518
// saveChanges() records the token its publish left on disk, so a peer that
@@ -3463,8 +3572,14 @@ describe("DiffViewProvider", () => {
34633572
})
34643573
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
34653574

3466-
await expect(diffViewProvider.revertChanges()).resolves.toBeUndefined()
3467-
expect(vscode.workspace.applyEdit).toHaveBeenCalled()
3575+
// The new contract: a session with no baseline has no version to bind a
3576+
// restore to, so the rollback preserves the disk and reports the conflict
3577+
// explicitly instead of saving bytes it cannot tie to a checked version.
3578+
await expect(diffViewProvider.revertChanges()).rejects.toMatchObject({
3579+
name: "RollbackConflictError",
3580+
oursToken: "<no-session-version>",
3581+
})
3582+
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
34683583
})
34693584

34703585
it("drops the rollback baseline when the session is finalized", async () => {
@@ -3919,6 +4034,19 @@ describe("DiffViewProvider", () => {
39194034

39204035
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockSavedEditor as any)
39214036
;(diffViewProvider as any).closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
4037+
// The CAS rollback needs both sides of the version comparison: this session
4038+
// left the token and the disk still reports it.
4039+
const scrollStats = {
4040+
isDirectory: () => false,
4041+
dev: BigInt(1),
4042+
ino: BigInt(2),
4043+
size: BigInt(300),
4044+
mtimeNs: BigInt(4_000_000_000n),
4045+
ctimeNs: BigInt(5_000_000_000n),
4046+
} as unknown as BigIntStats
4047+
vi.mocked(fs.stat).mockResolvedValue(scrollStats)
4048+
vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(scrollStats))
4049+
diffViewProvider["lastWrittenToken"] = versionTokenOfStat(scrollStats)
39224050
;(diffViewProvider as any).documentWasOpen = true
39234051
;(diffViewProvider as any).preEditScrollLine = 15
39244052
;(diffViewProvider as any).editType = "modify"
@@ -3947,12 +4075,29 @@ describe("DiffViewProvider", () => {
39474075
describe("userTouchedDocument close/keep behavior", () => {
39484076
const mockTargetPath = `${mockCwd}/mock-target-file.ts`
39494077

4078+
// Synthetic stat for the session's own publish, tokenized with the real
4079+
// versionTokenOfStat so the rollback's compare-and-swap sees a matching pair.
4080+
const ownStats = {
4081+
isDirectory: () => false,
4082+
dev: BigInt(1),
4083+
ino: BigInt(2),
4084+
size: BigInt(300),
4085+
mtimeNs: BigInt(4_000_000_000n),
4086+
ctimeNs: BigInt(5_000_000_000n),
4087+
} as unknown as BigIntStats
4088+
39504089
beforeEach(() => {
39514090
// The guarded-publish describe queues a stat mock that clearAllMocks does
39524091
// not undo. These tests model a session whose own publish is the last
3953-
// writer, so restore the file-wide default (no stat evidence) instead of
3954-
// letting a foreign token pose as a peer write.
3955-
vi.mocked(fs.stat).mockResolvedValue(undefined as unknown as Awaited<ReturnType<typeof fs.stat>>) // No stat evidence.
4092+
// writer, so pin the disk evidence and the session baseline to the same
4093+
// token instead of letting a foreign token pose as a peer write - the
4094+
// rollback now refuses to act without both sides of the comparison.
4095+
vi.mocked(fs.stat).mockResolvedValue(ownStats)
4096+
// The file-wide observation and version source are "v1" (see the top-level
4097+
// beforeEach): the session baseline must be the token the guarded publish
4098+
// actually recorded, and the stat above only has to exist for the rollback
4099+
// to have disk evidence to bind to.
4100+
diffViewProvider["lastWrittenToken"] = "v1"
39564101
})
39574102

39584103
const buildActiveDiffEditor = () => ({
@@ -4128,9 +4273,12 @@ describe("DiffViewProvider", () => {
41284273
release()
41294274
const [result] = await Promise.all([save, revert])
41304275

4131-
// Both rollback writes happened after the publish settled, so the final bytes
4132-
// on disk are the rollback's originalContent, not the cancelled edit.
4133-
expect(rollbackWritesAfterPublishSettled).toEqual([true, true])
4276+
// The rollback's document write happened after the publish settled; the
4277+
// disk publish went through the compare-and-swap (not the buffer save), so
4278+
// the final bytes on disk are the rollback's originalContent, not the
4279+
// cancelled edit, and the buffer was reconciled by reverting onto them.
4280+
expect(rollbackWritesAfterPublishSettled).toEqual([true])
4281+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert")
41344282
expect(result).toEqual({
41354283
newProblemsMessage: undefined,
41364284
userEdits: undefined,
@@ -4806,7 +4954,9 @@ describe("DiffViewProvider", () => {
48064954
await diffViewProvider.revertChanges()
48074955

48084956
expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath)
4809-
expect(vscode.window.showTextDocument).not.toHaveBeenCalled()
4957+
// The CAS-published rollback reconciles the buffer by reverting, which
4958+
// activates the document once; the tab itself is closed by closeFileTab.
4959+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert")
48104960
})
48114961

48124962
it("revertChanges() keeps the file open when the user touched it", async () => {
@@ -5087,6 +5237,17 @@ describe("DiffViewProvider", () => {
50875237
vi.mocked(vscode.workspace.applyEdit).mockResolvedValue(true)
50885238
;(diffViewProvider as any).closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
50895239
;(diffViewProvider as any).closeFileTab = closeFileTab
5240+
// The CAS rollback needs both sides of the version comparison: this session
5241+
// left "v1" (the file-wide observation) and the disk reports evidence.
5242+
vi.mocked(fs.stat).mockResolvedValue({
5243+
isDirectory: () => false,
5244+
dev: BigInt(1),
5245+
ino: BigInt(2),
5246+
size: BigInt(300),
5247+
mtimeNs: BigInt(4_000_000_000n),
5248+
ctimeNs: BigInt(5_000_000_000n),
5249+
} as unknown as BigIntStats)
5250+
diffViewProvider["lastWrittenToken"] = "v1"
50905251
;(diffViewProvider as any).relPath = "mock-target-file.ts"
50915252
;(diffViewProvider as any).documentWasOpen = false
50925253
;(diffViewProvider as any).userTouchedDocument = false
@@ -5100,7 +5261,9 @@ describe("DiffViewProvider", () => {
51005261
await diffViewProvider.revertChanges()
51015262

51025263
expect(closeFileTab).toHaveBeenCalledWith(mockTargetPath)
5103-
expect(vscode.window.showTextDocument).not.toHaveBeenCalled()
5264+
// The CAS-published rollback reconciles the buffer by reverting, which
5265+
// activates the document once; the tab itself is closed by closeFileTab.
5266+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert")
51045267
})
51055268
})
51065269

0 commit comments

Comments
 (0)