Skip to content

Commit 6485f06

Browse files
committed
fix: order cancellation against the guarded publish and session restart
Three teardown-ordering gaps in the interactive save path: - A cancellation that landed while the guarded publish was awaiting could write its rollback underneath the pending commit rename, leaving the cancelled edit as the final content. The provider now registers the in-flight publish, the rollback waits for it to settle, and the save reports no completion of its own when the cancellation claims the session, so the rollback is the last writer. - open() could start a new session while the previous reset() was still finalizing; the old finalization resumed after its awaits and cleared the new session's flags, listeners and deferred scroll timer, and left the new session already claimed. open() now serializes with the prior finalization and teardown, and clears the cancellation claim together with the rest of the teardown marker. - The completeness override on the guarded publish and its saveDirectly forwarding had no focused coverage: add the explicit-true refresh test and the provider-level forwarding test. Chain tracking: issue Zoo-Code-Org#1991 (epic Zoo-Code-Org#1375).
1 parent 41c97d8 commit 6485f06

3 files changed

Lines changed: 241 additions & 5 deletions

File tree

‎src/core/tools/__tests__/guardedWrite.spec.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,26 @@ describe("guardedWrite (S4a, epic #1375)", () => {
433433
expect(mockedSafeWriteText).toHaveBeenCalledTimes(2)
434434
expect(reg.get(abs("doc.txt"))?.complete).toBe(true)
435435
})
436+
it("upgrades a partial observation to complete when the caller carries an explicit completeness", async () => {
437+
// The move onto an existing target: the content was rebuilt from a complete view
438+
// of the file taken outside the read path, so the publish must record completeness
439+
// even though the registry entry came from a partial read. The default refresh
440+
// keeps a partial observation partial (covered above); the explicit true is the
441+
// only spelling that upgrades it, and it must survive the same refresh the
442+
// default and the explicit false use.
443+
const reg = new ObservationRegistry()
444+
reg.observe(abs("moved-onto.txt"), "v1", false)
445+
const task = createMockTask({ observationRegistry: reg })
446+
mockedComputeVersionToken
447+
.mockResolvedValueOnce("v1") // edit pre-write CAS
448+
.mockResolvedValueOnce("v2") // post-publish refresh
449+
450+
await guardedWrite(task, "moved-onto.txt", "full content", "edit", true)
451+
452+
expect(mockedSafeWriteText).toHaveBeenCalledTimes(1)
453+
expect(reg.get(abs("moved-onto.txt"))?.version).toBe("v2")
454+
expect(reg.get(abs("moved-onto.txt"))?.complete).toBe(true)
455+
})
436456

