Skip to content

Commit 48696b3

Browse files
authored
fix(core): keep 25 exited shells and save a shell's release reliably (#68134)
1 parent b1514bc commit 48696b3

4 files changed

Lines changed: 141 additions & 7 deletions

File tree

‎packages/core/src/shell.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -340,18 +340,20 @@ const makeRunPool = <E, Extra = {}>(options: {
340340

341341
const evict = Effect.fnUntraced(function* () {
342342
const evictable = exitOrder.filter((id) => runs.get(id)?.retain !== true)
343+
if (evictable.length <= EXITED_LIMIT) return
343344
for (const id of evictable.slice(0, evictable.length - EXITED_LIMIT)) yield* forget(id)
344345
})
345346

346347
// A retained shell is only evictable once released, so releasing may take it (or others) past the cap now.
348+
// Uninterruptible, so the daemon's saved flag always follows memory; an evicted shell has nothing left to save.
347349
const release = Effect.fnUntraced(function* (id: Shell.ID) {
348350
const run = runs.get(id)
349351
if (!run) return yield* new NotFoundError({ id })
350352
if (run.retain !== true) return
351353
run.retain = false
352-
yield* store(run)
353354
yield* evict()
354-
})
355+
if (runs.get(id) === run) yield* store(run)
356+
}, Effect.uninterruptible)
355357

356358
const finish = Effect.fnUntraced(function* (
357359
run: Run,

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -565,15 +565,23 @@ export const Plugin = {
565565
if (timeoutBackgrounds) invocation.timeout = 0
566566
}),
567567
)
568-
yield* context.progress({ shellID: info.id })
569-
const started =
570-
context.automation === undefined
568+
// Until start returns its data nothing else can release the shell, so a failure here stops it.
569+
const started = yield* Effect.gen(function* () {
570+
yield* context.progress({ shellID: info.id })
571+
return context.automation === undefined
571572
? yield* startJob(jobs, shell, {
572573
sessionID: context.sessionID,
573574
info,
574575
timeout: () => finalTimeout.value,
575576
})
576577
: undefined
578+
}).pipe(
579+
Effect.onError(() =>
580+
shell
581+
.release(info.id)
582+
.pipe(Effect.ignore, Effect.andThen(shell.stop(info.id, "killed").pipe(Effect.ignore))),
583+
),
584+
)
577585
running.set(info.id, { info, stopped, listener, started, timeout: finalTimeout })
578586
data = {
579587
shellID: info.id,

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

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { expect } from "bun:test"
2-
import { Deferred, Effect, Fiber, Layer, Queue, Scope, Sink, Stream } from "effect"
2+
import { Deferred, Effect, Exit, Fiber, Layer, Queue, Scope, Sink, Stream } from "effect"
33
import { ChildProcessSpawner } from "effect/process"
44
import { ExitCode, makeHandle, ProcessId } from "effect/process/ChildProcessSpawner"
55
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
@@ -242,3 +242,77 @@ it.live("keeps a retained shell and its flag across a server restart", () =>
242242
)
243243
}),
244244
)
245+
246+
const exitedShells = (env: Effect.Success<ReturnType<typeof daemonShells>>, shell: Shell.Interface) =>
247+
Effect.fnUntraced(function* (retain?: boolean) {
248+
const info = yield* shell.create({
249+
shell: "/bin/sh",
250+
command: "echo hello",
251+
timeout: 0,
252+
...(retain ? { retain: true } : {}),
253+
})
254+
const id = env.created().length
255+
env.daemon.exit(id, 0)
256+
yield* shell.wait(info.id)
257+
return info
258+
})
259+
260+
it.live("keeps up to 25 exited shells and evicts only the oldest past them", () =>
261+
Effect.gen(function* () {
262+
const env = yield* daemonShells()
263+
yield* env.withShell(env.directory, (shell) =>
264+
Effect.gen(function* () {
265+
const complete = exitedShells(env, shell)
266+
const infos = yield* Effect.forEach(Array.from({ length: 25 }), () => complete())
267+
const last = yield* complete()
268+
// Eviction runs after an exit's waiters resolve, so wait for the 26th exit to take the oldest.
269+
yield* until(shell.get(infos[0]!.id).pipe(Effect.exit, Effect.map(Exit.isFailure)))
270+
// With 13 to 25 exited shells, none went before it.
271+
for (const info of [...infos.slice(1), last])
272+
expect(yield* shell.get(info.id)).toMatchObject({ status: "exited" })
273+
}),
274+
)
275+
}),
276+
)
277+
278+
it.live("adopts 24 unretained and 1 retained exited shell without evicting any", () =>
279+
Effect.gen(function* () {
280+
const env = yield* daemonShells()
281+
const infos = yield* env.withShell(env.directory, (shell) =>
282+
Effect.gen(function* () {
283+
const complete = exitedShells(env, shell)
284+
const retained = yield* complete(true)
285+
return [retained, ...(yield* Effect.forEach(Array.from({ length: 24 }), () => complete()))]
286+
}),
287+
)
288+
yield* env.withShell(env.directory, (shell) =>
289+
Effect.gen(function* () {
290+
for (const info of infos) expect(yield* shell.get(info.id)).toMatchObject({ status: "exited" })
291+
}),
292+
)
293+
}),
294+
)
295+
296+
it.live("saves a release interrupted while it stores, so a restart does not keep the shell", () =>
297+
Effect.gen(function* () {
298+
const env = yield* daemonShells()
299+
const saved = () => env.daemon.processes[0]?.pipe?.metadata.retain === undefined
300+
const retained = yield* env.withShell(env.directory, (shell) =>
301+
Effect.gen(function* () {
302+
const info = yield* exitedShells(env, shell)(true)
303+
// Interrupted as soon as it starts to save, like a job cancelled during a user's stop.
304+
const released = yield* shell.release(info.id).pipe(Effect.forkChild({ startImmediately: true }))
305+
yield* Fiber.interrupt(released)
306+
yield* until(saved)
307+
return info
308+
}),
309+
)
310+
yield* env.withShell(env.directory, (shell) =>
311+
Effect.gen(function* () {
312+
// Released, so 25 newer unretained shells take it past the cap.
313+
yield* Effect.forEach(Array.from({ length: 25 }), () => exitedShells(env, shell)(), { discard: true })
314+
yield* until(shell.get(retained.id).pipe(Effect.exit, Effect.map(Exit.isFailure)))
315+
}),
316+
)
317+
}),
318+
)

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

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1367,6 +1367,45 @@ describe("ShellTool", () => {
13671367
}),
13681368
)
13691369

