Skip to content

Commit 7cb7c1e

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 52c6cb0 commit 7cb7c1e

8 files changed

Lines changed: 384 additions & 70 deletions

File tree

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

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import path from "path"
44

55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
66

7-
import { appendChanges, journalPath, loadChanges, type ChangeJournalEntry } from "../changeJournal"
7+
import { appendChanges, journalPath, journalQueueDepth, loadChanges, type ChangeJournalEntry } from "../changeJournal"
88

99
// appendChange (single-entry wrapper) is production code only in B2; these
1010
// units journal batch writes, so the spec keeps a local helper.
@@ -159,7 +159,7 @@ describe("changeJournal", () => {
159159
} finally {
160160
readSpy.mockRestore()
161161
}
162-
// The failed append wrote nothing: the next append still repairs and loads.
162+
// The failed append wrote nothing: the next append still loads and appends.
163163
await appendChange(tmpRoot, taskId, entry({ checkpointId: "after" }))
164164
const result = await loadChanges(tmpRoot, taskId)
165165
expect(result.map((e) => e.checkpointId)).toEqual(["good", "after"])
@@ -512,7 +512,7 @@ describe("changeJournal", () => {
512512
await appendChange(tmpRoot, taskId, entry({ checkpointId: "first" }))
513513

514514
// Truncate to a single character — definitely invalid JSON. The
515-
// append path repairs such a tail on the next write; a read must
515+
// append path rejects such a tail on the next write; a read must
516516
// not report the lost record as a complete (empty) history.
517517
await fs.writeFile(journalPath(tmpRoot, taskId), "{")
518518

@@ -533,4 +533,24 @@ describe("changeJournal", () => {
533533
expect(result[0].diffStats).toBeUndefined()
534534
})
535535
})
536+
537+
describe("journal queue lifecycle", () => {
538+
it("prunes the per-task queue entry once the update settles", async () => {
539+
const before = journalQueueDepth()
540+
541+
await appendChange(tmpRoot, taskId, entry({ checkpointId: "settled" }))
542+
// The pruning hook runs one microtask after the caller's promise
543+
// settles; drain it before asserting.
544+
await new Promise((resolve) => setImmediate(resolve))
545+
expect(journalQueueDepth()).toBe(before)
546+
547+
// In-flight updates hold their entries; settled ones prune again.
548+
const first = appendChange(tmpRoot, taskId, entry({ checkpointId: "one" }))
549+
const second = appendChange(tmpRoot, "other-task", entry({ checkpointId: "two" }))
550+
expect(journalQueueDepth()).toBe(before + 2)
551+
await Promise.all([first, second])
552+
await new Promise((resolve) => setImmediate(resolve))
553+
expect(journalQueueDepth()).toBe(before)
554+
})
555+
})
536556
})

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

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,22 @@ import path from "path"
55
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from "vitest"
66

77
import type { Task } from "../../task/Task"
8+
import { RepoPerTaskCheckpointService } from "../../../services/checkpoints"
9+
import { checkGitInstalled } from "../../../utils/git"
810
import { journalPath } from "../changeJournal"
911
import { checkpointSave } from "../index"
1012

