database-migration.test.ts 17 KB

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