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

shared-logical-scheduling.test.ts

386 lines12.4 KB

1/**
2 * # Which adapters share one logical scheduling boundary?
3 *
4 * Contract and source: the RFC #1659 driver protocol keys scheduling by the
5 * exact shared driver identity. Two fresh core adapters over that identity
6 * must not interleave a complete hydration scope with regular adapter work.
7 * Transparent wrappers must forward the identity unchanged, including when
8 * the identity itself is a function object.
9 *
10 * Independent relation and legal domain: a two-adapter history starts one
11 * hydration metadata query, holds it at the driver boundary, then requests one
12 * regular metadata query. Before release, exactly the first query may be
13 * admitted; after release, both operations must finish. The three legal driver
14 * forms are direct, transparently wrapped, and direct with a function-valued
15 * key. This relation records admissions without copying the production
16 * scheduler or invoking the opaque key. Promise-only discovery is a fourth
17 * form: the first operation reveals the shared identity and its complete
18 * hydration scope becomes the scheduler's already-running unit.
19 *
20 * Production boundary and checkpoint: both operations use
21 * `createSQLiteCorePersistenceAdapter`; the hydration operation enters through
22 * `runInHydrationScope`. The first checkpoint is immediately after the regular
23 * request enters the adapter, while the first query remains held. Losing
24 * wrapper identity or treating a function key as a getter synchronously admits
25 * the second query and fails the exact admission assertion.
26 *
27 * Known omissions: promise-only discovery coordinates adapters over the same
28 * wrapper identity. Distinct unbranded wrappers must forward the shared key
29 * before adapter construction. This focused contract test does not establish
30 * K=1 lane fairness, SQL result correctness, eventual progress under arbitrary
31 * I/O, or cross-process coordination. Those belong to the shared-driver oracle
32 * and provider refinements.
33 */
34import { describe, expect, it } from 'vitest'
35import fc from 'fast-check'
36import {
37 SQLITE_DRIVER_SHARED_LOGICAL_SCHEDULING_KEY,
38 createSQLiteCorePersistenceAdapter,
39 forwardSQLiteDriverSharedLogicalScheduling,
40} from '../src'
41import type { SQLiteDriver } from '../src'
42​
43type Deferred = {
44 promise: Promise<void>
45 resolve: () => void
47​
48function createDeferred(): Deferred {
49 let resolve!: () => void
50 const promise = new Promise<void>((settle) => {
51 resolve = settle
52 })
53 return { promise, resolve }
55​
56function fixtureQueryRows<T>(sql: string): ReadonlyArray<T> {
57 if (sql.includes(`FROM collection_registry`)) {
58 return [
59 {
60 table_name: `c_fixture`,
61 tombstone_table_name: `t_fixture`,
62 schema_version: 1,
63 } as T,
64 ]
65 }
66 return []
68​
69function isMetadataQuery(sql: string): boolean {
70 return sql.includes(`FROM collection_metadata`)
72​
73class FirstQueryGatedDriver implements SQLiteDriver {
74 readonly [SQLITE_DRIVER_SHARED_LOGICAL_SCHEDULING_KEY]: object
75 readonly admissions: Array<string> = []
76 readonly metadataAdmissions: Array<string> = []
77 readonly firstQueryEntered = createDeferred()
78 firstQueryAdmissionCount = 0
79 onQuery: (() => void) | undefined
80 private readonly firstQueryGate = createDeferred()
81 private holdFirstQuery = true
82​
83 constructor(sharedLogicalSchedulingKey: object = {}) {
84 this[SQLITE_DRIVER_SHARED_LOGICAL_SCHEDULING_KEY] =
85 sharedLogicalSchedulingKey
86 }
87​
88 exec(): Promise<void> {
89 this.admissions.push(`exec`)
90 return Promise.resolve()
91 }
92​
93 async query<T>(sql: string): Promise<ReadonlyArray<T>> {
94 this.admissions.push(`query`)
95 if (isMetadataQuery(sql)) {
96 this.metadataAdmissions.push(`query`)
97 this.onQuery?.()
98 }
99 if (this.holdFirstQuery && isMetadataQuery(sql)) {
100 this.holdFirstQuery = false
101 this.firstQueryAdmissionCount = this.admissions.length
102 this.firstQueryEntered.resolve()
103 await this.firstQueryGate.promise
104 }
105 return fixtureQueryRows<T>(sql)
106 }
107​
108 run(): Promise<void> {
109 this.admissions.push(`run`)
110 return Promise.resolve()
111 }
112​
113 transaction<T>(
114 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
115 ): Promise<T> {
116 this.admissions.push(`transaction`)
117 return fn(this)
118 }
119​
120 releaseFirstQuery(): void {
121 this.firstQueryGate.resolve()
122 }
124​
125class PromiseBrandedFirstQueryGatedDriver implements SQLiteDriver {
126 readonly admissions: Array<string> = []
127 readonly metadataAdmissions: Array<string> = []
128 readonly firstQueryEntered = createDeferred()
129 firstQueryAdmissionCount = 0
130 private readonly firstQueryGate = createDeferred()
131 private holdFirstQuery = true
132​
133 constructor(private readonly schedulingKey: object = {}) {}
134​
135 exec(): Promise<void> {
136 this.admissions.push(`exec`)
137 return this.brand(Promise.resolve())
138 }
139​
140 query<T>(sql: string): Promise<ReadonlyArray<T>> {
141 this.admissions.push(`query`)
142 if (isMetadataQuery(sql)) this.metadataAdmissions.push(`query`)
143 const result = (async () => {
144 if (this.holdFirstQuery && isMetadataQuery(sql)) {
145 this.holdFirstQuery = false
146 this.firstQueryAdmissionCount = this.admissions.length
147 this.firstQueryEntered.resolve()
148 await this.firstQueryGate.promise
149 }
150 return fixtureQueryRows<T>(sql)
151 })()
152 return this.brand(result)
153 }
154​
155 run(): Promise<void> {
156 this.admissions.push(`run`)
157 return this.brand(Promise.resolve())
158 }
159​
160 transaction<T>(
161 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
162 ): Promise<T> {
163 this.admissions.push(`transaction`)
164 return this.brand(fn(this))
165 }
166​
167 releaseFirstQuery(): void {
168 this.firstQueryGate.resolve()
169 }
170​
171 private brand<T>(promise: Promise<T>): Promise<T> {
172 Object.defineProperty(
173 promise,
174 SQLITE_DRIVER_SHARED_LOGICAL_SCHEDULING_KEY,
175 { value: this.schedulingKey },
176 )
177 return promise
178 }
180​
181class UnbrandedPromiseLookupDriver implements SQLiteDriver {
182 schedulingKeyLookups = 0
183​
184 exec(): Promise<void> {
185 return this.unbranded(Promise.resolve())
186 }
187​
188 query<T>(sql: string): Promise<ReadonlyArray<T>> {
189 return this.unbranded(Promise.resolve(fixtureQueryRows<T>(sql)))
190 }
191​
192 run(): Promise<void> {
193 return this.unbranded(Promise.resolve())
194 }
195​
196 transaction<T>(
197 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
198 ): Promise<T> {
199 return this.unbranded(fn(this))
200 }
201​
202 private unbranded<T>(promise: Promise<T>): Promise<T> {
203 Object.defineProperty(
204 promise,
205 SQLITE_DRIVER_SHARED_LOGICAL_SCHEDULING_KEY,
206 {
207 configurable: true,
208 get: () => {
209 this.schedulingKeyLookups++
210 return undefined
211 },
212 },
213 )
214 return promise
215 }
217​
218function createTransparentWrapper(driver: SQLiteDriver): SQLiteDriver {
219 return forwardSQLiteDriverSharedLogicalScheduling(driver, {
220 exec: (sql) => driver.exec(sql),
221 query: <T>(sql: string, params: ReadonlyArray<unknown> = []) =>
222 driver.query<T>(sql, params),
223 run: (sql, params = []) => driver.run(sql, params),
224 transaction: <T>(fn: (transactionDriver: SQLiteDriver) => Promise<T>) =>
225 driver.transaction(fn),
226 transactionWithDriver: <T>(
227 fn: (transactionDriver: SQLiteDriver) => Promise<T>,
228 ) =>
229 driver.transactionWithDriver
230 ? driver.transactionWithDriver(fn)
231 : driver.transaction(fn),
232 })
234​
235describe(`shared logical scheduling`, () => {
236 it.each([
237 {
238 name: `direct driver`,
239 key: {},
240 wrap: (driver: SQLiteDriver) => driver,
241 },
242 {
243 name: `transparent delegating driver`,
244 key: {},
245 wrap: createTransparentWrapper,
246 },
247 {
248 name: `twice-transparent delegating driver`,
249 key: {},
250 wrap: (driver: SQLiteDriver) =>
251 createTransparentWrapper(createTransparentWrapper(driver)),
252 },
253 {
254 name: `function-valued key`,
255 key: () => undefined,
256 wrap: (driver: SQLiteDriver) => driver,
257 },
258 ])(
259 `shares a scheduler across two fresh adapters through a $name`,
260 async ({ key, wrap }) => {
261 const underlying = new FirstQueryGatedDriver(key)
262 const driver = wrap(underlying)
263 const hydrateAdapter = createSQLiteCorePersistenceAdapter({ driver })
264 const regularAdapter = createSQLiteCorePersistenceAdapter({ driver })
265​
266 const hydrate = hydrateAdapter.runInHydrationScope!(async (scoped) => {
267 await scoped.loadCollectionMetadata!(`hydrate`)
268 })
269 await underlying.firstQueryEntered.promise
270​
271 const regular = regularAdapter.loadCollectionMetadata!(`regular`)
272​
273 expect(underlying.admissions).toHaveLength(
274 underlying.firstQueryAdmissionCount,
275 )
276​
277 underlying.releaseFirstQuery()
278 await Promise.all([hydrate, regular])
279 expect(underlying.metadataAdmissions).toEqual([`query`, `query`])
280 },
281 )
282​
283 it(`adopts a late-discovered promise identity before admitting peer work`, async () => {
284 const driver = new PromiseBrandedFirstQueryGatedDriver()
285 const hydrateAdapter = createSQLiteCorePersistenceAdapter({ driver })
286 const regularAdapter = createSQLiteCorePersistenceAdapter({ driver })
287​
288 const hydrate = hydrateAdapter.runInHydrationScope!(async (scoped) => {
289 await scoped.loadCollectionMetadata!(`hydrate`)
290 })
291 await driver.firstQueryEntered.promise
292​
293 const regular = regularAdapter.loadCollectionMetadata!(`regular`)
294​
295 expect(driver.admissions).toHaveLength(driver.firstQueryAdmissionCount)
296​
297 driver.releaseFirstQuery()
298 await Promise.all([hydrate, regular])
299 expect(driver.metadataAdmissions).toEqual([`query`, `query`])
300 })
301​
302 it(`keeps generated promise-discovered hydrate units non-preemptible`, async () => {
303 await fc.assert(
304 fc.asyncProperty(
305 fc.record({
306 hydrateQueries: fc.integer({ min: 1, max: 4 }),
307 peerQueries: fc.integer({ min: 1, max: 3 }),
308 }),
309 async ({ hydrateQueries, peerQueries }) => {
310 const driver = new PromiseBrandedFirstQueryGatedDriver()
311 const hydrateAdapter = createSQLiteCorePersistenceAdapter({ driver })
312 const peerAdapters = Array.from({ length: peerQueries }, () =>
313 createSQLiteCorePersistenceAdapter({ driver }),
314 )
315​
316 const hydrate = hydrateAdapter.runInHydrationScope!(
317 async (scoped) => {
318 for (let index = 0; index < hydrateQueries; index++) {
319 await scoped.loadCollectionMetadata!(`hydrate-${index}`)
320 }
321 },
322 )
323 await driver.firstQueryEntered.promise
324​
325 const peers = peerAdapters.map((adapter, index) =>
326 adapter.loadCollectionMetadata!(`peer-${index}`),
327 )
328 expect(driver.admissions).toHaveLength(
329 driver.firstQueryAdmissionCount,
330 )
331​
332 driver.releaseFirstQuery()
333 await Promise.all([hydrate, ...peers])
334 expect(driver.metadataAdmissions).toEqual(
335 Array.from({ length: hydrateQueries + peerQueries }, () => `query`),
336 )
337 },
338 ),
339 { seed: 1868, numRuns: 12, endOnFailure: true },
340 )
341 })
342​
343 it(`counts a rejected hydrate as a completed K=1 lane unit`, async () => {
344 const driver = new FirstQueryGatedDriver()
345 const hydrateAdapter = createSQLiteCorePersistenceAdapter({ driver })
346 const regularAdapter = createSQLiteCorePersistenceAdapter({ driver })
347 const events: Array<string> = []
348​
349 const initialRegular = regularAdapter.loadCollectionMetadata!(`initial`)
350 await driver.firstQueryEntered.promise
351 driver.onQuery = () => events.push(`query`)
352​
353 const failedHydrate = hydrateAdapter.runInHydrationScope!(() => {
354 events.push(`failed-hydrate`)
355 throw new Error(`expected hydrate failure`)
356 })
357 const failedHydrateExpectation = expect(failedHydrate).rejects.toThrow(
358 `expected hydrate failure`,
359 )
360 const regular = regularAdapter.loadCollectionMetadata!(`regular`)
361 const nextHydrate = hydrateAdapter.runInHydrationScope!(async (scoped) => {
362 events.push(`next-hydrate`)
363 await scoped.loadCollectionMetadata!(`hydrate`)
364 })
365​
366 driver.releaseFirstQuery()
367 await Promise.all([
368 initialRegular,
369 failedHydrateExpectation,
370 regular,
371 nextHydrate,
372 ])
373​
374 expect(events).toEqual([`failed-hydrate`, `query`, `next-hydrate`, `query`])
375 })
376​
377 it(`stops probing after the first returned promise lacks scheduling support`, async () => {
378 const driver = new UnbrandedPromiseLookupDriver()
379 const adapter = createSQLiteCorePersistenceAdapter({ driver })
380​
381 await adapter.loadCollectionMetadata!(`first`)
382 await adapter.loadCollectionMetadata!(`second`)
383​
384 expect(driver.schedulingKeyLookups).toBe(1)
385 })
386})