Open History to see the last commit
1/**
2 * Ordinary regression tests for cleanup of a persisted source that has a queued receipt, then restarts with the same
3 * persistence: the queued receipt is fenced, and the restarted owner accepts its own writes, in startup and subscription
4 * hydration phases, with and without the hydration routing probe. The fencing law is owned by persisted-oracle.test.ts,
5 * which keeps its model-checked hydration cases. The last test is a self-test of expectHydrationReceiptsPending from
6 * persisted-support.ts, the receipt-pending check the oracle file uses; it is not an oracle.
7 */
8import { describe, expect, it } from 'vitest'
9import { createCollection } from '@tanstack/db'
10import { persistedCollectionOptions } from '../src'
11import {
12 atPersistedOracleCheckpoint,
13 cleanupPersistedOracle,
14 createDeferred,
15 createRecordingAdapter,
16 expectHydrationReceiptsPending,
17 flushAsyncWork,
18 installHydrationRoutingProbe,
19 observeSettlement,
20 stripVirtualProps,
21} from './persisted-support'
22import type { Todo, TodoSyncParams } from './persisted-support'
23
24describe(`hydration source durability routing`, () => {
25 // Cleanup is a history action here, not only teardown. Queued source work
26 // has not entered storage when cleanup invalidates its sync run; releasing
27 // the old read cannot publish/store it in the replacement run. An already
28 // issued storage operation is outside this witness's no-write premise.
29 it.each(
30 [false, true].flatMap((scoped) =>
31 [`startup`, `subscription`].map((phase) => ({ scoped, phase })),
32 ),
33 )(
34 `cleanup fences a queued source receipt and permits restart: $phase scoped=$scoped`,
35 async ({ scoped, phase }) => {
36 const adapter = createRecordingAdapter()
37 const entered = createDeferred()
38 const release = createDeferred()
39 let holdRead = phase === `startup`
40 const resume = adapter.loadResumeSnapshot.bind(adapter)
41 const load = adapter.loadSubset.bind(adapter)
42 const hold = async <T>(snapshot: T) => {
43 if (holdRead) {
44 holdRead = false
45 entered.resolve()
46 await release.promise
47 }
48 return snapshot
49 }
50 adapter.loadResumeSnapshot = async (...args) => {
51 const snapshot = await resume(...args)
52 return args[1]?.includeRows === false ? snapshot : hold(snapshot)
53 }
54 adapter.loadSubset = async (...args) => hold(await load(...args))
55 const probe = scoped ? installHydrationRoutingProbe(adapter) : undefined
56 let source!: TodoSyncParams
57 const collection = createCollection(
58 persistedCollectionOptions<Todo, string>({
59 id: `scoped-cleanup-restart`,
60 getKey: (row) => row.id,
61 syncMode: phase === `subscription` ? `on-demand` : `eager`,
62 sync: {
63 sync: (params) => {
64 source = params
65 params.markReady()
66 return { loadSubset: () => true }
67 },
68 },
69 persistence: { adapter },
70 }),
71 )
72 const ready = collection.stateWhenReady()
73 void ready.catch(() => undefined)
74 let subset: Promise<unknown> | undefined
75 let receipt: Promise<void> | undefined
76 let hasPrimaryFailure = false
77 try {
78 if (phase === `subscription`) {
79 await atPersistedOracleCheckpoint(ready, `cleanup initial readiness`)
80 holdRead = true
81 subset = Promise.resolve(collection._sync.loadSubset({ limit: 1 }))
82 void subset.catch(() => undefined)
83 }
84 await atPersistedOracleCheckpoint(entered.promise, `cleanup held read`)
85 source.begin()
86 source.write({
87 type: `insert`,
88 value: { id: `obsolete`, title: `retired sync run` },
89 })
90 receipt = Promise.resolve(source.commit()).then(() => undefined)
91 const receiptState = observeSettlement(receipt)
92 const oldSource = source
93 const cleaning = collection.cleanup()
94 void cleaning.catch(() => undefined)
95 release.resolve()
96 await atPersistedOracleCheckpoint(
97 Promise.allSettled([cleaning, receipt, ready, subset]),
98 `cleanup invalidates buffered work`,
99 )
100 expect(receiptState.read().status).toBe(`rejected`)
101 expect(adapter.applyCommittedTxCalls).toEqual([])
102 expect(adapter.rows.size).toBe(0)
103 expect(collection.status).toBe(`cleaned-up`)
104 await atPersistedOracleCheckpoint(
105 collection.stateWhenReady(),
106 `replacement sync run ready`,
107 )
108 oldSource.begin()
109 oldSource.write({
110 type: `insert`,
111 value: { id: `obsolete`, title: `late callback` },
112 })
113 await oldSource.commit()
114 source.begin()
115 source.write({
116 type: `insert`,
117 value: { id: `fresh`, title: `replacement source` },
118 })
119 await atPersistedOracleCheckpoint(
120 Promise.resolve(source.commit()),
121 `replacement source durable`,
122 )
123 expect(collection.get(`obsolete`)).toBeUndefined()
124 expect(adapter.rows.has(`obsolete`)).toBe(false)
125 expect(stripVirtualProps(collection.get(`fresh`))).toEqual({
126 id: `fresh`,
127 title: `replacement source`,
128 })
129 expect(adapter.rows.get(`fresh`)).toEqual({
130 id: `fresh`,
131 title: `replacement source`,
132 })
133 expect(probe?.violations() ?? []).toEqual([])
134 } catch (error) {
135 hasPrimaryFailure = true
136 throw error
137 } finally {
138 release.resolve()
139 await cleanupPersistedOracle(
140 [
141 () => Promise.allSettled([ready, subset, receipt]),
142 () => collection.cleanup(),
143 ],
144 hasPrimaryFailure,
145 )
146 }
147 },
148 )
149
150 it(`rejects an early individual receipt even while its sibling is pending`, async () => {
151 const pending = createDeferred()
152 const receipts = [
153 observeSettlement(Promise.resolve()),
154 observeSettlement(pending.promise),
155 ]
156 // A task boundary drains promise reactions; no elapsed duration is treated
157 // as progress evidence. The other receipt remains causally held by a gate.
158 await flushAsyncWork()
159 try {
160 expect(() => expectHydrationReceiptsPending(receipts)).toThrow()
161 } finally {
162 pending.resolve()
163 }
164 })
165})