session-execution.test.ts 9.3 KB

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