Skip to content

Commit 6ece828

Browse files
Claude Agentclaude
andcommitted
fix(opencode): reserve tree-cap slot synchronously to close the spawn-count race
The tree lifetime gate read `started`, then awaited sessions.create, then wrote back `started + 1` — a lost-update race: N parallel spawns all read the same stale count, systematically undercounting the tree and making SUBAGENT_TREE_LIMIT bypassable. Reserve the slot synchronously in the gate instead (TurnBudget.reserve pattern: no yield between check and set on Bun's single thread) and release it via Effect.onExit when create fails or is interrupted, clamped at zero. Regression tests: 5 parallel spawns against __testHooks.treeLimit = 3 with a deterministic async boundary injected into create (the production I/O window) now yield exactly 3 successes and 2 SubagentTreeLimitErrors with the counter settling at the limit; a failing create releases its slot. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent e0df091 commit 6ece828

2 files changed

Lines changed: 128 additions & 17 deletions

File tree

‎packages/opencode/src/tool/task.ts‎

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -204,24 +204,43 @@ export const TaskTool = Tool.define(
204204
return yield* Effect.fail(SubagentLimits.budgetError())
205205
}
206206
}
207-
const created = yield* sessions.create({
208-
parentID: ctx.sessionID,
209-
title: params.description + ` (@${next.name} subagent)`,
210-
agent: next.name,
211-
permission: [
212-
...childPermission,
213-
...childToolDenies.filter(
214-
(deny) =>
215-
!childPermission.some(
216-
(rule) =>
217-
rule.permission === deny.permission &&
218-
rule.pattern === deny.pattern &&
219-
rule.action === deny.action,
220-
),
221-
),
222-
],
223-
})
207+
// Reserve the slot SYNCHRONOUSLY before the async create (the
208+
// TurnBudget.reserve pattern): Bun is single-threaded and there is
209+
// no yield between the `started` read above and this set, so N
210+
// parallel spawns each observe the updated count. Setting AFTER
211+
// `sessions.create` (the pre-fix order) was a lost-update race —
212+
// every racer wrote back its stale `started + 1` and the cap was
213+
// systematically undercounted. Released again on create failure or
214+
// interrupt so a session that never existed cannot eat the cap.
224215
treeSpawnCounts.set(rootID, started + 1)
216+
const created = yield* sessions
217+
.create({
218+
parentID: ctx.sessionID,
219+
title: params.description + ` (@${next.name} subagent)`,
220+
agent: next.name,
221+
permission: [
222+
...childPermission,
223+
...childToolDenies.filter(
224+
(deny) =>
225+
!childPermission.some(
226+
(rule) =>
227+
rule.permission === deny.permission &&
228+
rule.pattern === deny.pattern &&
229+
rule.action === deny.action,
230+
),
231+
),
232+
],
233+
})
234+
.pipe(
235+
Effect.onExit((exit) =>
236+
Exit.isSuccess(exit)
237+
? Effect.void
238+
: Effect.sync(() => {
239+
const current = treeSpawnCounts.get(rootID) ?? 0
240+
treeSpawnCounts.set(rootID, Math.max(0, current - 1))
241+
}),
242+
),
243+
)
225244
return created
226245
}))
227246

