Skip to content

Commit 05d01f3

Browse files
authored
refactor(task): route latch and isInitialized writes through events (RSK-06) (#2128)
* refactor(task): route latch and isInitialized writes through run-state events (RSK-06) * test(task): cover the default routed fields in the divergence check
1 parent 13c6f6c commit 05d01f3

8 files changed

Lines changed: 140 additions & 32 deletions

File tree

‎docs/architecture/task-lifecycle-target-architecture.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ Queued user input is out of scope for the kernel. The queued-input bugs (#1308,
245245
7. Abort drain. The chunk loop sees `abort`. If the task is not abandoned, the loop calls `abortStream` (`Task.ts:3492`). Only a non-abandoned abort reaches this call, for example a checkpoint-restore delete or a dispose. `abortStream` sets `didFinishAbortingStream` (`Task.ts:3225`). The `finally` block clears `isStreaming` (`Task.ts:3756`).
246246
8. Stream failure. A stream error without `abort` also calls `abortStream("streaming_failed")` (`Task.ts:3714`), which sets `didFinishAbortingStream` (`Task.ts:3225`). Then the loop retries. It does not abort. The per-request reset block (`Task.ts:3228-3245`) does not reset `didFinishAbortingStream`. Only `resumeAfterDelegation` resets it (`Task.ts:2884`). So the field stays true across later requests (race R-1 below).
247247
9. Completion. `attempt_completion` asks `completion_result` during the turn (`AttemptCompletionTool.ts:221`). The ask is usually still pending after the stream ends. On accept the task ends. On feedback the loop continues.
248-
10. New instance. `reopenParentFromDelegation` builds a new instance and calls `resumeAfterDelegation` (`ClineProvider.ts:4357, 4404`). Latches are per instance. No path reuses an aborted instance. The resets at `Task.ts:2881-2886` write the default values on the new instance.
248+
10. New instance. `reopenParentFromDelegation` builds a new instance and calls `resumeAfterDelegation` (`ClineProvider.ts:4357, 4404`). Latches are per instance. No path reuses an aborted instance. `resumeAfterDelegation` no longer resets the latches. It resets only the stream fields (`Task.ts:2884-2886`).
249249

250250
#### Transitions
251251

‎src/core/task/Task.ts‎

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3090,7 +3090,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
30903090
} catch (error) {
30913091
console.error("[Task#startTask] ignored-disabled-tools notice failed:", error)
30923092
}
3093-
this.isInitialized = true
3093+
this.markInitialized()
30943094

30953095
const imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images)
30963096

@@ -3216,7 +3216,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
32163216
}
32173217

32183218
if (this.pendingAction) {
3219-
this.isInitialized = true
3219+
this.markInitialized()
32203220
await this.resumePendingTaskAction(this.pendingAction)
32213221
return
32223222
}
@@ -3237,7 +3237,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
32373237
askType = "resume_task"
32383238
}
32393239

3240-
this.isInitialized = true
3240+
this.markInitialized()
32413241

32423242
const { response, text, images } = await this.ask(askType) // Calls `postStateToWebview`.
32433243

@@ -3564,11 +3564,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
35643564
}
35653565

35663566
public abortTask(isAbandoned = false): Promise<void> {
3567-
if (isAbandoned) {
3568-
this.abandoned = true
3569-
}
3570-
3571-
this.abort = true
3567+
this.requestAbort(isAbandoned)
35723568
this.cancelAssistantMessagePersistence()
35733569
this.abortPromise ??= this.abortTaskOnce()
35743570
return this.abortPromise
@@ -3656,13 +3652,13 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36563652
}
36573653

36583654
// A task being disposed is no longer serving requests: set the same
3659-
// cancellation state `abortTask()` sets, synchronously before the aborts
3655+
// abort latch `abortTask()` sets (disposal never sets abandoned), synchronously before the aborts
36603656
// below, so the request-construction guard (`abort || abandoned` in
36613657
// attemptApiRequest) and the outer loop's `abort` checks observe disposal
36623658
// even when it lands before any explicit cancel. Without this, only the
36633659
// signals below are cancelled and a request already past those checks
36643660
// could still build tools and call `createMessage()`.
3665-
this.abort = true
3661+
this.requestDispose()
36663662

