Skip to content

Commit 81d16f3

Browse files
easonliang28easonLiangWorldedtech
authored andcommitted
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 413fa01 commit 81d16f3

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
@@ -1154,6 +1154,28 @@ describe("DiffViewProvider", () => {
11541154
expect(safeWriteText).toHaveBeenCalledWith(`${mockCwd}/test.ts`, "new content")
11551155
})
11561156

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

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

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

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

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

0 commit comments

Comments
 (0)