Skip to content

Commit 6c3f11d

Browse files
authored
fix(core): release a shell when its call reads the result, not when its job does (#68130)
1 parent 48696b3 commit 6c3f11d

2 files changed

Lines changed: 123 additions & 5 deletions

File tree

‎packages/core/src/tool/plugin/shell.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ const notify = Effect.fnUntraced(function* (
185185
readonly settled: Deferred.Deferred<Output>
186186
readonly worker?: boolean
187187
readonly isClosed?: () => Effect.Effect<boolean>
188+
readonly release: Effect.Effect<void>
188189
},
189190
) {
190191
const info = (yield* jobs.wait({ id: input.id })).info
@@ -197,7 +198,7 @@ const notify = Effect.fnUntraced(function* (
197198
(input.isClosed !== undefined && (yield* input.isClosed()))
198199
) {
199200
if (info.notificationID) yield* jobs.completeBackground(info.notificationID)
200-
return
201+
return yield* input.release
201202
}
202203
const output = info.status === "completed" ? yield* Deferred.await(input.settled) : undefined
203204
const text = output ? (info.output ?? "") : info.status === "error" ? (info.error ?? "Command failed") : "Cancelled"
@@ -219,14 +220,14 @@ const notify = Effect.fnUntraced(function* (
219220
})
220221
.pipe(Effect.catchTag("Session.NotFoundError", () => Effect.void))
221222
if (info.notificationID) yield* jobs.completeBackground(info.notificationID)
223+
// The session has the result, so the shell no longer needs to outlive the exited cap.
224+
yield* input.release
222225
})
223226

224227
// Waits for the command to end and reads what it printed.
225228
const finished = Effect.fnUntraced(function* (shell: Shell.Interface, info: ShellSchema.Info) {
226229
const result = yield* shell.result(info)
227230
if (!result.capture) return yield* new Shell.NotFoundError({ id: info.id })
228-
// The call has read the final output, so the shell no longer needs to outlive the exited cap.
229-
yield* shell.release(info.id).pipe(Effect.ignore)
230231
const completed = result.info.time.completed ?? (yield* Clock.currentTimeMillis)
231232
return {
232233
...ShellResult.output(result),
@@ -317,6 +318,7 @@ export const reattach = Effect.fnUntraced(function* (input: {
317318
}) {
318319
const { job, settled } = yield* startJob(input.jobs, input.shell, { ...input, background: true })
319320
const notifying = notify(input.sessions, input.jobs, {
321+
release: input.shell.release(input.info.id).pipe(Effect.ignore),
320322
sessionID: input.sessionID,
321323
id: job.id,
322324
shellID: input.info.id,
@@ -406,12 +408,13 @@ export const Plugin = {
406408
const notifyWhenDone = (
407409
sessionID: SessionSchema.ID,
408410
id: string,
409-
shellID: string,
411+
shellID: ShellSchema.ID,
410412
command: string,
411413
settled: Deferred.Deferred<Output>,
412414
) =>
413415
shell.watch(
414416
notify(sessions, jobs, {
417+
release: shell.release(shellID).pipe(Effect.ignore),
415418
sessionID,
416419
id,
417420
shellID,
@@ -633,6 +636,7 @@ export const Plugin = {
633636
const { info, stopped, started } = entry
634637
if (started === undefined) {
635638
const output = yield* restore(finished(shell, info))
639+
yield* shell.release(info.id).pipe(Effect.ignore)
636640
if (output.timeout)
637641
return yield* new ToolFailure({ message: resultMessages(output, finalTimeout.value).join("\n\n") })
638642
return output
@@ -681,6 +685,8 @@ export const Plugin = {
681685
yield* notifyWhenDone(context.sessionID, job.id, info.id, info.command, settled)
682686
return backgroundResult(info, yield* Clock.currentTimeMillis, elapsed)
683687
}
688+
// The call reads the result now; its job no longer keeps the shell.
689+
yield* shell.release(info.id).pipe(Effect.ignore)
684690
if (result?.info.status === "error")
685691
return yield* Effect.fail(new Error(result.info.error ?? "Command failed"))
686692
if (result?.info.status === "cancelled") return yield* Effect.fail(new Error("Command cancelled"))
@@ -703,11 +709,13 @@ export const Plugin = {
703709
),
704710
),
705711
)
706-
return yield* finished(shell, info).pipe(
712+
const output = yield* finished(shell, info).pipe(
707713
Effect.catchTag("Shell.NotFoundError", () =>
708714
Effect.fail(new ToolFailure({ message: `Shell command ${id} ended and its output is no longer available.` })),
709715
),
710716
)
717+
yield* shell.release(id).pipe(Effect.ignore)
718+
return output
711719
})
712720

713721
// A real interrupt stops the command, unless the server is handing its daemon over: then the command and its job

‎packages/core/test/tool-shell.test.ts‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,18 @@ const runningShell = (command: string) =>
346346
Effect.map((info) => info!),
347347
)
348348

349+
// Completes more unretained shells than the exited cap keeps, so any shell no longer retained is evicted.
350+
const runQuietShells = (shell: Shell.Interface) =>
351+
Effect.forEach(
352+
Array.from({ length: 26 }),
353+
() =>
354+
Effect.gen(function* () {
355+
const info = yield* shell.create({ command: isWindows ? "[Console]::Out.Write('x')" : "printf x", timeout: 0 })
356+
yield* shell.wait(info.id)
357+
}),
358+
{ concurrency: 4, discard: true },
359+
)
360+
349361
// The shell's own durable Code Mode spec over a fresh runtime, so a test holds the program and suspends it itself.
350362
const durableShell = (
351363
info: Info,
@@ -1299,6 +1311,52 @@ describe("ShellTool", () => {
12991311
}),
13001312
)
13011313

1314+
codeModeIt.live("keeps a suspended Code Mode shell's result past the exited cap until the resume reads it", () =>
1315+
withTempDir((tmp) => {
1316+
reset()
1317+
return withSession(tmp.path, (registry) =>
1318+
Effect.gen(function* () {
1319+
const info = (yield* registry.list()).find((tool) => tool.id === "shell")!
1320+
const context: Context = {
1321+
sessionID,
1322+
...toolIdentity,
1323+
id: CallID.make("call-durable-shell-retained"),
1324+
progress: () => Effect.void,
1325+
tool: noToolCalls,
1326+
}
1327+
const counters = { starts: 0, cancels: 0, started: yield* Deferred.make<string>() }
1328+
const tool = durableShell(info, context, counters)
1329+
const runtime = () => CodeMode.make({ tools: { shell: tool } })
1330+
const gate = path.join(tmp.path, "gate")
1331+
const command = isWindows
1332+
? `while (!(Test-Path ${JSON.stringify(gate)})) { Start-Sleep -Milliseconds 20 }; [Console]::Out.Write('kept')`
1333+
: `while [ ! -f ${JSON.stringify(gate)} ]; do sleep 0.02; done; printf kept`
1334+
const program = runtime().program(`return await tools.shell(${JSON.stringify({ command })})`, undefined, {
1335+
runId: "durable-shell-retained",
1336+
})
1337+
const run = yield* Effect.forkScoped(program.run())
1338+
const shellID = ID.make(yield* Deferred.await(counters.started))
1339+
const suspended = yield* program.suspend()
1340+
if (suspended.ok !== "suspended") throw new Error("the run was not suspended")
1341+
expect(yield* Fiber.join(run)).toEqual(suspended)
1342+
1343+
const shell = yield* Shell.Service
1344+
const jobs = yield* Job.Service
1345+
yield* Effect.promise(() => Bun.write(gate, ""))
1346+
expect((yield* shell.wait(shellID)).status).toBe("exited")
1347+
// The job read the result while the call was suspended; that must not let newer completions evict it.
1348+
yield* jobs.wait({ id: shellID })
1349+
yield* runQuietShells(shell)
1350+
const outcome = yield* runtime().resume(CodeMode.toBytes(suspended.state)).run()
1351+
expect(outcome).toMatchObject({ ok: true, value: { exitCode: 0, output: "kept" } })
1352+
// The resumed call read it, so now it is evictable.
1353+
yield* runQuietShells(shell)
1354+
expect(yield* shell.get(shellID).pipe(Effect.flip)).toBeInstanceOf(Shell.NotFoundError)
1355+
}),
1356+
)
1357+
}),
1358+
)
1359+
13021360
codeModeIt.live("cancels and kills a durable Code Mode shell on a real interrupt", () =>
13031361
withTempDir((tmp) => {
13041362
reset()
@@ -2178,6 +2236,58 @@ describe("ShellTool", () => {
21782236
}),
21792237
)
21802238

2239+
it.live("releases a foreground call's shell once the call reads its result", () =>
2240+
withTempDir((tmp) => {
2241+
reset()
2242+
return withSession(tmp.path, (registry) =>
2243+
Effect.gen(function* () {
2244+
const shell = yield* Shell.Service
2245+
const updates: Metadata[] = []
2246+
yield* executeTool(registry, {
2247+
...call({ command: isWindows ? "[Console]::Out.Write('x')" : "printf x" }, "call-foreground-release"),
2248+
progress: (update) => Effect.sync(() => updates.push(update)),
2249+
})
2250+
const id = ID.make(String(updates[0]?.shellID))
2251+
yield* runQuietShells(shell)
2252+
expect(yield* shell.get(id).pipe(Effect.flip)).toBeInstanceOf(Shell.NotFoundError)
2253+
}),
2254+
)
2255+
}),
2256+
)
2257+
2258+
it.live("releases a background call's shell once its notice is sent", () =>
2259+
withTempDir((tmp) => {
2260+
reset()
2261+
return withSession(tmp.path, (registry) =>
2262+
Effect.gen(function* () {
2263+
const bus = yield* Bus.Service
2264+
const shell = yield* Shell.Service
2265+
const admitted = yield* bus.subscribe(SessionEvent.InboxEnqueued).pipe(
2266+
Stream.filter((event) => event.data.sessionID === sessionID && event.data.item.type === "synthetic"),
2267+
Stream.runHead,
2268+
Effect.forkScoped({ startImmediately: true }),
2269+
)
2270+
const result = yield* executeTool(
2271+
registry,
2272+
call(
2273+
{ command: isWindows ? "[Console]::Out.Write('x')" : "printf x", background: true },
2274+
"call-background-release",
2275+
),
2276+
)
2277+
const id = ID.make(String(result.metadata?.shellID))
2278+
expect((yield* Fiber.join(admitted))._tag).toBe("Some")
2279+
// The release follows the notice, so a later batch of completions may be the one that evicts it.
2280+
yield* runQuietShells(shell).pipe(
2281+
Effect.andThen(shell.get(id)),
2282+
Effect.flip,
2283+
Effect.retry({ times: 20 }),
2284+
Effect.flatMap((error) => (error instanceof Shell.NotFoundError ? Effect.void : Effect.fail(error))),
2285+
)
2286+
}),
2287+
)
2288+
}),
2289+
)
2290+
21812291
it.live("releases a cancelled background job's shell, so eviction still bounds retained shells", () =>
21822292
withTempDir((tmp) => {
21832293
reset()

0 commit comments

Comments
 (0)