36673663
// Cancel any in-progress HTTP request
36683664
try {
@@ -3762,7 +3758,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
37623758
*
37633759
* This method:
37643760
* - Clears any pending ask states
3765-
* - Resets abort and streaming flags
3761+
* - Resets streaming flags
37663762
* - Ensures next API call includes full context
37673763
* - Immediately continues task loop without user interaction
37683764
*/
@@ -3772,10 +3768,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
37723768
this.resumableAsk = undefined
37733769
this.interactiveAsk = undefined
37743770

3775-
// Reset abort and streaming state to ensure clean continuation
3776-
this.abort = false
3777-
this.abandoned = false
3778-
this.abortReason = undefined
3771+
// Reset streaming state to ensure clean continuation
37793772
this.didFinishAbortingStream = false
37803773
this.isStreaming = false
37813774
this.isWaitingForFirstChunk = false
@@ -3784,7 +3777,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
37843777
this.skipPrevResponseIdOnce = true
37853778

37863779
// Mark as initialized and active
3787-
this.isInitialized = true
3780+
this.markInitialized()
37883781
this.emit(RooCodeEventName.TaskActive, this.taskId)
37893782

37903783
// Load conversation history if not already loaded
@@ -4665,8 +4658,8 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
46654658
await abortStream(cancelReason, streamingFailedMessage)
46664659

46674660
if (this.abort) {
4668-
// ??= keeps the first reason; a cancel can land during abortStream after cancelReason was already computed.
4669-
this.abortReason ??= "user_cancelled"
4661+
// A cancel can land during abortStream after cancelReason was computed; setAbortReason keeps the first reason.
4662+
this.setAbortReason("user_cancelled")
46704663
await this.abortTask()
46714664
} else if (error instanceof OutputTokenLimitError) {
46724665
// Truncation repeats on an identical request, so never auto-retry it
@@ -4701,7 +4694,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
47014694
console.log(
47024695
`[Task#${this.taskId}.${this.instanceId}] Task aborted during mid-stream retry backoff`,
47034696
)
4704-
this.abortReason ??= "user_cancelled"
4697+
this.setAbortReason("user_cancelled")
47054698
await this.abortTask()
47064699
break
47074700
}

‎src/core/task/__tests__/Task.abort-reason-race.spec.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,8 @@ describe("Task abort-reason race", () => {
165165
const parsed = apiReqMsg?.text ? (JSON.parse(apiReqMsg.text) as { cancelReason?: string }) : {}
166166
if (parsed.cancelReason === "streaming_failed" && !task.didFinishAbortingStream) {
167167
// cancelTask sets abortReason before abort=true.
168-
task["abortReason"] = "user_cancelled"
169-
task["abort"] = true
168+
task.setAbortReason("user_cancelled")
169+
task.requestAbort(false)
170170
}
171171
})
172172

@@ -176,6 +176,7 @@ describe("Task abort-reason race", () => {
176176
expect(task.didFinishAbortingStream).toBe(true)
177177
expect(abortTaskSpy).toHaveBeenCalledOnce()
178178
expect(task.abortReason).toBe("user_cancelled")
179+
expect(task.runState.latches.reason).toBe("user_cancelled")
179180
})
180181

181182
it("keeps pre-existing abortReason when cancel lands during retry backoff", async () => {
@@ -202,8 +203,8 @@ describe("Task abort-reason race", () => {
202203
// Simulate cancel landing during backoff: cancelTask sets abortReason before abort=true.
203204
// Use a distinct seed value so ??= (keeps it) is distinguishable from = (overwrites).
204205
task["backoffAndAnnounce"] = async () => {
205-
task["abortReason"] = "streaming_failed"
206-
task["abort"] = true
206+
task.setAbortReason("streaming_failed")
207+
task.requestAbort(false)
207208
}
208209

209210
const abortTaskSpy = vi.spyOn(task, "abortTask")
@@ -212,5 +213,6 @@ describe("Task abort-reason race", () => {
212213
expect(result).toBe(false)
213214
expect(abortTaskSpy).toHaveBeenCalledOnce()
214215
expect(task.abortReason).toBe("streaming_failed")
216+
expect(task.runState.latches.reason).toBe("streaming_failed")
215217
})
216218
})

‎src/core/task/__tests__/Task.run-shadow.spec.ts‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,30 @@ describe("Task run-state write helpers", () => {
6262
expect(task.runRejections).toEqual([])
6363
})
6464

65+
it("keeps the cancelTask order: reason, abort, then abandon, with no rejections", async () => {
66+
task.setAbortReason("user_cancelled")
67+
await task.abortTask()
68+
task.requestAbandon()
69+
70+
expect(task.runRejections).toEqual([])
71+
expect(task.runState.latches).toEqual({
72+
abort: true,
73+
abandoned: true,
74+
disposed: true,
75+
reason: "user_cancelled",
76+
})
77+
})
78+
79+
it("drives disposeRequested from dispose and keeps the reason", async () => {
80+
task.setAbortReason("user_cancelled")
81+
await task.dispose()
82+
83+
expect(task.abort).toBe(true)
84+
expect(task.runState.latches.disposed).toBe(true)
85+
expect(task.runState.latches.reason).toBe("user_cancelled")
86+
expect(task.runRejections).toEqual([])
87+
})
88+
6589
it("keeps a stale didFinishAbortingStream on the next stream so the kernel mismatch shows race R-1", () => {
6690
task.markInitialized()
6791
task.markStreamStarted()
@@ -163,35 +187,46 @@ describe("Task run-state divergence report", () => {
163187
it("logs and counts a rejected event once when the check is enabled", () => {
164188
const task = makeTask(vscode.ExtensionMode.Test)
165189

166-
task.requestAbandon()
190+
task.markStreamEnded()
167191

168192
expect(divergenceWarnings()).toHaveLength(1)
169193
expect(divergenceWarnings()[0][1]).toMatchObject({
170194
taskId: task.taskId,
171195
kind: "rejection",
172-
event: { tag: "abandonRequested" },
196+
event: { tag: "streamEnded" },
173197
state: initialRunState,
174198
mismatched: [],
175199
})
176200
expect(divergenceMetrics()).toEqual([
177201
[
178202
TelemetryEventName.RUN_STATE_DIVERGENCE,
179-
expect.objectContaining({ taskId: task.taskId, kind: "rejection", eventTag: "abandonRequested" }),
203+
expect.objectContaining({ taskId: task.taskId, kind: "rejection", eventTag: "streamEnded" }),
180204
],
181205
])
182206
})
183207

184208
it("reports a repeated rejection of the same event once per task", () => {
185209
const task = makeTask(vscode.ExtensionMode.Test)
186210

187-
task.requestAbandon()
188-
task.requestAbandon()
211+
task.markStreamEnded()
212+
task.markStreamEnded()
189213

190214
expect(task.runRejections).toHaveLength(2)
191215
expect(divergenceWarnings()).toHaveLength(1)
192216
expect(divergenceMetrics()).toHaveLength(1)
193217
})
194218

219+
it("reports a rejection and an abandoned mismatch when abandon comes before abort", () => {
220+
const task = makeTask(vscode.ExtensionMode.Test)
221+
222+
task.requestAbandon()
223+
224+
const reports = divergenceWarnings().map(([, report]: unknown[]) => report)
225+
expect(reports).toHaveLength(2)
226+
expect(reports).toContainEqual(expect.objectContaining({ kind: "rejection", mismatched: [] }))
227+
expect(reports).toContainEqual(expect.objectContaining({ kind: "mismatch", mismatched: ["abandoned"] }))
228+
})
229+
195230
it("stays silent for a production build on the stable channel", () => {
196231
const task = makeTask(vscode.ExtensionMode.Production)
197232

‎src/core/task/run-state/__tests__/runStateDivergence.spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,25 @@ describe("findDivergences", () => {
8585
expect(divergence.raceId).toBeUndefined()
8686
})
8787

88+
it("compares the latch and phase fields by default and skips the stream fields", () => {
89+
const [divergence, ...rest] = findDivergences({
90+
event: { tag: "initialized" },
91+
state: initialRunState,
92+
fields: {
93+
abort: true,
94+
abandoned: true,
95+
abortReason: "user_cancelled",
96+
isInitialized: true,
97+
isStreaming: true,
98+
didFinishAbortingStream: true,
99+
},
100+
rejected: false,
101+
})
102+
expect(rest).toEqual([])
103+
expect(divergence).toMatchObject({ kind: "mismatch" })
104+
expect([...divergence.mismatched].sort()).toEqual(["abandoned", "abort", "abortReason", "isInitialized"])
105+
})
106+
88107
it("ignores a field that is not routed", () => {
89108
const divergences = findDivergences({
90109
event: { tag: "initialized" },

‎src/core/task/run-state/runStateDivergence.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ export type Divergence = {
1515
mismatched: Array<keyof RunStateFields>
1616
}
1717

18-
export const ROUTED_FIELDS: ReadonlyArray<keyof RunStateFields> = []
18+
export const ROUTED_FIELDS: ReadonlyArray<keyof RunStateFields> = ["abort", "abandoned", "abortReason", "isInitialized"]
1919

2020
export type KnownRace = { id: RaceId; matches: (divergence: Divergence) => boolean }
2121

‎src/core/webview/ClineProvider.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3614,7 +3614,7 @@ export class ClineProvider
36143614
let parentTask = task.parentTask
36153615

36163616
// Mark this as a user-initiated cancellation so provider-only rehydration can occur
3617-
task.abortReason = "user_cancelled"
3617+
task.setAbortReason("user_cancelled")
36183618

36193619
// Capture the current instance to detect if rehydrate already occurred elsewhere
36203620
const originalInstanceId = task.instanceId
@@ -3630,7 +3630,7 @@ export class ClineProvider
36303630
const abortPromise = task.abortTask()
36313631

36323632
// Immediately mark the original instance as abandoned to prevent any residual activity
3633-
task.abandoned = true
3633+
task.requestAbandon()
36343634

36353635
await pWaitFor(
36363636
() =>

0 commit comments

Comments
 (0)