437457
it("keeps the previous observation when the post-publish token cannot be computed (deletion race after publish)", async () => {
438458
const reg = new ObservationRegistry()

‎src/integrations/editor/DiffViewProvider.ts‎

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,14 @@ export class DiffViewProvider {
5050
* diagnostics or read provider state that a cancellation is closing underneath it.
5151
*/
5252
private teardownCancellationRequested = false
53+
/**
54+
* The guarded publish saveChanges() currently has in flight, if any. A cancellation that
55+
* lands while the publish is awaiting cannot be allowed to write its rollback underneath
56+
* the pending commit rename: the rename would land the cancelled edit on top of the
57+
* rollback. revertChanges() waits for this promise before touching the document, so the
58+
* rollback is the last writer and a cancelled save never leaves its edit published.
59+
*/
60+
private guardedSaveInFlight: Promise<unknown> | undefined
5361
/**
5462
* Whether this edit session has been closed (its reset has been claimed). A caller that
5563
* waited for someone else's teardown cannot decide this by reading provider state: isEditing
@@ -146,13 +154,26 @@ export class DiffViewProvider {
146154
}
147155

148156
async open(relPath: string): Promise<void> {
157+
// A new session may not start while the previous one is still finalizing or tearing
158+
// down. performFinalReset() clears the session fields wholesale when it resumes from
159+
// its awaits, so a session started underneath it would lose its flags, listeners and
160+
// deferred scroll timer to the old cleanup - and a runTeardown() still in flight would
161+
// be joined by the new session's first save, skipping that save's own cleanup.
162+
// Serialize: the prior finalization and teardown settle before this session claims
163+
// the provider.
164+
await this.finalizationInFlight?.catch(() => {})
165+
await this.teardownInFlight?.catch(() => {})
149166
this.relPath = relPath
150167
const fileExists = this.editType === "modify"
151168
const absolutePath = path.resolve(this.cwd, relPath)
152169
this.isEditing = true
153170
// A new diff session may reuse this provider after a cancelled one, so the teardown marker
154171
// starts clean: otherwise every later save would report itself cancelled without publishing.
155172
this.teardownPasses = 0
173+
// The cancellation claim belongs to the same marker: a cancellation that joined a pass
174+
// of the previous session and was never read back must not make this session's first
175+
// save report itself cancelled without publishing.
176+
this.teardownCancellationRequested = false
156177
// A new session has to be finalizable: a provider that was reset once would otherwise
157178
// report its finalization as already claimed.
158179
this.sessionFinalizationClaimed = false
@@ -712,7 +733,20 @@ export class DiffViewProvider {
712733
saveTask.observationRegistry.forget(absolutePath)
713734
}
714735
}
715-
await guardedWrite(saveTask, this.relPath, encodedContent, writeKind)
736+
const guardedSave = guardedWrite(saveTask, this.relPath, encodedContent, writeKind)
737+
// Register the publish before awaiting it: a cancellation that lands
738+
// mid-publish waits on this promise (revertChanges) instead of racing its
739+
// rollback against the commit rename. Cleared only while the entry is still
740+
// this save's link, so a retried save's promise is never dropped by an
741+
// earlier save finishing late.
742+
this.guardedSaveInFlight = guardedSave
743+
try {
744+
await guardedSave
745+
} finally {
746+
if (this.guardedSaveInFlight === guardedSave) {
747+
this.guardedSaveInFlight = undefined
748+
}
749+
}
716750
} catch (error) {
717751
// Autosave can publish the modified side of the diff before the user
718752
// accepts, so the bytes on disk may already be exactly what this save
@@ -837,7 +871,11 @@ export class DiffViewProvider {
837871
// already owns this session: that teardown closed the diff views and applied the auto-close
838872
// preferences. Running this save's own post-publish cleanup on top of it would tear the same
839873
// session down twice, so the save reports that it did not complete a save flow of its own.
840-
if (this.teardownPasses > 0) {
874+
// A cancellation that landed during the publish but has not started its pass yet claims
875+
// the session through teardownCancellationRequested before it waits for the publish to
876+
// settle; the claim is the same report, because that rollback - not this save's cleanup -
877+
// will be the last writer to the target.
878+
if (this.teardownPasses > 0 || this.teardownCancellationRequested) {
841879
return { newProblemsMessage: undefined, userEdits: undefined, finalContent: undefined }
842880
}
843881

@@ -1044,6 +1082,19 @@ export class DiffViewProvider {
10441082
return
10451083
}
10461084

1085+
// A guarded publish still in flight owns the target's bytes until it settles: its
1086+
// commit rename can land after a rollback save that started during the publish,
1087+
// leaving the cancelled edit as the final content. Claim the cancellation first - a
1088+
// save that settles underneath this wait sees the claim and reports no completed
1089+
// save instead of running its own post-publish cleanup - then wait for the publish
1090+
// to settle so this rollback is the last writer. A rejected publish wrote nothing,
1091+
// so waiting on a rejection is correct for the same reason.
1092+
this.teardownCancellationRequested = true
1093+
const pendingGuardedSave = this.guardedSaveInFlight
1094+
if (pendingGuardedSave) {
1095+
await pendingGuardedSave.catch(() => {})
1096+
}
1097+
10471098
const fileExists = this.editType === "modify"
10481099
const updatedDocument = this.activeDiffEditor.document
10491100
const absolutePath = path.resolve(this.cwd, this.relPath)

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

Lines changed: 168 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,6 +1155,28 @@ describe("DiffViewProvider", () => {
11551155
expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")
11561156
})
11571157

1158+
it("forwards a caller-supplied completeness through the direct publish", async () => {
1159+
// The move path: the destination's registry entry must carry the completeness
1160+
// the caller earned from the source's view, not the fresh-create default. A
1161+
// fresh create records complete by default, so the discriminating spelling is
1162+
// the explicit false; the explicit true on a second fresh target shows the
1163+
// parameter reaches the refresh in both directions.
1164+
mockTask.observationRegistry.clear()
1165+
vi.mocked(fs.access).mockRejectedValue(enoent())
1166+
1167+
await diffViewProvider.saveDirectly("moved-out.ts", "content", false, false, 0, "create", false)
1168+
expect(mockTask.observationRegistry.get(`${mockCwd}/moved-out.ts`)).toMatchObject({
1169+
version: "v1",
1170+
complete: false,
1171+
})
1172+
1173+
await diffViewProvider.saveDirectly("moved-in.ts", "content", false, false, 0, "create", true)
1174+
expect(mockTask.observationRegistry.get(`${mockCwd}/moved-in.ts`)).toMatchObject({
1175+
version: "v1",
1176+
complete: true,
1177+
})
1178+
})
1179+
11581180
it("rejects an observed write whose version token is stale", async () => {
11591181
// The file changed on disk after the read that recorded "v1".
11601182
vi.mocked(computeVersionToken).mockResolvedValue("v2")
@@ -3256,6 +3278,71 @@ describe("DiffViewProvider", () => {
32563278
expect((diffViewProvider as any).preEditScrollLine).toBeUndefined()
32573279
})
32583280

3281+
it("open() waits for a finalization still in flight before starting the new session", async () => {
3282+
// performFinalReset() clears the session fields when it resumes from its awaits.
3283+
// A session started underneath it would have its flags, listeners and deferred
3284+
// scroll timer wiped by the old cleanup, and the old finalization would leave the
3285+
// new session already claimed. open() has to serialize with the prior finalization.
3286+
let release: () => void = () => {}
3287+
const gate = new Promise<void>((resolve) => {
3288+
release = resolve
3289+
})
3290+
const closeOwnDiffView = vi.fn().mockImplementation(async () => {
3291+
await gate
3292+
})
3293+
diffViewProvider["closeOwnDiffView"] = closeOwnDiffView
3294+
;(diffViewProvider as any).relPath = "old.ts"
3295+
;(diffViewProvider as any).isEditing = true
3296+
3297+
const reset = diffViewProvider.reset()
3298+
while (closeOwnDiffView.mock.calls.length === 0) {
3299+
await new Promise((resolve) => setImmediate(resolve))
3300+
}
3301+
3302+
const mockEditor = {
3303+
document: {
3304+
uri: { fsPath: `${mockCwd}/new.ts`, scheme: "file" },
3305+
getText: vi.fn().mockReturnValue(""),
3306+
lineCount: 0,
3307+
},
3308+
selection: { active: { line: 0, character: 0 }, anchor: { line: 0, character: 0 } },
3309+
edit: vi.fn().mockResolvedValue(true),
3310+
revealRange: vi.fn(),
3311+
}
3312+
vi.mocked(vscode.window).visibleTextEditors = [mockEditor as any]
3313+
vi.mocked(vscode.window.showTextDocument).mockResolvedValue(mockEditor as any)
3314+
vi.mocked(vscode.workspace.onDidOpenTextDocument).mockImplementation((callback) => {
3315+
setTimeout(() => callback({ uri: { fsPath: `${mockCwd}/new.ts`, scheme: "file" } } as any), 0)
3316+
return { dispose: vi.fn() }
3317+
})
3318+
vi.mocked(vscode.window.onDidChangeVisibleTextEditors).mockReturnValue({ dispose: vi.fn() })
3319+
;(diffViewProvider as any).editType = "modify"
3320+
3321+
let openDone = false
3322+
const open = diffViewProvider.open("new.ts").then(() => {
3323+
openDone = true
3324+
})
3325+
await new Promise((resolve) => setImmediate(resolve))
3326+
// The new session has not started: the old finalization still owns the provider.
3327+
expect(openDone).toBe(false)
3328+
expect(closeOwnDiffView).toHaveBeenCalledTimes(1)
3329+
3330+
release()
3331+
await Promise.all([reset, open])
3332+
3333+
// The old finalization completed before the new session claimed the provider, so
3334+
// it could neither clear the new session's flags nor claim its finalization.
3335+
expect(openDone).toBe(true)
3336+
expect((diffViewProvider as any).isEditing).toBe(true)
3337+
expect((diffViewProvider as any).relPath).toBe("new.ts")
3338+
3339+
// The new session is finalizable: its own reset closes it and closes its own
3340+
// diff view - the old finalization's single close did not consume it.
3341+
await diffViewProvider.reset()
3342+
expect((diffViewProvider as any).isEditing).toBe(false)
3343+
expect(closeOwnDiffView).toHaveBeenCalledTimes(2)
3344+
})
3345+
32593346
it("saveChanges() calls revealRange(AtTop) when documentWasOpen and preEditScrollLine is set", async () => {
32603347
const mockRevealRange = vi.fn()
32613348
const mockSavedEditor = { revealRange: mockRevealRange }
@@ -3464,16 +3551,21 @@ describe("DiffViewProvider", () => {
34643551
}),
34653552
})
34663553

3467-
// The cancellation lands inside the guarded publish. The implementation has to be
3468-
// restored afterwards: clearAllMocks() drops call records but keeps queued
3554+
// The cancellation lands while the guarded publish is in flight. It is started
3555+
// without being awaited inside the publish: the rollback waits for the publish to
3556+
// settle before touching the document, so a rollback awaited inside the publish
3557+
// would deadlock against that wait. The implementation has to be restored
3558+
// afterwards: clearAllMocks() drops call records but keeps queued
34693559
// implementations, and a leaked publish would cancel every later save in this file.
3560+
let cancellation: Promise<void> | undefined
34703561
vi.mocked(safeWriteText).mockImplementation(async () => {
3471-
await diffViewProvider.revertChanges()
3562+
cancellation = diffViewProvider.revertChanges()
34723563
})
34733564

34743565
let result: Awaited<ReturnType<DiffViewProvider["saveChanges"]>> | undefined
34753566
try {
34763567
result = await diffViewProvider.saveChanges(false)
3568+
await cancellation
34773569
} finally {
34783570
vi.mocked(safeWriteText).mockReset()
34793571
vi.mocked(safeWriteText).mockResolvedValue(undefined)
@@ -3491,6 +3583,79 @@ describe("DiffViewProvider", () => {
34913583
expect(restorePreviewTabs).toHaveBeenCalledTimes(1)
34923584
})
34933585

3586+
it("a cancellation that lands during the guarded publish waits for it and keeps the rollback last", async () => {
3587+
// The commit rename is the commit point: a rollback that wrote originalContent
3588+
// while the rename was still pending would be overwritten by the cancelled edit.
3589+
// The rollback has to wait for the publish to settle, the save has to report no
3590+
// completion of its own, and the rollback's write must be the last one.
3591+
let release: () => void = () => {}
3592+
const gate = new Promise<void>((resolve) => {
3593+
release = resolve
3594+
})
3595+
let publishEntered = false
3596+
let publishSettled = false
3597+
vi.mocked(safeWriteText).mockImplementation(async () => {
3598+
publishEntered = true
3599+
await gate
3600+
publishSettled = true
3601+
})
3602+
// Records whether the publish had already settled at each rollback write, so
3603+
// the ordering assertion is about the writes themselves, not call counts.
3604+
const rollbackWritesAfterPublishSettled: boolean[] = []
3605+
const closeAllDiffViews = vi.fn().mockResolvedValue(undefined)
3606+
diffViewProvider["closeAllDiffViews"] = closeAllDiffViews
3607+
diffViewProvider["closeFileTab"] = vi.fn().mockResolvedValue(undefined)
3608+
diffViewProvider["restorePreviewTabs"] = vi.fn().mockResolvedValue(undefined)
3609+
const applyEdit = vi.mocked(vscode.workspace.applyEdit)
3610+
applyEdit.mockImplementation(() => {
3611+
rollbackWritesAfterPublishSettled.push(publishSettled)
3612+
return Promise.resolve(true)
3613+
})
3614+
const documentSave = vi.fn().mockImplementation(() => {
3615+
rollbackWritesAfterPublishSettled.push(publishSettled)
3616+
return Promise.resolve(undefined)
3617+
})
3618+
diffViewProvider["relPath"] = "mock-target-file.ts"
3619+
diffViewProvider["editType"] = "modify"
3620+
diffViewProvider["originalContent"] = "original"
3621+
diffViewProvider["newContent"] = "content"
3622+
diffViewProvider["activeDiffEditor"] = makeTextEditor({
3623+
document: makeTextDocument({
3624+
uri: makeUri(mockTargetPath),
3625+
getText: vi.fn().mockReturnValue("content"),
3626+
isDirty: false,
3627+
save: documentSave,
3628+
}),
3629+
})
3630+
3631+
const save = diffViewProvider.saveChanges(false)
3632+
while (!publishEntered) {
3633+
await new Promise((resolve) => setImmediate(resolve))
3634+
}
3635+
3636+
const revert = diffViewProvider.revertChanges()
3637+
await new Promise((resolve) => setImmediate(resolve))
3638+
3639+
// The rollback has not touched the document: the publish still owns the bytes.
3640+
expect(applyEdit).not.toHaveBeenCalled()
3641+
3642+
release()
3643+
const [result] = await Promise.all([save, revert])
3644+
3645+
// Both rollback writes happened after the publish settled, so the final bytes
3646+
// on disk are the rollback's originalContent, not the cancelled edit.
3647+
expect(rollbackWritesAfterPublishSettled).toEqual([true, true])
3648+
expect(result).toEqual({
3649+
newProblemsMessage: undefined,
3650+
userEdits: undefined,
3651+
finalContent: undefined,
3652+
})
3653+
// One pass over the tabs: the save added no cleanup of its own.
3654+
expect(closeAllDiffViews).toHaveBeenCalledTimes(1)
3655+
vi.mocked(safeWriteText).mockReset()
3656+
vi.mocked(safeWriteText).mockResolvedValue(undefined)
3657+
})
3658+
34943659
it("saveChanges() serializes its post-publish cleanup with a revertChanges() that lands during it", async () => {
34953660
// The cleanup closes the same tabs a cancellation would close. Going through the shared
34963661
// teardown state means the cancellation waits for the save instead of racing it.

0 commit comments

Comments
 (0)