Skip to content

Commit a5764dd

Browse files
committed
fix(checkpoints): address CodeRabbit review feedback (PR 1406)
1 parent 7b83143 commit a5764dd

2 files changed

Lines changed: 124 additions & 33 deletions

File tree

‎src/core/tools/ApplyPatchTool.ts‎

Lines changed: 53 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { formatResponse } from "../prompts/responses"
1111
import { RecordSource } from "../context-tracking/FileContextTrackerTypes"
1212
import { fileExistsAtPath } from "../../utils/fs"
1313
import { EXPERIMENT_IDS, experiments } from "../../shared/experiments"
14-
import { sanitizeUnifiedDiff, computeDiffStats } from "../diff/stats"
14+
import { sanitizeUnifiedDiff, computeDiffStats, type DiffStats } from "../diff/stats"
1515
import { BaseTool, ToolCallbacks } from "./BaseTool"
1616
import type { ToolUse } from "../../shared/tools"
1717
import { parsePatch, ParseError, processAllHunks } from "./apply-patch"
@@ -26,11 +26,13 @@ interface ApplyPatchParams {
2626
* the whole-patch success state (and therefore the per-patch checkpoint),
2727
* while `wrote` records whether the operation actually wrote a file — a no-op
2828
* update must not produce a change-journal entry for a file that was never
29-
* written.
29+
* written. `diffStats` carries the approval-diff statistics of a written file
30+
* so the journal entry can report the size of the change.
3031
*/
3132
interface ApplyPatchFileOpResult {
3233
succeeded: boolean
3334
wrote: boolean
35+
diffStats?: DiffStats
3436
}
3537

3638
export class ApplyPatchTool extends BaseTool<"apply_patch"> {
@@ -121,7 +123,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
121123
// — a no-op update must not be journaled). A rejected approval or a
122124
// failed local write never gets checkpointed as a success.
123125
let patchSucceeded = true
124-
const successfulChanges: ApplyPatchFileChange[] = []
126+
const successfulChanges: { change: ApplyPatchFileChange; diffStats?: DiffStats }[] = []
125127
for (const change of changes) {
126128
const relPath = change.path
127129
const absolutePath = path.resolve(task.cwd, relPath)
@@ -144,17 +146,30 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
144146

145147
if (change.type === "add") {
146148
// Create new file
147-
const addResult = await this.handleAddFile(change, absolutePath, relPath, task, callbacks, isWriteProtected)
149+
const addResult = await this.handleAddFile(
150+
change,
151+
absolutePath,
152+
relPath,
153+
task,
154+
callbacks,
155+
isWriteProtected,
156+
)
148157
patchSucceeded = addResult.succeeded && patchSucceeded
149158
if (addResult.wrote) {
150-
successfulChanges.push(change)
159+
successfulChanges.push({ change, diffStats: addResult.diffStats })
151160
}
152161
} else if (change.type === "delete") {
153162
// Delete file
154-
const deleteResult = await this.handleDeleteFile(absolutePath, relPath, task, callbacks, isWriteProtected)
163+
const deleteResult = await this.handleDeleteFile(
164+
absolutePath,
165+
relPath,
166+
task,
167+
callbacks,
168+
isWriteProtected,
169+
)
155170
patchSucceeded = deleteResult.succeeded && patchSucceeded
156171
if (deleteResult.wrote) {
157-
successfulChanges.push(change)
172+
successfulChanges.push({ change, diffStats: deleteResult.diffStats })
158173
}
159174
} else if (change.type === "update") {
160175
// Update file (a no-op update succeeds without writing)
@@ -168,7 +183,7 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
168183
)
169184
patchSucceeded = updateResult.succeeded && patchSucceeded
170185
if (updateResult.wrote) {
171-
successfulChanges.push(change)
186+
successfulChanges.push({ change, diffStats: updateResult.diffStats })
172187
}
173188
}
174189
}
@@ -194,23 +209,38 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
194209
const perWriteCheckpoints = (await task.providerRef?.deref()?.getState())?.perWriteCheckpoints
195210
if (perWriteCheckpoints !== false) {
196211
// B2: one journal entry per file that was actually written by
197-
// the patch (the simplest correct design for multi-file patches),
212+
// the patch (the simplest correct design for multi-file patches),
198213
// all referencing the single checkpoint above. A no-op update
199214
// contributes no entry because nothing was written. `movePath`,
200-
// when present, is the file's final location. diffStats is
201-
// omitted: the per-file approval diffs are computed inside the
202-
// handlers and are not retained after the patch completes.
203-
void checkpointSave(
215+
// when present, is the file's final location. Each entry
216+
// carries the approval-diff statistics the handler computed.
217+
// Await so the checkpoint (staging + commit + journal)
218+
// completes before queued messages are processed below;
219+
// otherwise a queued write's own checkpoint could interleave
220+
// with this commit.
221+
await checkpointSave(
204222
task,
205223
false,
206224
true,
207-
successfulChanges.map((change) => ({
225+
successfulChanges.map(({ change, diffStats }) => ({
208226
path: change.movePath ?? change.path,
209227
operation: change.type === "add" ? "create" : change.type,
228+
diffStats: diffStats
229+
? { additions: diffStats.added, deletions: diffStats.removed }
230+
: undefined,
210231
})),
211232
).catch(() => {})
212233
}
213234
}
235+
236+
// B2: deferred from the per-file handlers — a queued write must not
237+
// start until the post-patch checkpoint above has persisted. The
238+
// handlers used to process queued messages right after each
239+
// successful write; a write happened if and only if
240+
// `successfulChanges` is non-empty, so one call here preserves that.
241+
if (successfulChanges.length > 0) {
242+
task.processQueuedMessages()
243+
}
214244
} catch (error) {
215245
await handleError("apply patch", error as Error)
216246
await task.diffViewProvider.reset()
@@ -306,8 +336,9 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
306336
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, true)
307337
pushToolResult(message)
308338
await task.diffViewProvider.reset()
309-
task.processQueuedMessages()
310-
return { succeeded: true, wrote: true }
339+
// B2: processQueuedMessages is deferred to execute()'s post-patch hook
340+
// so it runs only after the post-patch checkpoint has completed.
341+
return { succeeded: true, wrote: true, diffStats }
311342
}
312343

313344
private async handleDeleteFile(
@@ -364,7 +395,8 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
364395

365396
task.didEditFile = true
366397
pushToolResult(`Successfully deleted ${relPath}`)
367-
task.processQueuedMessages()
398+
// B2: processQueuedMessages is deferred to execute()'s post-patch hook
399+
// so it runs only after the post-patch checkpoint has completed.
368400
return { succeeded: true, wrote: true }
369401
}
370402

@@ -544,14 +576,15 @@ export class ApplyPatchTool extends BaseTool<"apply_patch"> {
544576
const message = await task.diffViewProvider.pushToolWriteResult(task, task.cwd, false)
545577
pushToolResult(message)
546578
await task.diffViewProvider.reset()
547-
task.processQueuedMessages()
579+
// B2: processQueuedMessages is deferred to execute()'s post-patch hook
580+
// so it runs only after the post-patch checkpoint has completed.
548581
if (!moveSucceeded) {
549582
// The destination file was written on disk before the source
550583
// deletion failed, so the write must still be checkpointed and
551584
// journaled; the move itself is reported as failed.
552-
return { succeeded: false, wrote: true }
585+
return { succeeded: false, wrote: true, diffStats }
553586
}
554-
return { succeeded: true, wrote: true }
587+
return { succeeded: true, wrote: true, diffStats }
555588
}
556589

557590
override async handlePartial(task: Task, block: ToolUse<"apply_patch">): Promise<void> {

‎src/core/tools/__tests__/applyPatchTool.execute.spec.ts‎

Lines changed: 71 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,37 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
195195
expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch")
196196
expect(mockedCheckpointSave).not.toHaveBeenCalled()
197197
})
198+
199+
it("awaits the post-patch checkpoint before processing queued messages", async () => {
200+
// A pending checkpoint must not let queued messages (and the
201+
// writes they trigger) start first: execute() awaits the
202+
// post-patch checkpointSave and only then processes queued
203+
// messages, so a queued write's own checkpoint cannot interleave
204+
// with this commit.
205+
const order: string[] = []
206+
;(mockTask.processQueuedMessages as MockedFunction<() => void>).mockImplementation(() => {
207+
order.push("processQueuedMessages")
208+
})
209+
mockedCheckpointSave.mockImplementationOnce(() => {
210+
order.push("checkpointSave:start")
211+
return new Promise<void>((resolve) => {
212+
setTimeout(() => {
213+
order.push("checkpointSave:done")
214+
resolve()
215+
}, 10)
216+
}).then(() => undefined)
217+
})
218+
219+
await tool.execute({ patch: deletePatch }, mockTask as Task, {
220+
askApproval: mockAskApproval,
221+
handleError: mockHandleError,
222+
pushToolResult: mockPushToolResult,
223+
})
224+
225+
// The checkpoint fully completes before queued messages are
226+
// processed.
227+
expect(order).toEqual(["checkpointSave:start", "checkpointSave:done", "processQueuedMessages"])
228+
})
198229
})
199230