13+
// The recovery test that must re-initialize reaches RepoPerTaskCheckpointService
14+
// .create; every other test presets a service double or has no storage dir,
15+
// so the factory is only ever called through these mocks.
16+
vi.mock("../../../services/checkpoints", () => ({
17+
RepoPerTaskCheckpointService: { create: vi.fn() },
18+
}))
19+
20+
vi.mock("../../../utils/git", () => ({
21+
checkGitInstalled: vi.fn(),
22+
}))
23+
1124
vi.mock("@roo-code/telemetry", () => ({
1225
TelemetryService: {
1326
instance: {
@@ -45,6 +58,9 @@ function makeTask(options: {
4558
const providerDeref = {
4659
context: { globalStorageUri: options.storageDir === null ? undefined : { fsPath: globalStorageDir } },
4760
getState: vi.fn().mockResolvedValue(options.state ?? {}),
61+
// A re-initialized service sends an init warning through the provider;
62+
// the recovery test that re-initializes reaches it.
63+
postMessageToWebview: vi.fn(),
4864
}
4965

5066
const task = {
@@ -270,10 +286,56 @@ describe("checkpointSave change-card emission (B3a)", () => {
270286

271287
await expect(
272288
checkpointSave(task, false, true, { path: "src/b.ts", operation: "create", diff: "+y" }),
273-
).resolves.toBeDefined()
289+
).resolves.toMatchObject({ commit: "sha-recovered-1" })
274290
expect(task.enableCheckpoints).toBe(true)
275291
const journalRaw = await fs.readFile(journalPath(globalStorageDir, "task-card"), "utf8")
276-
expect(journalRaw).toContain("src/b.ts")
292+
const entries = journalRaw
293+
.split("\n")
294+
.filter((line) => line !== "")
295+
.map((line) => JSON.parse(line))
296+
expect(entries).toEqual([
297+
expect.objectContaining({ path: "src/b.ts", operation: "create", checkpointId: "sha-recovered-1" }),
298+
])
299+
})
300+
301+
it("does not reuse an uninitialized stored service during recovery", async () => {
302+
// A stored service whose shadow-git init never completed must not be
303+
// handed to saveCheckpoint by the recovery path: recovery must clear
304+
// it and re-initialize instead.
305+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
306+
const { task } = makeTask({})
307+
const svc = task.checkpointService as unknown as { saveCheckpoint: Mock; isInitialized: boolean }
308+
svc.saveCheckpoint = vi.fn().mockRejectedValueOnce(new Error("not initialized"))
309+
svc.isInitialized = false
310+
311+
const freshListeners = new Map<string, (...args: unknown[]) => void>()
312+
let freshInit = false
313+
const fresh = {
314+
on: vi.fn((event: string, cb: (...args: unknown[]) => void) => freshListeners.set(event, cb)),
315+
initShadowGit: vi.fn(async () => {
316+
freshInit = true
317+
freshListeners.get("initialize")?.()
318+
}),
319+
get isInitialized() {
320+
return freshInit
321+
},
322+
saveCheckpoint: vi.fn().mockResolvedValue({ commit: "sha-recovered-2" }),
323+
isPathIgnored: vi.fn().mockResolvedValue(false),
324+
}
325+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(fresh as unknown as RepoPerTaskCheckpointService)
326+
327+
await expect(
328+
checkpointSave(task, false, true, { path: "src/a.ts", operation: "create", diff: "+x" }),
329+
).rejects.toThrow(/Checkpoint save failed after a file write/)
330+
expect(task.checkpointsDisabledByFailure).toBe(true)
331+
332+
await expect(
333+
checkpointSave(task, false, true, { path: "src/b.ts", operation: "create", diff: "+y" }),
334+
).resolves.toMatchObject({ commit: "sha-recovered-2" })
335+
// Recovery replaced the dead handle instead of reusing it: the failed
336+
// save ran exactly once and the live handle is the fresh service.
337+
expect(svc.saveCheckpoint).toHaveBeenCalledOnce()
338+
expect(task.checkpointService).toBe(fresh)
277339
})
278340

279341
it("fails a write-metadata save when recovery after an earlier failure cannot re-initialize", async () => {
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
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+
expect(task.checkpointsDisabledByFailure).toBe(true)
96+
})
97+
98+
it("does not store a service when Git is not installed", async () => {
99+
vi.mocked(checkGitInstalled).mockResolvedValue(false)
100+
const svc = serviceDouble(async () => {})
101+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
102+
103+
const task = makeTask()
104+
const service = await getCheckpointService(task)
105+
106+
expect(service).toBeUndefined()
107+
expect(task.checkpointService).toBeUndefined()
108+
expect(task.checkpointServiceInitializing).toBe(false)
109+
expect(task.enableCheckpoints).toBe(false)
110+
})
111+
112+
it("stores an initialized service on the success path", async () => {
113+
vi.mocked(checkGitInstalled).mockResolvedValue(true)
114+
const svc = serviceDouble(async () => {
115+
svc.completeInit()
116+
})
117+
vi.mocked(RepoPerTaskCheckpointService.create).mockReturnValue(svc as unknown as RepoPerTaskCheckpointService)
118+
119+
const task = makeTask()
120+
const service = await getCheckpointService(task)
121+
122+
expect(service).toBe(svc)
123+
expect(task.checkpointService).toBe(svc)
124+
expect(task.checkpointServiceInitializing).toBe(false)
125+
expect(task.enableCheckpoints).toBe(true)
126+
})
127+
})

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

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import path from "path"
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
66

77
import type { Task } from "../../task/Task"
8+
import type { RepoPerTaskCheckpointService } from "../../../services/checkpoints"
89
import type { ChangeJournalEntry } from "../changeJournal"
910
import { getCheckpointService } from "../index"
1011
import * as changeJournal from "../changeJournal"
@@ -18,21 +19,29 @@ vi.mock("../index", () => ({
1819
checkpointDiff: vi.fn(),
1920
}))
2021

21-
const mockedGetCheckpointService = getCheckpointService as unknown as ReturnType<typeof vi.fn>
22+
const mockedGetCheckpointService = vi.mocked(getCheckpointService)
2223

23-
function makeTask(): Task {
24+
/**
25+
* A minimal Task double: the rollback code reads only taskId and
26+
* providerRef.deref(). The double assertion is confined to this factory
27+
* (AGENTS.md last resort - the real Task carries the full session surface)
28+
* so every call site stays typed and cast-free.
29+
*/
30+
function makeTask(provider: unknown = { context: { globalStorageUri: { fsPath: globalStorageDir } } }): Task {
2431
return {
2532
taskId: "task-rollback",
26-
providerRef: {
27-
deref: vi.fn().mockReturnValue({ context: { globalStorageUri: { fsPath: globalStorageDir } } }),
28-
},
33+
providerRef: { deref: vi.fn().mockReturnValue(provider) },
2934
} as unknown as Task
3035
}
3136

32-
/** A checkpoint-service double with a recording restoreFile and a baseline. */
33-
function serviceWith(baseHash: string | undefined) {
37+
/**
38+
* A checkpoint-service double with a recording restoreFile and a baseline.
39+
* The rollback code consumes only these two members; the double assertion
40+
* is confined to this factory so the vi.mocked handle stays typed.
41+
*/
42+
function serviceWith(baseHash: string | undefined): RepoPerTaskCheckpointService {
3443
const restoreFile = vi.fn().mockResolvedValue(undefined)
35-
return { baseHash, restoreFile }
44+
return { baseHash, restoreFile } as unknown as RepoPerTaskCheckpointService
3645
}
3746

3847
async function seedJournal(entries: ChangeJournalEntry[]): Promise<void> {
@@ -123,10 +132,7 @@ describe("rollbackFile (B3c: undo the step's write to the file)", () => {
123132
it("fails when the journal location is unavailable (no global storage)", async () => {
124133
// No context on the provider double → the journal cannot even be
125134
// located: a clear failure, not a silent miss on the file lookup.
126-
const task = {
127-
taskId: "task-rollback",
128-
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
129-
} as unknown as Task
135+
const task = makeTask(null)
130136

131137
const service = serviceWith("base-0")
132138
mockedGetCheckpointService.mockResolvedValue(service)
@@ -186,7 +192,7 @@ describe("rollbackFile (B3c: undo the step's write to the file)", () => {
186192
it("reports the service error without throwing", async () => {
187193
await seedJournal([{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" }])
188194
const service = serviceWith("base-0")
189-
service.restoreFile.mockRejectedValue(new Error("pathspec did not match"))
195+
vi.mocked(service.restoreFile).mockRejectedValue(new Error("pathspec did not match"))
190196
mockedGetCheckpointService.mockResolvedValue(service)
191197

192198
const outcome = await rollbackFile(makeTask(), "sha-1", "src/a.ts")
@@ -198,7 +204,7 @@ describe("rollbackFile (B3c: undo the step's write to the file)", () => {
198204
it("stringifies non-Error rejections into the outcome", async () => {
199205
await seedJournal([{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" }])
200206
const service = serviceWith("base-0")
201-
service.restoreFile.mockRejectedValue("raw failure")
207+
vi.mocked(service.restoreFile).mockRejectedValue("raw failure")
202208
mockedGetCheckpointService.mockResolvedValue(service)
203209

204210
const outcome = await rollbackFile(makeTask(), "sha-1", "src/a.ts")
@@ -237,7 +243,7 @@ describe("rollbackStep (B3c: undo every file of the step)", () => {
237243
{ path: "src/b.ts", operation: "create", checkpointId: "sha-2" },
238244
])
239245
const service = serviceWith("base-0")
240-
service.restoreFile.mockRejectedValueOnce(new Error("pathspec did not match"))
246+
vi.mocked(service.restoreFile).mockRejectedValueOnce(new Error("pathspec did not match"))
241247
mockedGetCheckpointService.mockResolvedValue(service)
242248

243249
const outcome = await rollbackStep(makeTask(), ["src/a.ts", "src/b.ts"], "sha-2")
@@ -327,10 +333,7 @@ describe("rollbackStep (B3c: undo every file of the step)", () => {
327333
// No context on the provider double → the journal cannot even be
328334
// located. That is a failure, not an empty journal: reporting the
329335
// step as merely "not part of this checkpoint" would be misleading.
330-
const task = {
331-
taskId: "task-rollback",
332-
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
333-
} as unknown as Task
336+
const task = makeTask(null)
334337

335338
const service = serviceWith("base-0")
336339
mockedGetCheckpointService.mockResolvedValue(service)
@@ -385,10 +388,7 @@ describe("restoreLatestFile (B3c: forward direction)", () => {
385388
it("fails when the journal location is unavailable (no global storage)", async () => {
386389
// An unavailable journal is not "the task wrote nothing": a no-op
387390
// success would claim a restore that never happened.
388-
const task = {
389-
taskId: "task-rollback",
390-
providerRef: { deref: vi.fn().mockReturnValue(undefined) },
391-
} as unknown as Task
391+
const task = makeTask(null)
392392

393393
const service = serviceWith("base-0")
394394
mockedGetCheckpointService.mockResolvedValue(service)
@@ -476,7 +476,7 @@ describe("restoreLatestFile (B3c: forward direction)", () => {
476476
it("reports the service error without throwing", async () => {
477477
await seedJournal([{ path: "src/a.ts", operation: "create", checkpointId: "sha-1" }])
478478
const service = serviceWith("base-0")
479-
service.restoreFile.mockRejectedValue(new Error("index.lock held"))
479+
vi.mocked(service.restoreFile).mockRejectedValue(new Error("index.lock held"))
480480
mockedGetCheckpointService.mockResolvedValue(service)
481481

482482
const outcome = await restoreLatestFile(makeTask(), "src/a.ts")

0 commit comments

Comments
 (0)