Skip to content

Commit 4e4cf7f

Browse files
fix(diff-view): roll back through a compare-and-swap bound to the checked version
The existing-file rollback checked the disk token and then applied the buffer through VS Code's save path: the check was not bound to the publish, so a peer write landing after the check was silently overwritten by originalContent. The rollback now publishes the original bytes through replaceIfVersion - the version check and the publish inside one acquisition of the shared advisory lock, with lastWrittenToken as the expected version. A CAS rejection preserves the peer's bytes and raises RollbackConflictError naming the disk token it found; on success the buffer is reconciled by reverting onto the published bytes instead of saving over them. Without a version on either side (never published, or no disk evidence) there is nothing to compare, and the save fallback remains documented as such. The create branch no longer saves the dirty diff buffer before the delete - that save published the cancelled edit's content for a moment, unbound to the placeholder check - and unlinks only after the placeholder identity check inside the lock. A barrier test pauses the rollback's version read, lands a peer publish inside the pause, and verifies the peer's bytes remain.
1 parent 1c34cec commit 4e4cf7f

2 files changed

Lines changed: 222 additions & 54 deletions

File tree

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 107 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,12 @@ import type { FileObservation } from "../../core/task/observationRegistry"
2222
import { versionTokenOfStat } from "../../utils/versionToken"
2323
import { withFileLock } from "../../utils/fileLock"
2424
import { resolveLockKey } from "../../services/file-safety/safeWriteText"
25-
import { guardedWrite, GuardRejectedError, type GuardedWriteKind } from "../../core/tools/guardedWrite"
25+
import {
26+
guardedWrite,
27+
GuardRejectedError,
28+
replaceIfVersion,
29+
type GuardedWriteKind,
30+
} from "../../core/tools/guardedWrite"
2631

2732
import { DecorationController } from "./DecorationController"
2833

