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