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

persisted-direct-write-window.oracle.test.ts

617 lines21.6 KB

1import { describe, expect, it, vi } from 'vitest'
2import { DuplicateKeySyncError, createCollection } from '@tanstack/db'
3import { persistedCollectionOptions } from '../../db-sqlite-persistence-core/src'
4import { queryCollectionOptions } from '../src/query'
5import { declareOracle } from '../../db/tests/oracle-declaration.js'
6import {
7 checked,
8 createAdapter,
9 createStorage,
10 deferred,
11 flush,
12 heldQueryFn,
13 newQueryClient,
14 outcomeOf,
15 sortRows,
16 write,
17} from './persisted-direct-write-support'
18import type { QueryCollectionUtils } from '../src/query'
19import type { Op, Row, StorageKind } from './persisted-direct-write-support'
20/**
21 * # Does a direct write see the commits that came before it?
22 *
23 * A persisted Query Collection puts each source commit behind the persistence
24 * wrapper's apply lock. While another task holds that lock, a committed
25 * refetch waits there, and core has not accepted it yet. Its result is already
26 * in the Query cache. The contract: a direct write (`writeInsert`,
27 * `writeUpdate`, `writeDelete`, `writeUpsert`) that runs in that window is
28 * validated against, and applies on top of, the rows of every commit that came
29 * before it. Persistence must not change what the write does.
30 *
31 * The reference is the same Query Collection without persistence. It runs the
32 * same operations, but no lock exists, so the earlier refetch has applied when
33 * the write runs. The reference does not share the persistence wrapper, which
34 * is the code under judgment. It shares the Query Collection's direct-write
35 * code, so it cannot find a fault in that code that both paths share. The
36 * precedence rules for writes that interleave with refetches are pinned as
37 * unit tests in `persisted-direct-write.test.ts`; they are not an oracle.
38 *
39 * ## Contract and ownership table
40 *
41 * | Contract | History/domain | Production path | Observation and checkpoint | Owner and limits |
42 * | --- | --- | --- | --- | --- |
43 * | validation sees earlier commits | 4 write types x 2 lock holders x 2 key cases | utils.write* -> manual-sync -> persisted commit | outcome of the write: `ok` or the error name | this oracle |
44 * | the write applies on top | the same | the same | visible rows after every promise settles | this oracle |
45 * | the Query cache agrees | the same | updateCacheData | Query cache rows after settlement | this oracle |
46 * | storage agrees | the same | persisted durable write | stored rows after settlement equal the visible rows | this oracle |
47 * | real SQLite receives the same | a subset: each write type, `refetch-only`, `source-write`, and the ordering cases | the same, over the node SQLite adapter | the same observations | this oracle; the full matrix runs over an in-memory fake adapter |
48 * | rejected writes gain no precedence | 4 rejected writes during a held refetch, with and without persistence | utils.write* -> validation | rows and Query cache inside the refetch's fulfillment | unit tests in `persisted-direct-write.test.ts`; no oracle owner |
49 * | a later accepted write keeps precedence | a second write after a deferred result arrives, same key and sibling key | deferred merge | rows, Query cache and stored rows after settlement | unit tests in `persisted-direct-write.test.ts`; no oracle owner |
50 * | refetch settles after its rows apply | a deferred result, and one whose merged write is held | deferred merge -> result settlement | rows inside the refetch's fulfillment | unit tests in `persisted-direct-write.test.ts`; no oracle owner |
51 * | cleanup during the wait rejects | insert, upsert and batch while cleanup retires the sync run | manual-sync -> current-context check | outcome, stored rows, rows after a restart | unit tests in `persisted-direct-write.test.ts`; no oracle owner |
52 * | validation errors reject the promise | duplicate insert, with and without persistence | utils.writeInsert | `rejects.toBeInstanceOf(DuplicateKeySyncError)` | this oracle |
53 *
54 * Lock holders:
55 *
56 * - `source-write`: an earlier refetch's durable write is held after core
57 * applied it, so the lock stays busy.
58 * - `startup`: persisted startup hydration is held, so the first fetch result
59 * waits for it.
60 *
61 * A mutation confirmation does not take this lock for a Query Collection.
62 * `persistAndConfirmCollectionMutations` runs only for sync-absent
63 * collections, so that holder is outside this oracle.
64 *
65 * Key cases: `refetch-only` means only the waiting refetch holds key `k`.
66 * `both` means the applied rows hold `k`, and the waiting refetch changes it.
67 *
68 * The domain is a finite matrix of 16 cases, not a generated history, so no
69 * random campaign is claimed. The matrix comparison ignores whether an error
70 * is thrown at once or rejects later. The precedence rules and the
71 * duplicate-insert witness check that validation errors reject the promise.
72 *
73 * The driver checks that it reached the window: when the write runs, storage
74 * does not hold the waiting refetch's row for `k` yet. This check does not
75 * depend on when core accepts the refetch, which a fix may change. Each failure message carries
76 * both observations, so a failure keeps the case that broke the law.
77 */
78​
79type Holder = `source-write` | `startup`
80type KeyCase = `refetch-only` | `both`
81​
82type Observation = {
83 outcome: string
84 visible: Array<Row>
85 cache: Array<Row>
87​
88const ops: Array<Op> = [`insert`, `update`, `delete`, `upsert`]
89const holders: Array<Holder> = [`source-write`, `startup`]
90const keyCases: Array<KeyCase> = [`refetch-only`, `both`]
91​
92/** The applied rows before the window, and the waiting refetch's rows. */
93function scenario(keyCase: KeyCase): { base: Array<Row>; next: Array<Row> } {
94 return keyCase === `both`
95 ? {
96 base: [
97 { id: `a`, value: 1 },
98 { id: `k`, value: 1 },
99 ],
100 next: [
101 { id: `a`, value: 2 },
102 { id: `k`, value: 5 },
103 ],
104 }
105 : {
106 base: [{ id: `a`, value: 1 }],
107 next: [
108 { id: `a`, value: 2 },
109 { id: `k`, value: 5 },
110 ],
111 }
113​
114/**
115 * Reference: no persistence. The waiting refetch has applied when the write
116 * runs, so its rows decide validation.
117 */
118async function reference(op: Op, keyCase: KeyCase): Promise<Observation> {
119 const { base, next } = scenario(keyCase)
120 let server = base
121 const queryClient = newQueryClient()
122 const queryKey = [`reference`, op, keyCase]
123 const collection = createCollection(
124 queryCollectionOptions<Row>({
125 id: `reference-${op}-${keyCase}`,
126 queryKey,
127 queryFn: () => Promise.resolve(server.map((row) => ({ ...row }))),
128 queryClient,
129 getKey: (row) => row.id,
130 startSync: true,
131 }),
132 )
133 return checked(async () => {
134 await collection.preload()
135 server = next
136 await collection.utils.refetch()
137 const { outcome } = await outcomeOf(() => write(collection.utils, op))
138 await flush()
139 return {
140 outcome,
141 visible: sortRows(collection.values()),
142 cache: sortRows(queryClient.getQueryData(queryKey) ?? []),
143 }
144 }, [() => collection.cleanup()])
146​
147/**
148 * Production driver: the persisted Query Collection. The write runs while the
149 * refetch that carries `next` waits on the apply lock.
150 */
151async function persisted(
152 op: Op,
153 holder: Holder,
154 keyCase: KeyCase,
155 kind: StorageKind = `fake`,
156): Promise<
157 Observation & { stored: Array<Row>; timing: string; waited: boolean }
158> {
159 const { base, next } = scenario(keyCase)
160 const id = `persisted-${kind}-${op}-${holder}-${keyCase}`
161 const storage = createStorage(kind, base, id)
162 const adapter = storage.adapter
163 const queryClient = newQueryClient()
164 const queryKey = [`persisted`, kind, op, holder, keyCase]
165 const release = deferred()
166 const entered = deferred()
167 let server = base
168 let hold = false
169​
170 if (holder === `source-write`) {
171 const applyCommittedTx = adapter.applyCommittedTx.bind(adapter)
172 adapter.applyCommittedTx = async (...args) => {
173 if (hold && args[1].mutations.length > 0) {
174 hold = false
175 entered.resolve()
176 await release.promise
177 }
178 return applyCommittedTx(...args)
179 }
180 } else {
181 // Hold startup hydration: the row read after the metadata read. The
182 // source starts after the metadata read, and its first fetch returns
183 // `next`.
184 server = next
185 const loadResumeSnapshot = adapter.loadResumeSnapshot
186 adapter.loadResumeSnapshot = async (collectionId, options) => {
187 if (options?.includeRows !== false) {
188 entered.resolve()
189 await release.promise
190 }
191 return loadResumeSnapshot(collectionId, options)
192 }
193 }
194​
195 const errors = vi.spyOn(console, `error`).mockImplementation(() => {})
196 const collection = createCollection(
197 persistedCollectionOptions<
198 Row,
199 string | number,
200 never,
201 QueryCollectionUtils<Row>
202 >({
203 ...queryCollectionOptions<Row>({
204 id,
205 queryKey,
206 queryFn: () => Promise.resolve(server.map((row) => ({ ...row }))),
207 queryClient,
208 getKey: (row) => row.id,
209 startSync: true,
210 }),
211 persistence: storage.persistence,
212 }),
213 )
214 const pending: Array<Promise<unknown>> = []
215 return checked(async () => {
216 if (holder === `source-write`) {
217 await collection.preload()
218 // R1 changes `a` and holds the lock in its durable write.
219 hold = true
220 server = [{ id: `a`, value: 2 }, ...base.filter((r) => r.id !== `a`)]
221 pending.push(collection.utils.refetch())
222 await entered.promise
223 // R2 carries `next`; its commit waits behind the busy lock.
224 server = next
225 pending.push(collection.utils.refetch())
226 } else {
227 pending.push(collection.preload())
228 await entered.promise
229 }
230 // The Query cache holds `next` once its result is committed.
231 await vi.waitFor(() =>
232 expect(sortRows(queryClient.getQueryData(queryKey) ?? [])).toEqual(
233 sortRows(next),
234 ),
235 )
236 // The window: the refetch is committed, but its durable write has not
237 // finished, because another task holds the lock.
238 const waited =
239 (await storage.storedRows(id)).find((row) => row.id === `k`)?.value !== 5
240 const settled = outcomeOf(() => write(collection.utils, op))
241 release.resolve()
242 const { outcome, timing } = await settled
243 await Promise.allSettled(pending)
244 await flush()
245 await flush()
246 return {
247 outcome,
248 timing,
249 waited,
250 visible: sortRows(collection.values()),
251 cache: sortRows(queryClient.getQueryData(queryKey) ?? []),
252 stored: await storage.storedRows(id),
253 }
254 }, [
255 () => release.resolve(),
256 () => errors.mockRestore(),
257 () => collection.cleanup(),
258 () => storage.close(),
259 ])
261​
262/**
263 * The matrix law: a direct write that runs while an earlier refetch waits for
264 * the apply lock returns the outcome and rows of the no-persistence reference,
265 * and storage then holds the visible rows. The reference is the model: it runs
266 * the same operations after the waiting refetch has applied. The driver's
267 * `waited` observation shows that the write ran inside the window.
268 */
269async function compareWriteWithReference(
270 op: Op,
271 holder: Holder,
272 keyCase: KeyCase,
273 kind: StorageKind = `fake`,
274): Promise<void> {
275 const expected = await reference(op, keyCase)
276 const actual = await persisted(op, holder, keyCase, kind)
277 const label = kind === `sqlite` ? `sqlite` : `persisted`
278 // The driver reached the window: core had not accepted `next`.
279 expect(actual.waited, `the refetch waited on the lock`).toBe(true)
280 const observed = {
281 outcome: actual.outcome,
282 visible: actual.visible,
283 cache: actual.cache,
284 }
285 expect(
286 observed,
287 `${label} ${JSON.stringify(observed)} != reference ${JSON.stringify(expected)}`,
288 ).toEqual(expected)
289 expect(actual.stored, `storage matches the visible rows`).toEqual(
290 actual.visible,
291 )
293​
294declareOracle({
295 check: [
296 compareWriteWithReference,
297 compareLaterRefetchOrder,
298 compareDuplicateInsert,
299 ],
300})
301​
302describe(`persisted direct writes behind a waiting refetch`, () => {
303 for (const holder of holders) {
304 for (const keyCase of keyCases) {
305 for (const op of ops) {
306 it(`${op} with ${holder} holding the lock, key ${keyCase}`, async () => {
307 await compareWriteWithReference(op, holder, keyCase)
308 })
309 }
310 }
311 }
312})
313​
314/**
315 * ## A later refetch while the direct write waits
316 *
317 * A direct write W waits for earlier commits. A third refetch R3 can return
318 * during that wait. The ordering law comes from the merge rule for direct
319 * writes and in-flight fetches:
320 *
321 * - If R3 started before W was called, R3 has older server data for W's keys.
322 * W wins on its keys, and R3 wins on the other keys.
323 * - If R3 started after W was called, R3 reflects the server after the write,
324 * so R3 wins.
325 *
326 * W writes `k`. R3 either changes `k` (same key) or only changes `a`
327 * (different key). The reference runs the same timeline without persistence:
328 * W applies at once, and R3 returns afterwards.
329 */
330type Start = `before` | `after`
331type Touch = `same` | `different`
332​
333function laterRows(touch: Touch): Array<Row> {
334 return touch === `same`
335 ? [
336 { id: `a`, value: 2 },
337 { id: `k`, value: 6 },
338 ]
339 : [
340 { id: `a`, value: 7 },
341 { id: `k`, value: 5 },
342 ]
344​
345async function referenceOrder(start: Start, touch: Touch): Promise<Array<Row>> {
346 const server: Array<Row> = [
347 { id: `a`, value: 2 },
348 { id: `k`, value: 5 },
349 ]
350 const held = heldQueryFn(() => server)
351 const queryClient = newQueryClient()
352 const collection = createCollection(
353 queryCollectionOptions<Row>({
354 id: `reference-order-${start}-${touch}`,
355 queryKey: [`reference-order`, start, touch],
356 queryFn: held.queryFn,
357 queryClient,
358 getKey: (row) => row.id,
359 startSync: true,
360 }),
361 )
362 return checked(async () => {
363 await collection.preload()
364 let r3: Promise<unknown> | undefined
365 if (start === `before`) {
366 held.arm()
367 r3 = collection.utils.refetch()
368 await vi.waitFor(() => expect(held.calls.length).toBe(1))
369 }
370 await outcomeOf(() => collection.utils.writeUpdate({ id: `k`, value: 9 }))
371 if (start === `after`) {
372 held.arm()
373 r3 = collection.utils.refetch()
374 await vi.waitFor(() => expect(held.calls.length).toBe(1))
375 }
376 held.disarm()
377 held.calls[0]!.resolve(laterRows(touch))
378 await r3
379 await flush()
380 await flush()
381 return sortRows(collection.values())
382 }, [() => collection.cleanup()])
384​
385async function persistedOrder(
386 start: Start,
387 touch: Touch,
388 kind: StorageKind = `fake`,
389): Promise<{ visible: Array<Row>; stored: Array<Row>; waited: boolean }> {
390 const base: Array<Row> = [
391 { id: `a`, value: 1 },
392 { id: `k`, value: 1 },
393 ]
394 const id = `persisted-order-${kind}-${start}-${touch}`
395 const storage = createStorage(kind, base, id)
396 const adapter = storage.adapter
397 let server = base
398 const held = heldQueryFn(() => server)
399 const release = deferred()
400 const entered = deferred()
401 let hold = false
402 const applyCommittedTx = adapter.applyCommittedTx.bind(adapter)
403 adapter.applyCommittedTx = async (...args) => {
404 if (hold && args[1].mutations.length > 0) {
405 hold = false
406 entered.resolve()
407 await release.promise
408 }
409 return applyCommittedTx(...args)
410 }
411 const errors = vi.spyOn(console, `error`).mockImplementation(() => {})
412 const queryClient = newQueryClient()
413 const collection = createCollection(
414 persistedCollectionOptions<
415 Row,
416 string | number,
417 never,
418 QueryCollectionUtils<Row>
419 >({
420 ...queryCollectionOptions<Row>({
421 id,
422 queryKey: [`persisted-order`, start, touch],
423 queryFn: held.queryFn,
424 queryClient,
425 getKey: (row) => row.id,
426 startSync: true,
427 }),
428 persistence: storage.persistence,
429 }),
430 )
431 const pending: Array<Promise<unknown>> = []
432 return checked(async () => {
433 await collection.preload()
434 // R1 holds the lock; R2 (a=2, k=5) commits and waits behind it.
435 hold = true
436 server = [
437 { id: `a`, value: 2 },
438 { id: `k`, value: 1 },
439 ]
440 pending.push(collection.utils.refetch())
441 await entered.promise
442 server = [
443 { id: `a`, value: 2 },
444 { id: `k`, value: 5 },
445 ]
446 pending.push(collection.utils.refetch())
447 await vi.waitFor(() =>
448 expect(
449 sortRows(
450 queryClient.getQueryData([`persisted-order`, start, touch]) ?? [],
451 ),
452 ).toEqual(sortRows(server)),
453 )
454 const waited =
455 (await storage.storedRows(id)).find((row) => row.id === `k`)?.value !== 5
456 if (start === `before`) {
457 held.arm()
458 pending.push(collection.utils.refetch())
459 await vi.waitFor(() => expect(held.calls.length).toBe(1))
460 }
461 const w = outcomeOf(() =>
462 collection.utils.writeUpdate({ id: `k`, value: 9 }),
463 )
464 if (start === `after`) {
465 held.arm()
466 pending.push(collection.utils.refetch())
467 await vi.waitFor(() => expect(held.calls.length).toBe(1))
468 }
469 held.disarm()
470 // R3 returns while W still waits for R2.
471 held.calls[0]!.resolve(laterRows(touch))
472 await flush()
473 release.resolve()
474 await w
475 await Promise.allSettled(pending)
476 for (let i = 0; i < 20; i++) await flush()
477 return {
478 visible: sortRows(collection.values()),
479 stored: await storage.storedRows(id),
480 waited,
481 }
482 }, [
483 () => release.resolve(),
484 () => errors.mockRestore(),
485 () => collection.cleanup(),
486 () => storage.close(),
487 ])
489​
490/**
491 * The ordering law for a later refetch: the write's result matches the
492 * no-persistence reference, and storage holds the visible rows.
493 */
494async function compareLaterRefetchOrder(
495 start: Start,
496 touch: Touch,
497 kind: StorageKind = `fake`,
498): Promise<void> {
499 const expected = await referenceOrder(start, touch)
500 const actual = await persistedOrder(start, touch, kind)
501 const label = kind === `sqlite` ? `sqlite` : `persisted`
502 expect(actual.waited, `the write waited on the lock`).toBe(true)
503 expect(
504 actual.visible,
505 `${label} ${JSON.stringify(actual.visible)} != reference ${JSON.stringify(expected)}`,
506 ).toEqual(expected)
507 expect(actual.stored, `storage matches the visible rows`).toEqual(
508 actual.visible,
509 )
511​
512describe(`a later refetch while a persisted direct write waits`, () => {
513 for (const start of [`before`, `after`] as const) {
514 for (const touch of [`same`, `different`] as const) {
515 it(`R3 started ${start} the write, ${touch} key`, async () => {
516 await compareLaterRefetchOrder(start, touch)
517 })
518 }
519 }
520})
521​
522/**
523 * ## Real SQLite receives the same law
524 *
525 * The matrix above runs over an in-memory fake adapter, which supplies the
526 * durable-write delay. This subset runs the same drivers over the node SQLite
527 * adapter, gated the same way: each write type with the key that only the
528 * waiting refetch holds and an earlier refetch's durable write holding the
529 * lock, plus the four ordering cases.
530 */
531describe(`real SQLite: persisted direct writes behind a waiting refetch`, () => {
532 for (const op of ops) {
533 it(`${op} with source-write holding the lock, key refetch-only`, async () => {
534 await compareWriteWithReference(
535 op,
536 `source-write`,
537 `refetch-only`,
538 `sqlite`,
539 )
540 })
541 }
542 for (const start of [`before`, `after`] as const) {
543 for (const touch of [`same`, `different`] as const) {
544 it(`R3 started ${start} the write, ${touch} key`, async () => {
545 await compareLaterRefetchOrder(start, touch, `sqlite`)
546 })
547 }
548 }
549})
550​
551/**
552 * ## A persisted insert of an existing key
553 *
554 * Without persistence, core rejects a sync insert of a key that it already
555 * holds. Persistence stores every sync insert as an update, so before this
556 * check a persisted `writeInsert` of an existing key replaced the row. This
557 * witness needs no lock window: the key is applied before the write runs.
558 */
559/**
560 * The duplicate-insert law: without persistence, core rejects a sync insert of an existing key;
561 * the persisted collection must reject it too, and keep the stored row.
562 */
563async function compareDuplicateInsert(): Promise<void> {
564 const base: Array<Row> = [{ id: `k`, value: 1 }]
565 const reference = createCollection(
566 queryCollectionOptions<Row>({
567 id: `reference-duplicate-insert`,
568 queryKey: [`reference-duplicate-insert`],
569 queryFn: () => Promise.resolve(base.map((row) => ({ ...row }))),
570 queryClient: newQueryClient(),
571 getKey: (row) => row.id,
572 startSync: true,
573 }),
574 )
575 const adapter = createAdapter(base)
576 const persistedCollection = createCollection(
577 persistedCollectionOptions<
578 Row,
579 string | number,
580 never,
581 QueryCollectionUtils<Row>
582 >({
583 ...queryCollectionOptions<Row>({
584 id: `persisted-duplicate-insert`,
585 queryKey: [`persisted-duplicate-insert`],
586 queryFn: () => Promise.resolve(base.map((row) => ({ ...row }))),
587 queryClient: newQueryClient(),
588 getKey: (row) => row.id,
589 startSync: true,
590 }),
591 persistence: { adapter },
592 }),
593 )
594 await checked(async () => {
595 await reference.preload()
596 await persistedCollection.preload()
597 // The returned promise rejects with DuplicateKeySyncError. A
598 // synchronous throw fails here, because it escapes the call before
599 // `expect` receives a promise.
600 for (const collection of [reference, persistedCollection]) {
601 await expect(
602 collection.utils.writeInsert({ id: `k`, value: 9 }),
603 ).rejects.toBeInstanceOf(DuplicateKeySyncError)
604 }
605 await flush()
606 expect(sortRows(persistedCollection.values())).toEqual(
607 sortRows(reference.values()),
608 )
609 expect(sortRows(adapter.rows.values())).toEqual([{ id: `k`, value: 1 }])
610 }, [() => reference.cleanup(), () => persistedCollection.cleanup()])
612​
613describe(`a persisted direct insert of an existing key`, () => {
614 it(`rejects like the reference and keeps the row`, async () => {
615 await compareDuplicateInsert()
616 })
617})