Skip to content

Commit 092a2e9

Browse files
fix(checkpoints): hand an expired caller back to the initialization still in flight
A second lookup waits on the initialization it joined, bounded by its own checkpointTimeout. When that window closed the shared TimeoutError was handled as an initialization failure: the webview was told the initialization had timed out, checkpoints were disabled for the whole task, and the initializing flag was released while the lookup that started the initialization was still awaiting initShadowGit. The released flag let a later lookup create a second RepoPerTaskCheckpointService over the same task directory while the first was still committing, and the disabled flag meant the baseline save that gave up could never be retried on a later loop entry, even if the initialization it waited on succeeded a moment later. Track the in-flight initialization in a per-task map that is cleared only when the operation settles, so a wait that retains the lock until the operation settles or cancellation is confirmed has something to retain: a caller whose own window expires now reports no service with a WAIT_TIMEOUT warning and changes nothing else, and a later lookup joins the same operation instead of racing it into a second shadow git. With no handle left to join the wait still reports an initialization timeout and releases the task, exactly as before. Churn note: git diff --numstat for src/core/checkpoints/index.ts on this commit is 77 added and 34 removed, while git diff -w --numstat on the same commit is 44 added and 1 removed, so about a third of the growth the size instrument charges - extension 321 to 368 against a 500 cap - is the re-indentation the try block and the async closure force, not new logic. The wait could be extracted into a helper to dodge that re-indentation; not done here because 368 against 500 leaves the pull under the size cap and re-cutting to shave indentation churn buys nothing today.
1 parent 53d221e commit 092a2e9

2 files changed

Lines changed: 156 additions & 34 deletions

File tree

‎src/core/checkpoints/__tests__/getCheckpointService.spec.ts‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,82 @@ describe("getCheckpointService initialization failures", () => {
124124
expect(task.enableCheckpoints).toBe(true)
125125
})
126126
})
127+
128+
describe("getCheckpointService initialization handoff", () => {
129+
beforeEach(() => {
130+
vi.mocked(checkGitInstalled).mockReset()
131+
vi.mocked(RepoPerTaskCheckpointService.create).mockReset()
132+
})
133+
134+
it("hands a caller whose own window expired back to the initialization still running", async () => {
135+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
136+
let releaseInit = () => {}
137+
const initGate = new Promise<void>((resolve) => {
138+
releaseInit = resolve
139+
})
140+
const svc = serviceDouble(async () => {
141+
await initGate
142+
svc.completeInit()
143+
})
144+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
145+
146+
const task = makeTask()
147+
const provider = task.providerRef.deref()
148+
// A caller window far shorter than the initialization it joined: the wait is bounded per
149+
// caller, so this one has to give up while the operation it waited on keeps running.
150+
task.checkpointTimeout = 0.05
151+
152+
const started = getCheckpointService(task)
153+
const joined = await getCheckpointService(task, { interval: 10 })
154+
155+
expect(joined).toBeUndefined()
156+
// An expired window is this caller running out of patience, not the initialization failing:
157+
// it reports no service, but it neither ends the initialization it did not start nor takes
158+
// the task's checkpoints away - the save that gave up is retried on a later loop entry.
159+
expect(task.enableCheckpoints).toBe(true)
160+
expect(task.checkpointServiceInitializing).toBe(true)
161+
expect(provider?.postMessageToWebview).toHaveBeenCalledWith({
162+
type: "checkpointInitWarning",
163+
checkpointWarning: { type: "WAIT_TIMEOUT", timeout: 0.05 },
164+
})
165+
expect(provider?.postMessageToWebview).not.toHaveBeenCalledWith({
166+
type: "checkpointInitWarning",
167+
checkpointWarning: { type: "INIT_TIMEOUT", timeout: 0.05 },
168+
})
169+
170+
releaseInit()
171+
172+
const [starter, late] = await Promise.all([started, getCheckpointService(task, { interval: 10 })])
173+
174+
expect(starter).toBe(svc)
175+
// The late lookup joins the operation that was still in flight rather than starting another
176+
// one, so the task ends up with a single shadow git directory and a single service.
177+
expect(late).toBe(svc)
178+
expect(RepoPerTaskCheckpointService.create).toHaveBeenCalledTimes(1)
179+
expect(task.checkpointService).toBe(svc)
180+
})
181+
182+
it("still releases the task when a flag is left with no initialization behind it", async () => {
183+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
184+
const svc = serviceDouble(async () => {})
185+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
186+
187+
const task = makeTask()
188+
const provider = task.providerRef.deref()
189+
task.checkpointTimeout = 0.05
190+
// A released flag with no service behind it and nothing in the in-flight map: there is no
191+
// operation left to join, so the wait can only end in a timeout, and that one is reported
192+
// as the initialization having failed - the behavior this file pins above.
193+
task.checkpointServiceInitializing = true
194+
195+
const service = await getCheckpointService(task, { interval: 10 })
196+
197+
expect(service).toBeUndefined()
198+
expect(task.enableCheckpoints).toBe(false)
199+
expect(RepoPerTaskCheckpointService.create).not.toHaveBeenCalled()
200+
expect(provider?.postMessageToWebview).toHaveBeenCalledWith({
201+
type: "checkpointInitWarning",
202+
checkpointWarning: { type: "INIT_TIMEOUT", timeout: 0.05 },
203+
})
204+
})
205+
})

‎src/core/checkpoints/index.ts‎

Lines changed: 77 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ function sendCheckpointInitWarn(task: Task, type?: "WAIT_TIMEOUT" | "INIT_TIMEOU
2828
})
2929
}
3030

