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

hydration-commit.opfs.ts

587 lines20.4 KB

1/**
2 * Receiving witness for persisted-oracle.test.ts's source durability laws.
3 * Chromium OPFS supplies the actual scheduler, worker, SQL and durable state.
4 * Startup/subscription/after-ready histories cross default/browser coordinators,
5 * empty/populated storage and a single insert/rich replacement history. Three
6 * Collections have distinct schemas: A commits within hydration, B hydrates
7 * behind it, and already-ready C requests ordinary durability during A's hold.
8 *
9 * The spec computes rows/metadata from the declared history, independently of
10 * this driver. A real row SELECT supplies the held-read premise. Its exact
11 * scope is retained only as a diagnostic identity, never used for storage.
12 * Coordinator instrumentation associates each nested transaction with the
13 * supplied live scope before detecting a scheduled public-adapter call. Thus
14 * an unrelated regular operation overlapping hydration is not called a cycle.
15 * All calls still reach production unchanged.
16 *
17 * Comparison cuts are held read, actual nested routing, and completed receipts,
18 * exact owning-scope exit (16 held-read histories), peer readiness, durable
19 * reads, and reopen. Eight after-ready controls have no held owning scope. Cleanup
20 * copies the primary observation first and records each secondary failure;
21 * page disposal owns remaining JS resources if the production cycle is red.
22 * Other browsers, multi-tab election, physical I/O failures, arbitrary fairness
23 * storms and cancellation remain with their existing owners.
24 */
25import { createCollection } from '../../db/src/index'
26import {
27 BrowserCollectionCoordinator,
28 createBrowserWASQLitePersistence,
29 openBrowserWASQLiteOPFSDatabase,
30 persistedCollectionOptions,
31} from '../src/index'
32import type { Collection, SyncConfig } from '../../db/src/index'
33import type { HydrationPersistenceAdapter } from '../../db-sqlite-persistence-core/src/index'
34​
35type Row = { id: string; value: number }
36type Phase = `startup` | `subscription` | `after-ready`
37type Receipt = `pending` | `fulfilled` | `rejected`
38export type HydrationCommitObservation = {
39 phase: Phase
40 baseline: boolean
41 rich: boolean
42 browserCoordinator: boolean
43 rowReads: number
44 cycleCalls: number
45 held: {
46 receipts: Array<Receipt>
47 rows: Array<Row>
48 ordinary: Receipt
49 interleavedSql: Array<string>
50 peerHydrationAdmitted: boolean
51 ordinaryAdmitted: boolean
52 } | null
53 receipts: Array<Receipt>
54 sourceStatus: string
55 peerStatus: string
56 ordinaryReceipt: Receipt
57 owningScopeExited: boolean | null
58 tailScheduling: Array<`public-apply` | `regular-scope`>
59 peerWorkBeforeScopeExit: Array<string>
60 ordinaryCommitSqlCalls: number
61 rows: Array<Row>
62 durableRows: Array<Row> | null
63 durableMetadata: Array<{ key: string; value: unknown }> | null
64 durableRowMetadata: Array<{ key: string | number; metadata: unknown }> | null
65 peerRows: Array<Row> | null
66 ordinaryRows: Array<Row> | null
67 schemas: Array<{ collection_id: string; schema_version: number }> | null
68 reopenedRows: Array<Row> | null
69 errors: Array<string>
71declare global {
72 interface Window {
73 __hydrationCommitResult?: HydrationCommitObservation
74 __hydrationCommitError?: string
75 __hydrationCommitCleanupErrors?: Array<string>
76 __hydrationCommitDone?: boolean
77 }
79function deferred() {
80 let resolve!: () => void
81 const promise = new Promise<void>((settle) => {
82 resolve = settle
83 })
84 return { promise, resolve }
86function publicRows(collection: Collection<Row, string>): Array<Row> {
87 return [...collection.values()]
88 .map(({ id, value }) => ({ id, value }))
89 .sort((a, b) => a.id.localeCompare(b.id))
91async function run(): Promise<void> {
92 const params = new URL(location.href).searchParams
93 const phase = params.get(`phase`) as Phase
94 if (![`startup`, `subscription`, `after-ready`].includes(phase))
95 throw new Error(`Invalid phase`)
96 const baseline = params.get(`baseline`) === `true`
97 const rich = params.get(`rich`) === `true`
98 const browserCoordinator = params.get(`coordinator`) === `browser`
99 const databaseName = `hc-${crypto.randomUUID()}.sqlite`
100 const database = await openBrowserWASQLiteOPFSDatabase({ databaseName })
101 const cleanup: Array<() => void | Promise<unknown>> = []
102 const cleanupErrors: Array<string> = []
103 const releaseRead = deferred()
104 let disposeCoordinator: (() => void) | undefined
105 let captured: HydrationCommitObservation | undefined
106 let cycleCalls = 0
107 try {
108 const coordinator = browserCoordinator
109 ? new BrowserCollectionCoordinator({ dbName: databaseName })
110 : undefined
111 if (coordinator) disposeCoordinator = () => coordinator.dispose()
112 const readEntered = deferred()
113 const cycle = deferred()
114 const sourceStarted = deferred()
115 const sourceReady = deferred()
116 const peerReady = deferred()
117 const scopeExited = deferred()
118 const peerHydrationAdmission = deferred()
119 const ordinaryAdmission = deferred()
120 let observeContenders = false
121 let peerHydrationAdmitted = false
122 let ordinaryAdmitted = false
123 let scopePremiseError: Error | undefined
124 let holdRead = false
125 let readHeld = false
126 const interleavedSql: Array<string> = []
127 let rowReads = 0
128 let scopeSequence = 0
129 let heldScope: number | undefined
130 let owningScopeExited: boolean | null =
131 phase === `after-ready` ? null : false
132 const liveScopes = new Map<number, HydrationPersistenceAdapter>()
133 let ordinaryCommitSqlCalls = 0
134 const peerWorkBeforeScopeExit: Array<string> = []
135 const observePeerWork = (operation: string) => {
136 if (heldScope !== undefined && liveScopes.has(heldScope)) {
137 peerWorkBeforeScopeExit.push(operation)
138 }
139 }
140 const persistence = createBrowserWASQLitePersistence({
141 database: {
142 execute: async <T>(sql: string, bindings?: ReadonlyArray<unknown>) => {
143 if (readHeld) interleavedSql.push(sql)
144 // Every ordinary apply reads its applied_tx/version state before
145 // writing. Observe C at that real SQL boundary, through scope exit.
146 // Election stream-position reads intentionally bypass this scheduler
147 // and are not regular work (getStreamPosition's existing contract).
148 if (sql.includes(`AS already_applied`) && bindings?.includes(`c`)) {
149 ordinaryCommitSqlCalls++
150 observePeerWork(`ordinary-commit-sql`)
151 }
152 const result = await database.execute<T>(sql, bindings)
153 if (sql.includes(`SELECT key, value, metadata, row_version FROM`)) {
154 rowReads++
155 if (holdRead) {
156 holdRead = false
157 // Public A scopes are serialized by the real shared scheduler.
158 // Key by callback invocation, since SQLite reuses its loan object.
159 // An invalid premise fails here instead of waiting for a lost exit.
160 if (liveScopes.size !== 1) {
161 scopePremiseError = new Error(
162 `Held read requires exactly one owning callback; got ${liveScopes.size}`,
163 )
164 readEntered.resolve()
165 throw scopePremiseError
166 }
167 heldScope = liveScopes.keys().next().value
168 readHeld = true
169 readEntered.resolve()
170 await releaseRead.promise
171 readHeld = false
172 }
173 }
174 return result
175 },
176 },
177 ...(coordinator ? { coordinator } : {}),
178 })
179 const resolved = persistence.resolvePersistenceForCollection!({
180 collectionId: `a`,
181 mode: `sync-present`,
182 schemaVersion: 11,
183 })
184 const adapter = resolved.adapter
185 const bAdapter = persistence.resolvePersistenceForCollection!({
186 collectionId: `b`,
187 mode: `sync-present`,
188 schemaVersion: 22,
189 }).adapter
190 const cAdapter = persistence.resolvePersistenceForCollection!({
191 collectionId: `c`,
192 mode: `sync-present`,
193 schemaVersion: 33,
194 }).adapter
195 const seed = (id: string, row: Row, target: typeof adapter) =>
196 target.applyCommittedTx(id, {
197 txId: `seed-${id}`,
198 term: 1,
199 seq: 1,
200 rowVersion: 1,
201 mutations: [{ type: `insert`, key: row.id, value: row }],
202 })
203 if (baseline) await seed(`a`, { id: `baseline`, value: 0 }, adapter)
204 await seed(`b`, { id: `peer-baseline`, value: 22 }, bAdapter)
205 const runScope = adapter.runInHydrationScope!.bind(adapter)
206 const pendingHydrations = new Set<Promise<unknown>>()
207 adapter.runInHydrationScope = (task) => {
208 const result = runScope(async (scoped) => {
209 const scope = ++scopeSequence
210 liveScopes.set(scope, scoped)
211 try {
212 return await task(scoped)
213 } finally {
214 liveScopes.delete(scope)
215 if (scope === heldScope) {
216 owningScopeExited = true
217 scopeExited.resolve()
218 }
219 }
220 })
221 pendingHydrations.add(result)
222 void result.then(
223 () => pendingHydrations.delete(result),
224 () => pendingHydrations.delete(result),
225 )
226 return result
227 }
228 // Each method enqueues synchronously before returning its promise. Observe
229 // that return without awaiting completion, which is blocked by A's read.
230 const bHydrate = bAdapter.runInHydrationScope!.bind(bAdapter)
231 bAdapter.runInHydrationScope = (task) => {
232 const result = bHydrate((scoped) => {
233 observePeerWork(`peer-hydrate`)
234 return task(scoped)
235 })
236 if (observeContenders) {
237 peerHydrationAdmitted = true
238 peerHydrationAdmission.resolve()
239 }
240 return result
241 }
242 const admitOrdinary = () => {
243 if (observeContenders) {
244 ordinaryAdmitted = true
245 ordinaryAdmission.resolve()
246 }
247 }
248 // Default coordinator uses public apply; browser leadership uses the
249 // regular-scope API before its writer lock. Observe both real entry paths.
250 const cApply = cAdapter.applyCommittedTx.bind(cAdapter)
251 cAdapter.applyCommittedTx = (...args) => {
252 const result = cApply(...args)
253 admitOrdinary()
254 return result
255 }
256 const cRegular = cAdapter.runInRegularScope!.bind(cAdapter)
257 cAdapter.runInRegularScope = (task) => {
258 const result = cRegular((scoped) => {
259 observePeerWork(`ordinary-scope`)
260 return task(scoped)
261 })
262 admitOrdinary()
263 return result
264 }
265 const nested = new Set<string>()
266 const tailTransactions = new Set<string>()
267 let tailStarted = false
268 const tailScheduling: HydrationCommitObservation[`tailScheduling`] = []
269 const aRegular = adapter.runInRegularScope!.bind(adapter)
270 adapter.runInRegularScope = (task) => {
271 const result = aRegular(task)
272 if (tailStarted && tailTransactions.size > 0)
273 tailScheduling.push(`regular-scope`)
274 return result
275 }
276 const request = resolved.coordinator!.requestApplyCommittedTx.bind(
277 resolved.coordinator!,
278 )
279 resolved.coordinator!.requestApplyCommittedTx = async (id, tx, scoped) => {
280 const nestedHere =
281 id === `a` &&
282 scoped !== undefined &&
283 [...liveScopes.values()].includes(scoped)
284 if (nestedHere) nested.add(tx.txId)
285 if (id === `a` && tailStarted) tailTransactions.add(tx.txId)
286 try {
287 return await request(id, tx, scoped)
288 } finally {
289 if (nestedHere) nested.delete(tx.txId)
290 }
291 }
292 const apply = adapter.applyCommittedTx.bind(adapter)
293 adapter.applyCommittedTx = (id, tx) => {
294 const result = apply(id, tx)
295 if (id === `a` && tailStarted && tailTransactions.has(tx.txId))
296 tailScheduling.push(`public-apply`)
297 if (id === `a` && nested.has(tx.txId)) {
298 cycleCalls++
299 cycle.resolve()
300 }
301 return result
302 }
303 const errors: Array<string> = []
304 const receiptStates: Array<Receipt> = []
305 const receiptPromises: Array<Promise<void>> = []
306 let source!: Parameters<SyncConfig<Row, string>[`sync`]>[0]
307 const commit = (edit: () => void) => {
308 source.begin()
309 edit()
310 const index = receiptStates.push(`pending`) - 1
311 const receipt = Promise.resolve(source.commit()).then(
312 () => {
313 receiptStates[index] = `fulfilled`
314 },
315 (error: unknown) => {
316 receiptStates[index] = `rejected`
317 errors.push(String(error))
318 },
319 )
320 receiptPromises.push(receipt)
321 }
322 const sourceHistory = () => {
323 commit(() =>
324 source.write({ type: `insert`, value: { id: `r1`, value: 1 } }),
325 )
326 if (!rich) return
327 commit(() => source.metadata!.collection.set(`cursor`, 7))
328 commit(() => {
329 source.metadata!.collection.set(`cursor`, 8)
330 source.truncate()
331 source.write({ type: `insert`, value: { id: `r2`, value: 2 } })
332 source.metadata!.row.set(`r2`, { owner: `source` })
333 })
334 commit(() =>
335 source.write({ type: `update`, value: { id: `r2`, value: 3 } }),
336 )
337 commit(() =>
338 source.write({ type: `insert`, value: { id: `temporary`, value: 4 } }),
339 )
340 commit(() => source.write({ type: `delete`, key: `temporary` }))
341 }
342 let ordinarySource!: Parameters<SyncConfig<Row, string>[`sync`]>[0]
343 const c = createCollection(
344 persistedCollectionOptions<Row, string>({
345 id: `c`,
346 schemaVersion: 33,
347 persistence,
348 getKey: (row) => row.id,
349 sync: {
350 sync: (controls) => {
351 ordinarySource = controls
352 controls.markReady()
353 },
354 },
355 }),
356 )
357 cleanup.unshift(() => c.cleanup())
358 await c.preload()
359 holdRead = phase === `startup`
360 const a = createCollection(
361 persistedCollectionOptions<Row, string>({
362 id: `a`,
363 schemaVersion: 11,
364 persistence,
365 getKey: (row) => row.id,
366 startSync: true,
367 syncMode: phase === `subscription` ? `on-demand` : `eager`,
368 sync: {
369 sync: (controls) => {
370 source = controls
371 if (phase === `startup`) sourceHistory()
372 controls.markReady()
373 sourceStarted.resolve()
374 return { loadSubset: () => true }
375 },
376 },
377 }),
378 )
379 cleanup.unshift(() => a.cleanup())
380 a.onFirstReady(() => {
381 sourceReady.resolve()
382 if (phase === `after-ready`) sourceHistory()
383 })
384 await sourceStarted.promise
385 if (phase === `subscription`) {
386 await sourceReady.promise
387 holdRead = true
388 const subscription = a.subscribeChanges(() => {}, {
389 includeInitialState: true,
390 })
391 cleanup.unshift(() => subscription.unsubscribe())
392 }
393 if (phase !== `after-ready`) await readEntered.promise
394 else {
395 await sourceReady.promise
396 scopeExited.resolve()
397 }
398 if (scopePremiseError) throw scopePremiseError
399 if (phase === `subscription`) sourceHistory()
400 observeContenders = true
401 const b = createCollection(
402 persistedCollectionOptions<Row, string>({
403 id: `b`,
404 schemaVersion: 22,
405 persistence,
406 getKey: (row) => row.id,
407 startSync: true,
408 sync: { sync: ({ markReady }) => markReady() },
409 }),
410 )
411 cleanup.unshift(() => b.cleanup())
412 b.onFirstReady(peerReady.resolve)
413 ordinarySource.begin()
414 ordinarySource.write({
415 type: `insert`,
416 value: { id: `ordinary`, value: 33 },
417 })
418 let ordinaryReceipt: Receipt = `pending`
419 const ordinaryDone = Promise.resolve(ordinarySource.commit()).then(
420 () => {
421 ordinaryReceipt = `fulfilled`
422 },
423 (error: unknown) => {
424 ordinaryReceipt = `rejected`
425 errors.push(String(error))
426 },
427 )
428 // Both contenders have crossed their real scheduling API before the cut.
429 // No task tick or SQL latency is used as evidence of admission.
430 await Promise.all([
431 peerHydrationAdmission.promise,
432 ordinaryAdmission.promise,
433 ])
434 const held =
435 phase === `after-ready`
436 ? null
437 : {
438 receipts: [...receiptStates],
439 rows: publicRows(a),
440 ordinary: ordinaryReceipt,
441 interleavedSql: [...interleavedSql],
442 peerHydrationAdmitted,
443 ordinaryAdmitted,
444 }
445 releaseRead.resolve()
446 await Promise.race([
447 cycle.promise,
448 Promise.all([
449 sourceReady.promise,
450 ...receiptPromises,
451 peerReady.promise,
452 ordinaryDone,
453 scopeExited.promise,
454 ]),
455 ])
456 let durableRows: Array<Row> | null = null
457 let durableMetadata: Array<{ key: string; value: unknown }> | null = null
458 let durableRowMetadata: Array<{
459 key: string | number
460 metadata: unknown
461 }> | null = null
462 let peerRows: Array<Row> | null = null
463 let ordinaryRows: Array<Row> | null = null
464 let schemas: HydrationCommitObservation[`schemas`] = null
465 const reopenedRows: Array<Row> | null = null
466 if (cycleCalls === 0) {
467 // Truncate can trigger a follow-up subset hydrate. Join all public A
468 // invocations already requested by the source history before issuing an
469 // ordinary tail; the originally held callback alone is not quiescence.
470 while (pendingHydrations.size > 0) {
471 await Promise.all([...pendingHydrations])
472 }
473 // Record the tail at the coordinator's ordinary scheduling boundary. Rows
474 // alone cannot distinguish a cached, expired loan from ordinary routing.
475 tailStarted = true
476 commit(() =>
477 source.write({ type: `insert`, value: { id: `tail`, value: 9 } }),
478 )
479 await receiptPromises.at(-1)
480 tailStarted = false
481 const durable = await adapter.loadSubset(`a`, {})
482 durableRows = durable
483 .map(({ value }) => value as Row)
484 .sort((x, y) => x.id.localeCompare(y.id))
485 durableRowMetadata = durable
486 .filter(({ metadata }) => metadata !== undefined)
487 .map(({ key, metadata }) => ({ key, metadata }))
488 durableMetadata = await adapter.loadCollectionMetadata!(`a`)
489 peerRows = (await bAdapter.loadSubset(`b`, {})).map(
490 ({ value }) => value as Row,
491 )
492 ordinaryRows = (await cAdapter.loadSubset(`c`, {})).map(
493 ({ value }) => value as Row,
494 )
495 schemas = [
496 ...(await database.execute<{
497 collection_id: string
498 schema_version: number
499 }>(
500 `SELECT collection_id, schema_version FROM collection_registry ORDER BY collection_id`,
501 )),
502 ]
503 }
504 captured = structuredClone({
505 phase,
506 baseline,
507 rich,
508 browserCoordinator,
509 rowReads,
510 cycleCalls,
511 held,
512 receipts: receiptStates,
513 sourceStatus: a.status,
514 peerStatus: b.status,
515 ordinaryReceipt,
516 owningScopeExited,
517 tailScheduling,
518 peerWorkBeforeScopeExit,
519 ordinaryCommitSqlCalls,
520 rows: publicRows(a),
521 durableRows,
522 durableMetadata,
523 durableRowMetadata,
524 peerRows,
525 ordinaryRows,
526 schemas,
527 reopenedRows,
528 errors,
529 })
530 window.__hydrationCommitResult = captured
531 if (cycleCalls === 0) {
532 await a.cleanup()
533 const reopened = createCollection(
534 persistedCollectionOptions<Row, string>({
535 id: `a`,
536 schemaVersion: 11,
537 persistence,
538 getKey: (row) => row.id,
539 syncMode: `eager`,
540 }),
541 )
542 cleanup.unshift(() => reopened.cleanup())
543 await reopened.preload()
544 captured.reopenedRows = publicRows(reopened)
545 window.__hydrationCommitResult = structuredClone(captured)
546 }
547 } catch (error) {
548 window.__hydrationCommitError = String(error)
549 } finally {
550 releaseRead.resolve()
551 // A real cycle prevents Collection teardown; closing the worker and the
552 // isolated Playwright page releases it. Other cleanup failures cannot
553 // replace the already-copied primary observation or skip database close.
554 if (params.get(`cleanupFault`) === `true`) {
555 cleanup.unshift(() => {
556 throw new Error(`injected first cleanup failure`)
557 })
558 cleanup.push(() => {
559 throw new Error(`injected last cleanup failure`)
560 })
561 }
562 for (const action of cleanup) {
563 if (cycleCalls > 0) break
564 try {
565 await action()
566 } catch (error) {
567 cleanupErrors.push(String(error))
568 }
569 }
570 try {
571 disposeCoordinator?.()
572 } catch (error) {
573 cleanupErrors.push(String(error))
574 }
575 try {
576 await database.close?.()
577 } catch (error) {
578 cleanupErrors.push(String(error))
579 }
580 window.__hydrationCommitCleanupErrors = cleanupErrors
581 window.__hydrationCommitDone = true
582 }
584void run().catch((error: unknown) => {
585 window.__hydrationCommitError = String(error)
586 window.__hydrationCommitDone = true
587})