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

opfs-request-order-oracle.ts

235 lines8.7 KB

1import { declareOracle } from '../../db/tests/oracle-declaration.js'
2/**
3 * # Does an OPFS connection answer requests in order and close after them?
4 *
5 * An OPFS connection owns one SQLite connection in its worker. Requests settle
6 * in the order the connection accepted them, each with the result a
7 * sequential connection would produce. Close is one more request in that
8 * order: it settles after every earlier request, and requests made after close
9 * starts are refused at once. Answered writes survive a reopen. This holds
10 * when an earlier request waits for the OPFS access handle.
11 *
12 * That wait is the worker's only task-level suspension point. OPFSCoopSyncVFS
13 * hands its access handle to another connection on request. Its next lock then
14 * queues a Web Lock and handle acquisition on wa-sqlite's `retryOps` and
15 * returns SQLITE_BUSY, and wa-sqlite's `retry()` awaits that work. A worker
16 * that handles messages during the wait lets close run while the statement is
17 * unfinalized. SQLite then refuses to close, and close settles first.
18 *
19 * The model is a sequential replay over the list of inserted values. A history
20 * chooses one to three inserts and selects, which execute meets a taken
21 * handle, whether the handle returns before or after close is submitted, and
22 * one execute after close. Where the handle wait starts and when it ends are
23 * driver choices: the model's prediction does not depend on them.
24 *
25 * Two drivers run the same examples through the public connection and the real
26 * worker module. The Node driver uses the real wa-sqlite WASM build over an
27 * in-memory VFS with OPFSCoopSyncVFS's lock protocol. The Chromium driver uses
28 * real OPFS and takes the handle through the VFS's own BroadcastChannel and
29 * Web Lock handoff. Both compare settlement values, settlement order, and the
30 * rows a fresh connection reads after close.
31 *
32 * Neither driver proves other browsers, frozen tabs, a crash between a write
33 * and close, or contention among more than one other handle holder.
34 */
35import type { BrowserWASQLiteDatabase } from '../src/wa-sqlite-driver'
36​
37export type ExecuteKind = `insert` | `select`
38​
39export type RequestOrderHistory = {
40 executes: Array<ExecuteKind>
41 handleTakenBefore: number | undefined
42 handleReturns: `before-close` | `after-close`
43 executeAfterClose: boolean
45​
46export type RequestSettlement =
47 | { label: string; status: `fulfilled`; value: unknown }
48 | { label: string; status: `rejected`; name: string; message: string }
49​
50export type RequestOrderObservation = {
51 handleWaitReached: boolean
52 settlements: Array<RequestSettlement>
53 reopenedRows: unknown
55​
56// How a driver takes the access handle from the connection under test, waits
57// until a request is blocked on it, lets a submitted message reach the worker,
58// and gives the handle back.
59export type AccessHandleControl = {
60 take: () => Promise<void>
61 untilWaiting: () => Promise<boolean>
62 untilDelivered: () => Promise<void>
63 give: () => Promise<void>
65​
66export type OpenDatabase = (
67 databaseName: string,
68) => Promise<BrowserWASQLiteDatabase>
69​
70const closedConnection = {
71 name: `SQLiteConnectionClosedError`,
72 message: `Browser OPFS worker connection is closed`,
74​
75function sqlFor(kind: ExecuteKind, index: number): string {
76 return kind === `insert`
77 ? `INSERT INTO t VALUES (${index})`
78 : `SELECT x FROM t ORDER BY x`
80​
81// Sequential reference: replay the history over a list of inserted values.
82export function expectedRequestOrder(history: RequestOrderHistory): {
83 settlements: Array<RequestSettlement>
84 reopenedRows: Array<{ x: number }>
85} {
86 const values: Array<number> = []
87 const settlements: Array<RequestSettlement> = history.executes.map(
88 (kind, index): RequestSettlement => {
89 if (kind === `insert`) {
90 values.push(index)
91 return { label: `execute-${index}`, status: `fulfilled`, value: [] }
92 }
93 return {
94 label: `execute-${index}`,
95 status: `fulfilled`,
96 value: values.map((x) => ({ x })),
97 }
98 },
99 )
100 settlements.push({ label: `close`, status: `fulfilled`, value: undefined })
101 if (history.executeAfterClose) {
102 settlements.push({
103 label: `execute-after-close`,
104 status: `rejected`,
105 ...closedConnection,
106 })
107 }
108 return { settlements, reopenedRows: values.map((x) => ({ x })) }
110​
111// The refinement check. Values compare as a set keyed by label; order compares
112// the accepted requests, which must settle in submission order with close
113// last. A refused request settles before close because admission rejects it
114// at once.
115export function findRequestOrderViolation(
116 history: RequestOrderHistory,
117 observation: RequestOrderObservation,
118): string | undefined {
119 if (history.handleTakenBefore !== undefined && !observation.handleWaitReached)
120 return `premise not reached: no request waited for the access handle`
121 const expected = expectedRequestOrder(history)
122 const byLabel = (settlements: ReadonlyArray<RequestSettlement>) =>
123 JSON.stringify(
124 [...settlements].sort((a, b) => a.label.localeCompare(b.label)),
125 )
126 if (byLabel(observation.settlements) !== byLabel(expected.settlements)) {
127 return `settlements differ: expected ${byLabel(expected.settlements)}, got ${byLabel(observation.settlements)}`
128 }
129 const order = observation.settlements.map(({ label }) => label)
130 const accepted = order.filter((label) => label !== `execute-after-close`)
131 const expectedAccepted = [
132 ...history.executes.map((_, index) => `execute-${index}`),
133 `close`,
134 ]
135 if (JSON.stringify(accepted) !== JSON.stringify(expectedAccepted)) {
136 return `accepted requests settled as ${accepted.join(`,`)}, expected ${expectedAccepted.join(`,`)}`
137 }
138 if (
139 history.executeAfterClose &&
140 order.indexOf(`execute-after-close`) > order.indexOf(`close`)
141 ) {
142 return `the refused request settled after close`
143 }
144 if (
145 JSON.stringify(observation.reopenedRows) !==
146 JSON.stringify(expected.reopenedRows)
147 ) {
148 return `reopened rows ${JSON.stringify(observation.reopenedRows)}, expected ${JSON.stringify(expected.reopenedRows)}`
149 }
150 return undefined
152​
153function errorFields(error: unknown): { name: string; message: string } {
154 return error instanceof Error
155 ? { name: error.name, message: error.message }
156 : { name: `NonError`, message: String(error) }
158​
159// The shared production driver: public open, execute, and close, with the
160// access handle taken and returned at the history's points.
161export async function observeRequestOrder(
162 open: OpenDatabase,
163 handle: AccessHandleControl,
164 history: RequestOrderHistory,
165 databaseName: string,
166): Promise<RequestOrderObservation> {
167 const database = await open(databaseName)
168 await database.execute(`CREATE TABLE t(x INTEGER)`)
169​
170 const settlements: Array<RequestSettlement> = []
171 const pending: Array<Promise<void>> = []
172 const track = (label: string, promise: Promise<unknown>) => {
173 pending.push(
174 promise.then(
175 (value) => {
176 settlements.push({ label, status: `fulfilled`, value })
177 },
178 (error: unknown) => {
179 settlements.push({ label, status: `rejected`, ...errorFields(error) })
180 },
181 ),
182 )
183 }
184​
185 for (const [index, kind] of history.executes.entries()) {
186 if (index === history.handleTakenBefore) await handle.take()
187 track(`execute-${index}`, database.execute(sqlFor(kind, index)))
188 }
189 const handleWaitReached =
190 history.handleTakenBefore === undefined || (await handle.untilWaiting())
191 if (history.handleReturns === `before-close`) await handle.give()
192 track(`close`, Promise.resolve(database.close!()))
193 if (history.executeAfterClose) {
194 track(`execute-after-close`, database.execute(`SELECT 1`))
195 }
196 if (history.handleReturns === `after-close`) {
197 // Close must reach the worker while the earlier request still waits.
198 await handle.untilDelivered()
199 await handle.give()
200 }
201 await Promise.all(pending)
202​
203 const reopened = await open(databaseName)
204 try {
205 return {
206 handleWaitReached,
207 settlements,
208 reopenedRows: await reopened.execute(`SELECT x FROM t ORDER BY x`),
209 }
210 } finally {
211 await reopened.close!()
212 }
214​
215// Every handle placement over one- and two-execute shapes, both return points,
216// and with or without a refused request.
217export const requestOrderExamples: Array<RequestOrderHistory> = (
218 [[`insert`], [`insert`, `select`], [`select`, `insert`]] as const
219).flatMap((executes) =>
220 [undefined, ...executes.keys()].flatMap((handleTakenBefore) =>
221 ([`before-close`, `after-close`] as const).flatMap((handleReturns) =>
222 [false, true].map((executeAfterClose): RequestOrderHistory => ({
223 executes: [...executes],
224 handleTakenBefore,
225 handleReturns,
226 executeAfterClose,
227 })),
228 ),
229 ),
231​
232declareOracle({
233 check: [findRequestOrderViolation],
234 model: [expectedRequestOrder],
235})