instruction-state.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import { describe, expect } from "bun:test"
  2. import { and, asc, eq } from "drizzle-orm"
  3. import { Effect, Schema } from "effect"
  4. import { Database } from "@opencode-ai/core/database/database"
  5. import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
  6. import { LayerNode } from "@opencode-ai/util/effect/layer-node"
  7. import { Bus } from "@opencode-ai/core/bus"
  8. import { Event } from "@opencode-ai/schema/event"
  9. import { EventTable } from "@opencode-ai/core/event/sql"
  10. import { Instructions } from "@opencode-ai/core/instructions"
  11. import { Project } from "@opencode-ai/core/project"
  12. import { ProjectTable } from "@opencode-ai/core/project/sql"
  13. import { AbsolutePath } from "@opencode-ai/core/schema"
  14. import { InstructionState } from "@opencode-ai/core/session/instruction-state"
  15. import { SessionProjector } from "@opencode-ai/core/session/projector"
  16. import { SessionSchema } from "@opencode-ai/core/session/schema"
  17. import { InstructionBlobTable, InstructionStateTable, SessionTable } from "@opencode-ai/core/session/sql"
  18. import { testEffect } from "./lib/effect"
  19. const it = testEffect(AppNodeBuilder.build(LayerNode.group([Database.node, Bus.node, SessionProjector.node])))
  20. const source = (name: string, read: Effect.Effect<string | Instructions.Unavailable | Instructions.Removed>) =>
  21. Instructions.make({
  22. key: Instructions.Key.make(name),
  23. codec: Schema.toCodecJson(Schema.String),
  24. read,
  25. render: {
  26. initial: String,
  27. changed: (_previous, current) => current,
  28. removed: (previous) => `Removed ${previous}`,
  29. },
  30. })
  31. const setup = (sessionID: SessionSchema.ID) =>
  32. Effect.gen(function* () {
  33. const { db } = yield* Database.Service
  34. yield* db
  35. .insert(ProjectTable)
  36. .values({ id: Project.ID.global, worktree: AbsolutePath.make("/project"), sandboxes: [] })
  37. .onConflictDoNothing()
  38. .run()
  39. .pipe(Effect.orDie)
  40. yield* db
  41. .insert(SessionTable)
  42. .values({
  43. id: sessionID,
  44. project_id: Project.ID.global,
  45. slug: "instruction-state-test",
  46. directory: "/project",
  47. title: "Instruction state test",
  48. version: "test",
  49. })
  50. .run()
  51. .pipe(Effect.orDie)
  52. return { db, events: yield* Bus.Service }
  53. })
  54. const instructionEvents = (db: Database.Interface["db"], sessionID: SessionSchema.ID) =>
  55. db
  56. .select()
  57. .from(EventTable)
  58. .where(and(eq(EventTable.aggregate_id, sessionID), eq(EventTable.type, "session.instructions.updated.2")))
  59. .orderBy(asc(EventTable.seq))
  60. .all()
  61. .pipe(Effect.orDie)
  62. const preview = (db: Database.Interface["db"], sessionID: SessionSchema.ID, instructions: Instructions.Instructions) =>
  63. Instructions.read(instructions).pipe(
  64. Effect.flatMap((observed) => InstructionState.preview(db, sessionID, instructions, observed)),
  65. )
  66. describe("InstructionState", () => {
  67. it.effect("observes each source once without publishing events or inserting blobs", () =>
  68. Effect.gen(function* () {
  69. const sessionID = SessionSchema.ID.make("ses_instruction_observe")
  70. const { db, events } = yield* setup(sessionID)
  71. const reads = { first: 0, second: 0 }
  72. const instructions = Instructions.combine([
  73. source(
  74. "test/first",
  75. Effect.sync(() => {
  76. reads.first++
  77. return "first"
  78. }),
  79. ),
  80. source(
  81. "test/second",
  82. Effect.sync(() => {
  83. reads.second++
  84. return "second"
  85. }),
  86. ),
  87. ])
  88. const published: Event.Payload[] = []
  89. const unsubscribe = yield* events.listen((event) =>
  90. Effect.sync(() => {
  91. if (event.type === "session.instructions.updated") published.push(event)
  92. }),
  93. )
  94. const observation = yield* InstructionState.observe(db, instructions, sessionID)
  95. yield* unsubscribe
  96. expect(reads).toEqual({ first: 1, second: 1 })
  97. expect(observation).toEqual({
  98. sessionID,
  99. initial: true,
  100. current: {
  101. "test/first": Instructions.hash("first"),
  102. "test/second": Instructions.hash("second"),
  103. },
  104. delta: {
  105. "test/first": Instructions.hash("first"),
  106. "test/second": Instructions.hash("second"),
  107. },
  108. blobs: {
  109. [Instructions.hash("first")]: "first",
  110. [Instructions.hash("second")]: "second",
  111. },
  112. })
  113. expect(published).toEqual([])
  114. expect(yield* instructionEvents(db, sessionID)).toEqual([])
  115. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual([])
  116. }),
  117. )
  118. it.effect("commits initial metadata and changed and removed deltas without rereading sources", () =>
  119. Effect.gen(function* () {
  120. const sessionID = SessionSchema.ID.make("ses_instruction_commit")
  121. const { db, events } = yield* setup(sessionID)
  122. let current = "initial"
  123. let retired: string | Instructions.Removed = "retired"
  124. let reads = 0
  125. const instructions = Instructions.combine([
  126. source(
  127. "test/current",
  128. Effect.sync(() => {
  129. reads++
  130. return current
  131. }),
  132. ),
  133. source(
  134. "test/retired",
  135. Effect.sync(() => {
  136. reads++
  137. return retired
  138. }),
  139. ),
  140. ])
  141. const published: Event.Payload[] = []
  142. const unsubscribe = yield* events.listen((event) =>
  143. Effect.sync(() => {
  144. if (event.type === "session.instructions.updated") published.push(event)
  145. }),
  146. )
  147. const initial = yield* InstructionState.observe(db, instructions, sessionID)
  148. expect(reads).toBe(2)
  149. yield* InstructionState.commit(db, events, initial)
  150. expect(reads).toBe(2)
  151. current = "changed"
  152. retired = Instructions.removed
  153. const changed = yield* InstructionState.observe(db, instructions, sessionID)
  154. expect(reads).toBe(4)
  155. expect(changed).toMatchObject({
  156. sessionID,
  157. initial: false,
  158. current: { "test/current": Instructions.hash("changed") },
  159. delta: {
  160. "test/current": Instructions.hash("changed"),
  161. "test/retired": "removed",
  162. },
  163. blobs: { [Instructions.hash("changed")]: "changed" },
  164. })
  165. yield* InstructionState.commit(db, events, changed)
  166. expect(reads).toBe(4)
  167. yield* unsubscribe
  168. expect(published).toHaveLength(2)
  169. expect(published[0]?.metadata).toEqual({ instructions: { initial: true } })
  170. expect(published[1]?.metadata).toBeUndefined()
  171. expect((yield* instructionEvents(db, sessionID)).map((event) => event.data.delta)).toEqual([
  172. {
  173. "test/current": Instructions.hash("initial"),
  174. "test/retired": Instructions.hash("retired"),
  175. },
  176. {
  177. "test/current": Instructions.hash("changed"),
  178. "test/retired": "removed",
  179. },
  180. ])
  181. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toMatchObject({
  182. initial_values: {
  183. "test/current": Instructions.hash("initial"),
  184. "test/retired": Instructions.hash("retired"),
  185. },
  186. current_values: { "test/current": Instructions.hash("changed") },
  187. })
  188. expect(
  189. Object.fromEntries(
  190. (yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).map((row) => [row.hash, row.value]),
  191. ),
  192. ).toEqual({
  193. [Instructions.hash("initial")]: "initial",
  194. [Instructions.hash("retired")]: "retired",
  195. [Instructions.hash("changed")]: "changed",
  196. })
  197. }),
  198. )
  199. it.effect("keeps no-op observations free of events and blobs", () =>
  200. Effect.gen(function* () {
  201. const sessionID = SessionSchema.ID.make("ses_instruction_noop")
  202. const { db, events } = yield* setup(sessionID)
  203. const instructions = source("test/context", Effect.succeed("unchanged"))
  204. yield* InstructionState.prepare(db, events, instructions, sessionID)
  205. const beforeEvents = yield* instructionEvents(db, sessionID)
  206. const beforeBlobs = yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)
  207. const observation = yield* InstructionState.observe(db, instructions, sessionID)
  208. expect(observation).toEqual({
  209. sessionID,
  210. initial: false,
  211. current: { "test/context": Instructions.hash("unchanged") },
  212. delta: {},
  213. blobs: {},
  214. })
  215. yield* InstructionState.commit(db, events, observation)
  216. expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents)
  217. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs)
  218. }),
  219. )
  220. it.effect("assembles a fresh private update without repairing a missing cache", () =>
  221. Effect.gen(function* () {
  222. const sessionID = SessionSchema.ID.make("ses_instruction_generate")
  223. const { db, events } = yield* setup(sessionID)
  224. let value = "Initial context"
  225. const instructions = source(
  226. "test/context",
  227. Effect.sync(() => value),
  228. )
  229. yield* InstructionState.prepare(db, events, instructions, sessionID)
  230. yield* db
  231. .delete(InstructionStateTable)
  232. .where(eq(InstructionStateTable.session_id, sessionID))
  233. .run()
  234. .pipe(Effect.orDie)
  235. value = "Changed context"
  236. const beforeEvents = yield* instructionEvents(db, sessionID)
  237. const beforeBlobs = yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)
  238. const assembled = yield* preview(db, sessionID, instructions)
  239. expect(assembled).toEqual({ initial: "Initial context", updates: [], update: "Changed context" })
  240. expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents)
  241. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs)
  242. expect(
  243. yield* db
  244. .select()
  245. .from(InstructionStateTable)
  246. .where(eq(InstructionStateTable.session_id, sessionID))
  247. .get()
  248. .pipe(Effect.orDie),
  249. ).toBeUndefined()
  250. }),
  251. )
  252. it.effect("reads through a stale cache without repairing it", () =>
  253. Effect.gen(function* () {
  254. const sessionID = SessionSchema.ID.make("ses_instruction_generate_stale")
  255. const { db, events } = yield* setup(sessionID)
  256. let value = "Initial context"
  257. const instructions = source(
  258. "test/context",
  259. Effect.sync(() => value),
  260. )
  261. yield* InstructionState.prepare(db, events, instructions, sessionID)
  262. value = "Committed update"
  263. yield* InstructionState.prepare(db, events, instructions, sessionID)
  264. yield* db
  265. .update(InstructionStateTable)
  266. .set({ through_seq: 0, current_values: { "test/context": Instructions.hash("Initial context") } })
  267. .where(eq(InstructionStateTable.session_id, sessionID))
  268. .run()
  269. .pipe(Effect.orDie)
  270. value = "Private update"
  271. const beforeEvents = yield* instructionEvents(db, sessionID)
  272. const beforeBlobs = yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)
  273. const beforeState = yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)
  274. const assembled = yield* preview(db, sessionID, instructions)
  275. expect(assembled.initial).toBe("Initial context")
  276. expect(assembled.updates.map((entry) => entry.message.text)).toEqual(["Committed update"])
  277. expect(assembled.update).toBe("Private update")
  278. expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents)
  279. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs)
  280. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toEqual(beforeState)
  281. }),
  282. )
  283. it.effect("assembles initial instructions without persisting a baseline", () =>
  284. Effect.gen(function* () {
  285. const sessionID = SessionSchema.ID.make("ses_instruction_generate_initial")
  286. const { db } = yield* setup(sessionID)
  287. const instructions = source("test/context", Effect.succeed("Initial context"))
  288. expect(yield* preview(db, sessionID, instructions)).toEqual({
  289. initial: "Initial context",
  290. updates: [],
  291. update: "",
  292. })
  293. expect(yield* instructionEvents(db, sessionID)).toEqual([])
  294. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual([])
  295. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toBeUndefined()
  296. }),
  297. )
  298. it.effect("retains a committed value when fresh instructions are unavailable", () =>
  299. Effect.gen(function* () {
  300. const sessionID = SessionSchema.ID.make("ses_instruction_generate_unavailable")
  301. const { db, events } = yield* setup(sessionID)
  302. let value: string | Instructions.Unavailable = "Committed context"
  303. const instructions = source(
  304. "test/context",
  305. Effect.sync(() => value),
  306. )
  307. yield* InstructionState.prepare(db, events, instructions, sessionID)
  308. value = Instructions.unavailable
  309. const beforeEvents = yield* instructionEvents(db, sessionID)
  310. const beforeBlobs = yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)
  311. const beforeState = yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)
  312. expect(yield* preview(db, sessionID, instructions)).toEqual({
  313. initial: "Committed context",
  314. updates: [],
  315. update: "",
  316. })
  317. expect(yield* instructionEvents(db, sessionID)).toEqual(beforeEvents)
  318. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual(beforeBlobs)
  319. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toEqual(beforeState)
  320. }),
  321. )
  322. it.effect("blocks an unavailable initial instruction without persisting a baseline", () =>
  323. Effect.gen(function* () {
  324. const sessionID = SessionSchema.ID.make("ses_instruction_generate_blocked")
  325. const { db } = yield* setup(sessionID)
  326. const instructions = source("test/context", Effect.succeed(Instructions.unavailable))
  327. const error = yield* preview(db, sessionID, instructions).pipe(Effect.flip)
  328. expect(error).toBeInstanceOf(Instructions.InitializationBlocked)
  329. expect(error.keys).toEqual([Instructions.Key.make("test/context")])
  330. expect(yield* instructionEvents(db, sessionID)).toEqual([])
  331. expect(yield* db.select().from(InstructionBlobTable).all().pipe(Effect.orDie)).toEqual([])
  332. expect(yield* db.select().from(InstructionStateTable).get().pipe(Effect.orDie)).toBeUndefined()
  333. }),
  334. )
  335. it.effect("keeps prepare equivalent to observe followed by commit", () =>
  336. Effect.gen(function* () {
  337. const observedSessionID = SessionSchema.ID.make("ses_instruction_composed")
  338. const preparedSessionID = SessionSchema.ID.make("ses_instruction_prepared")
  339. const { db, events } = yield* setup(observedSessionID)
  340. yield* setup(preparedSessionID)
  341. let value: string | Instructions.Removed = "initial"
  342. let observedReads = 0
  343. let preparedReads = 0
  344. const observedInstructions = source(
  345. "test/context",
  346. Effect.sync(() => {
  347. observedReads++
  348. return value
  349. }),
  350. )
  351. const preparedInstructions = source(
  352. "test/context",
  353. Effect.sync(() => {
  354. preparedReads++
  355. return value
  356. }),
  357. )
  358. for (const next of ["initial", "changed", "changed", Instructions.removed] as const) {
  359. value = next
  360. yield* InstructionState.observe(db, observedInstructions, observedSessionID).pipe(
  361. Effect.flatMap((observation) => InstructionState.commit(db, events, observation)),
  362. )
  363. yield* InstructionState.prepare(db, events, preparedInstructions, preparedSessionID)
  364. }
  365. expect(observedReads).toBe(4)
  366. expect(preparedReads).toBe(4)
  367. expect((yield* instructionEvents(db, observedSessionID)).map((event) => event.data.delta)).toEqual(
  368. (yield* instructionEvents(db, preparedSessionID)).map((event) => event.data.delta),
  369. )
  370. const states = yield* db.select().from(InstructionStateTable).orderBy(asc(InstructionStateTable.session_id)).all()
  371. expect(states).toHaveLength(2)
  372. expect(
  373. states.map((state) => ({
  374. epoch_start: state.epoch_start,
  375. through_seq: state.through_seq,
  376. initial_values: state.initial_values,
  377. current_values: state.current_values,
  378. })),
  379. ).toEqual([
  380. {
  381. epoch_start: 0,
  382. through_seq: 2,
  383. initial_values: { "test/context": Instructions.hash("initial") },
  384. current_values: {},
  385. },
  386. {
  387. epoch_start: 0,
  388. through_seq: 2,
  389. initial_values: { "test/context": Instructions.hash("initial") },
  390. current_values: {},
  391. },
  392. ])
  393. }),
  394. )
  395. })