Skip to content

Commit d8adce3

Browse files
Claude Agentclaude
andcommitted
fix(opencode): converge cancel and remove cascades against racing spawns
Two escape windows in the nested-agent teardown paths: - SessionRunState.cancelBackgroundJobs took a one-shot background.list() snapshot, so jobs started detached while the cascade ran escaped the cancel. The cascade now re-lists until a fresh snapshot has no new running matches (pass cap 5); the reachability frontier persists across passes. - Session.remove listed children once, so a child created inside the deletion window survived as an orphan and became a new root, resetting depth/tree limits relative to the leaked subtree. The cascade now re-lists children until empty (pass cap 5). Regression tests simulate the windows deterministically via interrupt finalizers: cancelling a job starts a late detached job / creates a late child, and BackgroundJob.cancel awaits the finalizer before the cascade continues. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 9f0406b commit d8adce3

3 files changed

Lines changed: 117 additions & 23 deletions

File tree

‎packages/opencode/src/session/run-state.ts‎

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,22 @@ export const defaultLayer = layer.pipe(
122122
Layer.provide(SessionStatus.defaultLayer),
123123
)
124124

125+
// Convergence cap for the cancel cascade's re-listing passes: jobs that
126+
// start detached while the cascade runs escape a one-shot list() snapshot,
127+
// so the cascade re-lists until a fresh snapshot has no new running matches.
128+
// The cap bounds a pathological spawn loop fighting the cancel.
129+
const CANCEL_PASS_CAP = 5
130+
125131
const cancelBackgroundJobs = Effect.fn("SessionRunState.cancelBackgroundJobs")(function* (
126132
background: BackgroundJob.Interface,
127133
sessionID: SessionID,
128134
seedSessionIDs?: ReadonlyArray<SessionID>,
129135
) {
130-
const jobs = yield* background.list()
131136
// The reachable frontier: the cancelled session, the optional seeds (the
132137
// session tree's descendants — the second cancel source for mid-tree
133138
// cancels whose job metadata chain is broken), and every session/job the
134-
// metadata chain (parentSessionId → sessionId) reaches from there.
139+
// metadata chain (parentSessionId → sessionId) reaches from there. It
140+
// persists across passes — reachability only ever grows.
135141
const pending = new Set<string>([sessionID, ...(seedSessionIDs ?? [])])
136142
const reaches = (job: BackgroundJob.Info) => {
137143
if (pending.has(job.id)) return true
@@ -141,26 +147,30 @@ const cancelBackgroundJobs = Effect.fn("SessionRunState.cancelBackgroundJobs")(f
141147
if (typeof job.metadata?.rootSessionId === "string" && pending.has(job.metadata.rootSessionId)) return true
142148
return typeof job.metadata?.parentSessionId === "string" && pending.has(job.metadata.parentSessionId)
143149
}
144-
// Expansion to a fixpoint over ALL job records — a completed mid-tree job
145-
// still bridges the chain to its children (the release race: the middle
146-
// task finished while its grandchild is still running). Only running jobs
147-
// are cancelled below; completed ones serve purely as bridges.
148-
let changed = true
149-
while (changed) {
150-
changed = false
151-
for (const job of jobs) {
152-
if (!reaches(job)) continue
153-
const before = pending.size
154-
pending.add(job.id)
155-
if (typeof job.metadata?.sessionId === "string") pending.add(job.metadata.sessionId)
156-
if (pending.size > before) changed = true
150+
const cancelled = new Set<string>()
151+
for (let pass = 0; pass < CANCEL_PASS_CAP; pass++) {
152+
const jobs = yield* background.list()
153+
// Expansion to a fixpoint over ALL job records — a completed mid-tree job
154+
// still bridges the chain to its children (the release race: the middle
155+
// task finished while its grandchild is still running). Only running jobs
156+
// are cancelled below; completed ones serve purely as bridges.
157+
let changed = true
158+
while (changed) {
159+
changed = false
160+
for (const job of jobs) {
161+
if (!reaches(job)) continue
162+
const before = pending.size
163+
pending.add(job.id)
164+
if (typeof job.metadata?.sessionId === "string") pending.add(job.metadata.sessionId)
165+
if (pending.size > before) changed = true
166+
}
157167
}
168+
const targets = jobs.filter((job) => job.status === "running" && reaches(job) && !cancelled.has(job.id))
169+
// Converged: the fresh snapshot has no new running matches.
170+
if (targets.length === 0) return
171+
for (const job of targets) cancelled.add(job.id)
172+
yield* Effect.forEach(targets, (job) => background.cancel(job.id), { concurrency: "unbounded", discard: true })
158173
}
159-
yield* Effect.forEach(
160-
jobs.filter((job) => job.status === "running" && reaches(job)),
161-
(job) => background.cancel(job.id),
162-
{ concurrency: "unbounded", discard: true },
163-
)
164174
})
165175

166176
function busyError(sessionID: SessionID) {

‎packages/opencode/src/session/session.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -706,6 +706,9 @@ export const layer: Layer.Layer<
706706
// below it (HARD_MAX_DEPTH levels × the per-tree spawn cap).
707707
const DESCENDANTS_CAP = 10_000
708708

709+
// Convergence cap for remove's children re-listing; see remove below.
710+
const REMOVE_CHILDREN_PASS_CAP = 5
711+
709712
const descendants: Interface["descendants"] = Effect.fn("Session.descendants")(function* (sessionID: SessionID) {
710713
const seen = new Set<SessionID>([sessionID])
711714
const result: Info[] = []
@@ -734,9 +737,17 @@ export const layer: Layer.Layer<
734737
)
735738

736739
if (hasInstance) yield* cancelBackgroundJobs(background, sessionID)
737-
const kids = yield* children(sessionID)
738-
for (const child of kids) {
739-
yield* remove(child.id)
740+
// Children are re-listed to convergence: a spawn racing the remove
741+
// cascade can insert a child after a one-shot children() snapshot,
742+
// leaving it behind as an orphan — and orphans count as roots, so
743+
// depth/tree limits would reset relative to the leaked subtree. The
744+
// cap bounds a pathological spawn loop fighting the removal.
745+
for (let pass = 0; pass < REMOVE_CHILDREN_PASS_CAP; pass++) {
746+
const kids = yield* children(sessionID)
747+
if (kids.length === 0) break
748+
for (const child of kids) {
749+
yield* remove(child.id)
750+
}
740751
}
741752

742753
yield* events.publish(SessionV1.Event.Deleted, { sessionID, info: session })

‎packages/opencode/test/session/nested-cancel.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,42 @@ describe("session.nested-cancel cancelBackgroundJobs", () => {
159159
expect((yield* jobs.get(otherChild.id))?.status).toBe("running")
160160
}),
161161
)
162+
163+
it.instance("cancel cascade converges on jobs started detached during the cascade", () =>
164+
Effect.gen(function* () {
165+
const jobs = yield* BackgroundJob.Service
166+
const runState = yield* SessionRunState.Service
167+
const { root, child, grandchild } = yield* seedTree()
168+
169+
// The escape window: cancelling the child's job starts a fresh detached
170+
// job under the tree from its interrupt finalizer — i.e. after the
171+
// cascade took its list() snapshot. BackgroundJob.cancel closes the job
172+
// scope and awaits the finalizer, so the late job deterministically
173+
// exists (and runs) before the cascade's next step.
174+
yield* jobs.start({
175+
id: child.id,
176+
type: "task",
177+
metadata: { parentSessionId: root.id, sessionId: child.id },
178+
run: Effect.never.pipe(
179+
Effect.onInterrupt(() =>
180+
jobs.start({
181+
id: grandchild.id,
182+
type: "task",
183+
metadata: { parentSessionId: child.id, sessionId: grandchild.id },
184+
run: Effect.never,
185+
}),
186+
),
187+
),
188+
})
189+
190+
yield* runState.cancel(root.id)
191+
192+
expect((yield* jobs.get(child.id))?.status).toBe("cancelled")
193+
// A one-shot snapshot lets the late job escape; the cascade must
194+
// re-list to convergence.
195+
expect((yield* jobs.get(grandchild.id))?.status).toBe("cancelled")
196+
}),
197+
)
162198
})
163199

164200
describe("session.nested-cancel SessionPrompt.cancel", () => {
@@ -231,4 +267,41 @@ describe("session.nested-cancel remove", () => {
231267
expect(after.length).toBe(0)
232268
}),
233269
)
270+
271+
it.instance("remove converges on children spawned inside the deletion window", () =>
272+
Effect.gen(function* () {
273+
const jobs = yield* BackgroundJob.Service
274+
const sessions = yield* Session.Service
275+
const { root, child } = yield* seedTree()
276+
277+
// The deletion window: the cascade's recursive remove(child) cancels the
278+
// child's job, whose interrupt finalizer creates a NEW child under the
279+
// root — after the root's children() snapshot was already taken.
280+
// BackgroundJob.cancel awaits the finalizer, so the late child
281+
// deterministically exists before the cascade returns to the root.
282+
const late: { id?: SessionID } = {}
283+
yield* jobs.start({
284+
id: child.id,
285+
type: "task",
286+
metadata: { sessionId: child.id },
287+
run: Effect.never.pipe(
288+
Effect.onInterrupt(() =>
289+
Effect.gen(function* () {
290+
const info = yield* sessions.create({ parentID: root.id, title: "late child" })
291+
late.id = info.id
292+
}),
293+
),
294+
),
295+
})
296+
297+
yield* sessions.remove(root.id)
298+
299+
// The late child must have been created inside the window…
300+
expect(late.id).toBeDefined()
301+
// …and the cascade must not leave it behind as an orphan that would
302+
// become a new root (resetting depth/tree limits for its subtree).
303+
expect(Option.isNone(yield* sessions.get(late.id!).pipe(Effect.option))).toBe(true)
304+
expect(yield* sessions.children(root.id)).toEqual([])
305+
}),
306+
)
234307
})

0 commit comments

Comments
 (0)