Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

sqlite-persistence.test.ts

548 lines18.6 KB

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 {
14 runSandboxCheckpointForkConformance,
15 runSandboxCheckpointStoreConformance,
16} from '@tanstack/ai-sandbox/testkit'
17import { sqlitePersistence, sqliteSandboxSnapshots } from './sqlite-persistence'
18​
19// Seven of eight stores are provided (chat state plus `generationRuns` +
20// `artifacts` + `blobs`). `activities` is optional AG-UI sidecar storage and
21// this example does not implement it, so it is declared in `skip`. Every
22// `runs` method is implemented, including the optional `listByThread`,
23// `listByParentRun`, and `listReclaimable`, so nothing is declared in
24// `skipMethods`. (`reconstructChat` needs `listByThread` to put back the
25// cards of children that a tool call started.)
26//
27// (Locks are not a store and the suite does not cover them: this backend has no
28// distributed lock primitive, which is a separate `withLocks` concern.)
29runPersistenceConformance(
30 'ts-react-chat example (node:sqlite)',
31 () => sqlitePersistence({ url: ':memory:', migrate: true }),
32 { skip: ['activities'] },
34​
35runSandboxCheckpointStoreConformance(
36 'ts-react-chat example (node:sqlite)',
37 (options) =>
38 sqliteSandboxSnapshots({
39 url: ':memory:',
40 migrate: true,
41 ...options,
42 }).checkpoints,
44​
45runSandboxCheckpointForkConformance(
46 'ts-react-chat example (node:sqlite)',
47 () => {
48 const snapshots = sqliteSandboxSnapshots({
49 url: ':memory:',
50 migrate: true,
51 })
52 return snapshots
53 },
55​
56describe('sqliteSandboxSnapshots fork transaction', () => {
57 it('uses one durable writer lease across two SQLite connections', async () => {
58 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-lease-'))
59 const file = join(dir, 'snapshots.db')
60 const first = sqliteSandboxSnapshots({ url: file, migrate: true })
61 const second = sqliteSandboxSnapshots({ url: file, migrate: true })
62 try {
63 const writer = await first.checkpoints.acquireWriter('thread')
64 await expect(
65 second.checkpoints.acquireWriter('thread'),
66 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_WRITER_CONFLICT' })
67 await writer.release()
68 const replacement = await second.checkpoints.acquireWriter('thread')
69 await expect(
70 first.checkpoints.append({
71 checkpoint: {
72 id: 'stale',
73 threadId: 'thread',
74 parentCheckpointId: null,
75 createdAt: 1,
76 reason: 'named',
77 files: [],
78 conversation: [],
79 artifacts: [],
80 },
81 expectedHeadId: null,
82 writer,
83 }),
84 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_WRITER_LOST' })
85 await replacement.release()
86 } finally {
87 first.close()
88 second.close()
89 rmSync(dir, { recursive: true, force: true })
90 }
91 })
92​
93 it('deletes dependent rows and permits the checkpoint id to be reused', async () => {
94 const snapshots = sqliteSandboxSnapshots({ url: ':memory:', migrate: true })
95 const writer = await snapshots.checkpoints.acquireWriter('thread')
96 const checkpoint = {
97 id: 'reusable',
98 threadId: 'thread',
99 parentCheckpointId: null,
100 createdAt: 1,
101 reason: 'named' as const,
102 files: [
103 {
104 path: 'a.txt',
105 kind: 'file' as const,
106 blobKey: `sandbox-files/sha256/${'a'.repeat(64)}`,
107 size: 1,
108 },
109 ],
110 conversation: [{ role: 'user' as const, content: 'one' }],
111 artifacts: [],
112 }
113 try {
114 await snapshots.checkpoints.append({
115 checkpoint,
116 expectedHeadId: null,
117 writer,
118 })
119 await snapshots.checkpoints.deleteHead({
120 threadId: 'thread',
121 checkpointId: 'reusable',
122 writer,
123 })
124 await expect(
125 snapshots.checkpoints.append({
126 checkpoint,
127 expectedHeadId: null,
128 writer,
129 }),
130 ).resolves.toEqual({ headId: 'reusable' })
131 } finally {
132 snapshots.close()
133 }
134 })
135​
136 it('rejects a fork whose source blob reference is missing', async () => {
137 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-ref-'))
138 const file = join(dir, 'snapshots.db')
139 const snapshots = sqliteSandboxSnapshots({ url: file, migrate: true })
140 try {
141 const key = `sandbox-files/sha256/${'b'.repeat(64)}`
142 const sourceWriter = await snapshots.checkpoints.acquireWriter('source')
143 await snapshots.checkpoints.append({
144 checkpoint: {
145 id: 'source',
146 threadId: 'source',
147 parentCheckpointId: null,
148 createdAt: 1,
149 reason: 'named',
150 files: [{ path: 'a.txt', kind: 'file', blobKey: key, size: 1 }],
151 conversation: [],
152 artifacts: [],
153 },
154 expectedHeadId: null,
155 writer: sourceWriter,
156 })
157 const inspector = new DatabaseSync(file)
158 inspector
159 .prepare(
160 'DELETE FROM sandbox_checkpoint_blob_references WHERE blob_key = ?',
161 )
162 .run(key)
163 inspector.close()
164 const writer = await snapshots.checkpoints.acquireWriter('destination')
165 await expect(
166 snapshots.checkpoints.forkFromCheckpoint({
167 sourceThreadId: 'source',
168 sourceCheckpointId: 'source',
169 destinationThreadId: 'destination',
170 destinationCheckpointId: 'destination',
171 createdAt: 2,
172 writer,
173 }),
174 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ENTRY' })
175 expect(
176 await snapshots.persistence.stores.messages.loadThread('destination'),
177 ).toEqual([])
178 expect(await snapshots.checkpoints.getHead('destination')).toBeNull()
179 } finally {
180 snapshots.close()
181 rmSync(dir, { recursive: true, force: true })
182 }
183 })
184​
185 it.each([
186 {
187 path: 'file/child',
188 kind: 'file',
189 blobKey: `sandbox-files/sha256/${'c'.repeat(64)}`,
190 size: 1,
191 },
192 {
193 path: 'C:/absolute.txt',
194 kind: 'file',
195 blobKey: `sandbox-files/sha256/${'c'.repeat(64)}`,
196 size: 1,
197 },
198 {
199 path: 'bad',
200 kind: 'other',
201 blobKey: `sandbox-files/sha256/${'c'.repeat(64)}`,
202 size: 1,
203 },
204 { path: 'directory', kind: 'dir', blobKey: 'forbidden' },
205 ])('rejects invalid checkpoint entry $path', async (invalid) => {
206 const snapshots = sqliteSandboxSnapshots({ url: ':memory:', migrate: true })
207 try {
208 const writer = await snapshots.checkpoints.acquireWriter('thread')
209 const files =
210 invalid.path === 'file/child'
211 ? [
212 {
213 path: 'file',
214 kind: 'file' as const,
215 blobKey: `sandbox-files/sha256/${'d'.repeat(64)}`,
216 size: 1,
217 },
218 invalid,
219 ]
220 : [invalid]
221 const checkpoint = {
222 id: `invalid-${invalid.path}`,
223 threadId: 'thread',
224 parentCheckpointId: null,
225 createdAt: 1,
226 reason: 'named' as const,
227 files: [],
228 conversation: [],
229 artifacts: [],
230 }
231 Reflect.set(checkpoint, 'files', files)
232 await expect(
233 snapshots.checkpoints.append({
234 checkpoint,
235 expectedHeadId: null,
236 writer,
237 }),
238 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ENTRY' })
239 } finally {
240 snapshots.close()
241 }
242 })
243​
244 it.each<['files' | 'artifacts', unknown]>([
245 ['files', null],
246 ['files', 'not-an-array'],
247 ['files', [null]],
248 ['files', [1]],
249 ['artifacts', null],
250 ['artifacts', 'not-an-array'],
251 ['artifacts', [null]],
252 ['artifacts', [1]],
253 ])('rejects malformed checkpoint %s values', async (field, value) => {
254 const snapshots = sqliteSandboxSnapshots({ url: ':memory:', migrate: true })
255 try {
256 const writer = await snapshots.checkpoints.acquireWriter('thread')
257 const checkpoint = {
258 id: `malformed-${field}-${String(value)}`,
259 threadId: 'thread',
260 parentCheckpointId: null,
261 createdAt: 1,
262 reason: 'named' as const,
263 files: [],
264 conversation: [],
265 artifacts: [],
266 }
267 Reflect.set(checkpoint, field, value)
268 await expect(
269 snapshots.checkpoints.append({
270 checkpoint,
271 expectedHeadId: null,
272 writer,
273 }),
274 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ENTRY' })
275 } finally {
276 snapshots.close()
277 }
278 })
279​
280 it('rejects empty and non-string identifiers without changing state', async () => {
281 const snapshots = sqliteSandboxSnapshots({ url: ':memory:', migrate: true })
282 try {
283 const writer = await snapshots.checkpoints.acquireWriter('thread')
284 const before = {
285 head: await snapshots.checkpoints.getHead('thread'),
286 list: await snapshots.checkpoints.list('thread'),
287 references: await snapshots.checkpoints.listBlobReferences(),
288 }
289 await expect(
290 Reflect.apply(
291 snapshots.checkpoints.acquireWriter,
292 snapshots.checkpoints,
293 [''],
294 ),
295 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ID' })
296 await expect(
297 Reflect.apply(snapshots.checkpoints.list, snapshots.checkpoints, [{}]),
298 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ID' })
299 await expect(
300 Reflect.apply(snapshots.checkpoints.append, snapshots.checkpoints, [
301 {
302 checkpoint: {
303 id: 'invalid',
304 threadId: 7,
305 parentCheckpointId: null,
306 createdAt: 1,
307 reason: 'named',
308 files: [],
309 conversation: [],
310 artifacts: [],
311 },
312 expectedHeadId: null,
313 writer,
314 },
315 ]),
316 ).rejects.toMatchObject({ code: 'SANDBOX_SNAPSHOT_INVALID_ID' })
317 expect(await snapshots.checkpoints.getHead('thread')).toBe(before.head)
318 expect(await snapshots.checkpoints.list('thread')).toEqual(before.list)
319 expect(await snapshots.checkpoints.listBlobReferences()).toEqual(
320 before.references,
321 )
322 await writer.release()
323 } finally {
324 snapshots.close()
325 }
326 })
327​
328 it('rolls back the destination when checkpoint storage fails after transcript staging', async () => {
329 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-fork-'))
330 const file = join(dir, 'snapshots.db')
331 const snapshots = sqliteSandboxSnapshots({ url: file, migrate: true })
332 try {
333 const sourceWriter = await snapshots.checkpoints.acquireWriter('source')
334 const blobKey = `sandbox-files/sha256/${'a'.repeat(64)}`
335 await snapshots.checkpoints.append({
336 checkpoint: {
337 id: 'source-root',
338 threadId: 'source',
339 parentCheckpointId: null,
340 createdAt: 1,
341 reason: 'named',
342 files: [{ path: 'a.txt', kind: 'file', blobKey, size: 1 }],
343 conversation: [{ role: 'user', content: 'source' }],
344 artifacts: [],
345 },
346 expectedHeadId: null,
347 writer: sourceWriter,
348 })
349 const triggerDb = new DatabaseSync(file)
350 triggerDb.exec(`
351 CREATE TRIGGER fail_fork_checkpoint
352 BEFORE INSERT ON sandbox_checkpoints
353 WHEN NEW.checkpoint_id = 'fork-root'
354 BEGIN SELECT RAISE(ABORT, 'forced checkpoint failure'); END;
355 `)
356 triggerDb.close()
357 const destinationWriter =
358 await snapshots.checkpoints.acquireWriter('destination')
359 await expect(
360 snapshots.checkpoints.forkFromCheckpoint({
361 sourceThreadId: 'source',
362 sourceCheckpointId: 'source-root',
363 destinationThreadId: 'destination',
364 destinationCheckpointId: 'fork-root',
365 createdAt: 2,
366 writer: destinationWriter,
367 }),
368 ).rejects.toThrow('forced checkpoint failure')
369 expect(
370 await snapshots.persistence.stores.messages.loadThread('destination'),
371 ).toEqual([])
372 expect(await snapshots.checkpoints.list('destination')).toEqual([])
373 expect(await snapshots.checkpoints.getHead('destination')).toBeNull()
374 expect(await snapshots.checkpoints.listBlobReferences()).toEqual([
375 { key: blobKey, references: 1 },
376 ])
377 } finally {
378 snapshots.close()
379 rmSync(dir, { recursive: true, force: true })
380 }
381 })
382})
383​
384// SQL-specific case the in-memory reference backend cannot express: a real
385// query layer can get `NULL <= ?` wrong in ways JS's `undefined <= n`
386// (`NaN <= n`, always false) never surfaces. This pins the SQLite backend's
387// `detached_since IS NOT NULL` guard directly, independent of the shared
388// conformance suite.
389describe('sqlitePersistence runs.listReclaimable — SQL NULL handling', () => {
390 it('never returns a run whose detached_since column is NULL, regardless of ttlMs', async () => {
391 const persistence = sqlitePersistence({ url: ':memory:', migrate: true })
392 try {
393 const runs = persistence.stores.runs
394 if (!runs.listReclaimable) {
395 throw new Error('expected runs.listReclaimable to be implemented')
396 }
397 await runs.createOrResume({
398 runId: 'null-detached-run',
399 threadId: 'null-detached-thread',
400 startedAt: 1,
401 })
402 // detachedSince is never set on this run, so the column stays NULL.
403​
404 for (const ttlMs of [0, -1, Number.MAX_SAFE_INTEGER]) {
405 const reclaimable = await runs.listReclaimable({
406 now: Date.now(),
407 ttlMs,
408 })
409 expect(reclaimable.some((r) => r.runId === 'null-detached-run')).toBe(
410 false,
411 )
412 }
413 } finally {
414 persistence.close()
415 }
416 })
417})
418​
419// `CREATE TABLE IF NOT EXISTS` does not alter a table that already exists, so a
420// `.data/*.db` written by an earlier version of this example has none of the
421// durable-run columns. That file used to break hard AND early: `createRunStore`
422// prepares its `listReclaimable` statement eagerly and `node:sqlite` resolves
423// column names at prepare time, so the factory threw `no such column:
424// detached_since` before serving a single request. This pins the additive
425// migration against a genuinely old file rather than a fresh one.
426describe('sqlitePersistence migrate — an existing pre-durability database', () => {
427 it('adds the missing runs columns instead of throwing at prepare time', async () => {
428 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-migrate-'))
429 const file = join(dir, 'old.db')
430 try {
431 // A `runs` table exactly as it shipped BEFORE the durable-run fields.
432 const old = new DatabaseSync(file)
433 old.exec(`
434 CREATE TABLE runs (
435 run_id text PRIMARY KEY NOT NULL,
436 thread_id text NOT NULL,
437 status text NOT NULL,
438 started_at integer NOT NULL,
439 finished_at integer,
440 error text
441 );
442 `)
443 old.close()
444​
445 // Opening it must migrate rather than throw...
446 const persistence = sqlitePersistence({ url: file, migrate: true })
447 try {
448 const runs = persistence.stores.runs
449 await runs.createOrResume({
450 runId: 'migrated-run',
451 threadId: 'migrated-thread',
452 startedAt: 1,
453 })
454​
455 // ...and every added column must actually work, not merely exist. These
456 // are the fields takeover and the reaper depend on.
457 await runs.update('migrated-run', {
458 sandboxKey: 'sandbox-abc',
459 detachedSince: 500,
460 cancelRequested: true,
461 driverEpoch: 2,
462 })
463 expect(await runs.get('migrated-run')).toMatchObject({
464 sandboxKey: 'sandbox-abc',
465 detachedSince: 500,
466 cancelRequested: true,
467 driverEpoch: 2,
468 })
469​
470 // The eagerly-prepared statement is the one that used to throw.
471 if (!runs.listReclaimable) {
472 throw new Error('expected runs.listReclaimable to be implemented')
473 }
474 const reclaimable = await runs.listReclaimable({
475 now: 1_000,
476 ttlMs: 100,
477 })
478 expect(reclaimable.some((r) => r.runId === 'migrated-run')).toBe(true)
479​
480 // Pre-existing rows survive the migration; the new columns read back as
481 // absent rather than as a coerced falsy default.
482 const fresh = await runs.get('migrated-run')
483 expect(fresh?.threadId).toBe('migrated-thread')
484 } finally {
485 persistence.close()
486 }
487​
488 // Idempotent: opening the already-migrated file again is a no-op.
489 const again = sqlitePersistence({ url: file, migrate: true })
490 again.close()
491 } finally {
492 rmSync(dir, { recursive: true, force: true })
493 }
494 })
495})
496​
497describe('sqliteSandboxSnapshots migrate — an existing artifacts table', () => {
498 it('adds the artifact thread-order index and uses it for listForThread', () => {
499 const dir = mkdtempSync(join(tmpdir(), 'tanstack-sqlite-artifacts-'))
500 const file = join(dir, 'old.db')
501 try {
502 const old = new DatabaseSync(file)
503 old.exec(`
504 CREATE TABLE artifacts (
505 artifact_id text PRIMARY KEY NOT NULL,
506 run_id text NOT NULL,
507 thread_id text NOT NULL,
508 blob_key text,
509 name text NOT NULL,
510 mime_type text NOT NULL,
511 size integer NOT NULL,
512 source_url text,
513 created_at integer NOT NULL
514 );
515 CREATE INDEX artifacts_run_order
516 ON artifacts (run_id, created_at ASC, artifact_id ASC);
517 `)
518 old.close()
519​
520 const snapshots = sqliteSandboxSnapshots({ url: file, migrate: true })
521 snapshots.close()
522​
523 const inspector = new DatabaseSync(file)
524 try {
525 const indexes = inspector
526 .prepare("SELECT name FROM pragma_index_list('artifacts')")
527 .all()
528 expect(indexes).toContainEqual(
529 expect.objectContaining({ name: 'artifacts_thread_order' }),
530 )
531​
532 const plan = inspector
533 .prepare(
534 'EXPLAIN QUERY PLAN SELECT * FROM artifacts WHERE thread_id = ? ORDER BY created_at ASC, artifact_id ASC',
535 )
536 .all('thread')
537 expect(JSON.stringify(plan)).toContain(
538 'SEARCH artifacts USING INDEX artifacts_thread_order (thread_id=?)',
539 )
540 expect(JSON.stringify(plan)).not.toContain('USE TEMP B-TREE')
541 } finally {
542 inspector.close()
543 }
544 } finally {
545 rmSync(dir, { recursive: true, force: true })
546 }
547 })
548})