@@ -1222,6 +1227,9 @@ export class DiffViewProvider {
12221227
const fileExists = this.editType === "modify"
12231228
const updatedDocument = this.activeDiffEditor.document
12241229
const absolutePath = path.resolve(this.cwd, this.relPath)
1230+
// Captured while narrowed: the CAS below runs after awaits inside the
1231+
// teardown closure.
1232+
const displayRelPath = this.relPath
12251233

12261234
// Stop tracking touches and cancel any pending scroll-to-diff before any
12271235
// programmatic editor activation below.
@@ -1237,26 +1245,27 @@ export class DiffViewProvider {
12371245
// before the rollback acts, and an unguarded restore or unlink would
12381246
// clobber or delete bytes this session never wrote.
12391247
await withFileLock(await resolveLockKey(absolutePath), async () => {
1240-
// Decide against the disk state under the lock: the rollback may overwrite
1241-
// or remove the file only while it still carries the token this session
1242-
// last wrote (the post-publish observation for a modify, the placeholder
1243-
// token for a create). A different token means a peer published in the
1244-
// settled window: preserve the peer's bytes, close this session's views,
1245-
// and report the conflict explicitly.
1246-
// The same token source the publish and adoption paths use, so the
1247-
// comparison is apples to apples with what this session recorded.
1248-
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
1249-
const diskToken = diskStat === undefined ? undefined : versionTokenOfStat(diskStat)
1250-
const oursToken = this.lastWrittenToken ?? (fileExists ? undefined : this.placeholderVersion)
1251-
if (diskToken !== undefined && oursToken !== undefined && diskToken !== oursToken) {
1252-
await this.closeAllDiffViews()
1253-
throw new RollbackConflictError(absolutePath, oursToken, diskToken)
1254-
}
12551248
if (!fileExists) {
1256-
if (updatedDocument.isDirty) {
1257-
await updatedDocument.save()
1249+
// Decide against the disk state under the lock: the rollback may
1250+
// remove the file only while it still carries the token this session
1251+
// left there (the post-publish observation or the placeholder token).
1252+
// A different token means a peer published in the settled window:
1253+
// preserve the peer's bytes, close this session's views, and report
1254+
// the conflict explicitly. The same token source the publish and
1255+
// adoption paths use, so the comparison is apples to apples with
1256+
// what this session recorded.
1257+
const diskStat = await fs.stat(absolutePath, { bigint: true }).catch(() => undefined)
1258+
const diskToken = diskStat === undefined ? undefined : versionTokenOfStat(diskStat)
1259+
const oursToken = this.lastWrittenToken ?? this.placeholderVersion
1260+
if (diskToken !== undefined && oursToken !== undefined && diskToken !== oursToken) {
1261+
await this.closeAllDiffViews()
1262+
throw new RollbackConflictError(absolutePath, oursToken, diskToken)
12581263
}
1259-
1264+
// No save before the delete: saving the diff buffer would publish the
1265+
// cancelled edit's content to disk immediately before deleting it -
1266+
// a write the rollback never intended, unbound to the placeholder
1267+
// check above, and a visible flash of cancelled content for anyone
1268+
// reading the path in that window.
12601269
await this.closeAllDiffViews()
12611270
// The file was newly created for this edit; close its transiently
12621271
// opened tab before deleting it from disk.
@@ -1267,40 +1276,91 @@ export class DiffViewProvider {
12671276
for (let i = this.createdDirs.length - 1; i >= 0; i--) {
12681277
await fs.rmdir(this.createdDirs[i])
12691278
}
1270-
} else {
1271-
// Revert document.
1272-
const edit = new vscode.WorkspaceEdit()
1279+
}
1280+
// The modify rollback publishes through replaceIfVersion below: it
1281+
// takes this same lock itself, and withFileLock is not reentrant.
1282+
})
12731283

1274-
const fullRange = new vscode.Range(
1275-
updatedDocument.positionAt(0),
1276-
updatedDocument.positionAt(updatedDocument.getText().length),
1277-
)
1284+
if (fileExists) {
1285+
// Revert the existing file with an atomic guarded compare-and-swap
1286+
// publish: the original bytes reach the disk only while the path still
1287+
// carries the token this session last wrote, with the version check and
1288+
// the publish inside one acquisition of the shared advisory lock
1289+
// (replaceIfVersion). The old check-then-save applied the buffer through
1290+
// VS Code's save path without binding the publish to the checked
1291+
// version, so a peer publish landing after the check was silently
1292+
// overwritten. On a CAS rejection the peer's bytes stay on disk and the
1293+
// rollback reports the conflict.
1294+
const originalBytes = this.stripAllBOMs(this.originalContent ?? "")
1295+
const expectedToken = this.lastWrittenToken
1296+
// The CAS needs both sides of the comparison: the version this session
1297+
// left and the version the disk reports. The probe below only decides
1298+
// eligibility - replaceIfVersion re-reads the version under the lock,
1299+
// and that read is the authoritative check the publish is bound to.
1300+
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
1319+
}
1320+
}
12781321

1279-
edit.replace(updatedDocument.uri, fullRange, this.stripAllBOMs(this.originalContent ?? ""))
1322+
// Restore the buffer to the original content.
1323+
const edit = new vscode.WorkspaceEdit()
12801324

1281-
// Apply the edit and save, since contents shouldn't have changed
1282-
// this won't show in local history unless of course the user made
1283-
// changes and saved during the edit.
1284-
await vscode.workspace.applyEdit(edit)
1285-
await updatedDocument.save()
1325+
const fullRange = new vscode.Range(
1326+
updatedDocument.positionAt(0),
1327+
updatedDocument.positionAt(updatedDocument.getText().length),
1328+
)
12861329

1287-
await this.closeAllDiffViews()
1330+
edit.replace(updatedDocument.uri, fullRange, originalBytes)
1331+
await vscode.workspace.applyEdit(edit)
12881332

1289-
// Read auto-close preferences from state; fall back to defaults that
1290-
// preserve the existing behavior when unset.
1291-
const revertTask = this.taskRef.deref()
1292-
const revertState = await revertTask?.providerRef.deref()?.getState()
1293-
1294-
await this.keepOrCloseEditedFile(
1295-
absolutePath,
1296-
false,
1297-
revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
1298-
revertState?.autoCloseZooOpenedFilesAfterUserEdited ??
1299-
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
1300-
revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
1301-
)
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()
13021346
}
1303-
})
1347+
1348+
await this.closeAllDiffViews()
1349+
1350+
// Read auto-close preferences from state; fall back to defaults that
1351+
// preserve the existing behavior when unset.
1352+
const revertTask = this.taskRef.deref()
1353+
const revertState = await revertTask?.providerRef.deref()?.getState()
1354+
1355+
await this.keepOrCloseEditedFile(
1356+
absolutePath,
1357+
false,
1358+
revertState?.autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES,
1359+
revertState?.autoCloseZooOpenedFilesAfterUserEdited ??
1360+
DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED,
1361+
revertState?.autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES,
1362+
)
1363+
}
13041364
})
13051365
} catch (error) {
13061366
if (error instanceof RollbackConflictError) {

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

Lines changed: 115 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3274,6 +3274,10 @@ describe("DiffViewProvider", () => {
32743274
// The rollback has not touched the document: the probe still owns the decision.
32753275
expect(applyEdit).not.toHaveBeenCalled()
32763276

3277+
// The probe is about to adopt the publish: from here the disk carries this
3278+
// session's own token again, so the rollback's compare-and-swap can match it.
3279+
vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(previewStats))
3280+
32773281
releaseProbe()
32783282
const [result] = await Promise.all([save, revert])
32793283

@@ -3284,9 +3288,12 @@ describe("DiffViewProvider", () => {
32843288
userEdits: undefined,
32853289
finalContent: undefined,
32863290
})
3287-
// ...and the rollback is the last writer: both of its writes happened after
3288-
// the probe read, never against the bytes it was matching.
3289-
expect(rollbackWritesAfterProbe).toEqual([true, true])
3291+
// ...and the rollback is the last writer: its document write happened after
3292+
// the probe read, never against the bytes it was matching. The disk publish
3293+
// went through the compare-and-swap (not the buffer save), and the buffer was
3294+
// then reconciled by reverting onto the published bytes.
3295+
expect(rollbackWritesAfterProbe).toEqual([true])
3296+
expect(vscode.commands.executeCommand).toHaveBeenCalledWith("workbench.action.files.revert")
32903297
// One pass over the tabs: the save added no cleanup of its own.
32913298
expect(diffViewProvider["closeAllDiffViews"]).toHaveBeenCalledTimes(1)
32923299
})
@@ -3322,7 +3329,7 @@ describe("DiffViewProvider", () => {
33223329
size: 999n,
33233330
mtimeNs: 7n,
33243331
ctimeNs: 8n,
3325-
} as unknown as Awaited<ReturnType<typeof fs.stat>>)
3332+
} as unknown as BigIntStats)
33263333

