database-migration.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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("resets incompatible projected Session messages before adding sequence order", async () => {
  76. await run(
  77. Effect.gen(function* () {
  78. const db = yield* makeDb
  79. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
  80. yield* db.run(
  81. sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  82. )
  83. yield* db.run(
  84. sql`CREATE TABLE part (id text PRIMARY KEY, message_id text NOT NULL, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  85. )
  86. yield* db.run(sql`CREATE TABLE event (id text PRIMARY KEY, seq integer NOT NULL)`)
  87. yield* db.run(
  88. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  89. )
  90. yield* db.run(
  91. sql`CREATE INDEX session_message_session_time_created_id_idx ON session_message (session_id, time_created, id)`,
  92. )
  93. yield* db.run(
  94. sql`CREATE INDEX session_message_session_type_time_created_id_idx ON session_message (session_id, type, time_created, id)`,
  95. )
  96. yield* db.run(sql`INSERT INTO session (id) VALUES ('session')`)
  97. yield* db.run(
  98. sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES ('legacy_message', 'session', 1, 1, '{"role":"user"}')`,
  99. )
  100. yield* db.run(
  101. sql`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES ('legacy_part', 'legacy_message', 'session', 1, 1, '{"type":"text","text":"hello"}')`,
  102. )
  103. yield* db.run(
  104. sql`INSERT INTO session_message (id, session_id, type, time_created, time_updated, data) VALUES ('stale_projection', 'session', 'user', 1, 1, '{}')`,
  105. )
  106. yield* DatabaseMigration.applyOnly(db, [sessionMessageProjectionOrderMigration])
  107. expect(yield* db.all(sql`SELECT id, session_id, data FROM message`)).toEqual([
  108. { id: "legacy_message", session_id: "session", data: '{"role":"user"}' },
  109. ])
  110. expect(yield* db.all(sql`SELECT id, message_id, session_id, data FROM part`)).toEqual([
  111. {
  112. id: "legacy_part",
  113. message_id: "legacy_message",
  114. session_id: "session",
  115. data: '{"type":"text","text":"hello"}',
  116. },
  117. ])
  118. expect(yield* db.all(sql`SELECT id FROM session_message`)).toEqual([])
  119. yield* db.run(
  120. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('fresh_projection', 'session', 'user', 7, 2, 2, '{}')`,
  121. )
  122. expect(yield* db.get(sql`SELECT id, seq FROM session_message`)).toEqual({ id: "fresh_projection", seq: 7 })
  123. }),
  124. )
  125. })
  126. test("runs session usage backfill in order with schema changes", async () => {
  127. await run(
  128. Effect.gen(function* () {
  129. const db = yield* makeDb
  130. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`)
  131. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`)
  132. yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`)
  133. yield* db.run(
  134. 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}}}')`,
  135. )
  136. yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration])
  137. expect(
  138. yield* db.get(
  139. sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`,
  140. ),
  141. ).toEqual({
  142. cost: 1.25,
  143. tokens_input: 2,
  144. tokens_output: 3,
  145. tokens_reasoning: 4,
  146. tokens_cache_read: 5,
  147. tokens_cache_write: 6,
  148. })
  149. }),
  150. )
  151. })
  152. test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
  153. await run(
  154. Effect.gen(function* () {
  155. const db = yield* makeDb
  156. yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL, sandboxes text NOT NULL)`)
  157. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, directory text NOT NULL, path text)`)
  158. // Windows-shaped rows (drive + backslash) must be normalized.
  159. yield* db.run(
  160. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"win"}, ${"C:\\Repo\\Thing"}, ${JSON.stringify([
  161. "C:\\Repo\\Thing\\sandbox",
  162. ])})`,
  163. )
  164. yield* db.run(
  165. sql`INSERT INTO session (id, directory, path) VALUES (${"win"}, ${"C:\\Repo\\Thing\\packages\\api"}, ${"packages\\api"})`,
  166. )
  167. // UNC worktrees and their sandboxes must normalize too (not just drive paths).
  168. yield* db.run(
  169. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"unc"}, ${"\\\\server\\share"}, ${JSON.stringify([
  170. "\\\\server\\share\\sandbox",
  171. ])})`,
  172. )
  173. // The "/" worktree sentinel and POSIX paths (including a pathological
  174. // backslash in a POSIX filename) must survive byte-for-byte.
  175. yield* db.run(sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"global"}, ${"/"}, ${"[]"})`)
  176. yield* db.run(
  177. sql`INSERT INTO session (id, directory, path) VALUES (${"posix"}, ${"/home/me/we\\ird"}, ${"src\\weird"})`,
  178. )
  179. yield* DatabaseMigration.applyOnly(db, [normalizeStoragePathsMigration])
  180. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'win'`)).toEqual({
  181. worktree: "C:/Repo/Thing",
  182. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  183. })
  184. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'win'`)).toEqual({
  185. directory: "C:/Repo/Thing/packages/api",
  186. path: "packages/api",
  187. })
  188. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'unc'`)).toEqual({
  189. worktree: "//server/share",
  190. sandboxes: JSON.stringify(["//server/share/sandbox"]),
  191. })
  192. expect(yield* db.get(sql`SELECT worktree FROM project WHERE id = 'global'`)).toEqual({ worktree: "/" })
  193. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'posix'`)).toEqual({
  194. directory: "/home/me/we\\ird",
  195. path: "src\\weird",
  196. })
  197. }),
  198. )
  199. })
  200. test("maps native Windows paths through database columns", async () => {
  201. if (process.platform !== "win32") return
  202. await run(
  203. Effect.gen(function* () {
  204. const db = yield* makeDb
  205. yield* DatabaseMigration.apply(db)
  206. const projectID = ProjectV2.ID.make("codec_project")
  207. const worktree = AbsolutePath.make("C:\\Repo\\Thing")
  208. const sandbox = AbsolutePath.make("C:\\Repo\\Thing\\sandbox")
  209. const directory = "C:\\Repo\\Thing\\packages\\api"
  210. const sessionID = SessionSchema.ID.make("ses_codec")
  211. expect(() =>
  212. Effect.runSync(
  213. db
  214. .insert(ProjectTable)
  215. .values({
  216. id: ProjectV2.ID.make("invalid_path"),
  217. worktree: AbsolutePath.make("not-absolute"),
  218. sandboxes: [],
  219. time_created: 1,
  220. time_updated: 1,
  221. })
  222. .run(),
  223. ),
  224. ).toThrow()
  225. yield* db
  226. .insert(ProjectTable)
  227. .values({
  228. id: projectID,
  229. worktree,
  230. sandboxes: [sandbox],
  231. time_created: 1,
  232. time_updated: 1,
  233. })
  234. .run()
  235. yield* db
  236. .insert(SessionTable)
  237. .values({
  238. id: sessionID,
  239. project_id: projectID,
  240. slug: "codec",
  241. directory,
  242. path: "packages\\api",
  243. title: "Codec",
  244. version: "test",
  245. time_created: 1,
  246. time_updated: 1,
  247. })
  248. .run()
  249. expect(
  250. yield* db.get<{ worktree: string; sandboxes: string }>(
  251. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  252. ),
  253. ).toEqual({
  254. worktree: "C:/Repo/Thing",
  255. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  256. })
  257. expect(
  258. yield* db.get<{ directory: string; path: string }>(
  259. sql`SELECT directory, path FROM session WHERE id = ${sessionID}`,
  260. ),
  261. ).toEqual({
  262. directory: "C:/Repo/Thing/packages/api",
  263. path: "packages/api",
  264. })
  265. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  266. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  267. expect(project?.worktree).toBe(worktree)
  268. expect(project?.sandboxes).toEqual([sandbox])
  269. expect(session?.directory).toBe(directory)
  270. expect(session?.path).toBe("packages/api")
  271. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  272. sessionID,
  273. )
  274. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  275. const updated = yield* db
  276. .update(ProjectTable)
  277. .set({ worktree: moved, sandboxes: [moved] })
  278. .where(eq(ProjectTable.id, projectID))
  279. .returning()
  280. .get()
  281. expect(updated?.worktree).toBe(moved)
  282. expect(updated?.sandboxes).toEqual([moved])
  283. expect(
  284. yield* db.get<{ worktree: string; sandboxes: string }>(
  285. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  286. ),
  287. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  288. expect(
  289. (yield* db
  290. .select()
  291. .from(ProjectTable)
  292. .where(inArray(ProjectTable.worktree, [moved]))
  293. .get())?.id,
  294. ).toBe(projectID)
  295. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  296. expect(() =>
  297. Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()),
  298. ).toThrow()
  299. }),
  300. )
  301. })
  302. test("imports existing drizzle migration state", async () => {
  303. await run(
  304. Effect.gen(function* () {
  305. const db = yield* makeDb
  306. yield* db.run(
  307. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  308. )
  309. yield* db.run(sql`
  310. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  311. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  312. `)
  313. yield* DatabaseMigration.applyOnly(db, [])
  314. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  315. }),
  316. )
  317. })
  318. test("does not replay a migrated session metadata column", async () => {
  319. await run(
  320. Effect.gen(function* () {
  321. const db = yield* makeDb
  322. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  323. yield* db.run(
  324. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  325. )
  326. yield* db.run(sql`
  327. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  328. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  329. `)
  330. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  331. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  332. }),
  333. )
  334. })
  335. test("accepts the temporary replacement session metadata migration id", async () => {
  336. await run(
  337. Effect.gen(function* () {
  338. const db = yield* makeDb
  339. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  340. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  341. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  342. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  343. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  344. { id: "20260511173437_session-metadata" },
  345. { id: "20260530232709_lovely_romulus" },
  346. ])
  347. }),
  348. )
  349. })
  350. test("skips drizzle import when migration table already has state", async () => {
  351. await run(
  352. Effect.gen(function* () {
  353. const db = yield* makeDb
  354. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  355. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  356. yield* db.run(
  357. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  358. )
  359. yield* db.run(sql`
  360. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  361. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  362. `)
  363. yield* DatabaseMigration.applyOnly(db, [])
  364. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  365. }),
  366. )
  367. })
  368. })