database-migration.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import { describe, expect, test } from "bun:test"
  2. import { $ } from "bun"
  3. import { fileURLToPath } from "url"
  4. import path from "path"
  5. import { SqliteClient } from "@effect/sql-sqlite-bun"
  6. import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite"
  7. import { Effect, Layer } from "effect"
  8. import { eq, inArray, sql } from "drizzle-orm"
  9. import { DatabaseMigration } from "@opencode-ai/core/database/migration"
  10. import sessionUsageMigration from "@opencode-ai/core/database/migration/20260510033149_session_usage"
  11. import normalizeStoragePathsMigration from "@opencode-ai/core/database/migration/20260601010001_normalize_storage_paths"
  12. import sessionMessageProjectionOrderMigration from "@opencode-ai/core/database/migration/20260603040000_session_message_projection_order"
  13. import { ProjectV2 } from "@opencode-ai/core/project"
  14. import { ProjectTable } from "@opencode-ai/core/project/sql"
  15. import { AbsolutePath } from "@opencode-ai/core/schema"
  16. import { SessionSchema } from "@opencode-ai/core/session/schema"
  17. import { SessionTable } from "@opencode-ai/core/session/sql"
  18. import sessionMetadataMigration from "@opencode-ai/core/database/migration/20260511173437_session-metadata"
  19. import type { SqlClient as SqlClientService } from "effect/unstable/sql/SqlClient"
  20. import { Database } from "@opencode-ai/core/database/database"
  21. import { tmpdir } from "./fixture/tmpdir"
  22. const run = <A, E>(effect: Effect.Effect<A, E, SqlClientService>) =>
  23. Effect.runPromise(
  24. effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped),
  25. )
  26. const makeDb = EffectDrizzleSqlite.makeWithDefaults()
  27. describe("DatabaseMigration", () => {
  28. test("serializes concurrent embedded initialization for one database path", async () => {
  29. await using tmp = await tmpdir()
  30. const filename = path.join(tmp.path, "embedded.sqlite")
  31. const layers = [Database.layerFromPath(filename), Database.layerFromPath(filename)]
  32. await Effect.runPromise(
  33. Effect.all(
  34. layers.map((layer) => Effect.scoped(Layer.build(layer))),
  35. { concurrency: "unbounded" },
  36. ),
  37. )
  38. })
  39. if (process.platform === "linux") {
  40. test("declared schema has no ungenerated migrations", async () => {
  41. const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check`
  42. .quiet()
  43. .nothrow()
  44. expect(result.exitCode, result.stderr.toString()).toBe(0)
  45. expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate")
  46. }, 30_000)
  47. }
  48. test("applies tracked migrations to an empty database", async () => {
  49. await run(
  50. Effect.gen(function* () {
  51. const db = yield* makeDb
  52. yield* DatabaseMigration.apply(db)
  53. expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)).toEqual({
  54. name: "session",
  55. })
  56. expect(
  57. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_input'`),
  58. ).toEqual({ name: "session_input" })
  59. expect(yield* db.get(sql`SELECT count(*) as count FROM migration`)).toEqual({ count: 29 })
  60. expect(
  61. yield* db.all(
  62. sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('event_aggregate_seq_idx', 'event_aggregate_type_seq_idx', 'session_input_session_pending_seq_idx', 'session_input_session_pending_delivery_seq_idx', 'session_message_session_idx', 'session_message_session_type_idx', 'session_message_session_seq_idx', 'session_message_session_type_seq_idx', 'session_message_session_time_created_id_idx') ORDER BY name`,
  63. ),
  64. ).toEqual([
  65. { name: "event_aggregate_seq_idx" },
  66. { name: "event_aggregate_type_seq_idx" },
  67. { name: "session_input_session_pending_delivery_seq_idx" },
  68. { name: "session_message_session_seq_idx" },
  69. { name: "session_message_session_time_created_id_idx" },
  70. { name: "session_message_session_type_seq_idx" },
  71. ])
  72. }),
  73. )
  74. })
  75. test("backfills projected Session message order from durable event sequence", async () => {
  76. await run(
  77. Effect.gen(function* () {
  78. const db = yield* makeDb
  79. yield* db.run(sql`CREATE TABLE event (id text PRIMARY KEY, seq integer NOT NULL)`)
  80. yield* db.run(
  81. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, data text NOT NULL)`,
  82. )
  83. yield* db.run(
  84. sql`CREATE INDEX session_message_session_time_created_id_idx ON session_message (session_id, time_created, id)`,
  85. )
  86. yield* db.run(
  87. sql`CREATE INDEX session_message_session_type_time_created_id_idx ON session_message (session_id, type, time_created, id)`,
  88. )
  89. yield* db.run(sql`INSERT INTO event (id, seq) VALUES ('evt_z', 0), ('evt_a', 1)`)
  90. yield* db.run(
  91. sql`INSERT INTO session_message (id, session_id, type, time_created, data) VALUES ('evt_z', 'session', 'user', 0, '{}'), ('evt_a', 'session', 'user', 0, '{}')`,
  92. )
  93. yield* DatabaseMigration.applyOnly(db, [sessionMessageProjectionOrderMigration])
  94. expect(yield* db.all(sql`SELECT id, seq FROM session_message ORDER BY seq`)).toEqual([
  95. { id: "evt_z", seq: 0 },
  96. { id: "evt_a", seq: 1 },
  97. ])
  98. }),
  99. )
  100. })
  101. test("fails projected Session message order backfill without a durable event", async () => {
  102. await expect(
  103. run(
  104. Effect.gen(function* () {
  105. const db = yield* makeDb
  106. yield* db.run(sql`CREATE TABLE event (id text PRIMARY KEY, seq integer NOT NULL)`)
  107. yield* db.run(
  108. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, data text NOT NULL)`,
  109. )
  110. yield* db.run(
  111. sql`INSERT INTO session_message (id, session_id, type, time_created, data) VALUES ('evt_missing', 'session', 'user', 0, '{}')`,
  112. )
  113. yield* DatabaseMigration.applyOnly(db, [sessionMessageProjectionOrderMigration])
  114. }),
  115. ),
  116. ).rejects.toThrow("Cannot migrate session_message projections without matching durable events")
  117. })
  118. test("runs session usage backfill in order with schema changes", async () => {
  119. await run(
  120. Effect.gen(function* () {
  121. const db = yield* makeDb
  122. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`)
  123. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`)
  124. yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`)
  125. yield* db.run(
  126. sql`INSERT INTO message (id, session_id, data) VALUES ('message_1', 'session_1', '{"role":"assistant","cost":1.25,"tokens":{"input":2,"output":3,"reasoning":4,"cache":{"read":5,"write":6}}}')`,
  127. )
  128. yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration])
  129. expect(
  130. yield* db.get(
  131. sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`,
  132. ),
  133. ).toEqual({
  134. cost: 1.25,
  135. tokens_input: 2,
  136. tokens_output: 3,
  137. tokens_reasoning: 4,
  138. tokens_cache_read: 5,
  139. tokens_cache_write: 6,
  140. })
  141. }),
  142. )
  143. })
  144. test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
  145. await run(
  146. Effect.gen(function* () {
  147. const db = yield* makeDb
  148. yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL, sandboxes text NOT NULL)`)
  149. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, directory text NOT NULL, path text)`)
  150. // Windows-shaped rows (drive + backslash) must be normalized.
  151. yield* db.run(
  152. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"win"}, ${"C:\\Repo\\Thing"}, ${JSON.stringify([
  153. "C:\\Repo\\Thing\\sandbox",
  154. ])})`,
  155. )
  156. yield* db.run(
  157. sql`INSERT INTO session (id, directory, path) VALUES (${"win"}, ${"C:\\Repo\\Thing\\packages\\api"}, ${"packages\\api"})`,
  158. )
  159. // UNC worktrees and their sandboxes must normalize too (not just drive paths).
  160. yield* db.run(
  161. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"unc"}, ${"\\\\server\\share"}, ${JSON.stringify([
  162. "\\\\server\\share\\sandbox",
  163. ])})`,
  164. )
  165. // The "/" worktree sentinel and POSIX paths (including a pathological
  166. // backslash in a POSIX filename) must survive byte-for-byte.
  167. yield* db.run(sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"global"}, ${"/"}, ${"[]"})`)
  168. yield* db.run(
  169. sql`INSERT INTO session (id, directory, path) VALUES (${"posix"}, ${"/home/me/we\\ird"}, ${"src\\weird"})`,
  170. )
  171. yield* DatabaseMigration.applyOnly(db, [normalizeStoragePathsMigration])
  172. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'win'`)).toEqual({
  173. worktree: "C:/Repo/Thing",
  174. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  175. })
  176. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'win'`)).toEqual({
  177. directory: "C:/Repo/Thing/packages/api",
  178. path: "packages/api",
  179. })
  180. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'unc'`)).toEqual({
  181. worktree: "//server/share",
  182. sandboxes: JSON.stringify(["//server/share/sandbox"]),
  183. })
  184. expect(yield* db.get(sql`SELECT worktree FROM project WHERE id = 'global'`)).toEqual({ worktree: "/" })
  185. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'posix'`)).toEqual({
  186. directory: "/home/me/we\\ird",
  187. path: "src\\weird",
  188. })
  189. }),
  190. )
  191. })
  192. test("maps native Windows paths through database columns", async () => {
  193. if (process.platform !== "win32") return
  194. await run(
  195. Effect.gen(function* () {
  196. const db = yield* makeDb
  197. yield* DatabaseMigration.apply(db)
  198. const projectID = ProjectV2.ID.make("codec_project")
  199. const worktree = AbsolutePath.make("C:\\Repo\\Thing")
  200. const sandbox = AbsolutePath.make("C:\\Repo\\Thing\\sandbox")
  201. const directory = "C:\\Repo\\Thing\\packages\\api"
  202. const sessionID = SessionSchema.ID.make("ses_codec")
  203. expect(() =>
  204. Effect.runSync(
  205. db
  206. .insert(ProjectTable)
  207. .values({
  208. id: ProjectV2.ID.make("invalid_path"),
  209. worktree: AbsolutePath.make("not-absolute"),
  210. sandboxes: [],
  211. time_created: 1,
  212. time_updated: 1,
  213. })
  214. .run(),
  215. ),
  216. ).toThrow()
  217. yield* db
  218. .insert(ProjectTable)
  219. .values({
  220. id: projectID,
  221. worktree,
  222. sandboxes: [sandbox],
  223. time_created: 1,
  224. time_updated: 1,
  225. })
  226. .run()
  227. yield* db
  228. .insert(SessionTable)
  229. .values({
  230. id: sessionID,
  231. project_id: projectID,
  232. slug: "codec",
  233. directory,
  234. path: "packages\\api",
  235. title: "Codec",
  236. version: "test",
  237. time_created: 1,
  238. time_updated: 1,
  239. })
  240. .run()
  241. expect(
  242. yield* db.get<{ worktree: string; sandboxes: string }>(
  243. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  244. ),
  245. ).toEqual({
  246. worktree: "C:/Repo/Thing",
  247. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  248. })
  249. expect(
  250. yield* db.get<{ directory: string; path: string }>(
  251. sql`SELECT directory, path FROM session WHERE id = ${sessionID}`,
  252. ),
  253. ).toEqual({
  254. directory: "C:/Repo/Thing/packages/api",
  255. path: "packages/api",
  256. })
  257. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  258. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  259. expect(project?.worktree).toBe(worktree)
  260. expect(project?.sandboxes).toEqual([sandbox])
  261. expect(session?.directory).toBe(directory)
  262. expect(session?.path).toBe("packages/api")
  263. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  264. sessionID,
  265. )
  266. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  267. const updated = yield* db
  268. .update(ProjectTable)
  269. .set({ worktree: moved, sandboxes: [moved] })
  270. .where(eq(ProjectTable.id, projectID))
  271. .returning()
  272. .get()
  273. expect(updated?.worktree).toBe(moved)
  274. expect(updated?.sandboxes).toEqual([moved])
  275. expect(
  276. yield* db.get<{ worktree: string; sandboxes: string }>(
  277. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  278. ),
  279. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  280. expect(
  281. (yield* db
  282. .select()
  283. .from(ProjectTable)
  284. .where(inArray(ProjectTable.worktree, [moved]))
  285. .get())?.id,
  286. ).toBe(projectID)
  287. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  288. expect(() =>
  289. Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()),
  290. ).toThrow()
  291. }),
  292. )
  293. })
  294. test("imports existing drizzle migration state", async () => {
  295. await run(
  296. Effect.gen(function* () {
  297. const db = yield* makeDb
  298. yield* db.run(
  299. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  300. )
  301. yield* db.run(sql`
  302. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  303. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  304. `)
  305. yield* DatabaseMigration.applyOnly(db, [])
  306. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  307. }),
  308. )
  309. })
  310. test("does not replay a migrated session metadata column", async () => {
  311. await run(
  312. Effect.gen(function* () {
  313. const db = yield* makeDb
  314. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  315. yield* db.run(
  316. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  317. )
  318. yield* db.run(sql`
  319. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  320. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  321. `)
  322. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  323. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  324. }),
  325. )
  326. })
  327. test("accepts the temporary replacement session metadata migration id", async () => {
  328. await run(
  329. Effect.gen(function* () {
  330. const db = yield* makeDb
  331. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  332. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  333. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  334. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  335. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  336. { id: "20260511173437_session-metadata" },
  337. { id: "20260530232709_lovely_romulus" },
  338. ])
  339. }),
  340. )
  341. })
  342. test("skips drizzle import when migration table already has state", async () => {
  343. await run(
  344. Effect.gen(function* () {
  345. const db = yield* makeDb
  346. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  347. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  348. yield* db.run(
  349. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  350. )
  351. yield* db.run(sql`
  352. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  353. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  354. `)
  355. yield* DatabaseMigration.applyOnly(db, [])
  356. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  357. }),
  358. )
  359. })
  360. })