33273334
await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError)
33283335

@@ -3333,6 +3340,70 @@ describe("DiffViewProvider", () => {
33333340
expect(diffViewProvider["sessionFinalizationClaimed"]).toBe(true)
33343341
})
33353342

3343+
it("revertChanges() binds the rollback publish to the version it checked (barrier)", async () => {
3344+
// Barrier: the rollback reads the disk version, a peer publishes while that
3345+
// read is in flight, and the publish must still be bound to the checked
3346+
// version. The old check-then-save wrote originalContent over the peer
3347+
// regardless of what the check found; the compare-and-swap re-reads the
3348+
// version under the lock at publish time, sees the peer token, and leaves
3349+
// the peer bytes on disk.
3350+
const cleanEditor = {
3351+
document: {
3352+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
3353+
getText: vi.fn().mockReturnValue("new content"),
3354+
lineCount: 0,
3355+
encoding: "utf8",
3356+
isDirty: false,
3357+
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
3358+
save: vi.fn().mockResolvedValue(undefined),
3359+
},
3360+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3361+
edit: vi.fn().mockResolvedValue(true),
3362+
revealRange: vi.fn(),
3363+
} as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface.
3364+
diffViewProvider["activeDiffEditor"] = cleanEditor
3365+
diffViewProvider["relPath"] = "test.ts"
3366+
diffViewProvider.editType = "modify"
3367+
diffViewProvider["originalContent"] = "original"
3368+
diffViewProvider["lastWrittenToken"] = versionTokenOfStat(previewStats)
3369+
const peerStats = {
3370+
...previewStats,
3371+
size: 999n,
3372+
mtimeNs: 7n,
3373+
ctimeNs: 8n,
3374+
} as unknown as BigIntStats
3375+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
3376+
let releasePeer: () => void = () => {}
3377+
const peerWindow = new Promise<void>((resolve) => {
3378+
releasePeer = resolve
3379+
})
3380+
vi.mocked(computeVersionToken).mockImplementation(async () => {
3381+
// The rollback's authoritative version read pauses here; the test lets
3382+
// a peer publish land inside the pause, and the read returns the peer
3383+
// version the publish then has to be compared against.
3384+
await peerWindow
3385+
return versionTokenOfStat(peerStats)
3386+
})
3387+
3388+
const revert = diffViewProvider.revertChanges()
3389+
while (vi.mocked(computeVersionToken).mock.calls.length === 0) {
3390+
await new Promise((resolve) => setImmediate(resolve))
3391+
}
3392+
// The peer publishes while the rollback is mid-check.
3393+
vi.mocked(fs.stat).mockResolvedValue(peerStats)
3394+
releasePeer()
3395+
3396+
// The publish rejected on the peer version and named it as the conflict.
3397+
await expect(revert).rejects.toMatchObject({
3398+
name: "RollbackConflictError",
3399+
diskToken: versionTokenOfStat(peerStats),
3400+
})
3401+
// The peer's content remains: the rollback never published over the peer
3402+
// and never touched the buffer.
3403+
expect(safeWriteText).not.toHaveBeenCalledWith(expect.any(String), "original")
3404+
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
3405+
})
3406+
33363407
it("reports a peer publish that landed after a real successful save as a rollback conflict", async () => {
33373408
// The rollback baseline must come from this session's own publish: a real
33383409
// saveChanges() records the token its publish left on disk, so a peer that
@@ -3360,12 +3431,16 @@ describe("DiffViewProvider", () => {
33603431
diffViewProvider.editType = "modify"
33613432
diffViewProvider["originalContent"] = "original"
33623433
// No manual lastWrittenToken: the successful save above must have recorded it.
3363-
vi.mocked(fs.stat).mockResolvedValue({
3434+
const peerStats = {
33643435
...previewStats,
33653436
size: 999n,
33663437
mtimeNs: 7n,
33673438
ctimeNs: 8n,
3368-
} as unknown as Awaited<ReturnType<typeof fs.stat>>)
3439+
} as unknown as BigIntStats
3440+
vi.mocked(fs.stat).mockResolvedValue(peerStats)
3441+
// The rollback compare-and-swap reads the version through the same source
3442+
// the publish uses: the peer token, not this session token.
3443+
vi.mocked(computeVersionToken).mockResolvedValue(versionTokenOfStat(peerStats))
33693444

33703445
await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError)
33713446
expect(vscode.workspace.applyEdit).not.toHaveBeenCalled()
@@ -3428,13 +3503,46 @@ describe("DiffViewProvider", () => {
34283503
size: 999n,
34293504
mtimeNs: 7n,
34303505
ctimeNs: 8n,
3431-
} as unknown as Awaited<ReturnType<typeof fs.stat>>)
3506+
} as unknown as BigIntStats)
34323507

34333508
await expect(diffViewProvider.revertChanges()).rejects.toBeInstanceOf(RollbackConflictError)
34343509

34353510
expect(fs.unlink).not.toHaveBeenCalled()
34363511
})
34373512

