Skip to content

Commit 911ae24

Browse files
easonliang28easonLiangWorldedtech
authored andcommitted
fix(checkpoints): harden task-start baseline and service init per review
- Task: settings-read failure falls back to default-on; baseline done flag set only after a real commit so a no-commit save is retried on a later loop entry - getCheckpointService: never store/return an uninitialized service; clear the initializing flag when initShadowGit fails - checkpointSave (B3+): recovery reuses only an initialized handle - changeJournal (B3+): prune settled journalQueues entries; move and correct the appendChanges/loadChanges doc comments - specs: baseline retry/reject tests, getCheckpointService init-failure regression tests, recovery assertion strengthening, rollback.spec typed doubles, journal queue lifecycle test
1 parent 8865c4a commit 911ae24

4 files changed

Lines changed: 222 additions & 13 deletions

File tree

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest"
2+
3+
import type { Task } from "../../task/Task"
4+
import { RepoPerTaskCheckpointService } from "../../../services/checkpoints"
5+
import { checkGitInstalled } from "../../../utils/git"
6+
import { getCheckpointService } from "../index"
7+
8+
vi.mock("../../../services/checkpoints", () => ({
9+
RepoPerTaskCheckpointService: { create: vi.fn() },
10+
}))
11+
12+
vi.mock("../../../utils/git", () => ({
13+
checkGitInstalled: vi.fn(),
14+
}))
15+
16+
vi.mock("../../../utils/path", () => ({
17+
getWorkspacePath: vi.fn(() => "/workspace"),
18+
}))
19+
20+
vi.mock("../../../i18n", () => ({
21+
t: (key: string) => key,
22+
}))
23+
24+
/**
25+
* Structural service double: getCheckpointService only registers listeners,
26+
* awaits initShadowGit, and reads isInitialized. The double assertion at the
27+
* create() call sites is confined to this file (AGENTS.md last-resort cast):
28+
* the real class carries a Git handle and event surface the test never
29+
* exercises.
30+
*/
31+
function serviceDouble(initShadowGitImpl: () => Promise<void>) {
32+
const listeners = new Map<string, (...args: unknown[]) => void>()
33+
let initialized = false
34+
const svc = {
35+
on: vi.fn((event: string, cb: (...args: unknown[]) => void) => {
36+
listeners.set(event, cb)
37+
}),
38+
initShadowGit: vi.fn(() => initShadowGitImpl()),
39+
get isInitialized() {
40+
return initialized
41+
},
42+
completeInit: () => {
43+
initialized = true
44+
listeners.get("initialize")?.()
45+
},
46+
}
47+
return svc
48+
}
49+
50+
function makeTask(): Task {
51+
return {
52+
taskId: "task-init",
53+
cwd: "/workspace",
54+
enableCheckpoints: true,
55+
checkpointService: undefined,
56+
checkpointServiceInitializing: false,
57+
checkpointTimeout: 1,
58+
providerRef: {
59+
deref: vi.fn().mockReturnValue({
60+
context: { globalStorageUri: { fsPath: "/tmp/b3-init-storage" } },
61+
postMessageToWebview: vi.fn(),
62+
log: vi.fn(),
63+
}),
64+
},
65+
say: vi.fn().mockResolvedValue(undefined),
66+
} as unknown as Task
67+
}
68+
69+
describe("getCheckpointService initialization failures", () => {
70+
beforeEach(() => {
71+
vi.mocked(checkGitInstalled).mockReset()
72+
vi.mocked(RepoPerTaskCheckpointService.create).mockReset()
73+
})
74+
75+
it("does not store a service whose shadow-git initialization failed", async () => {
76+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
77+
const failing = serviceDouble(async () => {
78+
throw new Error("shadow git init exploded")
79+
})
80+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(
81+
failing as unknown as RepoPerTaskCheckpointService,
82+
)
83+
84+
const task = makeTask()
85+
const service = await getCheckpointService(task)
86+
87+
// The failed service must not be stored: a stored uninitialized handle
88+
// would be returned by the fast path to every later save, and the
89+
// initializing flag must not strand later lookups in a wait for an
90+
// initialization that already died.
91+
expect(service).toBeUndefined()
92+
expect(task.checkpointService).toBeUndefined()
93+
expect(task.checkpointServiceInitializing).toBe(false)
94+
expect(task.enableCheckpoints).toBe(false)
95+
})
96+
97+
it("does not store a service when Git is not installed", async () => {
98+
vi.mocked(checkGitInstalled).mockResolvedValue(false)
99+
const svc = serviceDouble(async () => {})
100+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
101+
102+
const task = makeTask()
103+
const service = await getCheckpointService(task)
104+
105+
expect(service).toBeUndefined()
106+
expect(task.checkpointService).toBeUndefined()
107+
expect(task.checkpointServiceInitializing).toBe(false)
108+
expect(task.enableCheckpoints).toBe(false)
109+
})
110+
111+
it("stores an initialized service on the success path", async () => {
112+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
113+
const svc = serviceDouble(async () => {
114+
svc.completeInit()
115+
})
116+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
117+
118+
const task = makeTask()
119+
const service = await getCheckpointService(task)
120+
121+
expect(service).toBe(svc)
122+
expect(task.checkpointService).toBe(svc)
123+
expect(task.checkpointServiceInitializing).toBe(false)
124+
expect(task.enableCheckpoints).toBe(true)
125+
})
126+
})

