/** * Real Electric and Chromium OPFS receiving histories for ordered source * publication. PostgreSQL supplies the source rows. Delaying before fetch * lets one response carry several writes. Delaying after fetch preserves an * older callback while a peer establishes the durable head. */ import { expect } from '@playwright/test' import { makePgClient } from '../../db-collection-e2e/support/global-setup' import { sourceHeadViolation, sourcePublicationViolation, sourceSubscriberViolation, } from '../tests/electric-convergence-oracle' import { requiredBrowserObservations } from '../tests/browser-required-observations' import type { BrowserContext, Page } from '@playwright/test' import type {} from './electric-source-prefix.opfs' export const interleavedElectricSchedules = [ `split stale`, `coalesced stale`, `forward overlap`, `partial update and delete before forward overlap`, `invalid partial update at the established position`, `held initial snapshot`, `held initial snapshot with forward overlap`, `covered insert before its peer notice`, `covered update before its peer notice`, ] as const export const journalGapSchedule = `journal gap with a reinserted row` export type InterleavedElectricSchedule = (typeof interleavedElectricSchedules)[number] | typeof journalGapSchedule const observe = (page: Page) => page.evaluate(() => window.__electricSourcePrefix!.observe()) export async function runInterleavedElectricPublication( context: BrowserContext, pageUrl: string, providerUrl: string, history: { schedule: InterleavedElectricSchedule; tag?: string }, compare: (checkpoint: string, judge: () => T) => T = ( _checkpoint, judge, ) => judge(), ) { const { schedule, tag } = history const first = tag ? `v1-${tag}` : `v1` const second = tag ? `v2-${tag}` : `v2` const later = tag ? `later-${tag}` : `later` const table = `electric_ordering_${crypto.randomUUID().replaceAll(`-`, ``).slice(0, 12)}` const pg = makePgClient() const pages: Array = [] const diagnostics: Array = [] const heldSnapshot = schedule.startsWith(`held initial snapshot`) const invalid = schedule === `invalid partial update at the established position` const forward = schedule.endsWith(`forward overlap`) || invalid const deleted = schedule.startsWith(`partial update and delete`) || invalid const covered = schedule.startsWith(`covered `) const journal = schedule === journalGapSchedule const coveredInsert = schedule === `covered insert before its peer notice` const includesExtra = deleted || covered const url = `${pageUrl}?${new URLSearchParams({ table, collectionId: table, databaseId: table, includeExtra: String(includesExtra) })}` const reach = requiredBrowserObservations( `browser.electric-interleaved-source-publication.opfs`, [ heldSnapshot ? `both real streams request an initial snapshot` : `two real streams resumed at one provider position`, `fast stream applied its provider head`, covered ? `covered SDK response released while its peer notice is held` : journal ? `three missed or delayed source transactions enter SQLite journal recovery` : invalid ? `invalid partial update delivered at the established source position` : forward ? `one complete provider batch includes earlier writes and a new write` : `older HTTP response held across fast application`, `publication compared after the response`, ], { replaying: false }, ) reach.beginHistory() const call = ( page: Page, action: | `releaseFetch` | `arm` | `releaseOne` | `releaseAndContinue` | `recordPublications` | `holdCommitNotices`, ) => page.evaluate((name) => window.__electricSourcePrefix![name](), action) const ready = (page: Page) => expect .poll(async () => (await observe(page)).status, { timeout: 30_000 }) .toBe(`ready`) const open = async (hold = false, holdFetch = false) => { const page = await context.newPage() pages.push(page) page.on(`pageerror`, (error) => diagnostics.push(error)) await page.goto(`${url}&holdInitial=${hold}&holdFetch=${holdFetch}`) await page.waitForFunction( () => window.__electricSourcePrefix || window.__electricSourcePrefixFailure, undefined, { timeout: 45_000 }, ) const failure = await page.evaluate( () => window.__electricSourcePrefixFailure, ) if (failure) throw new Error(failure) return page } const close = async (page: Page) => { if (page.isClosed()) return try { diagnostics.push( ...(await page.evaluate( () => window.__electricSourcePrefix?.cleanup() ?? [], )), ) } finally { await page.close() } } const pendingChanges = async (page: Page) => { await expect .poll( async () => { const state = await observe(page) if (state.pending[0] === 0) await call(page, `releaseOne`) return (await observe(page)).pending[0] ?? 0 }, { timeout: 30_000 }, ) .toBeGreaterThan(0) return (await observe(page)).pendingChanges[0]! } const holdCompletingResponse = async (page: Page) => { const changes: Awaited> = [] for (let count = 0; count < 12; count++) { await expect .poll(async () => (await observe(page)).pending.length, { timeout: 30_000, }) .toBeGreaterThan(0) const state = await observe(page) changes.push(...state.pendingChanges[0]!) if (state.pendingComplete[0] && changes.length > 0) return { changes, end: state.pendingOffsets[0] } await call(page, `releaseOne`) } throw new Error( `Electric did not deliver an up-to-date response for the batch`, ) } const selectSource = async () => ( await pg.query<{ id: string; label: string; extra?: string }>( `SELECT id, label${includesExtra ? `, extra` : ``} FROM public.${table} ORDER BY id`, ) ).rows // A PostgreSQL COMMIT can resolve before Electric has received the WAL. // Wait at the provider boundary before sending the gated catch-up request. const awaitProviderWrite = (handle: string, offset: string, label: string) => expect .poll( async () => { const response = await context.request.get( `${providerUrl}?${new URLSearchParams({ table: `public.${table}`, handle, offset, })}`, ) const messages = response.ok() ? ((await response.json()) as Array<{ value?: { label?: string } }>) : [] return messages.some(({ value }) => value?.label === label) }, { timeout: 30_000 }, ) .toBe(true) const awaitValue = (page: Page, label: string | undefined) => expect .poll( async () => (await observe(page)).baseRows.find(({ id }) => id === `target`) ?.label, { timeout: 30_000 }, ) .toBe(label) let failure: { error: unknown } | undefined await pg.connect() try { await pg.query( `CREATE TABLE public.${table} (id TEXT PRIMARY KEY, label TEXT NOT NULL${includesExtra ? `, extra TEXT NOT NULL DEFAULT 'retained'` : ``})`, ) await pg.query( `INSERT INTO public.${table} (id, label) VALUES ('anchor', 'anchor')${coveredInsert ? `` : `, ('target', 'initial')`}`, ) const seed = heldSnapshot ? undefined : await open() if (seed) await ready(seed) const { offset, handle: resumedHandle } = seed ? ((await observe(seed)).resume as { offset: string; handle: string }) : { offset: `-1`, handle: null } const seedPosition = { offset, handle: resumedHandle } if (seed) await close(seed) const waitForSeedRequest = async (page: Page) => { await expect .poll(async () => (await observe(page)).requests[0], { timeout: 30_000, }) .toEqual(seedPosition) } // Initialize both OPFS connections before releasing a provider // response that would start writing to the shared database. const cold = heldSnapshot ? await open(true, forward) : undefined if (cold) await waitForSeedRequest(cold) const a = await open(schedule === `coalesced stale`, true) await waitForSeedRequest(a) const b = cold ?? (await open(true, forward)) await waitForSeedRequest(b) if (schedule !== `coalesced stale`) { await call(a, `releaseFetch`) await ready(a) } const { handle } = ( heldSnapshot ? (await observe(a)).resume : seedPosition ) as { handle: string } if (!forward && !heldSnapshot) { await expect .poll(async () => (await observe(b)).pending[0], { timeout: 30_000 }) .toBe(0) await call(b, `releaseOne`) await ready(b) } reach.reach( heldSnapshot ? `both real streams request an initial snapshot` : `two real streams resumed at one provider position`, ) if (journal) { await call(b, `recordPublications`) await call(b, `holdCommitNotices`) const before = await observe(b) const baseline = await selectSource() const awaitFastPublication = async () => { const source = await selectSource() await expect .poll(async () => (await observe(a)).baseRows) .toEqual(source) return source } await pg.query( `UPDATE public.${table} SET label = $1 WHERE id = 'anchor'`, [first], ) const updated = await awaitFastPublication() await pg.query(`DELETE FROM public.${table} WHERE id = 'target'`) const deletedRows = await awaitFastPublication() await pg.query(`INSERT INTO public.${table} VALUES ('target', $1)`, [ later, ]) const head = await awaitFastPublication() reach.reach(`fast stream applied its provider head`) await expect .poll(async () => (await observe(b)).holdsCurrentDurableNotice) .toBe(true) expect((await observe(b)).heldNotices).toBeGreaterThanOrEqual(3) await b.evaluate(() => window.__electricSourcePrefix!.deliverLatestCommitNotice(), ) // The scan queues behind the recovery's apply turn. The first // publication of the durable head can happen before its final delta. await b.evaluate(() => window.__electricSourcePrefix!.settlePeerRecovery(), ) await expect .poll(async () => (await observe(b)).pulledJournalDeltas.slice( before.pulledJournalDeltas.length, ), ) .toContain(3) reach.reach( `three missed or delayed source transactions enter SQLite journal recovery`, ) const after = await observe(b) compare( `Electric journal recovery follows source publication order`, () => { expect( sourceSubscriberViolation( [baseline, updated, deletedRows, head], after.publications, ), ).toBeUndefined() expect( sourceHeadViolation(head, { durableRows: after.durableRows, tabs: [{ ...after, rows: after.baseRows }], }), ).toBeUndefined() expect(after.subscriberRows).toEqual(head) expect(after.sourceErrors).toEqual([]) }, ) } else if (covered) { const baseline = await selectSource() await call(b, `recordPublications`) await call(b, `holdCommitNotices`) await pg.query( coveredInsert ? `INSERT INTO public.${table} (id, label, extra) VALUES ('target', 'peer', 'peer field')` : `UPDATE public.${table} SET label = 'peer', extra = 'peer field' WHERE id = 'target'`, ) await awaitValue(a, `peer`) const peer = await selectSource() const batch = await holdCompletingResponse(b) expect(batch.changes).toEqual([ { operation: coveredInsert ? `insert` : `update`, values: { id: `target`, label: `peer`, extra: `peer field` }, }, ]) await expect .poll( async () => { const state = await observe(b) return { notices: state.heldNotices, resume: state.resume } }, { timeout: 30_000 }, ) .toMatchObject({ notices: expect.any(Number), resume: { handle, offset: batch.end }, }) const before = await observe(b) expect(before.heldNotices).toBeGreaterThan(0) expect(before.baseRows).toEqual(baseline) expect(before.durableRows).toEqual(peer) reach.reach(`fast stream applied its provider head`) await call(a, `arm`) await b.evaluate(() => window.__electricSourcePrefix!.releaseMatchingWrite(`peer`), ) reach.reach(`covered SDK response released while its peer notice is held`) await pg.query( `UPDATE public.${table} SET label = 'successor' WHERE id = 'target'`, ) const successor = await holdCompletingResponse(b) expect(successor.changes).toEqual([ { operation: `update`, values: { id: `target`, label: `successor` } }, ]) const receiptError = await b.evaluate(() => window.__electricSourcePrefix!.releaseMatchingWrite(`successor`).then( () => undefined, (error: unknown) => String(error), ), ) const recorded = await observe(b) const sourceHead = await selectSource() expect({ receiptError, difference: sourceHeadViolation(sourceHead, { durableRows: recorded.durableRows, tabs: [{ ...recorded, rows: recorded.baseRows }], }), publication: sourceSubscriberViolation( [baseline, peer, sourceHead], recorded.publications, ), errors: recorded.sourceErrors, subscriberRows: recorded.subscriberRows, compatible: recorded.compatible, resume: recorded.resume, fullSnapshot: recorded.requests.some(({ offset }) => offset === `-1`), }).toEqual({ receiptError: undefined, difference: undefined, publication: undefined, errors: [], subscriberRows: sourceHead, compatible: true, resume: expect.objectContaining({ handle, offset: successor.end }), fullSnapshot: false, }) } else { const initialBatch = heldSnapshot && !forward ? await holdCompletingResponse(b) : undefined if (initialBatch) { expect((await observe(b)).pendingHandles[0]).toBe(handle) expect(initialBatch.changes).toEqual( expect.arrayContaining([ { operation: `insert`, values: { id: `target`, label: `initial` }, }, { operation: `insert`, values: { id: `anchor`, label: `anchor` }, }, ]), ) expect(initialBatch.changes).toHaveLength(2) } await pg.query( `UPDATE public.${table} SET label = $1 WHERE id = 'target'`, [first], ) if (schedule !== `coalesced stale`) await awaitValue(a, first) let olderOffset = initialBatch?.end if (!forward && !heldSnapshot) { expect(await pendingChanges(b)).toEqual([ { operation: `update`, values: { id: `target`, label: first } }, ]) olderOffset = (await observe(b)).pendingOffsets[0] expect(olderOffset).toEqual(expect.any(String)) expect((await observe(b)).pendingComplete[0]).toBe(true) if (schedule === `split stale`) await expect .poll(async () => (await observe(a)).resume) .toMatchObject({ offset: olderOffset }) } await pg.query( deleted ? `DELETE FROM public.${table} WHERE id = 'target'` : `UPDATE public.${table} SET label = $1 WHERE id = 'target'`, deleted ? [] : [second], ) if (schedule === `coalesced stale`) { await awaitProviderWrite(handle, olderOffset!, second) await call(a, `releaseFetch`) const batch = await holdCompletingResponse(a) expect(batch.changes).toEqual([ { operation: `update`, values: { id: `target`, label: first } }, { operation: `update`, values: { id: `target`, label: second } }, ]) await call(a, `releaseOne`) await expect .poll(async () => (await observe(a)).resume) .toMatchObject({ handle, offset: batch.end }) } await awaitValue(a, deleted ? undefined : second) if (!heldSnapshot) await expect .poll(async () => (await observe(b)).baseRows) .toEqual(await selectSource()) await call(a, `arm`) const head = await selectSource() const previous = await observe(a) const { offset: headOffset } = previous.resume as { offset: string } expect(previous.progress).toEqual(expect.any(String)) expect(previous.compatible).toBe(true) const journal = await a.evaluate(() => window.__electricSourcePrefix!.resumeJournal(), ) if (!forward && !heldSnapshot) expect( journal.some( (position) => position.handle === handle && position.offset === olderOffset, ), ).toBe(schedule === `split stale`) reach.reach(`fast stream applied its provider head`) await Promise.all([ call(a, `recordPublications`), call(b, `recordPublications`), ]) if (invalid) { await close(b) const receiver = await open(true) await expect .poll(async () => (await observe(receiver)).requests[0]) .toEqual({ handle, offset: headOffset }) await expect .poll(async () => (await observe(receiver)).pending[0]) .toBe(0) await call(receiver, `releaseOne`) await ready(receiver) await call(receiver, `recordPublications`) await pg.query( `UPDATE public.${table} SET label = 'must not publish' WHERE id = 'anchor'`, ) expect(await pendingChanges(receiver)).toEqual([ { operation: `update`, values: { id: `anchor`, label: `must not publish` }, }, ]) expect((await observe(receiver)).pendingRequests[0]).toEqual({ handle, offset: headOffset, }) const errors = await receiver.evaluate(() => window.__electricSourcePrefix!.releaseInvalidUpdate(), ) reach.reach( `invalid partial update delivered at the established source position`, ) await expect .poll(async () => (await observe(receiver)).resume) .toMatchObject({ kind: `reset` }) .catch(() => undefined) const rejected = await observe(receiver) compare(`invalid successor preserves the established snapshot`, () => { expect(rejected.error).toMatch(/unseen row/) expect(rejected.status).toBe(`ready`) expect(rejected.resume).toMatchObject({ kind: `reset` }) expect( sourceSubscriberViolation([head], rejected.publications), ).toBeUndefined() expect( sourcePublicationViolation( [head], [ rejected.baseRows, rejected.durableRows, rejected.subscriberRows ?? [], ], ), ).toBeUndefined() expect(errors).toEqual( Array.from({ length: 4 }, () => rejected.error), ) }) } else if (forward) { await pg.query( deleted ? `INSERT INTO public.${table} (id, label) VALUES ('target', $1)` : `UPDATE public.${table} SET label = $1 WHERE id = 'anchor'`, [later], ) await awaitProviderWrite( handle, (previous.resume as { offset: string }).offset, later, ) await call(b, `releaseFetch`) const batch = await holdCompletingResponse(b) const prefixLength = heldSnapshot ? 2 : 0 expect(batch.changes).toHaveLength(prefixLength + 3) if (heldSnapshot) expect(batch.changes.slice(0, prefixLength)).toEqual( expect.arrayContaining([ { operation: `insert`, values: { id: `anchor`, label: `anchor` }, }, { operation: `insert`, values: { id: `target`, label: `initial` }, }, ]), ) expect(batch.changes.slice(prefixLength)).toEqual([ { operation: `update`, values: { id: `target`, label: first } }, deleted ? { operation: `delete`, values: expect.objectContaining({ id: `target` }), } : { operation: `update`, values: { id: `target`, label: second } }, deleted ? { operation: `insert`, values: { id: `target`, label: later, extra: `retained` }, } : { operation: `update`, values: { id: `anchor`, label: later }, }, ]) reach.reach( `one complete provider batch includes earlier writes and a new write`, ) await call(b, `releaseAndContinue`) const sourceHead = await selectSource() await expect .poll( async () => { const states = await Promise.all([observe(a), observe(b)]) return sourceHeadViolation(sourceHead, { durableRows: states[0].durableRows, tabs: states.map((s) => ({ ...s, rows: s.baseRows })), }) }, { timeout: 30_000 }, ) .toBeUndefined() .catch(() => undefined) const states = await Promise.all([observe(a), observe(b)]) compare(`forward overlap publishes the source head`, () => { expect( sourceHeadViolation(sourceHead, { durableRows: states[0].durableRows, tabs: states.map((state) => ({ ...state, rows: state.baseRows })), }), ).toBeUndefined() for (const state of states) { expect(state.sourceErrors).toEqual([]) expect( sourceSubscriberViolation( heldSnapshot ? [[], head, sourceHead] : [head, sourceHead], state.publications, ), ).toBeUndefined() expect( sourcePublicationViolation( [sourceHead], [state.subscriberRows ?? []], ), ).toBeUndefined() } expect(states[0].resume).toMatchObject({ handle, offset: batch.end }) expect(states[0].progress).not.toBe(previous.progress) expect(states[0].compatible).toBe(true) }) await close(a) await close(b) const reopened = await open() await ready(reopened) const opened = await observe(reopened) compare(`cold opener after forward overlap`, () => { expect( sourceHeadViolation(sourceHead, { durableRows: opened.durableRows, tabs: [{ ...opened, rows: opened.baseRows }], }), ).toBeUndefined() }) } else { expect((await observe(b)).pendingOffsets[0]).toBe(olderOffset) reach.reach(`older HTTP response held across fast application`) const laggingAtHead = sourcePublicationViolation([head], [(await observe(b)).baseRows]) === undefined const releaseError = await b .evaluate( ({ label, recoverFrom }) => window.__electricSourcePrefix!.releaseMatchingWrite( label, recoverFrom, ), { label: heldSnapshot ? `initial` : first, recoverFrom: schedule === `split stale` ? undefined : { handle, offset: headOffset }, }, ) .then( () => undefined, (error: unknown) => String(error), ) const lagging = await observe(b) await close(b) const surviving = await observe(a) const difference = sourcePublicationViolation( [head], [ surviving.baseRows, surviving.durableRows, ...(laggingAtHead ? [lagging.baseRows] : []), ], ) compare(`older callback preserves the established source head`, () => { expect(releaseError).toBeUndefined() expect( difference, `the closed tab's older callback must preserve the exposed and durable source head`, ).toBeUndefined() expect(surviving.progress).toBe(previous.progress) expect(surviving.resume).toMatchObject({ handle, offset: headOffset }) expect(surviving.compatible).toBe(true) if (laggingAtHead) expect( sourceSubscriberViolation([head], lagging.publications), ).toBeUndefined() if (schedule === `split stale`) { expect(lagging.error).toBeUndefined() expect(surviving.resume).toEqual(previous.resume) expect( lagging.requests.every( (request) => request.handle === handle && request.offset !== `-1`, ), ).toBe(true) } }) await pg.query( `UPDATE public.${table} SET label = 'after-close' WHERE id = 'anchor'`, ) await call(a, `releaseAndContinue`) const sourceHead = await selectSource() await expect .poll(async () => (await observe(a)).baseRows, { timeout: 30_000 }) .toEqual(sourceHead) .catch(() => undefined) const advanced = await observe(a) compare(`surviving tab advances after closing the lagging tab`, () => { expect(advanced.baseRows).toEqual(sourceHead) expect( sourceSubscriberViolation( [head, sourceHead], advanced.publications, ), ).toBeUndefined() expect( sourcePublicationViolation( [sourceHead], [advanced.subscriberRows ?? [], advanced.durableRows], ), ).toBeUndefined() expect(advanced.compatible).toBe(true) expect(advanced.progress).not.toBe(previous.progress) expect(advanced.resume).toMatchObject({ handle, offset: expect.any(String), }) expect((advanced.resume as { offset: string }).offset).not.toBe( headOffset, ) }) } } reach.reach(`publication compared after the response`) reach.assertReached() console.info( `Electric source publication reach`, schedule, Object.fromEntries(reach.counts()), ) } catch (error) { failure = { error } } finally { for (const page of pages.reverse()) { try { await close(page) } catch (error) { diagnostics.push(error) } } try { await pg.query(`DROP TABLE IF EXISTS public.${table}`) } catch (error) { diagnostics.push(error) } try { await pg.end() } catch (error) { diagnostics.push(error) } } if (failure && !diagnostics.length) throw failure.error if (failure) throw Object.assign( new Error( `${String(failure.error)}\nCleanup: ${diagnostics.map(String).join(`\n`)}`, { cause: failure.error }, ), { cleanupErrors: diagnostics }, ) expect(diagnostics).toEqual([]) return [...reach.counts()].map(([state]) => state) }