session-execution.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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/core/effect/layer-node"
  6. import { EventV2 } from "@opencode-ai/core/event"
  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 { SessionV2 } 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 { ToolOutputStore } from "@opencode-ai/core/tool-output-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, EventV2.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 LLMError({
  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. const storage = new ToolOutputStore.StorageError({ operation: "encode", cause: new Error("invalid output") })
  38. expect(SessionExecution.terminal(Exit.fail(storage))).toEqual({
  39. type: "failed",
  40. error: { type: "unknown", message: storage.message },
  41. })
  42. })
  43. test("defaults owner-scope interruption to shutdown and preserves explicit reasons", () => {
  44. const interrupted = Effect.runSyncExit(Effect.interrupt)
  45. expect(SessionExecution.terminal(interrupted)).toEqual({ type: "interrupted", reason: "shutdown" })
  46. expect(SessionExecution.terminal(interrupted, "user")).toEqual({ type: "interrupted", reason: "user" })
  47. expect(SessionExecution.terminal(interrupted, "superseded")).toEqual({ type: "interrupted", reason: "superseded" })
  48. expect(SessionExecution.terminal(Exit.fail(new UserInterruptedError()))).toEqual({
  49. type: "interrupted",
  50. reason: "user",
  51. })
  52. })
  53. it.effect("atomically consumes each suspension at most once", () =>
  54. Effect.gen(function* () {
  55. const database = yield* Database.Service
  56. const store = yield* SessionStore.Service
  57. const first = SessionV2.ID.make("ses_recover_first")
  58. const second = SessionV2.ID.make("ses_recover_second")
  59. yield* seedSessions(database, [first, second], { time_suspended: Date.now() })
  60. expect(yield* store.consumeSuspended(first)).toBe(true)
  61. expect(yield* store.consumeSuspended(first)).toBe(false)
  62. expect(yield* store.consumeSuspended(second)).toBe(true)
  63. expect(yield* suspensions(database)).toEqual({ [first]: false, [second]: false })
  64. }),
  65. )
  66. it.effect("suspension survives teardown interruption and clears when a drain finishes on its own", () =>
  67. Effect.gen(function* () {
  68. const database = yield* Database.Service
  69. const interrupted = SessionV2.ID.make("ses_suspend_interrupted")
  70. const completed = SessionV2.ID.make("ses_suspend_completed")
  71. yield* seedSessions(database, [interrupted, completed])
  72. const draining = yield* Deferred.make<void>()
  73. const release = yield* Deferred.make<void>()
  74. const scope = yield* Scope.make()
  75. const context = yield* buildExecution(scope, ({ sessionID }) =>
  76. sessionID === completed
  77. ? Deferred.await(release)
  78. : Deferred.succeed(draining, undefined).pipe(Effect.andThen(Effect.never)),
  79. )
  80. const execution = Context.get(context, SessionExecution.Service)
  81. const restart = Context.get(context, SessionRestart.Service)
  82. yield* execution.resume(interrupted).pipe(Effect.forkScoped)
  83. const completing = yield* execution.resume(completed).pipe(Effect.forkIn(scope))
  84. yield* Deferred.await(draining)
  85. yield* restart.suspendActiveSessions
  86. expect(yield* suspensions(database)).toEqual({ [interrupted]: true, [completed]: true })
  87. // A drain that finishes on its own after suspension clears its stale suspension.
  88. yield* Deferred.succeed(release, undefined)
  89. yield* Fiber.join(completing)
  90. yield* execution.awaitIdle(completed)
  91. expect((yield* suspensions(database))[completed]).toBe(false)
  92. // Teardown interruption preserves suspension for the next server start.
  93. yield* Scope.close(scope, Exit.void)
  94. expect((yield* suspensions(database))[interrupted]).toBe(true)
  95. }),
  96. )
  97. it.effect("resumes each suspended Session at most once", () =>
  98. Effect.gen(function* () {
  99. const database = yield* Database.Service
  100. const first = SessionV2.ID.make("ses_resume_first")
  101. const second = SessionV2.ID.make("ses_resume_second")
  102. yield* seedSessions(database, [first, second], { time_suspended: Date.now() })
  103. const drained: string[] = []
  104. const scope = yield* Scope.make()
  105. const context = yield* buildExecution(scope, ({ sessionID }) => Effect.sync(() => void drained.push(sessionID)))
  106. const restart = Context.get(context, SessionRestart.Service)
  107. yield* restart.resumeSuspendedSessions
  108. expect(drained.toSorted()).toEqual([first, second])
  109. expect(yield* suspensions(database)).toEqual({ [first]: false, [second]: false })
  110. yield* restart.resumeSuspendedSessions
  111. expect(drained.length).toBe(2)
  112. yield* Scope.close(scope, Exit.void)
  113. }),
  114. )
  115. })
  116. function seedSessions(
  117. database: Database.Service["Service"],
  118. sessionIDs: ReadonlyArray<SessionV2.ID>,
  119. values: { time_suspended?: number } = {},
  120. ) {
  121. return Effect.gen(function* () {
  122. yield* database.db
  123. .insert(ProjectTable)
  124. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  125. .run()
  126. .pipe(Effect.orDie)
  127. yield* database.db
  128. .insert(SessionTable)
  129. .values(
  130. sessionIDs.map((id) => ({
  131. id,
  132. project_id: Project.ID.global,
  133. slug: id,
  134. directory: "/project",
  135. title: id,
  136. version: "test",
  137. ...values,
  138. })),
  139. )
  140. .run()
  141. .pipe(Effect.orDie)
  142. })
  143. }
  144. function suspensions(database: Database.Service["Service"]) {
  145. return database.db
  146. .select({ id: SessionTable.id, suspended: SessionTable.time_suspended })
  147. .from(SessionTable)
  148. .all()
  149. .pipe(
  150. Effect.orDie,
  151. Effect.map((rows) => Object.fromEntries(rows.map((row) => [row.id, row.suspended !== null]))),
  152. )
  153. }
  154. /** Builds the local execution layer plus the restart actions against the test harness services. */
  155. function buildExecution(scope: Scope.Closeable, drain: SessionRunner.Interface["drain"]) {
  156. return Effect.gen(function* () {
  157. const database = yield* Database.Service
  158. const events = yield* EventV2.Service
  159. const store = yield* SessionStore.Service
  160. const runner = Layer.succeed(SessionRunner.Service, SessionRunner.Service.of({ drain }))
  161. const locations = Layer.effect(
  162. LocationServiceMap.Service,
  163. LayerMap.make(
  164. () =>
  165. // The local execution test only needs the Session runner from the Location graph.
  166. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
  167. runner as unknown as Layer.Layer<LocationServices>,
  168. ),
  169. )
  170. return yield* Layer.buildWithScope(
  171. SessionRestart.layer.pipe(
  172. Layer.provideMerge(SessionExecution.layer),
  173. Layer.provide(Layer.succeed(Database.Service, database)),
  174. Layer.provide(Layer.succeed(EventV2.Service, events)),
  175. Layer.provide(Layer.succeed(SessionStore.Service, store)),
  176. Layer.provide(locations),
  177. ),
  178. scope,
  179. )
  180. })
  181. }