diff --git a/packages/core/src/session/execution/restart.ts b/packages/core/src/session/execution/restart.ts index dde33930183..fc45c01df89 100644 --- a/packages/core/src/session/execution/restart.ts +++ b/packages/core/src/session/execution/restart.ts @@ -1,6 +1,6 @@ export * as SessionRestart from "./restart.js" -import { Context, Effect, Layer } from "effect" +import { Context, Effect, Fiber, Layer, Semaphore, Stream } from "effect" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Bus } from "../../bus.js" import { Job } from "../../job.js" @@ -28,9 +28,17 @@ export interface Options { * never accumulate: the budget is per-turn, not per-session. */ readonly maxAttempts?: number + /** + * Resumes that may be starting at once. A slot frees when the resumed turn + * settles its first step, ends, or has held the slot for 60 seconds, so a + * burst of interrupted turns cannot all issue their first request together. + */ + readonly maxConcurrentResumes?: number } const DEFAULT_MAX_ATTEMPTS = 10 +const DEFAULT_MAX_CONCURRENT_RESUMES = 3 +const RESUME_SLOT_TIMEOUT = "60 seconds" export interface Interface { /** @@ -39,6 +47,10 @@ export interface Interface { * shutdown (which preserves the claim on purpose). The claim is never * cleared here: only a terminal event releases it, so a death anywhere in * the resume path leaves the same orphaned claim for the next boot. + * + * Resumes start through a bounded gate, recovered subagents first, then + * Sessions most recently updated first. Completes once every resume has + * started, which can take minutes after a large restart; callers fork it. */ readonly resumeSuspendedSessions: Effect.Effect } @@ -73,6 +85,33 @@ export const layer = (options?: Options) => const sessions = yield* Session.Service const scope = yield* Effect.scope const maxAttempts = options?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS + const gate = yield* Semaphore.make(options?.maxConcurrentResumes ?? DEFAULT_MAX_CONCURRENT_RESUMES) + + const firstStep = (sessionID: SessionSchema.ID) => + bus.subscribe([SessionEvent.Step.Ended, SessionEvent.Step.Failed]).pipe( + Stream.filter((event) => event.data.sessionID === sessionID), + Stream.runHead, + ) + + // Waits for a slot, then runs `start`, which accounts for the resume and returns the + // started turn (or undefined when nothing started). The slot is held until that turn + // settles its first step, ends, or times out; returns once `start` has run. + const admit = (sessionID: SessionSchema.ID, start: Effect.Effect | undefined>) => + Effect.uninterruptibleMask((restore) => + Effect.gen(function* () { + yield* restore(gate.take(1)) + // Listen before the turn starts so its first step cannot settle unobserved. + const stepped = yield* firstStep(sessionID).pipe(Effect.forkIn(scope, { startImmediately: true })) + const release = Fiber.interrupt(stepped).pipe(Effect.andThen(gate.release(1)), Effect.asVoid) + const turn = yield* restore(start).pipe(Effect.onError(() => release)) + if (turn === undefined) return yield* release + yield* Effect.raceAll([turn, Fiber.join(stepped), Effect.sleep(RESUME_SLOT_TIMEOUT)]).pipe( + Effect.ignore, + Effect.ensuring(release), + Effect.forkIn(scope, { startImmediately: true }), + ) + }), + ) const prepareResume = Effect.fnUntraced(function* (sessionID: SessionSchema.ID) { // Durable before the resume runs, so a crash inside the resumed turn is @@ -138,13 +177,15 @@ export const layer = (options?: Options) => const recoverSubagent = Effect.fnUntraced(function* ( background: Job.Background, recovery: Extract, - suspended: ReadonlySet, + suspended: Set, ) { - const child = yield* store.get(recovery.childSessionID) - if (!child || child.parentID !== recovery.parentSessionID || !(yield* store.get(recovery.parentSessionID))) { + const orphaned = Effect.gen(function* () { + const child = yield* store.get(recovery.childSessionID) + if (child?.parentID === recovery.parentSessionID && (yield* store.get(recovery.parentSessionID))) return false yield* jobs.completeBackground(background.notificationID) - return - } + return true + }) + if (yield* orphaned) return const notify = Effect.fnUntraced(function* (result: Pick) { yield* SubagentCompletion.deliver(sessions, jobs, { @@ -159,33 +200,44 @@ export const layer = (options?: Options) => yield* notify(background) return } - if (yield* execution.isActive(recovery.childSessionID)) return - if (!(yield* prepareResume(recovery.childSessionID))) { - yield* notify({ status: "error", error: RESUME_EXHAUSTED.message }) - return - } + yield* admit( + recovery.childSessionID, + Effect.gen(function* () { + // The slot can take minutes to free, so check again what may have changed meanwhile. + if ((yield* jobs.get(background.id))?.status === "running") return undefined + if (yield* orphaned) return undefined + if (yield* execution.isActive(recovery.childSessionID)) return undefined + if (!(yield* prepareResume(recovery.childSessionID))) { + yield* notify({ status: "error", error: RESUME_EXHAUSTED.message }) + return undefined + } - yield* jobs.start({ - id: background.id, - type: "subagent", - title: recovery.description, - notificationID: background.notificationID, - recovery, - run: execution.resume(recovery.childSessionID).pipe( - Effect.andThen(store.context(recovery.childSessionID)), - Effect.map((messages) => { - const assistant = messages.findLast( - (message) => - message.type === "assistant" && message.time.completed !== undefined && message.error === undefined, - ) - return SubagentCompletion.text(assistant) - }), - ), - }) - yield* jobs.background(background.id) - yield* jobs.wait({ id: background.id }).pipe( - Effect.flatMap((result) => (result.info ? notify(result.info) : Effect.void)), - Effect.forkIn(scope), + yield* jobs.start({ + id: background.id, + type: "subagent", + title: recovery.description, + notificationID: background.notificationID, + recovery, + run: execution.resume(recovery.childSessionID).pipe( + Effect.andThen(store.context(recovery.childSessionID)), + Effect.map((messages) => { + const assistant = messages.findLast( + (message) => + message.type === "assistant" && + message.time.completed !== undefined && + message.error === undefined, + ) + return SubagentCompletion.text(assistant) + }), + ), + }) + yield* jobs.background(background.id) + yield* jobs.wait({ id: background.id }).pipe( + Effect.flatMap((result) => (result.info ? notify(result.info) : Effect.void)), + Effect.forkIn(scope), + ) + return jobs.wait({ id: background.id }) + }).pipe(Effect.ensuring(Effect.sync(() => suspended.delete(recovery.childSessionID)))), ) }) @@ -204,8 +256,9 @@ export const layer = (options?: Options) => ) yield* store.releaseChildClaims(children) yield* Effect.forEach( - // Admit shell outcomes before a recovered child can start its first model request. - pending.toSorted((a, b) => Number(a.recovery.kind === "subagent") - Number(b.recovery.kind === "subagent")), + // Admit shell outcomes before a recovered child can start its first model request, and + // deliver settled subagent results before running children wait for resume slots. + pending.toSorted((a, b) => recoveryRank(a) - recoveryRank(b)), Effect.fnUntraced(function* (background) { if ((yield* jobs.get(background.id))?.status === "running") return const recovery = background.recovery @@ -221,18 +274,33 @@ export const layer = (options?: Options) => yield* Effect.forEach( (yield* store.listSuspended()).filter((sessionID) => !resumed.has(sessionID)), (sessionID) => - execution - .resume(sessionID) - .pipe(Effect.ignore, Effect.forkIn(scope), Effect.when(prepareResume(sessionID))), - { concurrency: "unbounded", discard: true }, + admit( + sessionID, + Effect.gen(function* () { + // A queued Session may have been prompted, or finished, while it waited for a slot. + if (yield* execution.isActive(sessionID)) return undefined + if (!(yield* store.listSuspended()).includes(sessionID)) return undefined + if (!(yield* prepareResume(sessionID))) return undefined + return Fiber.await( + yield* execution + .resume(sessionID) + .pipe(Effect.ignore, Effect.forkIn(scope, { startImmediately: true })), + ) + }).pipe(Effect.ensuring(Effect.sync(() => suspended.delete(sessionID)))), + ), + { discard: true }, ) - // Async observers consult this set at delivery; later completions wake parents normally. + // Async observers consult this set at delivery. Each Session leaves it once its own resume + // is accounted for; later completions wake parents normally. suspended.clear() }), }) }), ) +const recoveryRank = (background: Job.Background) => + background.recovery.kind === "shell" ? 0 : background.status === "running" ? 2 : 1 + export const node = makeGlobalNode({ service: Service, layer: layer(), diff --git a/packages/core/src/session/store.ts b/packages/core/src/session/store.ts index c9698231bbc..25d9965c444 100644 --- a/packages/core/src/session/store.ts +++ b/packages/core/src/session/store.ts @@ -60,8 +60,9 @@ export interface Interface { messageID: SessionMessage.ID, ) => Effect.Effect<{ readonly sessionID: Session.ID; readonly message: SessionMessage.Info } | undefined> /** - * Top-level Sessions holding an execution claim. Recoverable background - * children are resumed separately through their durable Job records. + * Top-level Sessions holding an execution claim, most recently updated first. + * Recoverable background children are resumed separately through their + * durable Job records. */ readonly listSuspended: () => Effect.Effect> /** @@ -199,6 +200,7 @@ const layer = Layer.effect( .select({ sessionID: SessionTable.id }) .from(SessionTable) .where(and(isNotNull(SessionTable.time_suspended), isNull(SessionTable.parent_id))) + .orderBy(desc(SessionTable.time_updated), desc(SessionTable.id)) .all() .pipe( Effect.orDie, diff --git a/packages/core/test/session-execution.test.ts b/packages/core/test/session-execution.test.ts index eaa13565299..80533b1c38e 100644 --- a/packages/core/test/session-execution.test.ts +++ b/packages/core/test/session-execution.test.ts @@ -1,6 +1,7 @@ import type { FileSystem } from "@opencode/core/filesystem" import { describe, expect, test } from "bun:test" import { AIError, TransportError } from "@opencode/ai/effect" +import { Agent } from "@opencode/core/agent" import { Database } from "@opencode/core/database/database" import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" @@ -10,7 +11,10 @@ import { Job } from "@opencode/core/job" import { KV } from "@opencode/core/kv" import { LocationServiceMap } from "@opencode/core/location-service-map" import type { LocationServices } from "@opencode/core/location-services" +import { Model } from "@opencode/core/model" +import { Money } from "@opencode/schema/money" import { Project } from "@opencode/core/project" +import { Provider } from "@opencode/core/provider" import { ProjectTable } from "@opencode/core/project/sql" import { AbsolutePath } from "@opencode/core/schema" import { Session } from "@opencode/core/session" @@ -23,6 +27,7 @@ import { SessionRunner } from "@opencode/core/session/runner/index" import { SessionInboxTable, SessionTable } from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" import { Cause, Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Scope } from "effect" +import { TestClock } from "effect/testing" import { eq } from "drizzle-orm" import { testEffect } from "./lib/effect" @@ -216,28 +221,111 @@ describe("SessionExecution lifecycle", () => { }), ) - it.effect("starts every claimed execution without waiting for earlier drains to finish", () => + it.effect("gates resumes newest first and charges a queued Session only when it starts", () => Effect.gen(function* () { const database = yield* Database.Service - const sessionIDs = Array.from({ length: 5 }, (_, index) => Session.ID.make(`ses_resume_concurrent_${index}`)) - yield* seedSessions(database, sessionIDs, { time_suspended: Date.now() }) + const sessionIDs = Array.from({ length: 5 }, (_, index) => Session.ID.make(`ses_resume_gate_${index}`)) + yield* Effect.forEach( + sessionIDs, + (sessionID, index) => seedSessions(database, [sessionID], { time_suspended: 1, time_updated: index + 1 }), + { discard: true }, + ) + const [oldest, older, middle, newer, newest] = sessionIDs - const fourStarted = yield* Deferred.make() + const turns = sessionIDs.map(() => ({ begun: Deferred.makeUnsafe(), finish: Deferred.makeUnsafe() })) + const turn = (sessionID: Session.ID) => turns[sessionIDs.indexOf(sessionID)] const started: Session.ID[] = [] + const running = { now: 0, peak: 0 } const scope = yield* Scope.make() yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) - const context = yield* buildExecution(scope, ({ sessionID }) => - Effect.sync(() => { - started.push(sessionID) - if (started.length === 4) Deferred.doneUnsafe(fourStarted, Effect.void) - }).pipe(Effect.andThen(Effect.never)), + const context = yield* buildExecution( + scope, + ({ sessionID }) => + Effect.gen(function* () { + started.push(sessionID) + running.now++ + running.peak = Math.max(running.peak, running.now) + yield* Deferred.succeed(turn(sessionID).begun, undefined) + yield* Deferred.await(turn(sessionID).finish) + running.now-- + }), + { maxConcurrentResumes: 2 }, ) - const execution = Context.get(context, SessionExecution.Service) - const restart = Context.get(context, SessionRestart.Service) - yield* restart.resumeSuspendedSessions.pipe(Effect.forkIn(scope)) - yield* Deferred.await(fourStarted) + const sweep = yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions.pipe( + Effect.forkIn(scope), + ) + const queuedAttempts = (queued: ReadonlyArray) => + Effect.forEach(queued, (sessionID) => attempts(database, sessionID)) - expect([...(yield* execution.active)].toSorted()).toEqual(sessionIDs.toSorted()) + yield* Deferred.await(turn(newest).begun) + yield* Deferred.await(turn(newer).begun) + // Just short of the slot timeout, nothing else may start or be charged. + yield* TestClock.adjust("59 seconds") + expect(started).toEqual([newest, newer]) + expect(yield* queuedAttempts([middle, older, oldest])).toEqual([0, 0, 0]) + + // A finished turn frees its slot for the next queued Session. + yield* Deferred.succeed(turn(newest).finish, undefined) + yield* Deferred.await(turn(middle).begun) + expect(started).toEqual([newest, newer, middle]) + expect(running.peak).toBe(2) + expect(yield* queuedAttempts([middle, older, oldest])).toEqual([1, 0, 0]) + + // A turn still running after 60 seconds gives its slot up without being interrupted. + yield* TestClock.adjust("1 second") + yield* Deferred.await(turn(older).begun) + expect(started).toEqual([newest, newer, middle, older]) + expect(yield* queuedAttempts([oldest])).toEqual([0]) + + yield* Effect.forEach(turns, (item) => Deferred.succeed(item.finish, undefined), { discard: true }) + yield* Fiber.join(sweep) + yield* Deferred.await(turn(oldest).begun) + expect(started).toEqual([newest, newer, middle, older, oldest]) + }), + ) + + it.effect("frees a resume slot when the resumed turn settles its first step", () => + Effect.gen(function* () { + const database = yield* Database.Service + const bus = yield* Bus.Service + const first = Session.ID.make("ses_resume_step_first") + const second = Session.ID.make("ses_resume_step_second") + yield* seedSessions(database, [first], { time_suspended: 1, time_updated: 2 }) + yield* seedSessions(database, [second], { time_suspended: 1, time_updated: 1 }) + const assistantMessageID = SessionMessage.ID.make("msg_resume_step_first") + + const secondStarted = yield* Deferred.make() + const scope = yield* Scope.make() + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) + const context = yield* buildExecution( + scope, + ({ sessionID }) => + sessionID === second + ? Deferred.succeed(secondStarted, undefined).pipe(Effect.andThen(Effect.never)) + : Effect.gen(function* () { + yield* bus.publish(SessionEvent.Step.Started, { + sessionID, + assistantMessageID, + agent: Agent.defaultID, + model: { id: Model.ID.make("model"), providerID: Provider.ID.make("provider") }, + started: 0, + }) + yield* bus.publish(SessionEvent.Step.Ended, { + sessionID, + assistantMessageID, + finish: "stop", + cost: Money.USD.make(0), + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + }) + return yield* Effect.never + }), + { maxConcurrentResumes: 1 }, + ) + yield* Context.get(context, SessionRestart.Service).resumeSuspendedSessions.pipe(Effect.forkIn(scope)) + + // No clock advance and the first turn never ends: only its step can have freed the slot. + yield* Deferred.await(secondStarted) + expect(yield* Context.get(context, SessionExecution.Service).isActive(first)).toBe(true) }), ) @@ -866,6 +954,71 @@ describe("SessionRestart background recovery", () => { }), ) + it.effect("wakes a resumed parent for its child's result while older Sessions still wait for slots", () => + Effect.gen(function* () { + const database = yield* Database.Service + const jobs = yield* Job.Service + const parent = Session.ID.make("ses_gate_wake_parent") + const child = Session.ID.make("ses_gate_wake_child") + const blocking = Session.ID.make("ses_gate_wake_blocking") + const queued = Session.ID.make("ses_gate_wake_queued") + yield* seedSessions(database, [parent], { time_suspended: 1, time_updated: 3 }) + yield* seedSessions(database, [blocking], { time_suspended: 1, time_updated: 2 }) + yield* seedSessions(database, [queued], { time_suspended: 1, time_updated: 1 }) + yield* seedSessions(database, [child], { parent_id: parent, time_suspended: 1 }) + yield* jobs.start({ + id: child, + type: "subagent", + recovery: { + kind: "subagent", + parentSessionID: parent, + childSessionID: child, + agent: "explore", + description: "Inspect gated recovery", + }, + run: Effect.never, + }) + yield* jobs.background(child) + + const childRunning = yield* Deferred.make() + const release = yield* Deferred.make() + const blockingStarted = yield* Deferred.make() + const parentWoken = yield* Deferred.make() + const drained: Session.ID[] = [] + const scope = yield* Scope.make() + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)) + const restarted = yield* Job.make.pipe(Effect.provideService(Scope.Scope, scope)) + const context = yield* buildExecution( + scope, + ({ sessionID }) => + Effect.gen(function* () { + drained.push(sessionID) + if (sessionID === child) + return yield* Deferred.succeed(childRunning, undefined).pipe(Effect.andThen(Deferred.await(release))) + if (sessionID !== parent) + return yield* Deferred.succeed(blockingStarted, undefined).pipe(Effect.andThen(Effect.never)) + if (drained.filter((id) => id === parent).length === 2) yield* Deferred.succeed(parentWoken, undefined) + }), + { maxConcurrentResumes: 2 }, + restarted, + ) + const restart = Context.get(context, SessionRestart.Service) + yield* restart.resumeSuspendedSessions.pipe(Effect.forkIn(scope)) + + // The child and `blocking` hold both slots, so `queued` keeps the sweep open after the parent's turn ends. + yield* Deferred.await(childRunning) + yield* Deferred.await(blockingStarted) + yield* Context.get(context, SessionExecution.Service).awaitIdle(parent) + expect(drained).not.toContain(queued) + + yield* Deferred.succeed(release, undefined) + yield* Deferred.await(parentWoken) + expect(yield* SessionInbox.list(database.db, parent)).toMatchObject([ + { payload: { metadata: { source: "subagent", childID: child, state: "completed" } } }, + ]) + }), + ) + it.effect("delivers a subagent result persisted before restart without rerunning the child", () => Effect.gen(function* () { const database = yield* Database.Service @@ -1284,7 +1437,9 @@ function seedInbox( function seedSessions( database: Database.Service["Service"], sessionIDs: ReadonlyArray, - values: Partial> = {}, + values: Partial< + Pick + > = {}, ) { return Effect.gen(function* () { yield* database.db