‎src/core/checkpoints/index.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,15 @@ export async function getCheckpointService(task: Task, { interval = 250 }: { int
113113
const service = RepoPerTaskCheckpointService.create(options)
114114
task.checkpointServiceInitializing = true
115115
await checkGitInstallation(task, service, log, provider)
116+
if (!service.isInitialized) {
117+
// checkGitInstallation disables checkpoints when Git is unavailable and
118+
// logs initShadowGit failures without throwing: storing such a service
119+
// would hand later saves (and the fast path above) an uninitialized
120+
// handle whose isInitialized can never flip, so a failed
121+
// initialization must resolve to no service at all.
122+
task.checkpointServiceInitializing = false
123+
return undefined
124+
}
116125
task.checkpointService = service
117126
if (task.enableCheckpoints) {
118127
sendCheckpointInitWarn(task)
@@ -200,6 +209,10 @@ async function checkGitInstallation(
200209
} catch (err) {
201210
log(`[Task#getCheckpointService] initShadowGit -> ${err.message}`)
202211
task.enableCheckpoints = false
212+
// The "initialize" event never fires for a failed initShadowGit, so
213+
// clear the flag here or later lookups wait on an initialization
214+
// that already died.
215+
task.checkpointServiceInitializing = false
203216
}
204217
} catch (err) {
205218
log(`[Task#getCheckpointService] Unexpected error during Git check: ${err.message}`)

‎src/core/task/Task.ts‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3853,22 +3853,37 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
38533853
// An already-aborted task skips it too: the loop will never run, so the
38543854
// save would only add latency to a task that is being disposed.
38553855
if (!this.taskStartBaselineDone && !this._isHistoryTask && !this.abort) {
3856-
this.taskStartBaselineDone = true
3856+
let baselineEnabled: boolean | undefined
38573857
try {
3858-
const baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints
3859-
// Cancellation can arrive while the state lookup is pending; recheck
3860-
// before the save so a canceled task performs no checkpoint work.
3861-
if (baselineEnabled !== false && !this.abort) {
3858+
baselineEnabled = (await this.providerRef.deref()?.getState())?.perWriteCheckpoints
3859+
} catch (error) {
3860+
// A rejected state lookup must not abort task startup: fall back
3861+
// to the default-on semantics used when the setting is absent.
3862+
console.error("[Task] task-start baseline settings read failed:", error)
3863+
}
3864+
// Cancellation can arrive while the state lookup is pending; recheck
3865+
// before the save so a canceled task performs no checkpoint work.
3866+
if (baselineEnabled === false || this.abort) {
3867+
this.taskStartBaselineDone = true
3868+
} else {
3869+
try {
38623870
// allowEmpty=true so a clean workspace still produces the baseline
38633871
// commit; awaited so the first per-write checkpoint cannot interleave.
3864-
await this.checkpointSave(true, true)
3872+
const baseline = await this.checkpointSave(true, true)
3873+
// The flag is set only once the baseline actually committed: a save
3874+
// that no-ops behind a failed or timed-out service initialization is
3875+
// retried on a later loop entry instead of being marked done without
3876+
// a rollback point.
3877+
if (baseline?.commit) {
3878+
this.taskStartBaselineDone = true
3879+
}
3880+
} catch (error) {
3881+
// The baseline is best-effort and runs before TaskStarted: a
3882+
// checkpoint error must not abort task startup (startTask rethrows
3883+
// non-abort errors from initiateTaskLoop). Log and continue; the
3884+
// next loop entry retries the baseline.
3885+
console.error("[Task] task-start checkpoint baseline failed:", error)
38653886
}
3866-
} catch (error) {
3867-
// The baseline is best-effort and runs before TaskStarted: a rejected
3868-
// state lookup or a checkpoint error must not abort task startup
3869-
// (startTask rethrows non-abort errors from initiateTaskLoop). Log
3870-
// and continue; per-write saves still report their own failures.
3871-
console.error("[Task] task-start checkpoint baseline failed:", error)
38723887
}
38733888
}
38743889

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6833,7 +6833,10 @@ describe("Cline", () => {
68336833
startTask: false,
68346834
})
68356835
const taskAccess = getTaskTestAccess(task)
6836-
const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue(undefined)
6836+
// A committed baseline: the done flag is set only on a real
6837+
// commit, so the double must resolve one for the once-per-instance
6838+
// assertion to exercise the flag flip.
6839+
const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue({ commit: "baseline-commit" })
68376840
const state = await mockProvider.getState()
68386841
vi.spyOn(mockProvider, "getState").mockResolvedValue(state)
68396842

@@ -7016,6 +7019,58 @@ describe("Cline", () => {
70167019
expect(consoleErrorSpy).toHaveBeenCalledWith("[Task] task-start checkpoint baseline failed:", boom)
70177020
consoleErrorSpy.mockRestore()
70187021
})
7022+
7023+
it("retries the baseline on a later loop entry when a save produced no commit", async () => {
7024+
// getCheckpointService can resolve to no service (init failure or a
7025+
// bounded init wait timing out): the save then completes without a
7026+
// commit, and the baseline must not be marked done - a later loop
7027+
// entry gets to retry it instead of losing it forever.
7028+
const task = new Task({
7029+
provider: mockProvider,
7030+
apiConfiguration: mockApiConfig,
7031+
task: "retry baseline task",
7032+
startTask: false,
7033+
})
7034+
const taskAccess = getTaskTestAccess(task)
7035+
const saveSpy = vi
7036+
.spyOn(task, "checkpointSave")
7037+
.mockResolvedValueOnce(undefined)
7038+
.mockResolvedValue({ commit: "baseline-commit" })
7039+
const state = await mockProvider.getState()
7040+
vi.spyOn(mockProvider, "getState").mockResolvedValue(state)
7041+
7042+
vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true)
7043+
7044+
await taskAccess.initiateTaskLoop([])
7045+
expect(saveSpy).toHaveBeenCalledOnce()
7046+
7047+
await taskAccess.initiateTaskLoop([])
7048+
expect(saveSpy).toHaveBeenCalledTimes(2)
7049+
})
7050+
7051+
it("starts the task default-on when the baseline settings read rejects", async () => {
7052+
// ClineProvider.getState awaits custom-mode loading and can reject:
7053+
// a failed settings read must not stop task startup. Default-on
7054+
// semantics apply (the setting is treated as absent) and the loop
7055+
// still runs.
7056+
const task = new Task({
7057+
provider: mockProvider,
7058+
apiConfiguration: mockApiConfig,
7059+
task: "rejected-read baseline task",
7060+
startTask: false,
7061+
})
7062+
const taskAccess = getTaskTestAccess(task)
7063+
const saveSpy = vi.spyOn(task, "checkpointSave").mockResolvedValue({ commit: "baseline-commit" })
7064+
vi.spyOn(mockProvider, "getState").mockRejectedValueOnce(new Error("custom mode load failed"))
7065+
7066+
const requestSpy = vi.spyOn(task, "recursivelyMakeClineRequests").mockResolvedValue(true)
7067+
7068+
await taskAccess.initiateTaskLoop([])
7069+
7070+
expect(saveSpy).toHaveBeenCalledOnce()
7071+
expect(saveSpy).toHaveBeenCalledWith(true, true)
7072+
expect(requestSpy).toHaveBeenCalled()
7073+
})
70197074
})
70207075

70217076
describe("start()", () => {

0 commit comments

Comments
 (0)