200231
describe("checkpoint only for fully successful patches (B1)", () => {
@@ -306,6 +337,11 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
306337

307338
expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully")
308339
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
340+
// B2: the journal entry for a successful add carries the
341+
// approval-diff statistics (two added lines, no removals).
342+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
343+
{ path: "src/new.ts", operation: "create", diffStats: { additions: 2, deletions: 0 } },
344+
])
309345
})
310346

311347
it("does not record a checkpoint when the file to update does not exist", async () => {
@@ -486,6 +522,11 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
486522
"utf8",
487523
)
488524
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
525+
// B2: the journal entry for a successful move is keyed by the
526+
// destination path and carries the approval-diff statistics.
527+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
528+
{ path: "src/moved.ts", operation: "update", diffStats: { additions: 1, deletions: 1 } },
529+
])
489530
})
490531

491532
it("records a checkpoint when the in-place update succeeds", async () => {
@@ -497,12 +538,18 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
497538

498539
expect(mockPushToolResult).toHaveBeenCalledWith("File saved successfully")
499540
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
541+
// B2: the journal entry for a successful update carries the
542+
// approval-diff statistics.
543+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
544+
{ path: "src/test.ts", operation: "update", diffStats: { additions: 1, deletions: 1 } },
545+
])
500546
})
501547

