session-execution.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { describe, expect, test } from "bun:test"
  2. import { AIError, TransportReason } from "@opencode-ai/ai"
  3. import { Database } from "@opencode-ai/core/database/database"
  4. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  5. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  6. import { Bus } from "@opencode-ai/core/bus"
  7. import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
  8. import type { LocationServices } from "@opencode-ai/core/location-services"
  9. import { Project } from "@opencode-ai/core/project"
  10. import { ProjectTable } from "@opencode-ai/core/project/sql"
  11. import { AbsolutePath } from "@opencode-ai/core/schema"
  12. import { Session } from "@opencode-ai/core/session"
  13. import { SessionExecution } from "@opencode-ai/core/session/execution"
  14. import { SessionRestart } from "@opencode-ai/core/session/execution/restart"
  15. import { UserInterruptedError } from "@opencode-ai/core/session/error"
  16. import { SessionEvent } from "@opencode-ai/core/session/event"
  17. import { SessionRunner } from "@opencode-ai/core/session/runner"
  18. import { SessionTable } from "@opencode-ai/core/session/sql"
  19. import { SessionStore } from "@opencode-ai/core/session/store"
  20. import { Context, Deferred, Effect, Exit, Fiber, Layer, LayerMap, Scope } from "effect"
  21. import { testEffect } from "./lib/effect"
  22. const it = testEffect(AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, SessionStore.node])))
  23. describe("SessionExecution lifecycle", () => {
  24. test("classifies success and typed failure terminals", () => {
  25. expect(SessionExecution.terminal(Exit.succeed(undefined))).toEqual({ type: "succeeded" })
  26. expect(
  27. SessionExecution.terminal(
  28. Exit.fail(
  29. new AIError({
  30. module: "test",
  31. method: "stream",
  32. reason: new TransportReason({ message: "Disconnected" }),
  33. }),
  34. ),
  35. ),
  36. ).toEqual({ type: "failed", error: { type: "provider.transport", message: "Disconnected" } })
  37. })
  38. test("defaults owner-scope interruption to shutdown and preserves explicit reasons", () => {
  39. const interrupted = Effect.runSyncExit(Effect.interrupt)
  40. expect(SessionExecution.terminal(interrupted)).toEqual({ type: "interrupted", reason: "shutdown" })
  41. expect(SessionExecution.terminal(interrupted, "user")).toEqual({ type: "interrupted", reason: "user" })
  42. expect(SessionExecution.terminal(interrupted, "superseded")).toEqual({ type: "interrupted", reason: "superseded" })
  43. expect(SessionExecution.terminal(Exit.fail(new UserInterruptedError()))).toEqual({
  44. type: "interrupted",
  45. reason: "user",
  46. })
  47. })
  48. it.effect("atomically consumes each suspension at most once", () =>
  49. Effect.gen(function* () {
  50. const database = yield* Database.Service
  51. const store = yield* SessionStore.Service
  52. const first = Session.ID.make("ses_recover_first")
  53. const second = Session.ID.make("ses_recover_second")
  54. yield* seedSessions(database, [first, second], { time_suspended: Date.now() })
  55. expect(yield* store.consumeSuspended(first)).toBe(true)
  56. expect(yield* store.consumeSuspended(first)).toBe(false)
  57. expect(yield* store.consumeSuspended(second)).toBe(true)
  58. expect(yield* suspensions(database)).toEqual({ [first]: false, [second]: false })
  59. }),
  60. )
  61. it.effect("suspension survives teardown interruption and clears when a drain finishes on its own", () =>
  62. Effect.gen(function* () {
  63. const database = yield* Database.Service
  64. const interrupted = Session.ID.make("ses_suspend_interrupted")
  65. const completed = Session.ID.make("ses_suspend_completed")
  66. yield* seedSessions(database, [interrupted, completed])
  67. const draining = yield* Deferred.make<void>()
  68. const release = yield* Deferred.make<void>()
  69. const scope = yield* Scope.make()
  70. const context = yield* buildExecution(scope, ({ sessionID }) =>
  71. sessionID === completed
  72. ? Deferred.await(release)
  73. : Deferred.succeed(draining, undefined).pipe(Effect.andThen(Effect.never)),
  74. )
  75. const execution = Context.get(context, SessionExecution.Service)
  76. const restart = Context.get(context, SessionRestart.Service)
  77. yield* execution.resume(interrupted).pipe(Effect.forkScoped)
  78. const completing = yield* execution.resume(completed).pipe(Effect.forkIn(scope))
  79. yield* Deferred.await(draining)
  80. yield* restart.suspendActiveSessions
  81. expect(yield* suspensions(database)).toEqual({ [interrupted]: true, [completed]: true })
  82. // A drain that finishes on its own after suspension clears its stale suspension.
  83. yield* Deferred.succeed(release, undefined)
  84. yield* Fiber.join(completing)
  85. yield* execution.awaitIdle(completed)
  86. expect((yield* suspensions(database))[completed]).toBe(false)
  87. // Teardown interruption preserves suspension for the next server start.
  88. yield* Scope.close(scope, Exit.void)
  89. expect((yield* suspensions(database))[interrupted]).toBe(true)
  90. }),
  91. )
  92. it.effect("starts every suspended execution without waiting for earlier drains to finish", () =>
  93. Effect.gen(function* () {
  94. const database = yield* Database.Service
  95. const sessionIDs = Array.from({ length: 5 }, (_, index) => Session.ID.make(`ses_resume_concurrent_${index}`))
  96. yield* seedSessions(database, sessionIDs, { time_suspended: Date.now() })
  97. const fourStarted = yield* Deferred.make<void>()
  98. const started: Session.ID[] = []
  99. const scope = yield* Scope.make()
  100. yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
  101. const context = yield* buildExecution(scope, ({ sessionID }) =>
  102. Effect.sync(() => {
  103. started.push(sessionID)
  104. if (started.length === 4) Deferred.doneUnsafe(fourStarted, Effect.void)
  105. }).pipe(Effect.andThen(Effect.never)),
  106. )
  107. const execution = Context.get(context, SessionExecution.Service)
  108. const restart = Context.get(context, SessionRestart.Service)
  109. yield* restart.resumeSuspendedSessions.pipe(Effect.forkIn(scope))
  110. yield* Deferred.await(fourStarted)
  111. expect([...(yield* execution.active)].toSorted()).toEqual(sessionIDs.toSorted())
  112. }),
  113. )
  114. it.effect("resumes each suspended Session at most once", () =>
  115. Effect.gen(function* () {
  116. const database = yield* Database.Service
  117. const bus = yield* Bus.Service
  118. const first = Session.ID.make("ses_resume_first")
  119. const second = Session.ID.make("ses_resume_second")
  120. yield* seedSessions(database, [first, second], { time_suspended: Date.now() })
  121. const drained: string[] = []
  122. const continued: SessionEvent.Synthetic[] = []
  123. const scope = yield* Scope.make()
  124. const context = yield* buildExecution(scope, ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)))
  125. const execution = Context.get(context, SessionExecution.Service)
  126. const restart = Context.get(context, SessionRestart.Service)
  127. yield* bus.project(SessionEvent.Synthetic, (event) => Effect.sync(() => void continued.push(event)))
  128. yield* restart.resumeSuspendedSessions
  129. yield* Effect.forEach([first, second], execution.awaitIdle, { discard: true })
  130. expect(drained.toSorted()).toEqual([first, second])
  131. expect(continued.map((event) => event.data).toSorted((a, b) => a.sessionID.localeCompare(b.sessionID))).toEqual(
  132. [first, second].map((sessionID) => ({
  133. sessionID,
  134. text: "The server restarted while you were working. Continue from where you left off without repeating completed work.",
  135. description: "Continuing after restart",
  136. })),
  137. )
  138. expect(yield* suspensions(database)).toEqual({ [first]: false, [second]: false })
  139. yield* restart.resumeSuspendedSessions
  140. expect(drained.length).toBe(2)
  141. expect(continued.length).toBe(2)
  142. yield* Scope.close(scope, Exit.void)
  143. }),
  144. )
  145. })
  146. function seedSessions(
  147. database: Database.Service["Service"],
  148. sessionIDs: ReadonlyArray<Session.ID>,
  149. values: { time_suspended?: number } = {},
  150. ) {
  151. return Effect.gen(function* () {
  152. yield* database.db
  153. .insert(ProjectTable)
  154. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  155. .run()
  156. .pipe(Effect.orDie)
  157. yield* database.db
  158. .insert(SessionTable)
  159. .values(
  160. sessionIDs.map((id) => ({
  161. id,
  162. project_id: Project.ID.global,
  163. slug: id,
  164. directory: "/project",
  165. title: id,
  166. version: "test",
  167. ...values,
  168. })),
  169. )
  170. .run()
  171. .pipe(Effect.orDie)
  172. })
  173. }
  174. function suspensions(database: Database.Service["Service"]) {
  175. return database.db
  176. .select({ id: SessionTable.id, suspended: SessionTable.time_suspended })
  177. .from(SessionTable)
  178. .all()
  179. .pipe(
  180. Effect.orDie,
  181. Effect.map((rows) => Object.fromEntries(rows.map((row) => [row.id, row.suspended !== null]))),
  182. )
  183. }
  184. /** Builds the local execution layer plus the restart actions against the test harness services. */
  185. function buildExecution(scope: Scope.Closeable, drain: SessionRunner.Interface["drain"]) {
  186. return Effect.gen(function* () {
  187. const database = yield* Database.Service
  188. const bus = yield* Bus.Service
  189. const store = yield* SessionStore.Service
  190. const runner = Layer.succeed(SessionRunner.Service, SessionRunner.Service.of({ drain }))
  191. const locations = Layer.effect(
  192. LocationServiceMap.Service,
  193. LayerMap.make(
  194. () =>
  195. // The local execution test only needs the Session runner from the Location graph.
  196. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
  197. runner as unknown as Layer.Layer<LocationServices>,
  198. ),
  199. )
  200. return yield* Layer.buildWithScope(
  201. SessionRestart.layer.pipe(
  202. Layer.provideMerge(SessionExecution.layer),
  203. Layer.provide(Layer.succeed(Database.Service, database)),
  204. Layer.provide(Layer.succeed(Bus.Service, bus)),
  205. Layer.provide(Layer.succeed(SessionStore.Service, store)),
  206. Layer.provide(locations),
  207. ),
  208. scope,
  209. )
  210. })
  211. }