Open History to see the last commit
1/**
2 * Proves the in-example `node:sqlite` backend satisfies the full
3 * `AIPersistence` contract by running the shared conformance testkit from
4 * `@tanstack/ai-persistence`. This is exactly how you would verify your own
5 * hand-rolled adapter: point the testkit at your factory and keep it green.
6 */
7import { mkdtempSync, rmSync } from 'node:fs'
8import { tmpdir } from 'node:os'
9import { join } from 'node:path'
10import { DatabaseSync } from 'node:sqlite'
11import { describe, expect, it } from 'vitest'
12import { runPersistenceConformance } from '@tanstack/ai-persistence/testkit'
13import { sqlitePersistence } from './sqlite-persistence'
14
15// All seven stores are provided — the four chat state stores plus
16// `generationRuns` + `artifacts` + `blobs` — so no STORE is skipped. One
17// OPTIONAL `runs` method is genuinely missing here, and the suite requires the
18// omission to be declared: `listByThread` (this example never renders a
19// thread's past runs). Declaring it is what makes vitest report that case as
20// SKIPPED; leaving it undeclared fails the suite, so a missing method can never
21// read as a pass. `findActiveRun` and `listReclaimable` ARE implemented, so they
22// stay under test.
23//
24// (Locks are not a store and the suite does not cover them: this backend has no
25// distributed lock primitive, which is a separate `withLocks` concern.)
26runPersistenceConformance(
27 'ts-react-chat example (node:sqlite)',
28 () => sqlitePersistence({ url: ':memory:', migrate: true }),
29 { skipMethods: ['runs.listByThread'] },
30)
31
32// SQL-specific case the in-memory reference backend cannot express: a real
33// query layer can get `NULL <= ?` wrong in ways JS's `undefined <= n`
34// (`NaN <= n`, always false) never surfaces. This pins the SQLite backend's
35// `detached_since IS NOT NULL` guard directly, independent of the shared
36// conformance suite.
37describe('sqlitePersistence runs.listReclaimable — SQL NULL handling', () => {
38 it('never returns a run whose detached_since column is NULL, regardless of ttlMs', async () => {
39 const persistence = sqlitePersistence({ url: ':memory:', migrate: true })
40 try {
41 const runs = persistence.stores.runs
42 if (!runs.listReclaimable) {
43 throw new Error('expected runs.listReclaimable to be implemented')
44 }
45 await runs.createOrResume({
46 runId: 'null-detached-run',
47 threadId: 'null-detached-thread',
48 startedAt: 1,
49 })
50 // detachedSince is never set on this run, so the column stays NULL.
51
52 for (const ttlMs of [0, -1, Number.MAX_SAFE_INTEGER]) {
53 const reclaimable = await runs.listReclaimable({
54 now: Date.now(),
55 ttlMs,
56 })
57 expect(reclaimable.some((r) => r.runId === 'null-detached-run')).toBe(
58 false,
59 )
60 }
61 } finally {
62 persistence.close()
63 }
64 })
65})
66
67// `CREATE TABLE IF NOT EXISTS` does not alter a table that already exists, so a
68// `.data/*.db` written by an earlier version of this example has none of the
69// durable-run columns. That file used to break hard AND early: `createRunStore`
70// prepares its `listReclaimable` statement eagerly and `node:sqlite` resolves
71// column names at prepare time, so the factory threw `no such column:
72// detached_since` before serving a single request. This pins the additive
73// migration against a genuinely old file rather than a fresh one.
74describe('sqlitePersistence migrate — an existing pre-durability database', () => {
75 it('adds the missing runs columns instead of throwing at prepare time', async () => {
76 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-migrate-'))
77 const file = join(dir, 'old.db')
78 try {
79 // A `runs` table exactly as it shipped BEFORE the durable-run fields.
80 const old = new DatabaseSync(file)
81 old.exec(`
82 CREATE TABLE runs (
83 run_id text PRIMARY KEY NOT NULL,
84 thread_id text NOT NULL,
85 status text NOT NULL,
86 started_at integer NOT NULL,
87 finished_at integer,
88 error text
89 );
90 `)
91 old.close()
92
93 // Opening it must migrate rather than throw...
94 const persistence = sqlitePersistence({ url: file, migrate: true })
95 try {
96 const runs = persistence.stores.runs
97 await runs.createOrResume({
98 runId: 'migrated-run',
99 threadId: 'migrated-thread',
100 startedAt: 1,
101 })
102
103 // ...and every added column must actually work, not merely exist. These
104 // are the fields takeover and the reaper depend on.
105 await runs.update('migrated-run', {
106 sandboxKey: 'sandbox-abc',
107 detachedSince: 500,
108 cancelRequested: true,
109 driverEpoch: 2,
110 })
111 expect(await runs.get('migrated-run')).toMatchObject({
112 sandboxKey: 'sandbox-abc',
113 detachedSince: 500,
114 cancelRequested: true,
115 driverEpoch: 2,
116 })
117
118 // The eagerly-prepared statement is the one that used to throw.
119 if (!runs.listReclaimable) {
120 throw new Error('expected runs.listReclaimable to be implemented')
121 }
122 const reclaimable = await runs.listReclaimable({
123 now: 1_000,
124 ttlMs: 100,
125 })
126 expect(reclaimable.some((r) => r.runId === 'migrated-run')).toBe(true)
127
128 // Pre-existing rows survive the migration; the new columns read back as
129 // absent rather than as a coerced falsy default.
130 const fresh = await runs.get('migrated-run')
131 expect(fresh?.threadId).toBe('migrated-thread')
132 } finally {
133 persistence.close()
134 }
135
136 // Idempotent: opening the already-migrated file again is a no-op.
137 const again = sqlitePersistence({ url: file, migrate: true })
138 again.close()
139 } finally {
140 rmSync(dir, { recursive: true, force: true })
141 }
142 })
143})