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

hydration-commit.opfs.ts

687 lines23.7 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 sourceStorageId: string
44 rowReads: number
45 cycleCalls: number
46 held: {
47 receipts: Array<Receipt>
48 rows: Array<Row>
49 ordinary: Receipt
50 interleavedSql: Array<string>
51 peerHydrationAdmitted: boolean
52 ordinaryAdmitted: boolean
53 } | null
54 receipts: Array<Receipt>
55 sourceStatus: string
56 peerStatus: string
57 ordinaryReceipt: Receipt
58 owningScopeExited: boolean | null
59 tailScheduling: Array<`public-apply` | `regular-scope`>
60 peerWorkBeforeScopeExit: Array<string>
61 ordinaryCommitSqlCalls: number
62 rows: Array<Row>
63 durableRows: Array<Row> | null
64 durableMetadata: Array<{ key: string; value: unknown }> | null
65 durableRowMetadata: Array<{ key: string | number; metadata: unknown }> | null
66 peerRows: Array<Row> | null
67 ordinaryRows: Array<Row> | null
68 schemas: Array<{ collection_id: string; schema_version: number }> | null
69 reopenedRows: Array<Row> | null
70 errors: Array<string>
72declare global {
73 interface Window {
74 __hydrationCommitResult?: HydrationCommitObservation
75 __hydrationCommitError?: string
76 __hydrationCommitCleanupErrors?: Array<string>
77 __hydrationCommitDone?: boolean
78 }
80function deferred() {
81 let resolve!: () => void
82 const promise = new Promise<void>((settle) => {
83 resolve = settle
84 })
85 return { promise, resolve }
87function publicRows(collection: Collection<Row, string>): Array<Row> {
88 return [...collection.values()]
89 .map(({ id, value }) => ({ id, value }))
90 .sort((a, b) => a.id.localeCompare(b.id))
92async function run(): Promise<void> {
93 const params = new URL(location.href).searchParams
94 const phase = params.get(`phase`) as Phase
95 if (![`startup`, `subscription`, `after-ready`].includes(phase))
96 throw new Error(`Invalid phase`)
97 const baseline = params.get(`baseline`) === `true`
98 const rich = params.get(`rich`) === `true`
99 const browserCoordinator = params.get(`coordinator`) === `browser`
100 const databaseName = `hc-${crypto.randomUUID()}.sqlite`
101 const database = await openBrowserWASQLiteOPFSDatabase({ databaseName })
102 const cleanup: Array<() => void | Promise<unknown>> = []
103 const cleanupErrors: Array<string> = []
104 const releaseRead = deferred()
105 let disposeCoordinator: (() => void) | undefined
106 let captured: HydrationCommitObservation | undefined
107 let cycleCalls = 0
108 try {
109 const coordinator = browserCoordinator
110 ? new BrowserCollectionCoordinator({ dbName: databaseName })
111 : undefined
112 if (coordinator) disposeCoordinator = () => coordinator.dispose()
113 const readEntered = deferred()
114 const cycle = deferred()
115 const sourceStarted = deferred()
116 const sourceReady = deferred()
117 const peerReady = deferred()
118 const scopeExited = deferred()
119 const peerHydrationAdmission = deferred()
120 const ordinaryAdmission = deferred()
121 let observeContenders = false
122 let peerHydrationAdmitted = false
123 let ordinaryAdmitted = false
124 let scopePremiseError: Error | undefined
125 let holdRead = false
126 let readHeld = false
127 const interleavedSql: Array<string> = []
128 let rowReads = 0
129 let scopeSequence = 0
130 let heldScope: number | undefined
131 let owningScopeExited: boolean | null =
132 phase === `after-ready` ? null : false
133 const liveScopes = new Map<number, HydrationPersistenceAdapter>()
134 let ordinaryCommitSqlCalls = 0
135 const peerWorkBeforeScopeExit: Array<string> = []
136 const observePeerWork = (operation: string) => {
137 if (heldScope !== undefined && liveScopes.has(heldScope)) {
138 peerWorkBeforeScopeExit.push(operation)
139 }
140 }
141 const persistence = createBrowserWASQLitePersistence({
142 database: {
143 execute: async <T>(sql: string, bindings?: ReadonlyArray<unknown>) => {
144 if (readHeld) interleavedSql.push(sql)
145 // Every ordinary apply reads its applied_tx/version state before
146 // writing. Observe C at that real SQL boundary, through scope exit.
147 // Election stream-position reads intentionally bypass this scheduler
148 // and are not regular work (getStreamPosition's existing contract).
149 if (sql.includes(`AS already_applied`) && bindings?.includes(`c`)) {
150 ordinaryCommitSqlCalls++
151 observePeerWork(`ordinary-commit-sql`)
152 }
153 const result = await database.execute<T>(sql, bindings)
154 if (sql.includes(`SELECT key, value, metadata, row_version FROM`)) {
155 rowReads++
156 if (holdRead) {
157 holdRead = false
158 // Public A scopes are serialized by the real shared scheduler.
159 // Key by callback invocation, since SQLite reuses its loan object.
160 // An invalid premise fails here instead of waiting for a lost exit.
161 if (liveScopes.size !== 1) {
162 scopePremiseError = new Error(
163 `Held read requires exactly one owning callback; got ${liveScopes.size}`,
164 )
165 readEntered.resolve()
166 throw scopePremiseError
167 }
168 heldScope = liveScopes.keys().next().value
169 readHeld = true
170 readEntered.resolve()
171 await releaseRead.promise
172 readHeld = false
173 }
174 }
175 return result
176 },
177 },
178 ...(coordinator ? { coordinator } : {}),
179 })
180 const resolved = persistence.resolvePersistenceForCollection!({
181 collectionId: `a`,
182 mode: `sync-present`,
183 schemaVersion: 11,
184 })
185 const adapter = resolved.adapter
186 // On-demand A writes its claimed physical cache ID. Keep that ID from the
187 // adapter's claim result so the scheduling and durable checks observe the
188 // same Collection without guessing a storage-name format.
189 let sourceStorageId = `a`
190 let sourceClaimId: string | undefined
191 if (phase === `subscription`) {
192 const claim = adapter.claimCacheGeneration?.bind(adapter)
193 if (!claim) throw new Error(`On-demand A requires a managed cache claim`)
194 adapter.claimCacheGeneration = async (id) => {
195 const result = await claim(id)
196 if (id === `a`) {
197 sourceStorageId = result.storageCollectionId
198 sourceClaimId = result.claimId
199 }
200 return result
201 }
202 }
203 const bAdapter = persistence.resolvePersistenceForCollection!({
204 collectionId: `b`,
205 mode: `sync-present`,
206 schemaVersion: 22,
207 }).adapter
208 const cAdapter = persistence.resolvePersistenceForCollection!({
209 collectionId: `c`,
210 mode: `sync-present`,
211 schemaVersion: 33,
212 }).adapter
213 const seed = (id: string, row: Row, target: typeof adapter) =>
214 target.applyCommittedTx(
215 { kind: `eager`, collectionId: id },
216 {
217 txId: `seed-${id}`,
218 term: 1,
219 seq: 1,
220 rowVersion: 1,
221 mutations: [{ type: `insert`, key: row.id, value: row }],
222 },
223 )
224 if (baseline && phase === `subscription`) {
225 const claim = await adapter.claimCacheGeneration!(`a`)
226 await adapter.applyCommittedTx(
227 {
228 kind: `managed`,
229 storageCollectionId: claim.storageCollectionId,
230 claimId: claim.claimId,
231 },
232 {
233 txId: `seed-a`,
234 term: 1,
235 seq: 1,
236 rowVersion: 1,
237 cacheGenerationClaimId: claim.claimId,
238 mutations: [
239 {
240 type: `insert`,
241 key: `baseline`,
242 value: { id: `baseline`, value: 0 },
243 },
244 ],
245 },
246 )
247 await adapter.releaseCacheGenerationClaim!(claim.claimId)
248 } else if (baseline) {
249 await seed(`a`, { id: `baseline`, value: 0 }, adapter)
250 }
251 await seed(`b`, { id: `peer-baseline`, value: 22 }, bAdapter)
252 const runScope = adapter.runInHydrationScope!.bind(adapter)
253 const pendingHydrations = new Set<Promise<unknown>>()
254 adapter.runInHydrationScope = (task) => {
255 const result = runScope(async (scoped) => {
256 const scope = ++scopeSequence
257 liveScopes.set(scope, scoped)
258 try {
259 return await task(scoped)
260 } finally {
261 liveScopes.delete(scope)
262 if (scope === heldScope) {
263 owningScopeExited = true
264 scopeExited.resolve()
265 }
266 }
267 })
268 pendingHydrations.add(result)
269 void result.then(
270 () => pendingHydrations.delete(result),
271 () => pendingHydrations.delete(result),
272 )
273 return result
274 }
275 // Each method enqueues synchronously before returning its promise. Observe
276 // that return without awaiting completion, which is blocked by A's read.
277 const bHydrate = bAdapter.runInHydrationScope!.bind(bAdapter)
278 bAdapter.runInHydrationScope = (task) => {
279 const result = bHydrate((scoped) => {
280 observePeerWork(`peer-hydrate`)
281 return task(scoped)
282 })
283 if (observeContenders) {
284 peerHydrationAdmitted = true
285 peerHydrationAdmission.resolve()
286 }
287 return result
288 }
289 const admitOrdinary = () => {
290 if (observeContenders) {
291 ordinaryAdmitted = true
292 ordinaryAdmission.resolve()
293 }
294 }
295 // Default coordinator uses public apply; browser leadership uses the
296 // regular-scope API before its writer lock. Observe both real entry paths.
297 const cApply = cAdapter.applyCommittedTx.bind(cAdapter)
298 cAdapter.applyCommittedTx = (...args) => {
299 const result = cApply(...args)
300 admitOrdinary()
301 return result
302 }
303 const cRegular = cAdapter.runInRegularScope!.bind(cAdapter)
304 cAdapter.runInRegularScope = (task) => {
305 const result = cRegular((scoped) => {
306 observePeerWork(`ordinary-scope`)
307 return task(scoped)
308 })
309 admitOrdinary()
310 return result
311 }
312 const nested = new Set<string>()
313 const tailTransactions = new Set<string>()
314 let tailStarted = false
315 const tailScheduling: HydrationCommitObservation[`tailScheduling`] = []
316 const aRegular = adapter.runInRegularScope!.bind(adapter)
317 adapter.runInRegularScope = (task) => {
318 const result = aRegular(task)
319 if (tailStarted && tailTransactions.size > 0)
320 tailScheduling.push(`regular-scope`)
321 return result
322 }
323 const request = resolved.coordinator!.requestApplyCommittedTx.bind(
324 resolved.coordinator!,
325 )
326 resolved.coordinator!.requestApplyCommittedTx = async (id, tx, scoped) => {
327 const nestedHere =
328 id === sourceStorageId &&
329 scoped !== undefined &&
330 [...liveScopes.values()].includes(scoped)
331 if (nestedHere) nested.add(tx.txId)
332 if (id === sourceStorageId && tailStarted) tailTransactions.add(tx.txId)
333 try {
334 return await request(id, tx, scoped)
335 } finally {
336 if (nestedHere) nested.delete(tx.txId)
337 }
338 }
339 const apply = adapter.applyCommittedTx.bind(adapter)
340 adapter.applyCommittedTx = (id, tx) => {
341 const result = apply(id, tx)
342 if (
343 (id.kind === `managed` ? id.storageCollectionId : id.collectionId) ===
344 sourceStorageId &&
345 tailStarted &&
346 tailTransactions.has(tx.txId)
347 )
348 tailScheduling.push(`public-apply`)
349 if (
350 (id.kind === `managed` ? id.storageCollectionId : id.collectionId) ===
351 sourceStorageId &&
352 nested.has(tx.txId)
353 ) {
354 cycleCalls++
355 cycle.resolve()
356 }
357 return result
358 }
359 const errors: Array<string> = []
360 const receiptStates: Array<Receipt> = []
361 const receiptPromises: Array<Promise<void>> = []
362 let source!: Parameters<SyncConfig<Row, string>[`sync`]>[0]
363 const commit = (edit: () => void) => {
364 source.begin()
365 edit()
366 const index = receiptStates.push(`pending`) - 1
367 const receipt = Promise.resolve(source.commit()).then(
368 () => {
369 receiptStates[index] = `fulfilled`
370 },
371 (error: unknown) => {
372 receiptStates[index] = `rejected`
373 errors.push(String(error))
374 },
375 )
376 receiptPromises.push(receipt)
377 }
378 const sourceHistory = () => {
379 commit(() =>
380 source.write({ type: `insert`, value: { id: `r1`, value: 1 } }),
381 )
382 if (!rich) return
383 commit(() => source.metadata!.collection.set(`cursor`, 7))
384 commit(() => {
385 source.metadata!.collection.set(`cursor`, 8)
386 source.truncate()
387 source.write({ type: `insert`, value: { id: `r2`, value: 2 } })
388 source.metadata!.row.set(`r2`, { owner: `source` })
389 })
390 commit(() =>
391 source.write({ type: `update`, value: { id: `r2`, value: 3 } }),
392 )
393 commit(() =>
394 source.write({ type: `insert`, value: { id: `temporary`, value: 4 } }),
395 )
396 commit(() => source.write({ type: `delete`, key: `temporary` }))
397 }
398 let ordinarySource!: Parameters<SyncConfig<Row, string>[`sync`]>[0]
399 const c = createCollection(
400 persistedCollectionOptions<Row, string>({
401 id: `c`,
402 schemaVersion: 33,
403 persistence,
404 getKey: (row) => row.id,
405 sync: {
406 sync: (controls) => {
407 ordinarySource = controls
408 controls.markReady()
409 },
410 },
411 }),
412 )
413 cleanup.unshift(() => c.cleanup())
414 await c.preload()
415 holdRead = phase === `startup`
416 const a = createCollection(
417 persistedCollectionOptions<Row, string>({
418 id: `a`,
419 schemaVersion: 11,
420 persistence,
421 getKey: (row) => row.id,
422 startSync: true,
423 syncMode: phase === `subscription` ? `on-demand` : `eager`,
424 sync: {
425 sync: (controls) => {
426 source = controls
427 if (phase === `startup`) sourceHistory()
428 controls.markReady()
429 sourceStarted.resolve()
430 return { loadSubset: () => true }
431 },
432 },
433 }),
434 )
435 cleanup.unshift(() => a.cleanup())
436 a.onFirstReady(() => {
437 sourceReady.resolve()
438 if (phase === `after-ready`) sourceHistory()
439 })
440 await sourceStarted.promise
441 if (phase === `subscription`) {
442 await sourceReady.promise
443 holdRead = true
444 const subscription = a.subscribeChanges(() => {}, {
445 includeInitialState: true,
446 })
447 cleanup.unshift(() => subscription.unsubscribe())
448 }
449 if (phase !== `after-ready`) await readEntered.promise
450 else {
451 await sourceReady.promise
452 scopeExited.resolve()
453 }
454 if (scopePremiseError) throw scopePremiseError
455 if (phase === `subscription`) sourceHistory()
456 observeContenders = true
457 const b = createCollection(
458 persistedCollectionOptions<Row, string>({
459 id: `b`,
460 schemaVersion: 22,
461 persistence,
462 getKey: (row) => row.id,
463 startSync: true,
464 sync: { sync: ({ markReady }) => markReady() },
465 }),
466 )
467 cleanup.unshift(() => b.cleanup())
468 b.onFirstReady(peerReady.resolve)
469 ordinarySource.begin()
470 ordinarySource.write({
471 type: `insert`,
472 value: { id: `ordinary`, value: 33 },
473 })
474 let ordinaryReceipt: Receipt = `pending`
475 const ordinaryDone = Promise.resolve(ordinarySource.commit()).then(
476 () => {
477 ordinaryReceipt = `fulfilled`
478 },
479 (error: unknown) => {
480 ordinaryReceipt = `rejected`
481 errors.push(String(error))
482 },
483 )
484 // Both contenders have crossed their real scheduling API before the cut.
485 // No task tick or SQL latency is used as evidence of admission.
486 await Promise.all([
487 peerHydrationAdmission.promise,
488 ordinaryAdmission.promise,
489 ])
490 const held =
491 phase === `after-ready`
492 ? null
493 : {
494 receipts: [...receiptStates],
495 rows: publicRows(a),
496 ordinary: ordinaryReceipt,
497 interleavedSql: [...interleavedSql],
498 peerHydrationAdmitted,
499 ordinaryAdmitted,
500 }
501 releaseRead.resolve()
502 await Promise.race([
503 cycle.promise,
504 Promise.all([
505 sourceReady.promise,
506 ...receiptPromises,
507 peerReady.promise,
508 ordinaryDone,
509 scopeExited.promise,
510 ]),
511 ])
512 let durableRows: Array<Row> | null = null
513 let durableMetadata: Array<{ key: string; value: unknown }> | null = null
514 let durableRowMetadata: Array<{
515 key: string | number
516 metadata: unknown
517 }> | null = null
518 let peerRows: Array<Row> | null = null
519 let ordinaryRows: Array<Row> | null = null
520 let schemas: HydrationCommitObservation[`schemas`] = null
521 const reopenedRows: Array<Row> | null = null
522 if (cycleCalls === 0) {
523 // Truncate can trigger a follow-up subset hydrate. Join all public A
524 // invocations already requested by the source history before issuing an
525 // ordinary tail; the originally held callback alone is not quiescence.
526 while (pendingHydrations.size > 0) {
527 await Promise.all([...pendingHydrations])
528 }
529 // Record the tail at the coordinator's ordinary scheduling boundary. Rows
530 // alone cannot distinguish a cached, expired loan from ordinary routing.
531 tailStarted = true
532 commit(() =>
533 source.write({ type: `insert`, value: { id: `tail`, value: 9 } }),
534 )
535 await receiptPromises.at(-1)
536 tailStarted = false
537 const sourceClaimContext = sourceClaimId
538 ? { cacheGenerationClaimId: sourceClaimId }
539 : undefined
540 const sourceTarget = sourceClaimId
541 ? {
542 kind: `managed` as const,
543 storageCollectionId: sourceStorageId,
544 claimId: sourceClaimId,
545 }
546 : { kind: `eager` as const, collectionId: sourceStorageId }
547 const durable = await adapter.loadSubset(
548 sourceTarget,
549 {},
550 sourceClaimContext,
551 )
552 durableRows = durable
553 .map(({ value }) => value as Row)
554 .sort((x, y) => x.id.localeCompare(y.id))
555 durableRowMetadata = durable
556 .filter(({ metadata }) => metadata !== undefined)
557 .map(({ key, metadata }) => ({ key, metadata }))
558 durableMetadata = await adapter.loadCollectionMetadata!(
559 sourceTarget,
560 sourceClaimContext,
561 )
562 peerRows = (
563 await bAdapter.loadSubset({ kind: `eager`, collectionId: `b` }, {})
564 ).map(({ value }) => value as Row)
565 ordinaryRows = (
566 await cAdapter.loadSubset({ kind: `eager`, collectionId: `c` }, {})
567 ).map(({ value }) => value as Row)
568 schemas = [
569 ...(await database.execute<{
570 collection_id: string
571 schema_version: number
572 }>(
573 `SELECT collection_id, schema_version FROM collection_registry ORDER BY collection_id`,
574 )),
575 ]
576 }
577 captured = structuredClone({
578 phase,
579 baseline,
580 rich,
581 browserCoordinator,
582 sourceStorageId,
583 rowReads,
584 cycleCalls,
585 held,
586 receipts: receiptStates,
587 sourceStatus: a.status,
588 peerStatus: b.status,
589 ordinaryReceipt,
590 owningScopeExited,
591 tailScheduling,
592 peerWorkBeforeScopeExit,
593 ordinaryCommitSqlCalls,
594 rows: publicRows(a),
595 durableRows,
596 durableMetadata,
597 durableRowMetadata,
598 peerRows,
599 ordinaryRows,
600 schemas,
601 reopenedRows,
602 errors,
603 })
604 window.__hydrationCommitResult = captured
605 if (cycleCalls === 0) {
606 await a.cleanup()
607 if (phase === `subscription`) {
608 // A partial on-demand cache does not certify offline Collection
609 // restore. A fresh claim still proves the current physical rows were
610 // durably stored after the first sync run releases its claim.
611 const freshClaim = await adapter.claimCacheGeneration!(`a`)
612 try {
613 captured.reopenedRows = (
614 await adapter.loadSubset(
615 {
616 kind: `managed`,
617 storageCollectionId: freshClaim.storageCollectionId,
618 claimId: freshClaim.claimId,
619 },
620 {},
621 {
622 cacheGenerationClaimId: freshClaim.claimId,
623 },
624 )
625 )
626 .map(({ value }) => value as Row)
627 .sort((x, y) => x.id.localeCompare(y.id))
628 } finally {
629 await adapter.releaseCacheGenerationClaim!(freshClaim.claimId)
630 }
631 } else {
632 const reopened = createCollection(
633 persistedCollectionOptions<Row, string>({
634 id: `a`,
635 schemaVersion: 11,
636 persistence,
637 getKey: (row) => row.id,
638 syncMode: `eager`,
639 }),
640 )
641 cleanup.unshift(() => reopened.cleanup())
642 await reopened.preload()
643 captured.reopenedRows = publicRows(reopened)
644 }
645 window.__hydrationCommitResult = structuredClone(captured)
646 }
647 } catch (error) {
648 window.__hydrationCommitError = String(error)
649 } finally {
650 releaseRead.resolve()
651 // A real cycle prevents Collection teardown; closing the worker and the
652 // isolated Playwright page releases it. Other cleanup failures cannot
653 // replace the already-copied primary observation or skip database close.
654 if (params.get(`cleanupFault`) === `true`) {
655 cleanup.unshift(() => {
656 throw new Error(`injected first cleanup failure`)
657 })
658 cleanup.push(() => {
659 throw new Error(`injected last cleanup failure`)
660 })
661 }
662 for (const action of cleanup) {
663 if (cycleCalls > 0) break
664 try {
665 await action()
666 } catch (error) {
667 cleanupErrors.push(String(error))
668 }
669 }
670 try {
671 disposeCoordinator?.()
672 } catch (error) {
673 cleanupErrors.push(String(error))
674 }
675 try {
676 await database.close?.()
677 } catch (error) {
678 cleanupErrors.push(String(error))
679 }
680 window.__hydrationCommitCleanupErrors = cleanupErrors
681 window.__hydrationCommitDone = true
682 }
684void run().catch((error: unknown) => {
685 window.__hydrationCommitError = String(error)
686 window.__hydrationCommitDone = true
687})