31+
/** In-flight shadow-git initializations per task. Creating the service and running
32+
* initShadowGit is the one checkpoint operation the per-task work queue below does not cover,
33+
* so it carries its own handle: a caller whose own bounded wait expires must not release an
34+
* initialization it did not start, because a released lookup creates a second
35+
* RepoPerTaskCheckpointService over the same task directory while the first is still
36+
* committing. The entry leaves the map only when the operation settles, so a late caller
37+
* either joins it or finds it gone, never both. */
38+
const checkpointInits = new Map<string, Promise<RepoPerTaskCheckpointService | undefined>>()
39+
3140
export async function getCheckpointService(task: Task, { interval = 250 }: { interval?: number } = {}) {
3241
if (!task.enableCheckpoints) {
3342
return undefined
@@ -78,27 +87,45 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int
7887
log,
7988
}
8089

81-
if (task.checkpointServiceInitializing) {
90+
const inFlight = checkpointInits.get(task.taskId)
91+
92+
if (inFlight || task.checkpointServiceInitializing) {
8293
const checkpointInitStartTime = Date.now()
8394
let warningShown = false
8495

85-
await pWaitFor(
86-
() => {
87-
const elapsed = Date.now() - checkpointInitStartTime
88-
89-
// Show warning if we're past the threshold and haven't shown it yet
90-
if (!warningShown && elapsed >= WARNING_THRESHOLD_MS) {
91-
warningShown = true
92-
sendCheckpointInitWarn(task, "WAIT_TIMEOUT", WARNING_THRESHOLD_MS / 1000)
93-
}
94-
95-
console.log(
96-
`[Task#getCheckpointService] waiting for service to initialize (${Math.round(elapsed / 1000)}s)`,
97-
)
98-
return !!task.checkpointService && !!task?.checkpointService?.isInitialized
99-
},
100-
{ interval, timeout: checkpointTimeoutMs },
101-
)
96+
try {
97+
await pWaitFor(
98+
() => {
99+
const elapsed = Date.now() - checkpointInitStartTime
100+
101+
// Show warning if we're past the threshold and haven't shown it yet
102+
if (!warningShown && elapsed >= WARNING_THRESHOLD_MS) {
103+
warningShown = true
104+
sendCheckpointInitWarn(task, "WAIT_TIMEOUT", WARNING_THRESHOLD_MS / 1000)
105+
}
106+
107+
console.log(
108+
`[Task#getCheckpointService] waiting for service to initialize (${Math.round(elapsed / 1000)}s)`,
109+
)
110+
return !!task.checkpointService && !!task?.checkpointService?.isInitialized
111+
},
112+
{ interval, timeout: checkpointTimeoutMs },
113+
)
114+
} catch (error) {
115+
// A handle still in the map means the initialization this caller joined is still
116+
// running: this caller's window closing is that caller's timeout, not the outcome of
117+
// the operation it waited on. Report no service and change nothing else - the caller
118+
// that started the initialization still owns the task's checkpoint state, and a later
119+
// lookup joins the same operation instead of creating a second shadow git for the
120+
// same task.
121+
if (error.name === "TimeoutError" && inFlight) {
122+
sendCheckpointInitWarn(task, "WAIT_TIMEOUT", checkpointTimeoutMs / 1000)
123+
return undefined
124+
}
125+
126+
throw error
127+
}
128+
102129
if (!task?.checkpointService) {
103130
sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout)
104131
task.enableCheckpoints = false
@@ -113,23 +140,39 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int
113140
return undefined
114141
}
115142

116-
const service = RepoPerTaskCheckpointService.create(options)
117-
task.checkpointServiceInitializing = true
118-
await checkGitInstallation(task, service, log, provider)
119-
if (!service.isInitialized) {
120-
// checkGitInstallation disables checkpoints when Git is unavailable and
121-
// logs initShadowGit failures without throwing: storing such a service
122-
// would hand later saves (and the fast path above) an uninitialized
123-
// handle whose isInitialized can never flip, so a failed
124-
// initialization must resolve to no service at all.
125-
task.checkpointServiceInitializing = false
126-
return undefined
127-
}
128-
task.checkpointService = service
129-
if (task.enableCheckpoints) {
130-
sendCheckpointInitWarn(task)
143+
const starting = (async () => {
144+
const service = RepoPerTaskCheckpointService.create(options)
145+
task.checkpointServiceInitializing = true
146+
await checkGitInstallation(task, service, log, provider)
147+
if (!service.isInitialized) {
148+
// checkGitInstallation disables checkpoints when Git is unavailable and
149+
// logs initShadowGit failures without throwing: storing such a service
150+
// would hand later saves (and the fast path above) an uninitialized
151+
// handle whose isInitialized can never flip, so a failed
152+
// initialization must resolve to no service at all.
153+
task.checkpointServiceInitializing = false
154+
return undefined
155+
}
156+
task.checkpointService = service
157+
if (task.enableCheckpoints) {
158+
sendCheckpointInitWarn(task)
159+
}
160+
return service
161+
})()
162+
163+
// Registered before this side awaits anything, so a lookup arriving on the next tick joins
164+
// this initialization instead of racing it into a second service.
165+
checkpointInits.set(task.taskId, starting)
166+
167+
try {
168+
return await starting
169+
} finally {
170+
// Settled is the only moment the operation stops being shared: success or failure, the
171+
// handle leaves the map when the work it names is over, not when a caller loses patience.
172+
if (checkpointInits.get(task.taskId) === starting) {
173+
checkpointInits.delete(task.taskId)
174+
}
131175
}
132-
return service
133176
} catch (err) {
134177
if (err.name === "TimeoutError" && task.enableCheckpoints) {
135178
sendCheckpointInitWarn(task, "INIT_TIMEOUT", task.checkpointTimeout)

0 commit comments

Comments
 (0)