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

multi-tab-electric-oracle.test.ts

1,462 lines57.0 KB

1// @vitest-environment node
2/**
3 * # Do Electric tabs that share one persisted database agree with the server?
4 *
5 * Several Browser tabs open the same persisted Electric Collection. Each tab
6 * runs its own Electric stream, and all of them store through one SQLite
7 * database and one elected leader. Tabs coordinate only through durable
8 * commits and the notices those commits broadcast. This file is the Browser
9 * host owner for three laws about that arrangement.
10 *
11 * Law 1, reserved commits survive a refetch storm. Authority:
12 * SyncPersistenceCapabilityV1 `reserveCommitTurn` (packages/db/src/types.ts),
13 * widened by maintainer decision on issue #2226 to every persisted
14 * hydration. Electric reserves every stream transaction. After a deploy, each
15 * tab's stream sends must-refetch; the tab commits a reset resume marker at
16 * once, then holds a reserved refetch transaction open until up-to-date. A
17 * peer's marker or refetch commit reaches the other tabs while their
18 * refetches are open. The law: every tab's refetch commits, no Collection
19 * enters `error`, and once every stream has delivered the new snapshot every
20 * tab shows it. The controlled-history owner for the same law is the
21 * persisted-reads grammar in
22 * packages/db-sqlite-persistence-core/tests/persisted-oracle.test.ts; this
23 * file is its receiving witness on the real Browser coordinator.
24 *
25 * Law 2, an open tab converges to the server head. Authority: the coverage
26 * map's eventual-consistency note for persisted multi-tab Collections
27 * (docs/contributing/oracle-coverage.md, issue #2209): a lagging tab may
28 * briefly store an older transaction, and every tab converges once the
29 * streams catch up. The generated histories below judge it: after every
30 * open tab catches up, the durable rows and every open tab show the server
31 * head, however earlier lagging commits left them. When a lagging tab
32 * commits an older row and then closes for good, nothing redelivers the head
33 * to the faster tab, so this law fails today. That history is pinned with
34 * `it.fails` until #2209 orders source writes by server position; generated
35 * histories never close a tab for good.
36 *
37 * Model: the server is a log of snapshots. A history names which snapshot
38 * each tab's stream has delivered; the expected public rows of a tab whose
39 * stream reached the head are the head snapshot. This file states no
40 * contract for which stream rows an on-demand Collection without subset
41 * demand exposes, so on-demand histories judge only commit acceptance and
42 * Collection status (a partial oracle). The model reads nothing from the
43 * coordinator, adapter, or Collection.
44 *
45 * Driver: each tab is a better-sqlite3 connection to one shared file, a
46 * `BrowserCollectionCoordinator` (BroadcastChannel and Web Locks in Node), and
47 * `createBrowserWASQLitePersistence`. A recording `ShapeStream` stands in for
48 * the Electric SDK; the test plays the server and delivers each tab's
49 * messages. Checkpoints wait for host quiescence: no SQL statement and no
50 * coordinator message for several tasks. Observations are each tab's
51 * Collection status and public rows, and the position from which a
52 * recovered tab's new stream starts.
53 *
54 * Law 3, a Collection whose source failed keeps showing durable rows.
55 * Authority: maintainer decision on PR #2265. A persisted Collection whose
56 * source failed still applies its peers' durable commits, so its public rows
57 * match the durable rows. A failure before the first load completes puts it
58 * in `error`; a later one leaves it `ready` with an error on its health node
59 * (#2168: after readiness, sync failures never change Collection status).
60 * This file judges it after resume invalidation, after a failed initial
61 * sync, and after a reset abandoned the source's transaction; the source
62 * must end its reserved transaction for the peers' commits to apply.
63 *
64 * Law 4, a Collection status changes only through its own source. Authority:
65 * maintainer decision on PR #2265. A peer's durable commit reloads a tab's
66 * rows but never moves its status: a tab whose own stream has not reached
67 * up-to-date stays `loading`, and a tab whose initial sync failed stays in
68 * `error` until it restarts.
69 *
70 * Law 5, a peer reset abandons an older reservation, and Electric fails
71 * loudly. Authority: maintainer decisions on PR #2265. A peer
72 * `collection:reset` abandons every reserved transaction that began before
73 * it. Electric still holds that transaction, so its next commit rejects and
74 * the source fails: a ready Collection keeps `ready` with an error on its
75 * health node, one that is still loading goes to `error`. The app recovers by
76 * restarting the tab.
77 * No shipped host sends `collection:reset` yet, so the histories post it on
78 * the tabs' coordinator channel as a peer would (a controlled premise).
79 *
80 * The generated histories below judge Laws 1, 3, 4, and 5 over interleaved
81 * server changes, deploys, deliveries, stops, and recoveries, against a
82 * model of the durable rows. One known gap is left out of them and pinned:
83 * a resumed tab that lags behind a peer can receive an update for a row the
84 * peer already deleted, and Electric's resume check then puts it in `error`.
85 *
86 * Electric's own cleanup abandon is redundant behind the persisted wrapper,
87 * which ends its transactions on cleanup, so that mutant survives here; the
88 * Electric descriptor-isolation oracle judges it without persistence.
89 *
90 * Limits: the stream is controlled, not the installed SDK over HTTP; one
91 * process hosts every tab; one Collection; no subset demand in on-demand
92 * Collections; no optimistic mutations; work amplification across tabs is
93 * not judged.
94 */
95import { mkdtempSync, rmSync } from 'node:fs'
96import { tmpdir } from 'node:os'
97import { join } from 'node:path'
98import { afterEach, describe, expect, it, vi } from 'vitest'
99import { fc } from '@fast-check/vitest'
100import { createCollection } from '@tanstack/db'
101import { createOracleReach } from '../../db/tests/oracle-reach.js'
102import { declareOracle } from '../../db/tests/oracle-declaration'
103import {
104 oraclePropertyOptions,
105 oracleReplayRequested,
106 oracleRuns,
107} from '../../db/tests/oracle-config'
108import { persistedCollectionOptions } from '../../db-sqlite-persistence-core/src'
109import { electricCollectionOptions } from '../../electric-db-collection/src/electric'
110import { BrowserCollectionCoordinator } from '../src/browser-coordinator'
111import { createBrowserWASQLitePersistence } from '../src/browser-persistence'
112import { createWASQLiteTestDatabase } from './helpers/wa-sqlite-test-db'
113import type {
114 Message,
115 Row,
116} from '../../electric-db-collection/node_modules/@electric-sql/client'
117import type { ElectricCollectionUtils } from '../../electric-db-collection/src/electric'
118​
119type Item = Row & { id: number; label: string }
120​
121// ---------------------------------------------------------------------------
122// Controlled Electric SDK boundary. Each stream records the position Electric
123// started it at and exposes the subscriber, so the test can play the server.
124// ---------------------------------------------------------------------------
125​
126type ControlledStream = {
127 tab: string
128 // The position Electric asked the server to start from.
129 startedAt: { handle: string | undefined; offset: string }
130 shapeHandle: string | undefined
131 lastOffset: string
132 // Set when Electric releases the stream; a stopped stream gets no messages.
133 stopped: boolean
134 send: (messages: Array<Message<Item>>) => void
135 // Electric's stream-error handler, which the test calls to fail the stream.
136 onError: (error: unknown) => unknown
137 // The subscriber's error callback, which the SDK calls when it stops
138 // retrying.
139 giveUp: (error: unknown) => void
141​
142const streams: Array<ControlledStream> = []
143​
144vi.mock(
145 `../../electric-db-collection/node_modules/@electric-sql/client`,
146 async (importOriginal) => {
147 const actual = await importOriginal<Record<string, unknown>>()
148 return {
149 ...actual,
150 ShapeStream: vi.fn(
151 (options: {
152 headers?: Record<string, string>
153 offset?: string
154 handle?: string
155 onError?: (error: unknown) => unknown
156 }) => {
157 const stream: ControlledStream = {
158 tab: options.headers?.[`x-tab`] ?? `unknown`,
159 startedAt: {
160 handle: options.handle,
161 offset: options.offset ?? `-1`,
162 },
163 stopped: false,
164 shapeHandle: options.handle,
165 lastOffset: options.offset ?? `-1`,
166 send: () => {
167 throw new Error(`stream for tab ${stream.tab} is not subscribed`)
168 },
169 onError: (error) => options.onError?.(error),
170 giveUp: () => {
171 throw new Error(`stream for tab ${stream.tab} is not subscribed`)
172 },
173 }
174 streams.push(stream)
175 return {
176 subscribe: (
177 send: ControlledStream[`send`],
178 giveUp: ControlledStream[`giveUp`],
179 ) => {
180 stream.send = send
181 stream.giveUp = giveUp
182 return () => undefined
183 },
184 unsubscribeAll: () => {
185 stream.stopped = true
186 },
187 requestSnapshot: vi.fn().mockResolvedValue(undefined),
188 fetchSnapshot: vi
189 .fn()
190 .mockResolvedValue({ metadata: {}, data: [] }),
191 forceDisconnectAndRefresh: vi.fn().mockResolvedValue(undefined),
192 isUpToDate: false,
193 get shapeHandle() {
194 return stream.shapeHandle
195 },
196 get lastOffset() {
197 return stream.lastOffset
198 },
199 }
200 },
201 ),
202 }
203 },
205​
206const upToDate: Message<Item> = { headers: { control: `up-to-date` } }
207const mustRefetch: Message<Item> = { headers: { control: `must-refetch` } }
208const insert = (row: Item): Message<Item> => ({
209 key: String(row.id),
210 value: row,
211 headers: { operation: `insert` },
212})
213const update = (row: Item): Message<Item> => ({
214 key: String(row.id),
215 value: row,
216 headers: { operation: `update` },
217})
218​
219const nextTask = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
220​
221// ---------------------------------------------------------------------------
222// Browser host: one database file, one coordinator and persistence per tab.
223// ---------------------------------------------------------------------------
224​
225type SyncMode = `eager` | `on-demand`
226type StreamStop =
227 | `error without retry`
228 | `SDK gives up`
229 | `signal aborted`
230 | `cleanup`
231 | `resume invalidated`
232​
233function openHost() {
234 const directory = mkdtempSync(join(tmpdir(), `tsdb-multi-tab-`))
235 const filename = join(directory, `shared.sqlite`)
236 const dbName = `multi-tab-${Math.random()}`
237 const closers: Array<() => Promise<void>> = []
238 let observer: ReturnType<typeof createWASQLiteTestDatabase> | undefined
239 // Host activity for the quiescence checkpoint, and the number of commit
240 // notices, read from the coordinator's own channel.
241 let activity = 0
242 let commitNotices = 0
243 let storageCollectionId: string | undefined
244 let resetEpoch = 0
245 const channel = new BroadcastChannel(`tsdb:coord:${dbName}`)
246 channel.onmessage = (event: MessageEvent) => {
247 activity++
248 const envelope = event.data as {
249 senderId?: string
250 collectionId?: string
251 payload?: { type?: string }
252 }
253 if (envelope.payload?.type === `tx:committed` && envelope.senderId) {
254 commitNotices++
255 storageCollectionId ??= envelope.collectionId
256 }
257 }
258​
259 const openTab = (tab: string, syncMode: SyncMode) => {
260 const database = createWASQLiteTestDatabase({ filename, timeout: 0 })
261 const execute = database.execute.bind(database)
262 database.execute = async <TRow>(
263 sql: string,
264 params: ReadonlyArray<unknown> = [],
265 ) => {
266 activity++
267 for (;;) {
268 try {
269 return await execute<TRow>(sql, params)
270 } catch (error) {
271 if ((error as { code?: string }).code !== `SQLITE_BUSY`) throw error
272 await nextTask()
273 }
274 }
275 }
276 const coordinator = new BrowserCollectionCoordinator({ dbName })
277 // The application's signal, which can stop the stream from outside.
278 let external = new AbortController()
279 const shapeOptions = {
280 url: `http://electric.test/v1/shape`,
281 params: { table: `items` },
282 headers: { 'x-tab': tab },
283 signal: external.signal,
284 }
285 const collection = createCollection(
286 persistedCollectionOptions<
287 Item,
288 string | number,
289 never,
290 ElectricCollectionUtils<Item>
291 >({
292 ...electricCollectionOptions<Item>({
293 id: `items`,
294 shapeOptions,
295 syncMode,
296 getKey: (row) => row.id,
297 startSync: true,
298 }),
299 persistence: createBrowserWASQLitePersistence({
300 database,
301 coordinator,
302 schemaMismatchPolicy: `reset`,
303 }),
304 }),
305 )
306 let open = true
307 const close = async () => {
308 if (!open) return
309 open = false
310 await collection.cleanup().catch(() => undefined)
311 coordinator.dispose()
312 await database.close?.()
313 }
314 closers.push(close)
315 const stream = () => {
316 const own = streams.filter((candidate) => candidate.tab === tab)
317 const latest = own[own.length - 1]
318 if (!latest) throw new Error(`tab ${tab} has no stream`)
319 return latest
320 }
321 return {
322 tab,
323 collection,
324 close,
325 hasStream: () => streams.some((candidate) => candidate.tab === tab),
326 streamCount: () =>
327 streams.filter((candidate) => candidate.tab === tab).length,
328 startedAt: () => stream().startedAt,
329 deliver: (
330 messages: Array<Message<Item>>,
331 position: { handle: string; offset: string },
332 ) => {
333 const current = stream()
334 if (current.stopped) {
335 throw new Error(`tab ${tab} delivered to a stopped stream`)
336 }
337 current.shapeHandle = position.handle
338 current.lastOffset = position.offset
339 current.send(messages)
340 },
341 // Each way a source stops for good: an error that `onError` does not
342 // retry, the SDK giving up its own retries, the application's signal
343 // aborting the stream, the application cleaning up the Collection, or
344 // a resumed stream sending an update for a row it never sent, which
345 // invalidates the persisted resume position.
346 stopStream: (how: StreamStop) => {
347 const error = new Error(`stream failed`)
348 if (how === `error without retry`) return stream().onError(error)
349 if (how === `SDK gives up`) return stream().giveUp(error)
350 if (how === `signal aborted`) return external.abort()
351 if (how === `cleanup`) return collection.cleanup()
352 const current = stream()
353 return current.send([update({ id: 99, label: `never sent` })])
354 },
355 // The application's recovery: clean up and start the Collection again.
356 // A signal that already aborted would stop the new stream too, so the
357 // restarted session gets a fresh signal.
358 restart: async () => {
359 await collection.cleanup()
360 external = new AbortController()
361 shapeOptions.signal = external.signal
362 void collection.preload().catch(() => undefined)
363 },
364 publicRows: () =>
365 Array.from(collection.values(), ({ id, label }) => ({
366 id,
367 label,
368 })).sort((left, right) => left.id - right.id),
369 }
370 }
371​
372 // The hosts are quiet when five 2 ms tasks pass with no SQL statement and
373 // no coordinator message, within 400 tasks; the bound turns a livelock into
374 // a named failure. Quiet is evidence, not proof, that every notice and
375 // hydration finished, because the public API exposes no completion signal
376 // for peer notices. Its premises are calibrated instead: declared reach
377 // shows the peer commit arrived, and the abandon and readiness mutants fail
378 // only when a hydration ran after that commit.
379 const quiesce = async (label: string) => {
380 let quietTasks = 0
381 for (let task = 0; task < 400 && quietTasks < 5; task++) {
382 const before = activity
383 await new Promise((resolve) => setTimeout(resolve, 2))
384 quietTasks = activity === before ? quietTasks + 1 : 0
385 }
386 if (quietTasks < 5) throw new Error(`hosts did not quiesce: ${label}`)
387 }
388​
389 return {
390 openTab,
391 quiesce,
392 commitNotices: () => commitNotices,
393 // A peer tab's collection reset, posted on the tabs' coordinator channel
394 // as a peer would post it. No shipped host sends this notice yet, so
395 // the premise is controlled; the tabs, their coordinators, and Electric
396 // receive it through production.
397 broadcastPeerReset: () => {
398 if (!storageCollectionId) {
399 throw new Error(`no commit notice named the storage collection yet`)
400 }
401 channel.postMessage({
402 v: 1,
403 dbName,
404 collectionId: storageCollectionId,
405 senderId: `peer-reset-tab`,
406 ts: Date.now(),
407 payload: {
408 type: `collection:reset`,
409 schemaVersion: 1,
410 resetEpoch: ++resetEpoch,
411 },
412 })
413 },
414 // The durable rows of the shared Collection, read through a connection of
415 // its own so the read counts as no host activity.
416 durableRows: async (): Promise<Array<Item>> => {
417 observer ??= createWASQLiteTestDatabase({ filename, timeout: 1000 })
418 const registry = await observer.execute<{ table_name: string }>(
419 `SELECT table_name FROM collection_registry WHERE collection_id = ?`,
420 [`items`],
421 )
422 const table = registry[0]?.table_name
423 if (!table) return []
424 const rows = await observer.execute<{ value: string }>(
425 `SELECT value FROM "${table}"`,
426 )
427 return rows
428 .map((row) => JSON.parse(row.value) as Item)
429 .map(({ id, label }) => ({ id, label }))
430 .sort((left, right) => left.id - right.id)
431 },
432 close: async () => {
433 await observer?.close?.()
434 for (const close of closers.reverse()) await close()
435 channel.close()
436 rmSync(directory, { recursive: true, force: true })
437 },
438 }
440​
441type Host = ReturnType<typeof openHost>
442type Tab = ReturnType<Host[`openTab`]>
443​
444async function openWarmTabs(host: Host, count: number, syncMode: SyncMode) {
445 const tabs: Array<Tab> = []
446 for (let index = 0; index < count; index++) {
447 const tab = host.openTab(String.fromCharCode(65 + index), syncMode)
448 for (let task = 0; task < 400 && !tab.hasStream(); task++) {
449 await new Promise((resolve) => setTimeout(resolve, 2))
450 }
451 expect(tab.hasStream()).toBe(true)
452 tabs.push(tab)
453 }
454 return tabs
456​
457// Generated-history campaigns (ORC-007): a fixed seed and a random seed
458// with the same property and budget. TANSTACK_DB_ORACLE_SEED with
459// TANSTACK_DB_ORACLE_PATH and TANSTACK_DB_ORACLE_PROPERTY=
460// browser.multi-tab-reserved-history replays one recorded counterexample;
461// TANSTACK_DB_ORACLE_RUNS_MULTIPLIER scales the budget.
462const GENERATED_PROPERTY = `browser.multi-tab-reserved-history`
463const GENERATED_FIXED_SEED = 952051961
464const GENERATED_RUNS = 80
465​
466async function waitForStream(tab: Tab, count: number) {
467 for (let task = 0; task < 400 && tab.streamCount() < count; task++) {
468 await new Promise((resolve) => setTimeout(resolve, 2))
469 }
470 expect(tab.streamCount()).toBe(count)
472​
473// The server after the deploy, answering a new stream from where it starts:
474// the head handle is up to date, a full-snapshot request gets the head
475// snapshot, and the old handle must refetch.
476async function serveHead(
477 host: Host,
478 tab: Tab,
479 startedAt: { handle: string | undefined; offset: string },
480) {
481 const head = { handle: `h2`, offset: `20_0` }
482 if (startedAt.handle === `h2`) tab.deliver([upToDate], head)
483 else if (startedAt.handle === undefined || startedAt.offset === `-1`) {
484 tab.deliver([...afterDeploy.map(insert), upToDate], head)
485 } else {
486 tab.deliver([mustRefetch], {
487 handle: startedAt.handle,
488 offset: startedAt.offset,
489 })
490 await host.quiesce(`tab ${tab.tab} restart refetch open`)
491 tab.deliver([...afterDeploy.map(insert), upToDate], head)
492 }
493 await host.quiesce(`tab ${tab.tab} restarted`)
495​
496// ---------------------------------------------------------------------------
497// The server log. Snapshot 1 is the state before a deploy, snapshot 2 after:
498// row 1 changes, row 2 is deleted, row 3 is new.
499// ---------------------------------------------------------------------------
500​
501const beforeDeploy: Array<Item> = [
502 { id: 1, label: `one` },
503 { id: 2, label: `two` },
505const afterDeploy: Array<Item> = [
506 { id: 1, label: `one, refetched` },
507 { id: 3, label: `three` },
509​
510describe(`multi-tab Electric over one persisted database`, () => {
511 let host: Host | undefined
512 afterEach(async () => {
513 await host?.close()
514 host = undefined
515 streams.length = 0
516 })
517​
518 // Law 1 grammar. Dimensions: two or three tabs; eager or on-demand
519 // Collections; which tab finishes its refetch first; whether every tab's
520 // must-refetch arrives before any refetch finishes (a storm) or each tab
521 // finishes before the next receives must-refetch (staggered, the
522 // neighbouring control); and whether the last tab's source stops for good
523 // while it holds an open reserved transaction, through each terminal path
524 // Electric has. That transaction is either its refetch or an ordinary batch
525 // of a stream that resumed from the persisted position, with no up-to-date
526 // yet. Resume invalidation needs the resumed batch: a refetch already
527 // replaces the snapshot, and on-demand Collections never validate resume.
528 //
529 // A source that stops for good abandons its reserved transaction
530 // (maintainer decision on #2226). So a stopped tab that is still open
531 // applies its peers' refetch from durable rows, as it did before
532 // reservations deferred hydrations. Electric then fails no further, except
533 // that resume invalidation fails the source, as Electric documents: the
534 // ready tab keeps `ready` with an error on its health node and still shows
535 // durable rows (Law 3). The
536 // application's recovery, cleanup and a restart, then brings
537 // the tab to the head. After resume invalidation the restart must request a
538 // full snapshot (electric.ts: "a full snapshot is required").
539 type StormHistory = {
540 tabCount: number
541 syncMode: SyncMode
542 finisher: `first` | `last`
543 arrival: `storm` | `staggered`
544 open: `refetch` | `resumed batch`
545 stop: `none` | StreamStop
546 recovery: `none` | `restart` | `reload`
547 }
548 const stormHistories: Array<StormHistory> = [2, 3].flatMap((tabCount) =>
549 ([`eager`, `on-demand`] as const).flatMap((syncMode) =>
550 ([`first`, `last`] as const).flatMap((finisher) =>
551 ([`storm`, `staggered`] as const).flatMap((arrival) =>
552 ([`refetch`, `resumed batch`] as const).flatMap((open) =>
553 (
554 [
555 ...(open === `refetch` ? ([`none`] as const) : []),
556 `error without retry`,
557 `SDK gives up`,
558 `signal aborted`,
559 `cleanup`,
560 ...(open === `resumed batch` && syncMode === `eager`
561 ? ([`resume invalidated`] as const)
562 : []),
563 ] as const
564 ).flatMap((stop) =>
565 (stop === `none`
566 ? ([`none`] as const)
567 : ([`restart`, `reload`] as const)
568 ).map((recovery) => ({
569 tabCount,
570 syncMode,
571 finisher,
572 arrival,
573 open,
574 stop,
575 recovery,
576 })),
577 ),
578 ),
579 ),
580 ),
581 ),
582 )
583 // The storm driver: it runs one cell on real tabs and checks every tab's
584 // rows and status against the law at each checkpoint.
585 const runStormHistory = async ({
586 tabCount,
587 syncMode,
588 finisher,
589 arrival,
590 open,
591 stop,
592 recovery,
593 }: (typeof stormHistories)[number]) => {
594 host = openHost()
595 const tabs = await openWarmTabs(host, tabCount, syncMode)
596 for (const tab of tabs) {
597 tab.deliver([...beforeDeploy.map(insert), upToDate], {
598 handle: `h1`,
599 offset: `10_0`,
600 })
601 await host.quiesce(`tab ${tab.tab} warm`)
602 }
603 type RefetchReach =
604 | `peer commit announced during an open refetch`
605 | `stopped tab resumed from the persisted position`
606 | `peer commit announced during the stopped tab's open transaction`
607 | `a source stopped while its transaction was open`
608 | `restarted tab opened a new stream`
609 const reach = createOracleReach<RefetchReach>(
610 `browser.multi-tab-reserved-refetch`,
611 [
612 ...(arrival === `storm`
613 ? ([`peer commit announced during an open refetch`] as const)
614 : []),
615 ...(open === `resumed batch`
616 ? ([`stopped tab resumed from the persisted position`] as const)
617 : []),
618 ...(stop === `none`
619 ? []
620 : ([
621 `peer commit announced during the stopped tab's open transaction`,
622 `a source stopped while its transaction was open`,
623 `restarted tab opened a new stream`,
624 ] as const)),
625 ],
626 )
627 reach.beginHistory()
628​
629 // The last tab to finish is the one whose source may stop.
630 const finishOrder = finisher === `first` ? tabs : [...tabs].reverse()
631 const stoppedIndex =
632 stop === `none` ? undefined : tabs.indexOf(finishOrder.at(-1)!)
633 if (open === `resumed batch`) {
634 // A page reload: the tab closes and reopens over the same database,
635 // resuming from its persisted position. Its first batch after the
636 // resume stays open, as a batch with no up-to-date does.
637 const closing = tabs[stoppedIndex!]!
638 const streamsBefore = closing.streamCount()
639 await closing.close()
640 await host.quiesce(`stopped tab closed`)
641 const reopened = host.openTab(closing.tab, syncMode)
642 await waitForStream(reopened, streamsBefore + 1)
643 tabs[stoppedIndex!] = reopened
644 if (reopened.startedAt().handle === `h1`) {
645 reach.reach(`stopped tab resumed from the persisted position`)
646 }
647 reopened.deliver([upToDate], { handle: `h1`, offset: `10_0` })
648 await host.quiesce(`stopped tab resumed`)
649 reopened.deliver([update({ id: 1, label: `one, unfinished` })], {
650 handle: `h1`,
651 offset: `11_0`,
652 })
653 await host.quiesce(`resumed batch open`)
654 }
655 const stoppedTab =
656 stoppedIndex === undefined ? undefined : tabs[stoppedIndex]
657 const refetchingTabs = (
658 finisher === `first` ? tabs : [...tabs].reverse()
659 ).filter((tab) => open === `refetch` || tab !== stoppedTab)
660 const noticesBefore = host.commitNotices()
661 const stopSource = async () => {
662 if (!stoppedTab || stop === `none`) return
663 if (host!.commitNotices() > noticesBefore) {
664 reach.reach(
665 `peer commit announced during the stopped tab's open transaction`,
666 )
667 }
668 void Promise.resolve(stoppedTab.stopStream(stop)).catch(() => undefined)
669 await host!.quiesce(`tab ${stoppedTab.tab} source stopped`)
670 reach.reach(`a source stopped while its transaction was open`)
671 }
672 const refetch = (tab: Tab) =>
673 tab.deliver([...afterDeploy.map(insert), upToDate], {
674 handle: `h2`,
675 offset: `20_0`,
676 })
677 if (arrival === `storm`) {
678 for (const tab of refetchingTabs)
679 tab.deliver([mustRefetch], { handle: `h1`, offset: `10_0` })
680 const noticesBeforeRefetch = host.commitNotices()
681 await host.quiesce(`every refetch open`)
682 // Each tab's reset marker is a peer notice for every other tab while
683 // its own reserved refetch is open.
684 if (host.commitNotices() > noticesBeforeRefetch) {
685 reach.reach(`peer commit announced during an open refetch`)
686 }
687 for (const tab of refetchingTabs) {
688 if (tab === stoppedTab) continue
689 refetch(tab)
690 await host.quiesce(`tab ${tab.tab} refetched`)
691 }
692 await stopSource()
693 } else {
694 for (const tab of refetchingTabs) {
695 tab.deliver([mustRefetch], { handle: `h1`, offset: `10_0` })
696 await host.quiesce(`tab ${tab.tab} refetch open`)
697 if (tab === stoppedTab) continue
698 refetch(tab)
699 await host.quiesce(`tab ${tab.tab} refetched`)
700 }
701 await stopSource()
702 }
703​
704 // Checkpoint 1, every source has delivered or stopped. A rejected
705 // reserved commit would fail its source. A stopped tab that is still
706 // open shows its peers' refetch, including one whose source failed on
707 // resume invalidation (Law 3); a cleaned-up tab has no rows. Eager rows
708 // must equal the head snapshot; on-demand rows are not judged (above).
709 // Resume invalidation comes after the tab was ready, so the tab stays
710 // `ready` and its health node records the source's error (#2168: after
711 // readiness, sync failures never change Collection status).
712 const stoppedStatus = stop === `cleanup` ? `cleaned-up` : `ready`
713 const judgesRowsBeforeRestart = (tab: Tab) =>
714 syncMode === `eager` && (tab !== stoppedTab || stop !== `cleanup`)
715 const judgesSourceError = (tab: Tab) =>
716 tab === stoppedTab && stop === `resume invalidated`
717 const observe = (judgesRows: (tab: Tab) => boolean) =>
718 tabs.map((tab) => ({
719 tab: tab.tab,
720 status: tab.collection.status,
721 ...(judgesRows(tab) ? { rows: tab.publicRows() } : {}),
722 ...(judgesSourceError(tab)
723 ? { sourceError: tab.collection.health.error !== null }
724 : {}),
725 }))
726 expect(observe(judgesRowsBeforeRestart)).toEqual(
727 tabs.map((tab) => ({
728 tab: tab.tab,
729 status: tab === stoppedTab ? stoppedStatus : `ready`,
730 ...(judgesRowsBeforeRestart(tab) ? { rows: afterDeploy } : {}),
731 ...(judgesSourceError(tab) ? { sourceError: true } : {}),
732 })),
733 )
734​
735 // Checkpoint 2, after the application recovers the stopped tab and the
736 // server answers its new stream from where it starts. A restart cleans
737 // up and starts the same Collection again; a reload closes the tab and
738 // opens it again over the same database, so it reads only durable
739 // state.
740 if (stoppedTab) {
741 const streamsBefore = stoppedTab.streamCount()
742 let recovered = stoppedTab
743 if (recovery === `restart`) await stoppedTab.restart()
744 else {
745 await stoppedTab.close()
746 await host.quiesce(`tab ${stoppedTab.tab} closed`)
747 recovered = host.openTab(stoppedTab.tab, syncMode)
748 tabs[stoppedIndex!] = recovered
749 }
750 await waitForStream(recovered, streamsBefore + 1)
751 reach.reach(`restarted tab opened a new stream`)
752 const restartedAt = recovered.startedAt()
753 await serveHead(host, recovered, restartedAt)
754 if (stop === `resume invalidated`) {
755 expect(restartedAt).toEqual({ handle: undefined, offset: `-1` })
756 }
757 // The new sync run starts without the retired run's problems.
758 expect(observe(() => syncMode === `eager`)).toEqual(
759 tabs.map((tab) => ({
760 tab: tab.tab,
761 status: `ready`,
762 ...(syncMode === `eager` ? { rows: afterDeploy } : {}),
763 ...(judgesSourceError(tab) ? { sourceError: false } : {}),
764 })),
765 )
766 }
767 reach.assertReached()
768 }
769 it.each(stormHistories)(
770 `commits every reserved refetch across tabs ($tabCount tabs, $syncMode, $finisher finishes first, $arrival, open $open, stop: $stop, recovery: $recovery)`,
771 runStormHistory,
772 30_000,
773 )
774​
775 // Law 1 and Law 3, generated histories. The enumerated grammar above fixes
776 // one refetch storm and one stopped tab. These histories interleave, in any
777 // legal order:
778 //
779 // - server changes (insert, update, or delete of one of four rows);
780 // - deploys, after which every stream must refetch;
781 // - a peer reset, which abandons every open reserved transaction (Law 5);
782 // - deliveries to one tab: part of what its stream still owes, with no
783 // up-to-date, which leaves a reserved transaction open, or everything it
784 // owes and up-to-date, which commits it;
785 // - a tab's source stopping for good (each terminal path except resume
786 // invalidation, which the enumerated grammar owns);
787 // - recovery of a stopped tab, and a reload of a running tab.
788 //
789 // Model. The server is a log per shape handle. A tab's stream owes the log
790 // after its position, or must-refetch then the snapshot when its handle is
791 // stale. A tab's open transaction holds the messages delivered since it
792 // began; a commit applies them to the durable rows in commit order, after a
793 // truncate when the transaction is a refetch or a fresh snapshot. An
794 // abandoned transaction applies nothing. So the expected durable rows are a
795 // fold of committed batches. A lagging tab can commit an older value after
796 // a peer committed a newer one; that is the eventual-consistency note in
797 // the coverage map (#2209), so the fold keeps it rather than the server
798 // head.
799 //
800 // Checkpoint after every step, at host quiescence:
801 // - every status is the one the model owes: `error` only for a failed
802 // first load, `cleaned-up` only for a tab stopped by cleanup; a
803 // reset-abandoned commit fails the source, which keeps a ready tab
804 // `ready` with an error on its health node (Law 5);
805 // - the durable rows equal the fold;
806 // - every open tab with no open transaction shows the durable rows. That
807 // includes a tab whose source stopped: it abandoned its transaction, so
808 // its peers' commits apply to it (Law 1, Law 3).
809 // After the history, every tab recovers and catches up. Then every tab must
810 // show the durable rows, and the durable rows must be the server head when
811 // the fold says so.
812 //
813 // The model reads one production fact: the position a new stream asks the
814 // server to start from. The simulated server answers that request; the
815 // model does not judge it, except that a full-snapshot request must get a
816 // full snapshot.
817 type HistoryStep =
818 | { kind: `server change`; key: number; pick: number }
819 | { kind: `deploy` }
820 | { kind: `peer reset` }
821 | { kind: `advance`; tab: number; pick: number }
822 | { kind: `catch up`; tab: number; pick: number }
823 // A tab that closes for good. Generated histories never close a tab;
824 // only the pinned #2209 replay does (see below).
825 | { kind: `close`; tab: number }
826 | { kind: `stop`; tab: number; pick: number }
827 | { kind: `recover`; tab: number; pick: number }
828 const historyStep: fc.Arbitrary<HistoryStep> = fc.oneof(
829 {
830 weight: 3,
831 arbitrary: fc.record({
832 kind: fc.constant(`server change` as const),
833 key: fc.integer({ min: 1, max: 4 }),
834 pick: fc.nat(5),
835 }),
836 },
837 {
838 weight: 1,
839 arbitrary: fc.record({ kind: fc.constant(`deploy` as const) }),
840 },
841 {
842 weight: 1,
843 arbitrary: fc.record({ kind: fc.constant(`peer reset` as const) }),
844 },
845 {
846 weight: 3,
847 arbitrary: fc.record({
848 kind: fc.constant(`advance` as const),
849 tab: fc.nat(2),
850 pick: fc.nat(5),
851 }),
852 },
853 {
854 weight: 3,
855 arbitrary: fc.record({
856 kind: fc.constant(`catch up` as const),
857 tab: fc.nat(2),
858 // 0 delivers everything owed; n commits only the next n changes, as
859 // a server answering at an earlier moment does.
860 pick: fc.nat(3),
861 }),
862 },
863 {
864 weight: 3,
865 arbitrary: fc.record({
866 kind: fc.constant(`stop` as const),
867 tab: fc.nat(2),
868 pick: fc.nat(3),
869 }),
870 },
871 {
872 weight: 1,
873 arbitrary: fc.record({
874 kind: fc.constant(`recover` as const),
875 tab: fc.nat(2),
876 pick: fc.nat(1),
877 }),
878 },
879 )
880 const generatedHistory = fc.record({
881 tabCount: fc.integer({ min: 2, max: 3 }),
882 steps: fc.array(historyStep, { minLength: 8, maxLength: 24 }),
883 })
884 type GeneratedHistory = { tabCount: number; steps: Array<HistoryStep> }
885​
886 type ServerLog = {
887 handle: number
888 // Versions under the current handle; version 0 is the snapshot.
889 snapshot: Map<number, string>
890 changes: Array<{ version: number; message: Message<Item> }>
891 rows: Map<number, string>
892 }
893 type TabModel = {
894 stopped: StreamStop | undefined
895 // The position the stream has delivered: a handle and a version. An
896 // undefined handle means the stream owes a full snapshot.
897 handle: number | undefined
898 version: number
899 // Messages of the open transaction, and whether it truncates first.
900 open: Array<Message<Item>> | undefined
901 truncates: boolean
902 // Collection readiness: a new sync run is `loading` until its own
903 // stream's first up-to-date. A stop before then is the final initial
904 // failure, which puts the Collection in `error` (Electric's initial-sync
905 // law). A Collection status changes only through its own source: a
906 // peer's durable commit reloads the rows but leaves the status alone
907 // (maintainer decision on PR #2265, Law 4).
908 ready: boolean
909 // A sync run that resumed from a persisted position, so Electric checks
910 // that each update names a row it holds.
911 resumed: boolean
912 failedInitialSync: boolean
913 // The stop that ended an open transaction, until the tab recovers. A
914 // peer commit in that interval is the premise of the abandon law.
915 stoppedMidTransaction: StreamStop | undefined
916 closed: boolean
917 // A peer reset abandoned this tab's open transaction. Electric still
918 // holds it, so its next commit rejects and the source fails (maintainer
919 // decision on PR #2265, Law 5); the app then restarts it.
920 abandonedByReset: boolean
921 failedByReset: boolean
922 }
923 const stops: ReadonlyArray<StreamStop> = [
924 `error without retry`,
925 `SDK gives up`,
926 `signal aborted`,
927 `cleanup`,
928 ]
929 const rowsOf = (rows: Map<number, string>): Array<Item> =>
930 [...rows]
931 .map(([id, label]) => ({ id, label }))
932 .sort((left, right) => left.id - right.id)
933 const position = (log: ServerLog, version: number) => ({
934 handle: `h${log.handle}`,
935 offset: `${version}_0`,
936 })
937 // The request a new stream made, read as a model position.
938 const requestedPosition = (
939 startedAt: { handle: string | undefined; offset: string },
940 log: ServerLog,
941 ): Pick<TabModel, `handle` | `version`> => {
942 if (startedAt.handle === undefined || startedAt.offset === `-1`) {
943 return { handle: undefined, version: -1 }
944 }
945 const handle = Number(startedAt.handle.slice(1))
946 const version = Number(startedAt.offset.split(`_`)[0])
947 return handle === log.handle
948 ? { handle, version }
949 : { handle, version: Number.NaN }
950 }
951​
952 const runGeneratedHistory = async (
953 { tabCount, steps }: GeneratedHistory,
954 onKnownGap: () => void,
955 ) => {
956 host = openHost()
957 const activeHost = host
958 const tabs = await openWarmTabs(activeHost, tabCount, `eager`)
959 const log: ServerLog = {
960 handle: 1,
961 snapshot: new Map(beforeDeploy.map((row) => [row.id, row.label])),
962 changes: [],
963 rows: new Map(beforeDeploy.map((row) => [row.id, row.label])),
964 }
965 const durable = new Map<number, string>()
966 const models: Array<TabModel> = tabs.map(() => ({
967 stopped: undefined,
968 handle: undefined,
969 version: -1,
970 open: undefined,
971 truncates: false,
972 ready: false,
973 failedInitialSync: false,
974 resumed: false,
975 stoppedMidTransaction: undefined,
976 closed: false,
977 abandonedByReset: false,
978 failedByReset: false,
979 }))
980 let serverVersion = 0
981 generatedReach.beginHistory()
982​
983 const commit = (model: TabModel) => {
984 if (model.truncates) durable.clear()
985 for (const message of model.open ?? []) {
986 if (!(`key` in message)) continue
987 const row = message.value
988 if (message.headers.operation === `delete`) durable.delete(row.id)
989 else durable.set(row.id, row.label)
990 }
991 model.open = undefined
992 model.truncates = false
993 }
994 const abandon = (model: TabModel) => {
995 model.open = undefined
996 model.truncates = false
997 }
998 // What the server sends one tab next: must-refetch for a stale handle,
999 // the snapshot for a full-snapshot request, or the changes it owes.
1000 const deliver = async (
1001 index: number,
1002 upTo: number | `all`,
1003 commits: boolean,
1004 ) => {
1005 const tab = tabs[index]!
1006 const model = models[index]!
1007 if (model.handle !== undefined && model.handle !== log.handle) {
1008 tab.deliver([mustRefetch], {
1009 handle: `h${model.handle}`,
1010 offset: `${Math.max(model.version, 0)}_0`,
1011 })
1012 generatedReach.reach(`must-refetch delivered`)
1013 abandon(model)
1014 model.open = []
1015 model.truncates = true
1016 model.handle = undefined
1017 model.version = -1
1018 await activeHost.quiesce(`tab ${tab.tab} must-refetch`)
1019 if (!commits) return
1021 const messages: Array<Message<Item>> = []
1022 if (model.handle === undefined) {
1023 model.open ??= []
1024 model.truncates = true
1025 messages.push(
1026 ...rowsOf(log.snapshot).map(insert),
1027 ...log.changes.map((change) => change.message),
1029 model.handle = log.handle
1030 model.version = serverVersion
1031 } else {
1032 const owed = log.changes.filter(
1033 (change) => change.version > model.version,
1035 const count = upTo === `all` ? owed.length : Math.min(upTo, owed.length)
1036 messages.push(...owed.slice(0, count).map((change) => change.message))
1037 model.version = count > 0 ? owed[count - 1]!.version : model.version
1038 if (messages.length > 0) model.open ??= []
1040 // Electric's updates carry only changed columns (the shape's default
1041 // replica), so an update cannot create a row the tab does not hold,
1042 // and Electric drops it. The tab holds the durable rows, or, inside a
1043 // refetch, the snapshot it has received. Known gap: a resumed tab
1044 // instead reports an unseen row and fails (issue #2267). Generated
1045 // campaigns leave that history out; the pinned replay below keeps it.
1046 const held = new Set<number>(model.truncates ? [] : durable.keys())
1047 const track = (message: Message<Item>) => {
1048 if (!(`key` in message)) return
1049 if (message.headers.operation === `delete`)
1050 held.delete(message.value.id)
1051 else held.add(message.value.id)
1053 for (const message of model.open ?? []) track(message)
1054 const applied = messages.filter((message) => {
1055 if (
1056 `key` in message &&
1057 message.headers.operation === `update` &&
1058 !held.has(message.value.id)
1059 ) {
1060 if (model.resumed && !model.truncates) onKnownGap()
1061 return false
1063 track(message)
1064 return true
1065 })
1066 model.open?.push(...applied)
1067 const complete = commits
1068 if (messages.length === 0 && !complete) return
1069 tab.deliver(
1070 complete ? [...messages, upToDate] : messages,
1071 position(log, model.version),
1073 if (complete && model.abandonedByReset) {
1074 generatedReach.reach(
1075 `reset-abandoned commit put the Collection in error`,
1077 abandon(model)
1078 model.abandonedByReset = false
1079 model.failedByReset = true
1080 } else if (complete) {
1081 commit(model)
1082 model.ready = true
1084 await activeHost.quiesce(`tab ${tab.tab} delivered`)
1086 const recover = async (index: number, how: `restart` | `reload`) => {
1087 const stopped = tabs[index]!
1088 const streamsBefore = stopped.streamCount()
1089 let recovered = stopped
1090 if (how === `restart`) await stopped.restart()
1091 else {
1092 await stopped.close()
1093 await activeHost.quiesce(`tab ${stopped.tab} closed`)
1094 recovered = activeHost.openTab(stopped.tab, `eager`)
1095 tabs[index] = recovered
1097 abandon(models[index]!)
1098 await waitForStream(recovered, streamsBefore + 1)
1099 generatedReach.reach(`tab recovered`)
1100 const requested = requestedPosition(recovered.startedAt(), log)
1101 Object.assign(models[index]!, {
1102 stopped: undefined,
1103 ready: false,
1104 failedInitialSync: false,
1105 resumed: requested.handle !== undefined,
1106 stoppedMidTransaction: undefined,
1107 abandonedByReset: false,
1108 failedByReset: false,
1109 ...requested,
1110 })
1111 await activeHost.quiesce(`tab ${recovered.tab} recovered`)
1113​
1114 const check = async (label: string, head?: Array<Item>) => {
1115 const expectedDurable = head ?? rowsOf(durable)
1116 // A tab closed for good is a cleaned-up Collection with no rows.
1117 const judgesRows = (index: number) =>
1118 models[index]!.open === undefined &&
1119 models[index]!.stopped !== `cleanup` &&
1120 !models[index]!.closed
1121 const expectedStatus = (index: number) =>
1122 models[index]!.stopped === `cleanup` || models[index]!.closed
1123 ? `cleaned-up`
1124 : models[index]!.failedInitialSync ||
1125 (models[index]!.failedByReset && !models[index]!.ready)
1126 ? `error`
1127 : models[index]!.ready
1128 ? `ready`
1129 : `loading`
1130 const expected = {
1131 durableRows: expectedDurable,
1132 tabs: tabs.map((tab, index) => ({
1133 tab: tab.tab,
1134 status: expectedStatus(index),
1135 ...(judgesRows(index) ? { rows: expectedDurable } : {}),
1136 // The reset-abandoned source failed (Law 5).
1137 ...(models[index]!.failedByReset ? { sourceError: true } : {}),
1138 })),
1140 const actual = {
1141 durableRows: await activeHost.durableRows(),
1142 tabs: tabs.map((tab, index) => ({
1143 tab: tab.tab,
1144 status: tab.collection.status,
1145 ...(judgesRows(index) ? { rows: tab.publicRows() } : {}),
1146 ...(models[index]!.failedByReset
1147 ? { sourceError: tab.collection.health.error !== null }
1148 : {}),
1149 })),
1151 // fast-check reports only the message, so it carries both sides, plus
1152 // each errored Collection's reason, which `preload()` rejects with.
1153 const errors = await Promise.all(
1154 tabs.map((tab) =>
1155 tab.collection.status === `error`
1156 ? tab.collection.preload().then(
1157 () => undefined,
1158 (error: unknown) => `${tab.tab}: ${String(error)}`,
1160 : undefined,
1161 ),
1163 expect(
1164 actual,
1165 `${label}\nactual ${JSON.stringify(actual)}\nexpected ${JSON.stringify(expected)}\nerrors ${JSON.stringify(errors.filter(Boolean))}`,
1166 ).toEqual(expected)
1168​
1169 // Warm start: every tab delivers the snapshot and commits it.
1170 for (const index of tabs.keys()) await deliver(index, `all`, true)
1171 await check(`warm`)
1172​
1173 for (const [stepIndex, step] of steps.entries()) {
1174 const openBefore = models.some((model) => model.open !== undefined)
1175 const unreadyBefore = models.some(
1176 (model) =>
1177 model.stopped !== `cleanup` &&
1178 (!model.ready || model.failedInitialSync),
1180 const noticesBefore = activeHost.commitNotices()
1181 if (step.kind === `server change`) {
1182 serverVersion++
1183 const present = log.rows.has(step.key)
1184 const operation = !present
1185 ? `insert`
1186 : step.pick % 3 === 0
1187 ? `delete`
1188 : `update`
1189 const row = { id: step.key, label: `v${serverVersion}` }
1190 if (operation === `delete`) log.rows.delete(step.key)
1191 else log.rows.set(step.key, row.label)
1192 log.changes.push({
1193 version: serverVersion,
1194 message: {
1195 key: String(row.id),
1196 value: row,
1197 headers: { operation },
1198 },
1199 })
1200 } else if (step.kind === `close`) {
1201 const index = step.tab % tabs.length
1202 await tabs[index]!.close()
1203 abandon(models[index]!)
1204 models[index]!.closed = true
1205 await activeHost.quiesce(`tab ${tabs[index]!.tab} closed for good`)
1206 } else if (step.kind === `peer reset`) {
1207 // A peer reset abandons every open reserved transaction that began
1208 // before it (maintainer decision on PR #2265). It changes no durable
1209 // row, so every tab reloads the same durable rows.
1210 if (models.some((model) => model.open !== undefined)) {
1211 generatedReach.reach(`peer reset abandoned an open transaction`)
1213 for (const model of models) {
1214 if (model.open !== undefined && model.stopped === undefined) {
1215 model.abandonedByReset = true
1217 abandon(model)
1219 activeHost.broadcastPeerReset()
1220 await activeHost.quiesce(`peer reset applied`)
1221 } else if (step.kind === `deploy`) {
1222 log.handle++
1223 serverVersion = 0
1224 log.snapshot = new Map(log.rows)
1225 log.changes = []
1226 } else {
1227 // A stop goes to a tab with an open transaction when there is one,
1228 // so the generator reaches the state the abandon law is about.
1229 const openTabs = models.flatMap((model, index) =>
1230 model.open !== undefined && model.stopped === undefined
1231 ? [index]
1232 : [],
1234 // Only `recover` recovers a stopped tab. Another step aimed at a
1235 // stopped tab goes to a running one, so a stopped tab stays stopped
1236 // while its peers commit.
1237 const runningTabs = models.flatMap((model, index) =>
1238 model.stopped === undefined && !model.failedByReset ? [index] : [],
1240 const index =
1241 step.kind === `stop` && openTabs.length > 0
1242 ? openTabs[step.tab % openTabs.length]!
1243 : step.kind !== `recover` &&
1244 (models[step.tab % tabs.length]!.stopped !== undefined ||
1245 models[step.tab % tabs.length]!.failedByReset) &&
1246 runningTabs.length > 0
1247 ? runningTabs[step.tab % runningTabs.length]!
1248 : step.tab % tabs.length
1249 const model = models[index]!
1250 if (
1251 model.stopped !== undefined ||
1252 model.failedByReset ||
1253 step.kind === `recover`
1254 ) {
1255 // A running tab can only reload; a stopped tab restarts or reloads.
1256 const how =
1257 (model.stopped === undefined && !model.failedByReset) ||
1258 (step.kind === `recover` && step.pick === 1)
1259 ? `reload`
1260 : `restart`
1261 await recover(index, how)
1262 } else if (step.kind === `stop`) {
1263 const how = stops[step.pick % stops.length]!
1264 if (model.open !== undefined) {
1265 generatedReach.reach(`source stopped with an open transaction`)
1266 model.stoppedMidTransaction = how
1268 void Promise.resolve(tabs[index]!.stopStream(how)).catch(
1269 () => undefined,
1271 model.stopped = how
1272 // Electric abandons the dead transaction itself, so nothing errors.
1273 model.abandonedByReset = false
1274 abandon(model)
1275 model.failedInitialSync = how !== `cleanup` && !model.ready
1276 await activeHost.quiesce(`tab ${tabs[index]!.tab} stopped`)
1277 } else {
1278 await deliver(
1279 index,
1280 step.kind === `catch up`
1281 ? step.pick === 0
1282 ? `all`
1283 : step.pick
1284 : step.pick + 1,
1285 step.kind === `catch up`,
1289 if (activeHost.commitNotices() > noticesBefore) {
1290 for (const model of models) {
1291 const stop = model.stoppedMidTransaction
1292 if (
1293 stop === `error without retry` ||
1294 stop === `SDK gives up` ||
1295 stop === `signal aborted`
1296 ) {
1297 generatedReach.reach(`peer commit after ${stop} mid-transaction`)
1301 if (unreadyBefore && activeHost.commitNotices() > noticesBefore) {
1302 generatedReach.reach(`peer commit while a tab was not ready`)
1304 if (openBefore && activeHost.commitNotices() > noticesBefore) {
1305 const stillOpen = models.some((model) => model.open !== undefined)
1306 if (stillOpen) {
1307 generatedReach.reach(
1308 `peer commit during an open reserved transaction`,
1312 if (rowsOf(durable).some(({ id, label }) => log.rows.get(id) !== label)) {
1313 generatedReach.reach(`durable rows behind the server`)
1315 await check(`after step ${stepIndex}: ${JSON.stringify(step)}`)
1317​
1318 // Law 2: every open tab recovers and catches up, and then the durable
1319 // rows and every open tab show the server head. Each tab's last batch
1320 // rewrites every row that changed after its position, so no lagging
1321 // commit survives the catch-up.
1322 for (const index of tabs.keys()) {
1323 if (models[index]!.closed) continue
1324 if (
1325 models[index]!.stopped !== undefined ||
1326 models[index]!.failedByReset
1327 ) {
1328 await recover(index, `restart`)
1330 await deliver(index, `all`, true)
1332 await check(`after every tab caught up`, rowsOf(log.rows))
1334​
1335 type GeneratedReach =
1336 | `must-refetch delivered`
1337 | `peer commit during an open reserved transaction`
1338 | `source stopped with an open transaction`
1339 | `tab recovered`
1340 | `durable rows behind the server`
1341 | `peer commit while a tab was not ready`
1342 | `peer commit after error without retry mid-transaction`
1343 | `peer commit after SDK gives up mid-transaction`
1344 | `peer commit after signal aborted mid-transaction`
1345 | `peer reset abandoned an open transaction`
1346 | `reset-abandoned commit put the Collection in error`
1347 // The storm driver and the generated-history driver are the checks; the
1348 // generated driver folds committed batches into its own model of durable
1349 // rows. The storm cells and the generated-history arbitrary are the grammar.
1350 declareOracle({
1351 check: [runStormHistory, runGeneratedHistory],
1352 grammar: [stormHistories, generatedHistory],
1353 })
1354​
1355 const createGeneratedReach = () =>
1356 createOracleReach<GeneratedReach>(`browser.multi-tab-reserved-history`, [
1357 `must-refetch delivered`,
1358 `peer commit during an open reserved transaction`,
1359 `source stopped with an open transaction`,
1360 `tab recovered`,
1361 `durable rows behind the server`,
1362 `peer commit while a tab was not ready`,
1363 `peer commit after error without retry mid-transaction`,
1364 `peer commit after SDK gives up mid-transaction`,
1365 `peer commit after signal aborted mid-transaction`,
1366 `peer reset abandoned an open transaction`,
1367 `reset-abandoned commit put the Collection in error`,
1368 ])
1369 let generatedReach = createGeneratedReach()
1370​
1371 const runGeneratedCampaign = async (
1372 parameters: ReturnType<typeof oraclePropertyOptions>,
1373 ) => {
1374 generatedReach = createGeneratedReach()
1375 await fc.assert(
1376 fc.asyncProperty(generatedHistory, async (history) => {
1377 try {
1378 // fc.pre discards a history that reaches the known gap.
1379 await runGeneratedHistory(history, () => fc.pre(false))
1380 } finally {
1381 await host?.close()
1382 host = undefined
1383 streams.length = 0
1385 }),
1386 parameters,
1388 console.info(
1389 `multi-tab generated reach`,
1390 Object.fromEntries(generatedReach.counts()),
1392 generatedReach.assertReached()
1394 it.skipIf(oracleReplayRequested())(
1395 `keeps reserved commits lawful across generated multi-tab histories (fixed seed)`,
1396 () =>
1397 runGeneratedCampaign({
1398 numRuns: oracleRuns(GENERATED_RUNS),
1399 seed: GENERATED_FIXED_SEED,
1400 }),
1401 600_000,
1403 it(
1404 `keeps reserved commits lawful across generated multi-tab histories (random or replayed)`,
1405 () =>
1406 runGeneratedCampaign(
1407 oraclePropertyOptions(GENERATED_RUNS, GENERATED_PROPERTY),
1408 ),
1409 600_000,
1411​
1412 // Known gap #2267, pinned: the shrunk generated history in which a resumed tab
1413 // that lags behind its peer receives an update for a row the peer already
1414 // deleted. It replays through the same driver and checks with the known-gap
1415 // detector off. Remove `fails` when Electric's resume check stops treating
1416 // rows from peers' commits as this stream's evidence.
1417 it.fails(
1418 `keeps a resumed lagging tab out of error when a peer deleted the row it updates`,
1419 () =>
1420 runGeneratedHistory(
1422 tabCount: 2,
1423 steps: [
1424 { kind: `recover`, tab: 1, pick: 0 },
1425 { kind: `server change`, key: 2, pick: 1 },
1426 { kind: `server change`, key: 1, pick: 0 },
1427 { kind: `server change`, key: 2, pick: 0 },
1428 { kind: `server change`, key: 1, pick: 0 },
1429 { kind: `advance`, tab: 0, pick: 0 },
1430 ],
1431 },
1432 () => undefined,
1433 ),
1434 60_000,
1436​
1437 // Known gap #2209, pinned: tab A commits v1 and v2; tab B's lagging stream
1438 // then commits only v1, so the durable row falls back to v1, and B closes
1439 // for good. Nothing redelivers the head to A, so Law 2's final check fails.
1440 // Generated histories never close a tab for good, which leaves this
1441 // history out of them; it replays through the same driver and checks.
1442 // Remove `fails` when source writes are ordered by server position.
1443 it.fails(
1444 `converges an open tab to the head after a lagging tab commits an older row and closes`,
1445 () =>
1446 runGeneratedHistory(
1448 tabCount: 2,
1449 steps: [
1450 { kind: `server change`, key: 1, pick: 1 },
1451 { kind: `catch up`, tab: 0, pick: 0 },
1452 { kind: `server change`, key: 1, pick: 1 },
1453 { kind: `catch up`, tab: 0, pick: 0 },
1454 { kind: `catch up`, tab: 1, pick: 1 },
1455 { kind: `close`, tab: 1 },
1456 ],
1457 },
1458 () => undefined,
1459 ),
1460 60_000,