‎packages/opencode/test/tool/task.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,6 +1171,98 @@ describe("tool.task tree cap", () => {
11711171
),
11721172
),
11731173
)
1174+
1175+
it.instance("enforces the cap atomically under parallel spawns (lost-update race)", () =>
1176+
Effect.gen(function* () {
1177+
SubagentLimits.__testHooks.treeLimit = 3
1178+
const sessions = yield* Session.Service
1179+
// Production session creation does real async I/O; the in-process test
1180+
// create is effectively synchronous, so the racers would never yield
1181+
// inside the gate window here. Reinstate the async boundary
1182+
// deterministically: every racer reaches `create` (and thus passed the
1183+
// gate) before any create completes — the exact lost-update window.
1184+
const wrapped: typeof sessions = {
1185+
...sessions,
1186+
create: (input) => Effect.yieldNow.pipe(Effect.andThen(sessions.create(input))),
1187+
}
1188+
const { chat, assistant } = yield* seed()
1189+
const tool = yield* TaskTool.pipe(Effect.provideService(Session.Service, wrapped))
1190+
const def = yield* tool.init()
1191+
const promptOps = stubOps()
1192+
1193+
// 5 spawns race through the gate: the reservation must be a synchronous
1194+
// check-and-set so EXACTLY treeLimit succeed. The pre-fix sequence
1195+
// (read started → async sessions.create → set started+1) let every
1196+
// racer read the same stale count and systematically undercount.
1197+
const exits = yield* Effect.all(
1198+
Array.from({ length: 5 }, () =>
1199+
def
1200+
.execute(taskParams, taskCtx({ sessionID: chat.id, messageID: assistant.id, promptOps }))
1201+
.pipe(Effect.exit),
1202+
),
1203+
{ concurrency: "unbounded" },
1204+
)
1205+
1206+
const refused = exits.filter((exit) => defectOf(exit) instanceof SubagentLimits.SubagentTreeLimitError)
1207+
expect(exits.filter(Exit.isSuccess)).toHaveLength(3)
1208+
expect(refused).toHaveLength(2)
1209+
// Exactly the cap's worth of child sessions exist...
1210+
expect(yield* sessions.children(chat.id)).toHaveLength(3)
1211+
// ...and the counter settled AT the limit: the next spawn reports 3/3.
1212+
const followUp = yield* def
1213+
.execute(taskParams, taskCtx({ sessionID: chat.id, messageID: assistant.id, promptOps }))
1214+
.pipe(Effect.exit)
1215+
const error = defectOf(followUp)
1216+
expect(error).toBeInstanceOf(SubagentLimits.SubagentTreeLimitError)
1217+
expect((error as SubagentLimits.SubagentTreeLimitError).started).toBe(3)
1218+
}).pipe(
1219+
Effect.ensuring(
1220+
Effect.sync(() => {
1221+
SubagentLimits.__testHooks.treeLimit = undefined
1222+
}),
1223+
),
1224+
),
1225+
)
1226+
1227+
it.instance("releases the reserved slot again when session creation fails", () =>
1228+
Effect.gen(function* () {
1229+
SubagentLimits.__testHooks.treeLimit = 1
1230+
const real = yield* Session.Service
1231+
let explode = false
1232+
const wrapped: typeof real = {
1233+
...real,
1234+
create: (input) => (explode ? Effect.die(new Error("injected create failure")) : real.create(input)),
1235+
}
1236+
const { chat, assistant } = yield* seed()
1237+
const tool = yield* TaskTool.pipe(Effect.provideService(Session.Service, wrapped))
1238+
const def = yield* tool.init()
1239+
const promptOps = stubOps()
1240+
1241+
// The reservation happens BEFORE sessions.create; when create dies the
1242+
// slot must be released again or the failed attempt eats the cap.
1243+
explode = true
1244+
const failed = yield* def
1245+
.execute(taskParams, taskCtx({ sessionID: chat.id, messageID: assistant.id, promptOps }))
1246+
.pipe(Effect.exit)
1247+
expect(Exit.isFailure(failed)).toBe(true)
1248+
expect(defectOf(failed)).not.toBeInstanceOf(SubagentLimits.SubagentTreeLimitError)
1249+
expect(yield* real.children(chat.id)).toHaveLength(0)
1250+
1251+
// The tree's single slot is still available after the failed create.
1252+
explode = false
1253+
const result = yield* def.execute(
1254+
taskParams,
1255+
taskCtx({ sessionID: chat.id, messageID: assistant.id, promptOps }),
1256+
)
1257+
expect((yield* real.get(result.metadata.sessionId)).parentID).toBe(chat.id)
1258+
}).pipe(
1259+
Effect.ensuring(
1260+
Effect.sync(() => {
1261+
SubagentLimits.__testHooks.treeLimit = undefined
1262+
}),
1263+
),
1264+
),
1265+
)
11741266
})
11751267

11761268
describe("tool.task root routing", () => {

0 commit comments

Comments
 (0)