Open History to see the last commit
1import { DatabaseSync } from 'node:sqlite'
2import { describe, expect, it, vi } from 'vitest'
3import { eq } from '@tanstack/db'
4import { SQLiteCorePersistenceAdapter } from '../../db-sqlite-persistence-core/src'
5import { useLiveQuery } from '../src/useLiveQuery'
6import { createSerializedNodeSqliteDriver as createDriver } from '../../db-sqlite-persistence-core/tests/helpers/node-sqlite-driver'
7import {
8 A1,
9 A2,
10 FRAMEWORK_HISTORY_IDS,
11 coverageRecords,
12 createReceivingSource,
13 receivingHistory,
14 recordCheckpoints,
15 session2SourceOptions,
16} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
17import { coverageViolations } from '../../db-sqlite-persistence-core/tests/persisted-demand-coverage-model-oracle'
18import type {
19 Session1Record,
20 Session2Record,
21 SourceEvent,
22} from '../../db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract'
23import type { QueryObservation } from '../../db-sqlite-persistence-core/tests/persisted-demand-coverage-model-oracle'
24
25/**
26 * # Does a Vue live query settle offline on a covered on-demand demand?
27 *
28 * Receiving witness for persisted demand coverage. The law, the histories, and
29 * the checkpoint records are the receiving contract's
30 * (`db-sqlite-persistence-core/tests/contracts/persisted-demand-coverage-receiving-contract.ts`),
31 * and the shared judge (`db-sqlite-persistence-core/tests/persisted-demand-coverage-model-oracle.ts`)
32 * judges each record. The law's authority is
33 * `docs/contributing/oracle-reviews/2026-10-20-on-demand-network-first-law.md`.
34 *
35 * Histories: `FRAMEWORK_HISTORY_IDS` (`covered`, `never`, and
36 * `covered-upstream-fails-at-once`). Session 1 is online and answers its load
37 * at once through the source, or loads nothing. Session 2 is offline on the
38 * same `node:sqlite` database, with the history's upstream behavior.
39 *
40 * Production path: `useLiveQuery` -> `createLiveQueryObserver` -> the live
41 * query's on-demand `loadSubset` -> the persisted wrapper, which waits for the
42 * network-first wait and then settles a covered demand from its restored rows.
43 *
44 * Observation: at each checkpoint of session 2, the composable's `isReady` and
45 * `data`.
46 *
47 * Limits: this witness checks the wrapper's settlement through query
48 * readiness and rows. It uses one filter, one composable instance per session, and no component lifecycle.
49 */
50
51function groupA(
52 collection: ReturnType<typeof createReceivingSource>[`collection`],
53) {
54 return useLiveQuery((q) =>
55 q.from({ row: collection }).where(({ row }) => eq(row.group, `a`)),
56 )
57}
58
59function observeQuery(query: ReturnType<typeof groupA>): QueryObservation {
60 if (!query.isReady.value) return { status: `loading` }
61 return {
62 status: `ready`,
63 rows: query.data.value.map((row) => row.id).sort(),
64 }
65}
66
67describe(`Vue useLiveQuery over a persisted on-demand Collection offline`, () => {
68 it.each(FRAMEWORK_HISTORY_IDS.map(receivingHistory))(
69 `$description`,
70 async (history) => {
71 vi.spyOn(console, `warn`).mockImplementation(() => {})
72 vi.spyOn(console, `error`).mockImplementation(() => {})
73 const driver = createDriver(new DatabaseSync(`:memory:`))
74 const persistence = () => ({
75 adapter: new SQLiteCorePersistenceAdapter({ driver }),
76 })
77
78 const session1Events: Array<SourceEvent> = []
79 if (history.session1.length > 0) {
80 const first = createReceivingSource({
81 persistence: persistence(),
82 waitMs: 0,
83 behavior: `answer-at-once`,
84 events: session1Events,
85 answerRows: [A1, A2],
86 })
87 const query = groupA(first.collection)
88 await vi.waitFor(() => expect(query.isReady.value).toBe(true))
89 await new Promise((resolve) => setTimeout(resolve, 50))
90 await first.collection.cleanup({ dependents: true })
91 }
92 const session1: Session1Record = { events: session1Events }
93
94 const second = createReceivingSource({
95 persistence: persistence(),
96 ...session2SourceOptions(history),
97 events: [],
98 })
99 const loadStartedAt = Date.now()
100 const query = groupA(second.collection)
101 try {
102 const checkpoints = await recordCheckpoints(
103 () => observeQuery(query),
104 () => second.received.length,
105 loadStartedAt,
106 )
107 const session2: Session2Record = {
108 sent: [...second.received],
109 ...checkpoints,
110 }
111 // Positive witness: session 2 asked the offline source for group a.
112 expect(session2.sent.length).toBeGreaterThan(0)
113 const records = coverageRecords(history, session1, session2)
114 expect(coverageViolations(records.beforeDeadline)).toEqual([])
115 expect(coverageViolations(records.afterDeadline)).toEqual([])
116 } finally {
117 await second.collection.cleanup({ dependents: true })
118 }
119 },
120 )
121})