session-execution.test.ts 8.2 KB

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