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