502548
it("records one journal write per file change for a multi-file patch", async () => {
503549
// src/a.ts does not exist (add); src/b.ts does (update).
504550
mockedFileExistsAtPath.mockImplementation((filePath: string) =>
505-
Promise.resolve(!String(filePath).toLowerCase().endsWith("a.ts")))
551+
Promise.resolve(!String(filePath).toLowerCase().endsWith("a.ts")),
552+
)
506553
const multiPatch = [
507554
"*** Begin Patch",
508555
"*** Add File: src/a.ts",
@@ -521,9 +568,11 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
521568
})
522569

523570
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
571+
// B2: each journal entry carries the approval-diff statistics of
572+
// its file change.
524573
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
525-
{ path: "src/a.ts", operation: "create" },
526-
{ path: "src/b.ts", operation: "update" },
574+
{ path: "src/a.ts", operation: "create", diffStats: { additions: 1, deletions: 0 } },
575+
{ path: "src/b.ts", operation: "update", diffStats: { additions: 1, deletions: 1 } },
527576
])
528577
})
529578

@@ -556,7 +605,7 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
556605
// written, even though the whole patch succeeded.
557606
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
558607
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
559-
{ path: "src/new.ts", operation: "create" },
608+
{ path: "src/new.ts", operation: "create", diffStats: { additions: 1, deletions: 0 } },
560609
])
561610
})
562611

@@ -584,10 +633,11 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
584633

585634
// The failed operation is reported to the model...
586635
expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("File already exists"))
587-
// ...and the successful subset is checkpointed and journaled.
636+
// ...and the successful subset is checkpointed and journaled,
637+
// with the written file's diff statistics.
588638
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
589639
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
590-
{ path: "src/second.ts", operation: "create" },
640+
{ path: "src/second.ts", operation: "create", diffStats: { additions: 1, deletions: 0 } },
591641
])
592642
})
593643

@@ -613,14 +663,22 @@ describe("ApplyPatchTool.execute - delete file success path", () => {
613663
// reported as a failed tool error - but the destination write was
614664
// made on disk and must still be covered by the checkpoint/journal.
615665
expect(mockedCheckpointSave).toHaveBeenCalledOnce()
616-
expect(mockedCheckpointSave).toHaveBeenCalledWith(
617-
mockTask as Task,
618-
false,
619-
true,
620-
[expect.objectContaining({ path: "src/new-location.ts", operation: "update" })],
621-
)
666+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
667+
expect.objectContaining({ path: "src/new-location.ts", operation: "update" }),
668+
])
669+
// B2: even a failed move's destination write carries the
670+
// approval-diff statistics in the journal payload.
671+
expect(mockedCheckpointSave).toHaveBeenCalledWith(mockTask as Task, false, true, [
672+
{
673+
path: "src/new-location.ts",
674+
operation: "update",
675+
diffStats: { additions: 1, deletions: 1 },
676+
},
677+
])
622678
expect(mockTask.recordToolError).toHaveBeenCalledWith("apply_patch")
623-
expect(mockPushToolResult).toHaveBeenCalledWith(expect.stringContaining("could not delete the original file"))
679+
expect(mockPushToolResult).toHaveBeenCalledWith(
680+
expect.stringContaining("could not delete the original file"),
681+
)
624682
})
625683
})
626684
})

0 commit comments

Comments
 (0)