1370+
codeModeIt.live("stops and releases a durable Code Mode shell whose start fails after its spawn", () =>
1371+
withTempDir((tmp) => {
1372+
reset()
1373+
return withSession(tmp.path, (registry) =>
1374+
Effect.gen(function* () {
1375+
const info = (yield* registry.list()).find((tool) => tool.id === "shell")!
1376+
const durable = durablePhases(info.execute)
1377+
if (durable === undefined) throw new Error("shell is not registered as a durable tool")
1378+
let shellID: ID | undefined
1379+
const context: Context = {
1380+
sessionID,
1381+
...toolIdentity,
1382+
id: CallID.make("call-durable-start-fails"),
1383+
progress: (update) =>
1384+
Effect.suspend(() => {
1385+
shellID = ID.make(String(update.shellID))
1386+
return Effect.die(new Error("progress failed"))
1387+
}),
1388+
tool: noToolCalls,
1389+
}
1390+
const exit = yield* durable.start({ command: idleCommand }, context).pipe(Effect.exit)
1391+
expect(Exit.isFailure(exit)).toBe(true)
1392+
const shell = yield* Shell.Service
1393+
const stopped = yield* shell.wait(shellID!).pipe(Effect.timeout("5 seconds"))
1394+
expect(stopped.status).toBe("killed")
1395+
// Released, so newer unretained completions take it past the cap.
1396+
const quiet = isWindows ? "[Console]::Out.Write('x')" : "printf x"
1397+
yield* Effect.forEach(
1398+
Array.from({ length: 26 }),
1399+
() =>
1400+
shell.create({ command: quiet, timeout: 0 }).pipe(Effect.flatMap((created) => shell.wait(created.id))),
1401+
{ concurrency: 4, discard: true },
1402+
)
1403+
yield* evicted(shell, shellID!)
1404+
}),
1405+
)
1406+
}),
1407+
)
1408+
13701409
codeModeIt.live("stops a durable Code Mode shell an unawaited call leaves behind", () =>
13711410
withTempDir((tmp) => {
13721411
reset()
@@ -2165,7 +2204,8 @@ describe("ShellTool", () => {
21652204
}),
21662205
{ concurrency: 4 },
21672206
)
2168-
expect(yield* shell.get(cancelled).pipe(Effect.flip)).toBeInstanceOf(Shell.NotFoundError)
2207+
// Eviction runs after an exit's waiters resolve, so poll for it.
2208+
yield* evicted(shell, cancelled)
21692209
}),
21702210
)
21712211
}),
@@ -3530,3 +3570,13 @@ describe("ShellTool stopped", () => {
35303570
}),
35313571
)
35323572
})
3573+
3574+
function evicted(shell: Shell.Interface, id: ID) {
3575+
return Effect.gen(function* () {
3576+
for (let attempt = 0; attempt < 1_000; attempt++) {
3577+
if (Exit.isFailure(yield* shell.get(id).pipe(Effect.exit))) return
3578+
yield* Effect.promise(() => Bun.sleep(5))
3579+
}
3580+
throw new Error(`shell ${id} was never evicted`)
3581+
})
3582+
}

0 commit comments

Comments
 (0)