Open History to see the last commit
1// Hand-written TrailBase lifecycle controls: a load failure rejects readiness
2// while stream cancellation is still pending, so a late cancellation cannot
3// turn the failed startup into readiness; and fixed reload, on-demand reload,
4// and aborted-load scenarios compare with hand-written or service rows. The
5// law that the generated and fixed lifecycle histories check is owned by
6// lifecycle-oracle.property.test.ts.
7import { expect, it, vi } from 'vitest'
8import { createCollection, createLiveQueryCollection } from '@tanstack/db'
9import { trailBaseCollectionOptions } from '../src/trailbase'
10import { MockRecordApi } from './mock-record-api'
11import {
12 deferred,
13 failure,
14 invalidValue,
15 observe,
16 sortedRows,
17 source,
18 turn,
19} from './lifecycle-support'
20import type { Event, ListResponse } from 'trailbase'
21import type { RaceRow, Row } from './lifecycle-support'
22
23it.each([`resolve`, `reject`] as const)(
24 `rejects startup before stream cancellation can %s`,
25 async (cancellation) => {
26 const reports: Array<Array<unknown>> = []
27 const unhandled: Array<unknown> = []
28 const failures: Array<unknown> = []
29 const onUnhandled = (error: unknown) => unhandled.push(error)
30 const reported = vi
31 .spyOn(console, `error`)
32 .mockImplementation((...args) => {
33 reports.push(args)
34 })
35 process.on(`unhandledRejection`, onUnhandled)
36 const active = source()
37 const cancelled = deferred<void>()
38 active.cancel.mockImplementation(() => cancelled.promise)
39 const api = new MockRecordApi<Row>()
40 api.subscribe.mockResolvedValue(active.stream)
41 api.list.mockImplementation(() => active.list.promise)
42 const collection = createCollection(
43 trailBaseCollectionOptions({
44 recordApi: api,
45 getKey: (row: Row) => row.id,
46 syncMode: `eager`,
47 parse: {
48 value: () => {
49 throw failure
50 },
51 },
52 serialize: {},
53 }),
54 )
55 const preload = observe(collection.preload())
56 try {
57 await turn()
58 expect(api.list).toHaveBeenCalledOnce()
59 active.controller.enqueue({ Insert: { id: 1, value: invalidValue } })
60 await turn()
61 expect(active.cancel).toHaveBeenCalledOnce()
62 // Cleanup I/O is still pending, but it cannot postpone the load error.
63 expect(preload.result).toBe(`rejected`)
64 expect(preload.error).toBe(failure)
65 expect(collection.status).toBe(`error`)
66 active.list.resolve({ records: [] })
67 await turn()
68 expect(preload.result).toBe(`rejected`)
69 expect(collection.status).toBe(`error`)
70 } catch (error) {
71 failures.push(error)
72 } finally {
73 if (cancellation === `resolve`) cancelled.resolve()
74 else cancelled.reject(new Error(`cancel failure`))
75 active.list.resolve({ records: [] })
76 try {
77 await collection.cleanup()
78 } catch (error) {
79 failures.push(error)
80 }
81 await turn()
82 try {
83 // Observe the final cancellation/list continuations before restoring
84 // either recorder. Loading failure is reported through preload, not
85 // console.error, and canceled transport errors must stay observed.
86 expect(reports).toEqual([])
87 expect(unhandled).toEqual([])
88 expect(preload.result).toBe(`rejected`)
89 expect(preload.error).toBe(failure)
90 expect(active.stream.locked).toBe(false)
91 expect(active.cancel).toHaveBeenCalledOnce()
92 expect(collection.status).toBe(`cleaned-up`)
93 } catch (error) {
94 failures.push(error)
95 } finally {
96 process.off(`unhandledRejection`, onUnhandled)
97 reported.mockRestore()
98 }
99 }
100 if (failures.length === 1) throw failures[0]
101 if (failures.length > 1)
102 throw new AggregateError(failures, `Startup and cleanup checks failed`, {
103 cause: failures[0],
104 })
105 },
106)
107
108/**
109 * ## Does a reload recover a failed startup?
110 *
111 * Law (the error surface's reload contract): `reload()` runs `sync` again
112 * while the Collection still shows `error`. The new run's own outcome decides
113 * the reload: a subscription that listens makes it ready and the reload
114 * resolves; a subscription that rejects fails the reload, and the status stays
115 * `error`. The adapter cannot read Collection status to learn whether this run
116 * is ready, because status still shows the failed run.
117 *
118 * Grammar (exhaustive, 2 histories): the first subscription rejects; the
119 * reload's subscription listens or rejects. Checkpoints: after the reload
120 * settles (or a bounded wait), compare its outcome, status, and subscribe
121 * calls.
122 */
123it.each([`listens`, `rejects`] as const)(
124 `a reload after a failed startup settles when the new subscription %s`,
125 async (outcome) => {
126 const stream = new ReadableStream<Event>({ start() {} })
127 const api = new MockRecordApi<RaceRow>()
128 api.subscribe
129 .mockImplementationOnce(() => Promise.reject(failure))
130 .mockImplementationOnce(() =>
131 outcome === `listens`
132 ? Promise.resolve(stream)
133 : Promise.reject(new Error(`reload subscription failed`)),
134 )
135 api.list.mockImplementation(() => Promise.resolve({ records: [] }))
136 const reported = vi.spyOn(console, `error`).mockImplementation(() => {})
137 const collection = createCollection(
138 trailBaseCollectionOptions({
139 recordApi: api,
140 getKey: (row: RaceRow) => row.id,
141 startSync: true,
142 parse: {},
143 serialize: {},
144 }),
145 )
146 try {
147 await collection.preload().catch(() => undefined)
148 expect(collection.status).toBe(`error`)
149 const settled = await Promise.race([
150 collection.reload().then(
151 () => `resolved`,
152 () => `rejected`,
153 ),
154 new Promise((resolve) => setTimeout(() => resolve(`pending`), 500)),
155 ])
156 expect(settled).toBe(outcome === `listens` ? `resolved` : `rejected`)
157 expect(collection.status).toBe(outcome === `listens` ? `ready` : `error`)
158 expect(api.subscribe).toHaveBeenCalledTimes(2)
159 } finally {
160 await collection.cleanup()
161 reported.mockRestore()
162 }
163 },
164)
165
166/**
167 * ## Does a reload of a ready Collection end with the service's rows?
168 *
169 * Law (the reload contract, maintainer decision F19): a reload keeps the rows
170 * on screen until it completes. The new run's writes apply on the kept rows,
171 * and only a snapshot or the run's own truncate replaces them; a run that
172 * sends neither completes the reload at its `markReady()`. Once the reload
173 * settles, an eager Collection holds the service's current rows, so a row
174 * the service deleted between the runs is gone.
175 *
176 * Reference: the service is a key/value relation that `list` reads at the
177 * moment it is called, in key order, 256 rows to a page with a cursor. The
178 * expected rows never come from the adapter.
179 *
180 * Grammar (exhaustive, 10 histories): the service holds 3 rows (one page)
181 * or 258 rows (two pages); between the runs it changes nothing, updates row
182 * 1, deletes row 2, or inserts a new row; or, while the reload's last page
183 * is held, it inserts a new row that page does not list and the listener
184 * delivers its `Insert` event (`insert-event`). Checkpoints: while the
185 * reload's last page is held, every row the Collection showed before the
186 * reload that the service still has is still shown, and the reload has not
187 * settled; after the page is released, the reload resolves, the status is
188 * `ready`, and the rows equal the service's.
189 */
190it.each(
191 [3, 258].flatMap((size) =>
192 ([`none`, `update`, `delete`, `insert`, `insert-event`] as const).map(
193 (change) => ({
194 size,
195 change,
196 }),
197 ),
198 ),
199)(
200 `a reload of a ready eager Collection over $size rows ends with the service's rows after a $change`,
201 async ({ size, change }) => {
202 const service = new Map<number, RaceRow>()
203 for (let id = 1; id <= size; id++) service.set(id, { id, data: `v1` })
204 const api = new MockRecordApi<RaceRow>()
205 let listener: WritableStreamDefaultWriter<Event> | undefined
206 api.subscribe.mockImplementation(() => {
207 const stream = new TransformStream<Event>()
208 listener = stream.writable.getWriter()
209 return Promise.resolve(stream.readable)
210 })
211 let holdLastPage: Promise<void> | undefined
212 api.list.mockImplementation(async (options) => {
213 const after = Number(options?.pagination?.cursor ?? 0)
214 const records = [...service.values()]
215 .sort((a, b) => a.id - b.id)
216 .filter((row) => row.id > after)
217 .slice(0, 256)
218 if (records.length < 256) await holdLastPage
219 return { records, cursor: String(records.at(-1)?.id ?? after) }
220 })
221 const collection = createCollection(
222 trailBaseCollectionOptions({
223 recordApi: api,
224 getKey: (row: RaceRow) => row.id,
225 startSync: true,
226 parse: {},
227 serialize: {},
228 }),
229 )
230 try {
231 await collection.preload()
232 const before = sortedRows(collection.toArray)
233 expect(before).toEqual(sortedRows(service.values()))
234
235 if (change === `update`) service.set(1, { id: 1, data: `v2` })
236 else if (change === `delete`) service.delete(2)
237 else if (change === `insert`)
238 service.set(size + 1, { id: size + 1, data: `v1` })
239
240 let releaseLastPage!: () => void
241 holdLastPage = new Promise((resolve) => (releaseLastPage = resolve))
242 const reload = observe(collection.reload())
243 await turn()
244 if (change === `insert-event`) {
245 const row = { id: size + 1, data: `v1` }
246 service.set(row.id, row)
247 await listener!.write({ Insert: row })
248 await turn()
249 }
250 const shown = new Set(collection.toArray.map((row) => row.id))
251 expect(
252 before.filter((row) => service.has(row.id) && !shown.has(row.id)),
253 `kept rows the service still has stay while the reload runs`,
254 ).toEqual([])
255 expect(reload.result).toBe(`pending`)
256
257 releaseLastPage()
258 for (let i = 0; i < 5 && reload.result === `pending`; i++) await turn()
259 expect(reload.result).toBe(`fulfilled`)
260 expect(collection.status).toBe(`ready`)
261 expect(sortedRows(collection.toArray)).toEqual(
262 sortedRows(service.values()),
263 )
264 } finally {
265 await collection.cleanup()
266 }
267 },
268)
269
270/**
271 * ## Does an unchanged row survive an on-demand reload?
272 *
273 * Law (maintainer decisions F19 and snapshot-api §8): an on-demand reload
274 * keeps the rows; core replays the live query's demand through the new
275 * run, and the replayed pages apply on the kept rows (every page row is a
276 * full-row `update`, so a held key is never inserted). Core does not sweep
277 * after a reload (issue #2269), and a page cannot say a row is gone, so a
278 * row the service deleted while no stream listened stays: that is this
279 * adapter's limit for on-demand reloads.
280 *
281 * Reference: the same service as the eager reload lane. Between the runs
282 * the service updates row 1 and deletes row 2 with no change event; row 3
283 * is untouched. Checkpoint: once the reload settles and the replayed load
284 * has applied, row 1 shows its edit, row 3 survives, and row 2 keeps its
285 * last value.
286 */
287it(`an unchanged row survives an on-demand reload`, async () => {
288 const service = new Map<number, RaceRow>(
289 [1, 2, 3].map((id) => [id, { id, data: `v1` }]),
290 )
291 const api = new MockRecordApi<RaceRow>()
292 api.subscribe.mockImplementation(() =>
293 Promise.resolve(new ReadableStream<Event>({ start() {} })),
294 )
295 api.list.mockImplementation((options) => {
296 const after = Number(options?.pagination?.cursor ?? 0)
297 const records = [...service.values()]
298 .sort((a, b) => a.id - b.id)
299 .filter((row) => row.id > after)
300 .slice(0, 256)
301 return Promise.resolve({
302 records,
303 cursor: String(records.at(-1)?.id ?? after),
304 })
305 })
306 const collection = createCollection(
307 trailBaseCollectionOptions({
308 recordApi: api,
309 getKey: (row: RaceRow) => row.id,
310 syncMode: `on-demand`,
311 startSync: true,
312 parse: {},
313 serialize: {},
314 }),
315 )
316 const live = createLiveQueryCollection({
317 query: (q) => q.from({ row: collection }),
318 })
319 try {
320 await live.preload()
321 expect(sortedRows(collection.toArray)).toEqual(sortedRows(service.values()))
322
323 service.set(1, { id: 1, data: `v2` })
324 service.delete(2)
325 await collection.reload()
326 await vi.waitFor(() =>
327 expect(sortedRows(collection.toArray)).toEqual(
328 sortedRows([...service.values(), { id: 2, data: `v1` }]),
329 ),
330 )
331 expect(collection.status).toBe(`ready`)
332 } finally {
333 await live.cleanup()
334 await collection.cleanup()
335 }
336})
337
338/**
339 * ## Does an aborted load write no rows?
340 *
341 * Law (snapshot-api §8): an abort ends the load. Core stops listening to it
342 * at once, and the adapter must honor the signal: stop the fetch and write
343 * no rows for it. Reference: the service holds 3 rows; a subset load's list
344 * is held, the caller aborts, then the list answers. Checkpoints: the load
345 * rejects with `AbortError`, and after the late answer the Collection holds
346 * no row, while a later load lists every row.
347 */
348it(`an aborted load writes no rows and its late result changes nothing`, async () => {
349 const service = [1, 2, 3].map((id) => ({ id, data: `v1` }))
350 const page = deferred<ListResponse<RaceRow>>()
351 const api = new MockRecordApi<RaceRow>()
352 api.subscribe.mockImplementation(() =>
353 Promise.resolve(new ReadableStream<Event>({ start() {} })),
354 )
355 api.list
356 .mockImplementationOnce(() => page.promise)
357 .mockImplementation(() => Promise.resolve({ records: service }))
358 const collection = createCollection(
359 trailBaseCollectionOptions({
360 recordApi: api,
361 getKey: (row: RaceRow) => row.id,
362 syncMode: `on-demand`,
363 startSync: true,
364 parse: {},
365 serialize: {},
366 }),
367 )
368 try {
369 await collection.preload()
370 const abort = new AbortController()
371 const load = observe(
372 Promise.resolve(
373 collection._sync.loadSubset({ limit: 10, signal: abort.signal }),
374 ),
375 )
376 await vi.waitFor(() => expect(api.list).toHaveBeenCalledOnce())
377 abort.abort()
378 page.resolve({ records: service })
379 await turn()
380 expect(load.result).toBe(`rejected`)
381 expect(load.error).toMatchObject({ name: `AbortError` })
382 expect(collection.toArray).toEqual([])
383
384 await collection._sync.loadSubset({ limit: 10 })
385 expect(sortedRows(collection.toArray)).toEqual(sortedRows(service))
386 } finally {
387 await collection.cleanup()
388 }
389})