3513+
it("revertChanges() deletes the create placeholder without saving the diff buffer first", async () => {
3514+
// Saving the dirty diff buffer before the delete would publish the
3515+
// cancelled edit's content to disk for one moment before removing it -
3516+
// a write the rollback never intended and one that is not bound to the
3517+
// placeholder check. The delete must be the only disk action.
3518+
const documentSave = vi.fn().mockResolvedValue(undefined)
3519+
const dirtyEditor = {
3520+
document: {
3521+
uri: { fsPath: `${mockCwd}/test.ts`, scheme: "file" },
3522+
getText: vi.fn().mockReturnValue("placeholder content"),
3523+
lineCount: 0,
3524+
encoding: "utf8",
3525+
isDirty: true,
3526+
positionAt: vi.fn().mockReturnValue({ line: 0, character: 0 }),
3527+
save: documentSave,
3528+
},
3529+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3530+
edit: vi.fn().mockResolvedValue(true),
3531+
revealRange: vi.fn(),
3532+
} as unknown as vscode.TextEditor // Structural double: the rollback only reads document/tab surface.
3533+
diffViewProvider["activeDiffEditor"] = dirtyEditor
3534+
diffViewProvider["relPath"] = "test.ts"
3535+
diffViewProvider.editType = "create"
3536+
diffViewProvider["placeholderVersion"] = versionTokenOfStat(previewStats)
3537+
// The path still carries this session's placeholder token.
3538+
vi.mocked(fs.stat).mockResolvedValue(previewStats)
3539+
3540+
await diffViewProvider.revertChanges()
3541+
3542+
expect(documentSave).not.toHaveBeenCalled()
3543+
expect(fs.unlink).toHaveBeenCalledWith(`${mockCwd}/test.ts`)
3544+
})
3545+
34383546
it("a cancellation that lands after the rejected-save cleanup skips the rollback and finalizes", async () => {
34393547
// The discard cleanup reloaded the newer disk content and closed this
34403548
// session's views. A rollback after it would apply originalContent and save

0 commit comments

Comments
 (0)