From 284d1833b424b46c9143a23c552c59126e3ab4a0 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Mon, 23 Nov 2026 03:25:57 -0800 Subject: [PATCH 1/6] fix(offline-transactions): let waiting tabs take over Web Locks leadership Queue a follower for the leader lock so it takes over and replays the outbox when the leader releases or its tab closes. --- .changeset/web-locks-leader-takeover.md | 5 + docs/contributing/oracle-coverage.md | 3 + packages/db/tests/oracle-config.ts | 1 + packages/db/tests/oracle-replay-manifest.ts | 5 + .../src/coordination/WebLocksLeader.ts | 119 ++-- .../tests/web-locks-failover.test.ts | 141 +++++ .../web-locks-leader-oracle.property.test.ts | 598 ++++++++++++++++++ 7 files changed, 826 insertions(+), 46 deletions(-) create mode 100644 .changeset/web-locks-leader-takeover.md create mode 100644 packages/offline-transactions/tests/web-locks-failover.test.ts create mode 100644 packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts diff --git a/.changeset/web-locks-leader-takeover.md b/.changeset/web-locks-leader-takeover.md new file mode 100644 index 0000000000..4c94331899 --- /dev/null +++ b/.changeset/web-locks-leader-takeover.md @@ -0,0 +1,5 @@ +--- +'@tanstack/offline-transactions': patch +--- + +Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 56bc9081c9..b4486843e4 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4241,6 +4241,9 @@ The post-merge review added three missing domains to existing owners: contribution bag and source-row identity, as well as output length and zero getter reads. A multiple-key constructed history and duplicate-key/omitted-key calibration protect that distinction. +- [Web Locks leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts) + checks FIFO takeover across three tabs that request, release and close over a + controlled lock manager. It does not cover real browser contexts. - [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts) holds real storage-read delivery across successful and permanently rejected durable removals, with bounded scans, concurrent loads, and unfinished peers. diff --git a/packages/db/tests/oracle-config.ts b/packages/db/tests/oracle-config.ts index 7055495ab5..543b5fd923 100644 --- a/packages/db/tests/oracle-config.ts +++ b/packages/db/tests/oracle-config.ts @@ -436,6 +436,7 @@ const staticOracleProperties = [ `offline.leadership.startup`, `offline.leadership.stale-read`, `offline.leadership.storage-failure`, + `offline.web-locks-leader`, `offline.serializer.mutation-wire`, `offline.serializer.date-marker`, `offline.serializer.version-two`, diff --git a/packages/db/tests/oracle-replay-manifest.ts b/packages/db/tests/oracle-replay-manifest.ts index 7f2e1d3d34..bea27af169 100644 --- a/packages/db/tests/oracle-replay-manifest.ts +++ b/packages/db/tests/oracle-replay-manifest.ts @@ -1796,6 +1796,11 @@ const ownerGroups: ReadonlyArray< `offline`, `leadership.serial-work leadership.report leadership.delayed-read leadership.startup leadership.stale-read leadership.storage-failure`, ], + [ + `offline-transactions/tests/web-locks-leader-oracle.property.test.ts`, + `offline`, + `web-locks-leader`, + ], [ `offline-transactions/tests/transaction-serializer-oracle.property.test.ts`, `offline`, diff --git a/packages/offline-transactions/src/coordination/WebLocksLeader.ts b/packages/offline-transactions/src/coordination/WebLocksLeader.ts index 644ad6437f..dbbf20db80 100644 --- a/packages/offline-transactions/src/coordination/WebLocksLeader.ts +++ b/packages/offline-transactions/src/coordination/WebLocksLeader.ts @@ -3,6 +3,10 @@ import { BaseLeaderElection } from './LeaderElection' export class WebLocksLeader extends BaseLeaderElection { private lockName: string private releaseLock: (() => void) | null = null + // Set while this tab waits in the lock's queue, to leave it on release. + private waiting: AbortController | undefined + private pendingRequest: Promise | null = null + private requestGeneration = 0 constructor(lockName = `offline-executor-leader`) { super() @@ -18,64 +22,87 @@ export class WebLocksLeader extends BaseLeaderElection { return true } - try { - // First try to acquire the lock with ifAvailable - const available = await navigator.locks.request( - this.lockName, - { - mode: `exclusive`, - ifAvailable: true, - }, - (lock) => { - return lock !== null - }, - ) + if (this.waiting) { + return false + } - if (!available) { - return false - } + this.pendingRequest ??= this.acquireOrWait().finally(() => { + this.pendingRequest = null + }) + return this.pendingRequest + } - // Set state immediately to prevent duplicate notifications - // when the async lock acquisition calls notifyLeadershipChange(true). - // The guard in notifyLeadershipChange checks `isLeaderState !== isLeader`, - // so setting this to true here prevents the callback from firing again. - this.isLeaderState = true + private async acquireOrWait(): Promise { + const generation = this.requestGeneration + try { + return await new Promise((resolve, reject) => { + navigator.locks + .request(this.lockName, { ifAvailable: true }, (lock) => { + // Released while this request was pending. + if (generation !== this.requestGeneration) { + resolve(false) + return + } - // Lock is available, now acquire it for real and hold it - navigator.locks.request( - this.lockName, - { - mode: `exclusive`, - }, - async (lock) => { - if (lock) { - this.notifyLeadershipChange(true) - // Hold the lock until released - return new Promise((resolve) => { - this.releaseLock = () => { - this.notifyLeadershipChange(false) - resolve() - } - }) - } - }, - ) + if (!lock) { + this.waitForLeadership() + resolve(false) + return + } - return true + // Set state directly: the caller learns this result from the + // returned promise, so it is not a leadership change. + this.isLeaderState = true + resolve(true) + return this.holdLock() + }) + .catch(reject) + }) } catch (error) { - if (error instanceof Error && error.name === `AbortError`) { - return false - } console.warn(`Web Locks leadership request failed:`, error) return false } } + // Queues for the lock, which is granted when the current holder releases it + // or its tab closes. + private waitForLeadership(): void { + const waiting = new AbortController() + this.waiting = waiting + navigator.locks + .request(this.lockName, { signal: waiting.signal }, () => { + // An abort has no effect once the lock is granted. + if (this.waiting !== waiting) return + this.waiting = undefined + this.notifyLeadershipChange(true) + return this.holdLock() + }) + .catch((error: unknown) => { + if (waiting.signal.aborted) return + this.waiting = undefined + console.warn(`Web Locks leadership request failed:`, error) + }) + } + + private holdLock(): Promise { + return new Promise((resolve) => { + this.releaseLock = () => { + this.notifyLeadershipChange(false) + resolve() + } + }) + } + releaseLeadership(): void { - if (this.releaseLock) { - this.releaseLock() - this.releaseLock = null + this.requestGeneration++ + if (this.waiting) { + const waiting = this.waiting + this.waiting = undefined + waiting.abort() } + const release = this.releaseLock + this.releaseLock = null + release?.() } private isWebLocksSupported(): boolean { diff --git a/packages/offline-transactions/tests/web-locks-failover.test.ts b/packages/offline-transactions/tests/web-locks-failover.test.ts new file mode 100644 index 0000000000..da21cbd683 --- /dev/null +++ b/packages/offline-transactions/tests/web-locks-failover.test.ts @@ -0,0 +1,141 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { WebLocksLeader } from '../src/coordination/WebLocksLeader' +import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness' + +const waitUntil = async ( + predicate: () => boolean | Promise, + timeoutMs = 5000, +) => { + const deadline = Date.now() + timeoutMs + while (Date.now() < deadline) { + if (await predicate()) return + await new Promise((resolve) => setTimeout(resolve, 10)) + } + throw new Error(`Timed out waiting for condition`) +} + +// The smallest exclusive lock manager an executor needs. +const createLocks = () => { + let held = false + const pending: Array<() => void> = [] + const grant = (run: () => unknown, resolve: (value: unknown) => void) => { + held = true + void Promise.resolve(run()).then((value) => { + held = false + resolve(value) + pending.shift()?.() + }) + } + return { + request( + _name: string, + options: { ifAvailable?: boolean; signal?: AbortSignal }, + callback: (lock: object | null) => unknown, + ) { + return new Promise((resolve, reject) => { + if (options.ifAvailable && held) { + resolve(callback(null)) + return + } + const start = () => grant(() => callback({}), resolve) + if (!held) { + start() + return + } + pending.push(start) + options.signal?.addEventListener( + `abort`, + () => { + pending.splice(pending.indexOf(start), 1) + reject(new DOMException(`Aborted`, `AbortError`)) + }, + { once: true }, + ) + }) + }, + } +} + +describe(`Web Locks failover through the executor`, () => { + afterEach(() => vi.unstubAllGlobals()) + + it(`a waiting executor takes over and replays the outbox`, async () => { + vi.stubGlobal(`navigator`, { locks: createLocks() }) + const storage = new FakeStorageAdapter() + const leadership: Array = [] + + const first = createTestOfflineEnvironment({ + storage, + config: { leaderElection: new WebLocksLeader(`failover`) }, + mutationFn: () => { + throw new Error(`offline`) + }, + }) + await first.executor.waitForInit() + expect(first.executor.isOfflineEnabled).toBe(true) + + const transaction = first.executor.createOfflineTransaction({ + mutationFnName: first.mutationFnName, + autoCommit: false, + }) + transaction.mutate(() => { + first.collection.insert({ + id: `pending`, + value: `replay me`, + completed: false, + updatedAt: new Date(), + }) + }) + void transaction.commit().catch(() => undefined) + await waitUntil( + async () => (await first.executor.peekOutbox()).length === 1, + ) + + const replayed: Array = [] + const second = createTestOfflineEnvironment({ + storage, + config: { + leaderElection: new WebLocksLeader(`failover`), + onLeadershipChange: (isLeader) => leadership.push(isLeader), + }, + mutationFn: (params) => { + for (const mutation of params.transaction.mutations) { + replayed.push(String(mutation.key)) + } + second.applyMutations(params.transaction.mutations) + return { ok: true, mutations: params.transaction.mutations } + }, + }) + await second.executor.waitForInit() + expect(second.executor.isOfflineEnabled).toBe(false) + + first.executor.dispose() + await waitUntil(() => second.executor.isOfflineEnabled) + await waitUntil( + async () => (await second.executor.peekOutbox()).length === 0, + ) + + expect(leadership).toEqual([false, true]) + expect(replayed).toEqual([`pending`]) + second.executor.dispose() + }) + + it(`a disposed waiter leaves the queue`, async () => { + const locks = createLocks() + vi.stubGlobal(`navigator`, { locks }) + const first = new WebLocksLeader(`queue`) + const second = new WebLocksLeader(`queue`) + const third = new WebLocksLeader(`queue`) + expect(await first.requestLeadership()).toBe(true) + expect(await second.requestLeadership()).toBe(false) + expect(await third.requestLeadership()).toBe(false) + await new Promise((resolve) => setTimeout(resolve, 0)) + + second.releaseLeadership() + first.releaseLeadership() + await waitUntil(() => third.isLeader()) + + expect(second.isLeader()).toBe(false) + third.releaseLeadership() + }) +}) diff --git a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts new file mode 100644 index 0000000000..13889cb971 --- /dev/null +++ b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts @@ -0,0 +1,598 @@ +/** + * # Does a waiting tab take over when the Web Locks leader goes away? + * + * Law and source: one tab leads outbox processing, and "a follower can become + * the leader after the current leader leaves" (docs/guides/offline-transactions.md, + * issue #2463). The Web Locks API grants an exclusive lock to pending requests + * in request order and releases it when its holder's context ends. An abort + * has no effect on a request that has already been granted. + * + * Model: a FIFO of waiting tabs and one holder. A tab that finds the lock free + * leads at once without a change notification, since its request reports it. A + * tab that finds it held reports false and waits. When the holder releases or + * closes, the first waiter leads and is notified. A waiter that releases leaves + * the queue and never leads, even when the lock was already granted to it. A + * failed lock request reports false, warns once, and leaves the tab idle. + * + * History grammar: up to fourteen actions over three tabs: request, two + * requests in one turn, a request released in the same turn, a failed first or + * queued lock request, release, close, and a close whose next waiter releases + * before its grant runs. A closed tab takes no further actions. An environment + * can lack `navigator` or `navigator.locks`. + * + * Production driver: real `WebLocksLeader` instances over a controlled lock + * manager that follows the spec's request order, `ifAvailable` and `signal` + * rules, and models a closing context by dropping its held and pending locks. + * + * Refinement check: after every action, each request result, leader flag, + * change notification, lock holder, queue and warning count equals the model. + * + * Known omissions: one lock name, no steal or shared mode, and no real browser + * contexts. + */ +import { AsyncLocalStorage } from 'node:async_hooks' +import fc from 'fast-check' +import { expect, vi } from 'vitest' +import { WebLocksLeader } from '../src/coordination/WebLocksLeader' +import { + forwardAssertionJudgment, + recordAssertionJudgment, + recordedAssertionJudgment, +} from '../../db/tests/oracle-assertion-adapter' +import { oracleProperty } from '../../db/tests/oracle-property' + +const property = `offline.web-locks-leader` +const TABS = 3 +const MAX_ACTIONS = 14 + +const reachStates = [ + // A waiting tab led after the leader released. + `takeover-after-release`, + // A waiting tab led after the leader's context closed. + `takeover-after-close`, + // A waiting tab left the queue before it could lead. + `waiter-released`, + // A waiting tab asked again and kept one place in the queue. + `repeated-request-while-waiting`, + // Two requests in one turn shared one acquisition. + `concurrent-requests`, + // A request was released before its first lock callback ran. + `released-while-requesting`, + // The first lock request failed. + `first-request-failed`, + // The queued lock request failed. + `queued-request-failed`, + // A waiter released after its grant, before the grant's callback ran. + `released-after-grant`, + // The environment has no usable Web Locks API. + `unsupported-environment`, +] as const +type ReachState = (typeof reachStates)[number] + +type ActionType = + | `request` + | `request-twice` + | `request-then-release` + | `fail-first` + | `fail-queued` + | `release` + | `close` + | `close-then-release-next` +type Action = { type: ActionType; tab: number } +type Environment = `locks` | `no-locks` | `no-navigator` +type History = { environment: Environment; actions: Array } +type TabState = `idle` | `waiting` | `leader` | `closed` + +// --------------------------------------------------------------------------- +// Model +// --------------------------------------------------------------------------- + +class LeadershipModel { + readonly tabs: Array = Array.from( + { length: TABS }, + () => `idle` as const, + ) + readonly queue: Array = [] + readonly notifications: Array> = Array.from( + { length: TABS }, + () => [], + ) + warnings = 0 + + get holder(): number | undefined { + const index = this.tabs.indexOf(`leader`) + return index < 0 ? undefined : index + } + + private promoteNext(): number | undefined { + const next = this.queue.shift() + if (next === undefined) return undefined + this.tabs[next] = `leader` + this.notifications[next]!.push(true) + return next + } + + request(tab: number): boolean { + const state = this.tabs[tab]! + if (state === `leader`) return true + if (state === `waiting`) return false + if (this.holder === undefined) { + this.tabs[tab] = `leader` + return true + } + this.tabs[tab] = `waiting` + this.queue.push(tab) + return false + } + + /** Returns the tab that took over, if any. */ + release(tab: number): number | undefined { + const state = this.tabs[tab]! + if (state === `waiting`) { + this.queue.splice(this.queue.indexOf(tab), 1) + this.tabs[tab] = `idle` + return undefined + } + if (state !== `leader`) return undefined + this.tabs[tab] = `idle` + this.notifications[tab]!.push(false) + return this.promoteNext() + } + + /** Returns the tab that took over, if any. */ + close(tab: number): number | undefined { + const state = this.tabs[tab]! + if (state === `waiting`) this.queue.splice(this.queue.indexOf(tab), 1) + this.tabs[tab] = `closed` + return state === `leader` ? this.promoteNext() : undefined + } + + /** The leader closes and its next waiter releases before leading. */ + closeThenReleaseNext(tab: number): number { + const next = this.queue.shift()! + this.tabs[tab] = `closed` + this.tabs[next] = `idle` + this.promoteNext() + return next + } +} + +// --------------------------------------------------------------------------- +// History grammar +// --------------------------------------------------------------------------- + +const actionArbitrary: fc.Arbitrary = fc.record({ + type: fc.constantFrom( + `request`, + `request`, + `request`, + `request-twice`, + `request-then-release`, + `fail-first`, + `fail-queued`, + `release`, + `release`, + `close`, + `close-then-release-next`, + ), + tab: fc.nat({ max: TABS - 1 }), +}) +const historyArbitrary: fc.Arbitrary = fc.record({ + environment: fc.constantFrom( + `locks`, + `locks`, + `locks`, + `locks`, + `locks`, + `no-locks`, + `no-navigator`, + ), + actions: fc.array(actionArbitrary, { minLength: 1, maxLength: MAX_ACTIONS }), +}) + +const spliced = (generated: History, prefix: Array): History => ({ + environment: `locks`, + actions: [ + ...prefix, + ...generated.actions.slice(0, MAX_ACTIONS - prefix.length), + ], +}) +const act = (type: ActionType, tab: number): Action => ({ type, tab }) +const contested = [act(`request`, 0), act(`request`, 1)] + +// --------------------------------------------------------------------------- +// Production driver +// --------------------------------------------------------------------------- + +type LockRequest = { + tab: number + callback: (lock: { name: string; mode: string } | null) => unknown + resolve: (value: unknown) => void + reject: (reason: unknown) => void + signal?: AbortSignal + onAbort?: () => void +} + +// The tab whose code is running, across its awaits and lock callbacks. +const tabContext = new AsyncLocalStorage() + +/** Exclusive locks in request order, per the Web Locks API. */ +class ControlledLocks { + held: LockRequest | undefined + readonly pending: Array = [] + failFirst = false + failQueued = false + + request( + name: string, + options: { ifAvailable?: boolean; signal?: AbortSignal }, + callback: LockRequest[`callback`], + ): Promise { + const tab = tabContext.getStore() ?? -1 + return new Promise((resolve, reject) => { + if ( + (options.ifAvailable && this.failFirst) || + (!options.ifAvailable && this.failQueued) + ) { + this.failFirst = false + this.failQueued = false + reject(new DOMException(`Denied`, `SecurityError`)) + return + } + if (options.signal?.aborted) { + reject(new DOMException(`Aborted`, `AbortError`)) + return + } + const request: LockRequest = { + tab, + callback, + resolve, + reject, + signal: options.signal, + } + if (options.ifAvailable && (this.held || this.pending.length > 0)) { + queueMicrotask(() => { + resolve(tabContext.run(tab, () => callback(null))) + }) + return + } + if (options.signal) { + request.onAbort = () => { + const index = this.pending.indexOf(request) + if (index < 0) return + this.pending.splice(index, 1) + reject(new DOMException(`Aborted`, `AbortError`)) + } + options.signal.addEventListener(`abort`, request.onAbort, { + once: true, + }) + } + this.pending.push(request) + queueMicrotask(() => this.pump(name)) + }) + } + + // A grant is decided now and its callback runs later, so an abort in + // between has no effect. + private pump(name: string): void { + if (this.held) return + const request = this.pending.shift() + if (!request) return + if (request.onAbort) { + request.signal?.removeEventListener(`abort`, request.onAbort) + } + this.held = request + queueMicrotask(() => { + if (this.held !== request) return + const result = tabContext.run(request.tab, () => + request.callback({ name, mode: `exclusive` }), + ) + void Promise.resolve(result).then( + (value) => { + if (this.held !== request) return + this.held = undefined + request.resolve(value) + this.pump(name) + }, + (error: unknown) => { + if (this.held !== request) return + this.held = undefined + request.reject(error) + this.pump(name) + }, + ) + }) + } + + /** A closing context loses its locks, and its callbacks never run again. */ + close(tab: number, name: string): void { + for (let index = this.pending.length - 1; index >= 0; index--) { + if (this.pending[index]!.tab === tab) this.pending.splice(index, 1) + } + if (this.held?.tab === tab) { + this.held = undefined + this.pump(name) + } + } +} + +const LOCK = `oracle-leader` +const settle = async () => { + for (let turn = 0; turn < 4; turn++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +// A request that never settles is a wrong answer rather than a stalled test. +const observed = (result: Promise) => { + const outcome: { value?: boolean } = {} + void result.then((value) => { + outcome.value = value + }) + return outcome +} + +async function runUnsupported( + history: History, + reach: (state: ReachState) => void, +): Promise { + reach(`unsupported-environment`) + vi.stubGlobal( + `navigator`, + history.environment === `no-locks` ? {} : undefined, + ) + const leader = new WebLocksLeader(LOCK) + expect(WebLocksLeader.isSupported(), `isSupported`).toBe(false) + for (const [step, action] of history.actions.entries()) { + if (action.type !== `release`) { + const result = await leader.requestLeadership().catch(() => `threw`) + expect(result, `step ${step}: result`).toBe(false) + } else { + expect( + () => leader.releaseLeadership(), + `step ${step}: release`, + ).not.toThrow() + } + expect(leader.isLeader(), `step ${step}: leader`).toBe(false) + expect(console.warn, `step ${step}: warnings`).not.toHaveBeenCalled() + } +} + +async function runHistory( + history: History, + reach: (state: ReachState) => void, +): Promise { + const warn = vi.spyOn(console, `warn`).mockImplementation(() => {}) + try { + if (history.environment !== `locks`) { + await runUnsupported(history, reach) + return + } + const locks = new ControlledLocks() + vi.stubGlobal(`navigator`, { locks }) + expect(WebLocksLeader.isSupported(), `isSupported`).toBe(true) + const model = new LeadershipModel() + const leaders = Array.from({ length: TABS }, () => new WebLocksLeader(LOCK)) + const notifications: Array> = leaders.map(() => []) + leaders.forEach((leader, tab) => { + leader.onLeadershipChange((isLeader) => { + notifications[tab]!.push(isLeader) + }) + }) + const inTab = (tab: number, run: () => T) => tabContext.run(tab, run) + + const check = (label: string) => { + leaders.forEach((leader, tab) => { + if (model.tabs[tab] === `closed`) return + expect(leader.isLeader(), `${label}: tab ${tab} leader`).toBe( + model.tabs[tab] === `leader`, + ) + }) + expect(notifications, `${label}: notifications`).toEqual( + model.notifications, + ) + expect(locks.held?.tab, `${label}: holder`).toBe(model.holder) + expect( + locks.pending.map((request) => request.tab), + `${label}: queue`, + ).toEqual(model.queue) + expect(warn, `${label}: warnings`).toHaveBeenCalledTimes(model.warnings) + } + + for (const [step, action] of history.actions.entries()) { + const { type, tab } = action + const label = `step ${step} ${type} tab ${tab}` + const state = model.tabs[tab]! + if (state === `closed`) continue + const leader = leaders[tab]! + const request = () => + observed(inTab(tab, () => leader.requestLeadership())) + + if (type === `request`) { + if (state === `waiting`) reach(`repeated-request-while-waiting`) + const expected = model.request(tab) + const outcome = request() + await settle() + expect(outcome.value, `${label}: result`).toBe(expected) + } else if (type === `request-twice`) { + if (state === `idle`) reach(`concurrent-requests`) + const expected = model.request(tab) + const outcomes = [request(), request()] + await settle() + expect( + outcomes.map((outcome) => outcome.value), + `${label}: results`, + ).toEqual([expected, expected]) + } else if (type === `request-then-release`) { + if (state === `idle`) reach(`released-while-requesting`) + const expected = state === `leader` + model.release(tab) + const outcome = request() + expect( + () => inTab(tab, () => leader.releaseLeadership()), + `${label}: release`, + ).not.toThrow() + await settle() + expect(outcome.value, `${label}: result`).toBe(expected) + } else if (type === `fail-first`) { + if (state !== `idle`) continue + reach(`first-request-failed`) + locks.failFirst = true + model.warnings += 1 + const outcome = request() + await settle() + expect(outcome.value, `${label}: result`).toBe(false) + } else if (type === `fail-queued`) { + if (state !== `idle` || model.holder === undefined) continue + reach(`queued-request-failed`) + locks.failQueued = true + model.warnings += 1 + const outcome = request() + await settle() + expect(outcome.value, `${label}: result`).toBe(false) + } else if (type === `release`) { + const waited = state === `waiting` + const next = model.release(tab) + if (waited) reach(`waiter-released`) + if (next !== undefined) reach(`takeover-after-release`) + expect( + () => inTab(tab, () => leader.releaseLeadership()), + `${label}: release`, + ).not.toThrow() + await settle() + } else if (type === `close`) { + const next = model.close(tab) + if (next !== undefined) reach(`takeover-after-close`) + locks.close(tab, LOCK) + await settle() + } else { + if (state !== `leader` || model.queue.length === 0) continue + reach(`released-after-grant`) + const next = model.closeThenReleaseNext(tab) + locks.close(tab, LOCK) + expect( + () => inTab(next, () => leaders[next]!.releaseLeadership()), + `${label}: release`, + ).not.toThrow() + await settle() + } + check(label) + } + } finally { + warn.mockRestore() + vi.unstubAllGlobals() + } +} + +oracleProperty({ + id: property, + law: { + statement: `Exactly the first waiting tab takes over when the Web Locks leader releases or its context closes, and it is notified once. A tab that finds the lock free leads without a notification, repeated or concurrent requests keep one queue place, a tab that releases never leads afterward, and a failed lock request reports false and leaves the tab idle.`, + authority: `Issue #2463, docs/guides/offline-transactions.md "A follower can become the leader after the current leader leaves", and the Web Locks API request order.`, + limits: `Three tabs and one exclusive lock over a controlled lock manager; up to fourteen actions; no steal or shared mode, and no real browser contexts.`, + }, + owns: [ + `src/coordination/WebLocksLeader.ts#WebLocksLeader.requestLeadership`, + `src/coordination/WebLocksLeader.ts#WebLocksLeader.releaseLeadership`, + `src/coordination/WebLocksLeader.ts#WebLocksLeader.isSupported`, + ], + histories: { + arbitrary: historyArbitrary, + runs: 60, + fixedSeeds: [2463], + states: reachStates, + constructed: [ + { + name: `a waiter takes over after the leader releases`, + enters: [`takeover-after-release`], + build: (generated: History): History => + spliced(generated, [...contested, act(`release`, 0)]), + }, + { + name: `a waiter takes over after the leader closes`, + enters: [`takeover-after-close`], + build: (generated: History): History => + spliced(generated, [...contested, act(`close`, 0)]), + }, + { + name: `a released waiter is skipped for the next one`, + enters: [`waiter-released`, `takeover-after-release`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`request`, 2), + act(`release`, 1), + act(`release`, 0), + ]), + }, + { + name: `a repeated request keeps one queue place`, + enters: [`repeated-request-while-waiting`, `takeover-after-close`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`request`, 1), + act(`close`, 0), + ]), + }, + { + name: `two requests in one turn share one acquisition`, + enters: [`concurrent-requests`], + build: (generated: History): History => + spliced(generated, [ + act(`request-twice`, 0), + act(`request-twice`, 1), + act(`release`, 0), + ]), + }, + { + name: `a request is released in its own turn`, + enters: [`released-while-requesting`], + build: (generated: History): History => + spliced(generated, [ + act(`request-then-release`, 0), + act(`request`, 1), + act(`request-then-release`, 2), + ]), + }, + { + name: `failed lock requests leave the tab idle`, + enters: [`first-request-failed`, `queued-request-failed`], + build: (generated: History): History => + spliced(generated, [ + act(`fail-first`, 0), + act(`request`, 0), + act(`fail-queued`, 1), + act(`request`, 1), + act(`release`, 0), + ]), + }, + { + name: `a waiter releases after its grant`, + enters: [`released-after-grant`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`request`, 2), + act(`close-then-release-next`, 0), + ]), + }, + { + name: `the environment has no Web Locks API`, + enters: [`unsupported-environment`], + build: (generated: History): History => ({ + environment: + generated.actions.length % 2 === 0 ? `no-locks` : `no-navigator`, + actions: generated.actions, + }), + }, + ], + }, + resolve: (history: History) => ({ history }), + model: recordedAssertionJudgment, + driver: (plan: { history: History }, observe) => + recordAssertionJudgment(property, plan, observe, () => + runHistory(plan.history, (state) => observe(`reach`, state)), + ), + check: forwardAssertionJudgment, +}) From 97dda1b865880e12045d807ccb05800988106bc4 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Mon, 23 Nov 2026 23:56:12 -0800 Subject: [PATCH 2/6] fix(offline-transactions): address Web Locks takeover review A request made after a release, before the released attempt's lock callback ran, joined that void attempt, so the tab neither led nor waited. A release now detaches the pending attempt. A listener that released leadership while being told its tab leads ran before the release handle existed, so the lock stayed held. The handle is now installed first, and changes a listener causes wait until every listener heard the current one. A takeover now starts its outbox replay before the application's leadership callback, so a throwing callback cannot skip it. --- .changeset/web-locks-leader-takeover.md | 2 +- docs/contributing/oracle-coverage.md | 4 +- .../src/OfflineExecutor.ts | 10 +- .../src/coordination/LeaderElection.ts | 30 +++-- .../src/coordination/WebLocksLeader.ts | 15 ++- .../tests/web-locks-failover.test.ts | 59 +++++++++ .../web-locks-leader-oracle.property.test.ts | 125 +++++++++++++++++- 7 files changed, 222 insertions(+), 23 deletions(-) diff --git a/.changeset/web-locks-leader-takeover.md b/.changeset/web-locks-leader-takeover.md index 4c94331899..421f3632fe 100644 --- a/.changeset/web-locks-leader-takeover.md +++ b/.changeset/web-locks-leader-takeover.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': patch --- -Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. +Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on, and a leadership callback that throws no longer stops the takeover's replay. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index b4486843e4..3dce5afdb4 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4243,7 +4243,9 @@ The post-merge review added three missing domains to existing owners: calibration protect that distinction. - [Web Locks leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts) checks FIFO takeover across three tabs that request, release and close over a - controlled lock manager. It does not cover real browser contexts. + controlled lock manager, including a request renewed after a release in one + turn and a listener that releases or throws when told its tab leads. It does + not cover real browser contexts. - [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts) holds real storage-read delivery across successful and permanently rejected durable removals, with bounded scans, concurrent loads, and unfinished peers. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 13ee818c9d..f904e4ef5d 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -243,15 +243,17 @@ export class OfflineExecutor { this.isLeaderState = isLeader if (!isLeader) this.executor?.pause() - if (this.config.onLeadershipChange) { - this.config.onLeadershipChange(isLeader) - } - + // Replay starts first, so a failing application callback cannot + // stop a takeover from sending the outbox. if (isLeader) { this.loadAndReplayTransactions().catch((error) => { console.warn(`Failed to load and replay transactions:`, error) }) } + + if (this.config.onLeadershipChange) { + this.config.onLeadershipChange(isLeader) + } }, ) } diff --git a/packages/offline-transactions/src/coordination/LeaderElection.ts b/packages/offline-transactions/src/coordination/LeaderElection.ts index 6223aef01f..af8d99705d 100644 --- a/packages/offline-transactions/src/coordination/LeaderElection.ts +++ b/packages/offline-transactions/src/coordination/LeaderElection.ts @@ -3,6 +3,9 @@ import type { LeaderElection } from '../types' export abstract class BaseLeaderElection implements LeaderElection { protected isLeaderState = false protected listeners: Set<(isLeader: boolean) => void> = new Set() + // Changes a listener causes wait until every listener heard the current one. + private notifying = false + private readonly queued: Array = [] abstract requestLeadership(): Promise abstract releaseLeadership(): void @@ -20,16 +23,27 @@ export abstract class BaseLeaderElection implements LeaderElection { } protected notifyLeadershipChange(isLeader: boolean): void { - if (this.isLeaderState !== isLeader) { - this.isLeaderState = isLeader - - for (const listener of this.listeners) { - try { - listener(isLeader) - } catch (error) { - console.warn(`Leadership change listener error:`, error) + this.queued.push(isLeader) + if (this.notifying) return + this.notifying = true + try { + for ( + let next = this.queued.shift(); + next !== undefined; + next = this.queued.shift() + ) { + if (this.isLeaderState === next) continue + this.isLeaderState = next + for (const listener of this.listeners) { + try { + listener(next) + } catch (error) { + console.warn(`Leadership change listener error:`, error) + } } } + } finally { + this.notifying = false } } } diff --git a/packages/offline-transactions/src/coordination/WebLocksLeader.ts b/packages/offline-transactions/src/coordination/WebLocksLeader.ts index dbbf20db80..4edf94a346 100644 --- a/packages/offline-transactions/src/coordination/WebLocksLeader.ts +++ b/packages/offline-transactions/src/coordination/WebLocksLeader.ts @@ -26,9 +26,13 @@ export class WebLocksLeader extends BaseLeaderElection { return false } - this.pendingRequest ??= this.acquireOrWait().finally(() => { - this.pendingRequest = null - }) + // Requests share one attempt until a release voids it. + if (!this.pendingRequest) { + const attempt = this.acquireOrWait().finally(() => { + if (this.pendingRequest === attempt) this.pendingRequest = null + }) + this.pendingRequest = attempt + } return this.pendingRequest } @@ -74,8 +78,10 @@ export class WebLocksLeader extends BaseLeaderElection { // An abort has no effect once the lock is granted. if (this.waiting !== waiting) return this.waiting = undefined + // Hold first, so a listener that releases on the gain lets go. + const held = this.holdLock() this.notifyLeadershipChange(true) - return this.holdLock() + return held }) .catch((error: unknown) => { if (waiting.signal.aborted) return @@ -95,6 +101,7 @@ export class WebLocksLeader extends BaseLeaderElection { releaseLeadership(): void { this.requestGeneration++ + this.pendingRequest = null if (this.waiting) { const waiting = this.waiting this.waiting = undefined diff --git a/packages/offline-transactions/tests/web-locks-failover.test.ts b/packages/offline-transactions/tests/web-locks-failover.test.ts index da21cbd683..fbeaaaed83 100644 --- a/packages/offline-transactions/tests/web-locks-failover.test.ts +++ b/packages/offline-transactions/tests/web-locks-failover.test.ts @@ -120,6 +120,65 @@ describe(`Web Locks failover through the executor`, () => { second.executor.dispose() }) + it(`a takeover replays even when the leadership callback throws`, async () => { + vi.stubGlobal(`navigator`, { locks: createLocks() }) + const warn = vi.spyOn(console, `warn`).mockImplementation(() => {}) + const storage = new FakeStorageAdapter() + const first = createTestOfflineEnvironment({ + storage, + config: { leaderElection: new WebLocksLeader(`failover-callback`) }, + mutationFn: () => { + throw new Error(`offline`) + }, + }) + await first.executor.waitForInit() + const transaction = first.executor.createOfflineTransaction({ + mutationFnName: first.mutationFnName, + autoCommit: false, + }) + transaction.mutate(() => { + first.collection.insert({ + id: `pending`, + value: `replay me`, + completed: false, + updatedAt: new Date(), + }) + }) + void transaction.commit().catch(() => undefined) + await waitUntil( + async () => (await first.executor.peekOutbox()).length === 1, + ) + + const replayed: Array = [] + const second = createTestOfflineEnvironment({ + storage, + config: { + leaderElection: new WebLocksLeader(`failover-callback`), + onLeadershipChange: (isLeader) => { + if (isLeader) throw new Error(`application callback failed`) + }, + }, + mutationFn: (params) => { + for (const mutation of params.transaction.mutations) { + replayed.push(String(mutation.key)) + } + second.applyMutations(params.transaction.mutations) + return { ok: true, mutations: params.transaction.mutations } + }, + }) + try { + await second.executor.waitForInit() + first.executor.dispose() + await waitUntil( + async () => (await second.executor.peekOutbox()).length === 0, + ) + expect(replayed).toEqual([`pending`]) + } finally { + warn.mockRestore() + second.executor.dispose() + } + }) + it(`a disposed waiter leaves the queue`, async () => { const locks = createLocks() vi.stubGlobal(`navigator`, { locks }) diff --git a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts index 13889cb971..0069c26376 100644 --- a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts +++ b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts @@ -12,12 +12,17 @@ * tab that finds it held reports false and waits. When the holder releases or * closes, the first waiter leads and is notified. A waiter that releases leaves * the queue and never leads, even when the lock was already granted to it. A - * failed lock request reports false, warns once, and leaves the tab idle. + * request after a release starts a new acquisition, even in the turn of an + * earlier one, and a tab that releases while it is told it leads passes the + * lock to the next waiter after every listener heard the gain. A listener that + * throws is warned about once. A failed lock request reports false, warns + * once, and leaves the tab idle. * * History grammar: up to fourteen actions over three tabs: request, two - * requests in one turn, a request released in the same turn, a failed first or - * queued lock request, release, close, and a close whose next waiter releases - * before its grant runs. A closed tab takes no further actions. An environment + * requests in one turn, a request released in the same turn, a request, + * release and request in one turn, a tab armed to release from, or throw in, + * its own gain notification, a failed first or queued lock request, release, close, and a + * close whose next waiter releases before its grant runs. A closed tab takes no further actions. An environment * can lack `navigator` or `navigator.locks`. * * Production driver: real `WebLocksLeader` instances over a controlled lock @@ -66,6 +71,12 @@ const reachStates = [ `released-after-grant`, // The environment has no usable Web Locks API. `unsupported-environment`, + // A request, release and request in one turn left the tab in the queue. + `request-renewed-after-release`, + // A tab released while it was told it leads, and the next waiter led. + `released-on-gain`, + // A listener threw when told its tab leads, and the others still heard it. + `listener-threw`, ] as const type ReachState = (typeof reachStates)[number] @@ -73,6 +84,9 @@ type ActionType = | `request` | `request-twice` | `request-then-release` + | `request-release-request` + | `release-on-gain` + | `throw-on-gain` | `fail-first` | `fail-queued` | `release` @@ -98,6 +112,11 @@ class LeadershipModel { () => [], ) warnings = 0 + // Tabs whose observer releases when it is told the tab leads. + readonly armed = new Set() + gainReleases = 0 + // Tabs with a listener that throws when told the tab leads. + readonly throwing = new Set() get holder(): number | undefined { const index = this.tabs.indexOf(`leader`) @@ -109,9 +128,31 @@ class LeadershipModel { if (next === undefined) return undefined this.tabs[next] = `leader` this.notifications[next]!.push(true) + // A throwing listener is warned about once; the others still hear it. + if (this.throwing.delete(next)) this.warnings += 1 + if (this.armed.delete(next)) { + // Every listener hears the gain, then the release passes the lock on. + this.gainReleases++ + this.tabs[next] = `idle` + this.notifications[next]!.push(false) + this.promoteNext() + } return next } + /** + * An idle tab requests, releases and requests again in one turn. The first + * attempt is void; the second finds that attempt's request ahead of it, so + * it reports false and waits, leading once the void attempt lets go. + */ + requestReleaseRequest(tab: number): Array { + const free = this.holder === undefined + this.tabs[tab] = `waiting` + this.queue.push(tab) + if (free) this.promoteNext() + return [false, false] + } + request(tab: number): boolean { const state = this.tabs[tab]! if (state === `leader`) return true @@ -168,6 +209,9 @@ const actionArbitrary: fc.Arbitrary = fc.record({ `request`, `request-twice`, `request-then-release`, + `request-release-request`, + `release-on-gain`, + `throw-on-gain`, `fail-first`, `fail-queued`, `release`, @@ -374,7 +418,17 @@ async function runHistory( const model = new LeadershipModel() const leaders = Array.from({ length: TABS }, () => new WebLocksLeader(LOCK)) const notifications: Array> = leaders.map(() => []) + const armed = new Set() + const throwing = new Set() leaders.forEach((leader, tab) => { + // Registered first, so a release here runs before later listeners + // hear the gain. + leader.onLeadershipChange((isLeader) => { + if (isLeader && armed.delete(tab)) leader.releaseLeadership() + }) + leader.onLeadershipChange((isLeader) => { + if (isLeader && throwing.delete(tab)) throw new Error(`listener failed`) + }) leader.onLeadershipChange((isLeader) => { notifications[tab]!.push(isLeader) }) @@ -407,6 +461,8 @@ async function runHistory( const leader = leaders[tab]! const request = () => observed(inTab(tab, () => leader.requestLeadership())) + const gainReleases = model.gainReleases + const warnings = model.warnings if (type === `request`) { if (state === `waiting`) reach(`repeated-request-while-waiting`) @@ -434,6 +490,26 @@ async function runHistory( ).not.toThrow() await settle() expect(outcome.value, `${label}: result`).toBe(expected) + } else if (type === `request-release-request`) { + if (state !== `idle`) continue + reach(`request-renewed-after-release`) + const expected = model.requestReleaseRequest(tab) + const first = request() + expect( + () => inTab(tab, () => leader.releaseLeadership()), + `${label}: release`, + ).not.toThrow() + const second = request() + await settle() + expect([first.value, second.value], `${label}: results`).toEqual( + expected, + ) + } else if (type === `release-on-gain`) { + model.armed.add(tab) + armed.add(tab) + } else if (type === `throw-on-gain`) { + model.throwing.add(tab) + throwing.add(tab) } else if (type === `fail-first`) { if (state !== `idle`) continue reach(`first-request-failed`) @@ -476,6 +552,13 @@ async function runHistory( ).not.toThrow() await settle() } + if (model.gainReleases > gainReleases) reach(`released-on-gain`) + if ( + type !== `fail-first` && + type !== `fail-queued` && + model.warnings > warnings + ) + reach(`listener-threw`) check(label) } } finally { @@ -487,7 +570,7 @@ async function runHistory( oracleProperty({ id: property, law: { - statement: `Exactly the first waiting tab takes over when the Web Locks leader releases or its context closes, and it is notified once. A tab that finds the lock free leads without a notification, repeated or concurrent requests keep one queue place, a tab that releases never leads afterward, and a failed lock request reports false and leaves the tab idle.`, + statement: `Exactly the first waiting tab takes over when the Web Locks leader releases or its context closes, and it is notified once. A tab that finds the lock free leads without a notification, repeated or concurrent requests keep one queue place, a tab that releases never leads afterward, a request after a release starts a new acquisition, a tab that releases while it is told it leads passes the lock on after every listener heard the gain, and a failed lock request reports false and leaves the tab idle.`, authority: `Issue #2463, docs/guides/offline-transactions.md "A follower can become the leader after the current leader leaves", and the Web Locks API request order.`, limits: `Three tabs and one exclusive lock over a controlled lock manager; up to fourteen actions; no steal or shared mode, and no real browser contexts.`, }, @@ -495,6 +578,7 @@ oracleProperty({ `src/coordination/WebLocksLeader.ts#WebLocksLeader.requestLeadership`, `src/coordination/WebLocksLeader.ts#WebLocksLeader.releaseLeadership`, `src/coordination/WebLocksLeader.ts#WebLocksLeader.isSupported`, + `src/coordination/LeaderElection.ts`, ], histories: { arbitrary: historyArbitrary, @@ -555,6 +639,37 @@ oracleProperty({ act(`request-then-release`, 2), ]), }, + { + name: `a request after a release in one turn waits again`, + enters: [`request-renewed-after-release`, `takeover-after-release`], + build: (generated: History): History => + spliced(generated, [ + act(`request-release-request`, 0), + act(`request-release-request`, 1), + act(`release`, 0), + ]), + }, + { + name: `a tab releases while it is told it leads`, + enters: [`released-on-gain`, `takeover-after-release`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`request`, 2), + act(`release-on-gain`, 1), + act(`release`, 0), + ]), + }, + { + name: `a listener throws when told its tab leads`, + enters: [`listener-threw`, `takeover-after-release`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`throw-on-gain`, 1), + act(`release`, 0), + ]), + }, { name: `failed lock requests leave the tab idle`, enters: [`first-request-failed`, `queued-request-failed`], From ed15e4ab3f22feca76b5666a7d68a21e2fda7552 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 02:46:07 -0800 Subject: [PATCH 3/6] fix(offline-transactions): requeue a tab that releases and requests on its gain A listener that released leadership and requested it again while being told its tab leads got true from the request: the loss notification was still queued, so the notified leader state was true. The tab then held no lock and waited for none. A request now checks whether the lock is held, which a release clears at once, so it reports false and queues behind the waiters. --- .changeset/web-locks-leader-takeover.md | 2 +- docs/contributing/oracle-coverage.md | 3 +- .../src/coordination/WebLocksLeader.ts | 4 +- .../web-locks-leader-oracle.property.test.ts | 60 +++++++++++++++++-- 4 files changed, 60 insertions(+), 9 deletions(-) diff --git a/.changeset/web-locks-leader-takeover.md b/.changeset/web-locks-leader-takeover.md index 421f3632fe..6bd944e6e7 100644 --- a/.changeset/web-locks-leader-takeover.md +++ b/.changeset/web-locks-leader-takeover.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': patch --- -Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on, and a leadership callback that throws no longer stops the takeover's replay. +Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once, and a leadership callback that throws no longer stops the takeover's replay. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 3dce5afdb4..17e1d03866 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4244,7 +4244,8 @@ The post-merge review added three missing domains to existing owners: - [Web Locks leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts) checks FIFO takeover across three tabs that request, release and close over a controlled lock manager, including a request renewed after a release in one - turn and a listener that releases or throws when told its tab leads. It does + turn and a listener that releases, releases and requests again, or throws + when told its tab leads. It does not cover real browser contexts. - [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts) holds real storage-read delivery across successful and permanently rejected diff --git a/packages/offline-transactions/src/coordination/WebLocksLeader.ts b/packages/offline-transactions/src/coordination/WebLocksLeader.ts index 4edf94a346..82e96a1ffc 100644 --- a/packages/offline-transactions/src/coordination/WebLocksLeader.ts +++ b/packages/offline-transactions/src/coordination/WebLocksLeader.ts @@ -18,7 +18,9 @@ export class WebLocksLeader extends BaseLeaderElection { return false } - if (this.isLeaderState) { + // Possession, not the notified state: a release clears the handle at + // once, while its notification can still wait behind the gain's. + if (this.releaseLock) { return true } diff --git a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts index 0069c26376..5ebdf50254 100644 --- a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts +++ b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts @@ -14,14 +14,16 @@ * the queue and never leads, even when the lock was already granted to it. A * request after a release starts a new acquisition, even in the turn of an * earlier one, and a tab that releases while it is told it leads passes the - * lock to the next waiter after every listener heard the gain. A listener that + * lock to the next waiter after every listener heard the gain. If it requests + * again in that same listener, the request reports false and queues behind the + * waiters already there. A listener that * throws is warned about once. A failed lock request reports false, warns * once, and leaves the tab idle. * * History grammar: up to fourteen actions over three tabs: request, two * requests in one turn, a request released in the same turn, a request, - * release and request in one turn, a tab armed to release from, or throw in, - * its own gain notification, a failed first or queued lock request, release, close, and a + * release and request in one turn, a tab armed to release from, release and + * request again from, or throw in, its own gain notification, a failed first or queued lock request, release, close, and a * close whose next waiter releases before its grant runs. A closed tab takes no further actions. An environment * can lack `navigator` or `navigator.locks`. * @@ -77,6 +79,8 @@ const reachStates = [ `released-on-gain`, // A listener threw when told its tab leads, and the others still heard it. `listener-threw`, + // A listener released and requested again when told its tab leads. + `rerequested-on-gain`, ] as const type ReachState = (typeof reachStates)[number] @@ -87,6 +91,7 @@ type ActionType = | `request-release-request` | `release-on-gain` | `throw-on-gain` + | `rerequest-on-gain` | `fail-first` | `fail-queued` | `release` @@ -117,6 +122,13 @@ class LeadershipModel { gainReleases = 0 // Tabs with a listener that throws when told the tab leads. readonly throwing = new Set() + // Tabs whose observer releases, then requests again, when told it leads. + readonly rerequesting = new Set() + // Each tab's expected results for those requests, in order. + readonly rerequests: Array> = Array.from( + { length: TABS }, + () => [], + ) get holder(): number | undefined { const index = this.tabs.indexOf(`leader`) @@ -130,7 +142,15 @@ class LeadershipModel { this.notifications[next]!.push(true) // A throwing listener is warned about once; the others still hear it. if (this.throwing.delete(next)) this.warnings += 1 - if (this.armed.delete(next)) { + if (this.rerequesting.delete(next)) { + // The release passes the lock on; the request finds it still held, so + // it reports false and queues behind the waiters already there. + this.tabs[next] = `waiting` + this.notifications[next]!.push(false) + this.rerequests[next]!.push(false) + this.queue.push(next) + this.promoteNext() + } else if (this.armed.delete(next)) { // Every listener hears the gain, then the release passes the lock on. this.gainReleases++ this.tabs[next] = `idle` @@ -212,6 +232,7 @@ const actionArbitrary: fc.Arbitrary = fc.record({ `request-release-request`, `release-on-gain`, `throw-on-gain`, + `rerequest-on-gain`, `fail-first`, `fail-queued`, `release`, @@ -420,11 +441,17 @@ async function runHistory( const notifications: Array> = leaders.map(() => []) const armed = new Set() const throwing = new Set() + const rerequesting = new Set() + const rerequests = leaders.map(() => [] as Array<{ value?: boolean }>) leaders.forEach((leader, tab) => { // Registered first, so a release here runs before later listeners // hear the gain. leader.onLeadershipChange((isLeader) => { - if (isLeader && armed.delete(tab)) leader.releaseLeadership() + if (!isLeader) return + if (rerequesting.delete(tab)) { + leader.releaseLeadership() + rerequests[tab]!.push(observed(leader.requestLeadership())) + } else if (armed.delete(tab)) leader.releaseLeadership() }) leader.onLeadershipChange((isLeader) => { if (isLeader && throwing.delete(tab)) throw new Error(`listener failed`) @@ -451,6 +478,10 @@ async function runHistory( `${label}: queue`, ).toEqual(model.queue) expect(warn, `${label}: warnings`).toHaveBeenCalledTimes(model.warnings) + expect( + rerequests.map((outcomes) => outcomes.map((outcome) => outcome.value)), + `${label}: requests made on a gain`, + ).toEqual(model.rerequests) } for (const [step, action] of history.actions.entries()) { @@ -462,6 +493,7 @@ async function runHistory( const request = () => observed(inTab(tab, () => leader.requestLeadership())) const gainReleases = model.gainReleases + const rerequestCount = model.rerequests.flat().length const warnings = model.warnings if (type === `request`) { @@ -510,6 +542,9 @@ async function runHistory( } else if (type === `throw-on-gain`) { model.throwing.add(tab) throwing.add(tab) + } else if (type === `rerequest-on-gain`) { + model.rerequesting.add(tab) + rerequesting.add(tab) } else if (type === `fail-first`) { if (state !== `idle`) continue reach(`first-request-failed`) @@ -553,6 +588,8 @@ async function runHistory( await settle() } if (model.gainReleases > gainReleases) reach(`released-on-gain`) + if (model.rerequests.flat().length > rerequestCount) + reach(`rerequested-on-gain`) if ( type !== `fail-first` && type !== `fail-queued` && @@ -570,7 +607,7 @@ async function runHistory( oracleProperty({ id: property, law: { - statement: `Exactly the first waiting tab takes over when the Web Locks leader releases or its context closes, and it is notified once. A tab that finds the lock free leads without a notification, repeated or concurrent requests keep one queue place, a tab that releases never leads afterward, a request after a release starts a new acquisition, a tab that releases while it is told it leads passes the lock on after every listener heard the gain, and a failed lock request reports false and leaves the tab idle.`, + statement: `Exactly the first waiting tab takes over when the Web Locks leader releases or its context closes, and it is notified once. A tab that finds the lock free leads without a notification, repeated or concurrent requests keep one queue place, a tab that releases never leads afterward, a request after a release starts a new acquisition, a tab that releases while it is told it leads passes the lock on after every listener heard the gain and, if it requests again there, reports false and queues behind the existing waiters, and a failed lock request reports false and leaves the tab idle.`, authority: `Issue #2463, docs/guides/offline-transactions.md "A follower can become the leader after the current leader leaves", and the Web Locks API request order.`, limits: `Three tabs and one exclusive lock over a controlled lock manager; up to fourteen actions; no steal or shared mode, and no real browser contexts.`, }, @@ -660,6 +697,17 @@ oracleProperty({ act(`release`, 0), ]), }, + { + name: `a tab releases and requests again while told it leads`, + enters: [`rerequested-on-gain`, `takeover-after-release`], + build: (generated: History): History => + spliced(generated, [ + ...contested, + act(`request`, 2), + act(`rerequest-on-gain`, 1), + act(`release`, 0), + ]), + }, { name: `a listener throws when told its tab leads`, enters: [`listener-threw`, `takeover-after-release`], From ede5337abd4cb74b7f5fa3c65b7179d9b9d4a2eb Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 03:16:07 -0800 Subject: [PATCH 4/6] fix(offline-transactions): update leader state at once, queue only delivery The notification queue held a loss behind the gain being delivered, and the leader state changed only when the loss reached listeners. A BroadcastChannel leader that released and requested again inside its gain notification still read as leader, so the request returned true and started no election. The state now changes when the change happens; only listener delivery is queued. A fixed oracle property drives the BroadcastChannel fallback through that release and request, and checks that a release while not leading notifies nothing. --- .changeset/web-locks-leader-takeover.md | 2 +- docs/contributing/oracle-coverage.md | 5 +- .../db/tests/property-registry/adapters.ts | 6 ++ .../src/coordination/LeaderElection.ts | 7 +- .../web-locks-leader-oracle.property.test.ts | 92 +++++++++++++++++++ 5 files changed, 106 insertions(+), 6 deletions(-) diff --git a/.changeset/web-locks-leader-takeover.md b/.changeset/web-locks-leader-takeover.md index 6bd944e6e7..593499ed9a 100644 --- a/.changeset/web-locks-leader-takeover.md +++ b/.changeset/web-locks-leader-takeover.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': patch --- -Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once, and a leadership callback that throws no longer stops the takeover's replay. +Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once (also with the BroadcastChannel fallback), and a leadership callback that throws no longer stops the takeover's replay. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 17e1d03866..f07c1d0db0 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4245,8 +4245,9 @@ The post-merge review added three missing domains to existing owners: checks FIFO takeover across three tabs that request, release and close over a controlled lock manager, including a request renewed after a release in one turn and a listener that releases, releases and requests again, or throws - when told its tab leads. It does - not cover real browser contexts. + when told its tab leads. A fixed property drives the BroadcastChannel + fallback through the same release and request. It does not cover real + browser contexts. - [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts) holds real storage-read delivery across successful and permanently rejected durable removals, with bounded scans, concurrent loads, and unfinished peers. diff --git a/packages/db/tests/property-registry/adapters.ts b/packages/db/tests/property-registry/adapters.ts index 1fc8e6c33f..f80b7ec082 100644 --- a/packages/db/tests/property-registry/adapters.ts +++ b/packages/db/tests/property-registry/adapters.ts @@ -51,6 +51,7 @@ export const properties: ReadonlyArray = [ `offline.settlement.restored`, `offline.settlement.started-peer`, `offline.connectivity-replay`, + `offline.leader-reentrant-reacquisition`, ] export const owners: ReadonlyArray = [ @@ -174,4 +175,9 @@ export const owners: ReadonlyArray = [ `offline`, `connectivity-replay`, ], + [ + `offline-transactions/tests/web-locks-leader-oracle.property.test.ts`, + `offline`, + `leader-reentrant-reacquisition`, + ], ] diff --git a/packages/offline-transactions/src/coordination/LeaderElection.ts b/packages/offline-transactions/src/coordination/LeaderElection.ts index af8d99705d..fd37ee8845 100644 --- a/packages/offline-transactions/src/coordination/LeaderElection.ts +++ b/packages/offline-transactions/src/coordination/LeaderElection.ts @@ -3,7 +3,8 @@ import type { LeaderElection } from '../types' export abstract class BaseLeaderElection implements LeaderElection { protected isLeaderState = false protected listeners: Set<(isLeader: boolean) => void> = new Set() - // Changes a listener causes wait until every listener heard the current one. + // The state changes at once; listeners hear changes in order, so one that a + // listener causes waits until every listener heard the current one. private notifying = false private readonly queued: Array = [] @@ -23,6 +24,8 @@ export abstract class BaseLeaderElection implements LeaderElection { } protected notifyLeadershipChange(isLeader: boolean): void { + if (this.isLeaderState === isLeader) return + this.isLeaderState = isLeader this.queued.push(isLeader) if (this.notifying) return this.notifying = true @@ -32,8 +35,6 @@ export abstract class BaseLeaderElection implements LeaderElection { next !== undefined; next = this.queued.shift() ) { - if (this.isLeaderState === next) continue - this.isLeaderState = next for (const listener of this.listeners) { try { listener(next) diff --git a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts index 5ebdf50254..b44d2abd5d 100644 --- a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts +++ b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts @@ -41,6 +41,7 @@ import { AsyncLocalStorage } from 'node:async_hooks' import fc from 'fast-check' import { expect, vi } from 'vitest' import { WebLocksLeader } from '../src/coordination/WebLocksLeader' +import { BroadcastChannelLeader } from '../src/coordination/BroadcastChannelLeader' import { forwardAssertionJudgment, recordAssertionJudgment, @@ -759,3 +760,94 @@ oracleProperty({ ), check: forwardAssertionJudgment, }) + +// The BroadcastChannel fallback shares the notification queue. A tab that +// releases and requests again while told it leads must not lead: its current +// state is cleared at once, the request starts a new election and reports +// false, and every listener hears the gain before the loss. +const reentrantProperty = `offline.leader-reentrant-reacquisition` + +async function runBroadcastReacquisition(): Promise { + vi.useFakeTimers() + // The leader schedules through window, which fake timers leave alone here. + const timers = [ + vi + .spyOn(window, `setTimeout`) + .mockImplementation(((callback: () => void, delay?: number) => + setTimeout(callback, delay)) as never), + vi + .spyOn(window, `setInterval`) + .mockImplementation(((callback: () => void, delay?: number) => + setInterval(callback, delay)) as never), + ] + const posted: Array = [] + class ControlledChannel { + constructor(readonly name: string) {} + addEventListener() {} + removeEventListener() {} + postMessage(message: { type: string }) { + posted.push(message.type) + } + close() {} + } + vi.stubGlobal(`BroadcastChannel`, ControlledChannel) + const leader = new BroadcastChannelLeader(`oracle-reentrant`) + const heard: Array = [] + let armed = true + let outcome: { value?: boolean } = {} + let leaderAfterRelease: boolean | undefined + let electionsAfterRequest = 0 + leader.onLeadershipChange((isLeader) => { + if (!isLeader || !armed) return + armed = false + leader.releaseLeadership() + outcome = observed(leader.requestLeadership()) + leaderAfterRelease = leader.isLeader() + electionsAfterRequest = posted.filter((type) => type === `election`).length + }) + leader.onLeadershipChange((isLeader) => { + heard.push(isLeader) + }) + try { + void leader.requestLeadership() + // No other tab answers, so the election claims leadership. + await vi.advanceTimersByTimeAsync(10_000) + expect(heard, `listeners heard the gain, then the loss`).toEqual([ + true, + false, + ]) + expect(leaderAfterRelease, `released at once`).toBe(false) + expect(electionsAfterRequest, `the request started an election`).toBe(2) + await vi.advanceTimersByTimeAsync(1_000) + expect(outcome.value, `the request result`).toBe(false) + // Disposing releases again; a tab that is not leading notifies nothing. + leader.dispose() + expect(heard, `a release while not leading`).toEqual([true, false]) + } finally { + leader.dispose() + for (const timer of timers) timer.mockRestore() + vi.useRealTimers() + vi.unstubAllGlobals() + } +} + +oracleProperty<{ name: string }, ReturnType>({ + id: reentrantProperty, + law: { + statement: `A BroadcastChannel leader that releases and requests leadership again inside its own gain notification stops leading at once, starts a new election, reports false, and its listeners hear the gain before the loss; a later release while not leading notifies nothing.`, + authority: `Issue #2463, docs/guides/offline-transactions.md "Storage and leadership", and the LeaderElection contract in packages/offline-transactions/src/types.ts.`, + limits: `One tab over a controlled channel with fake timers; no peer answers the election.`, + }, + owns: [ + `src/coordination/BroadcastChannelLeader.ts#BroadcastChannelLeader.requestLeadership`, + `src/coordination/LeaderElection.ts`, + ], + histories: [{ name: `release and request again while told it leads` }], + label: ({ name }) => name, + model: recordedAssertionJudgment, + driver: (history, observe) => + recordAssertionJudgment(reentrantProperty, history, observe, () => + runBroadcastReacquisition(), + ), + check: forwardAssertionJudgment, +}) From e3ece5e289563ad00d7dfe562953b2146561d761 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 03:41:55 -0800 Subject: [PATCH 5/6] test(offline-transactions): model the BroadcastChannel leader fallback The reentrant reacquisition example wrapped fixed expectations in a property runner. It is now an ordinary test, and a generated oracle compares the BroadcastChannel leader with a timeline model of its elections, heartbeats, request results and notifications, including listeners that release, or release and request again, when told the tab leads. The model found two reentrancy bugs. A claim was still announced, with heartbeats, after a listener released inside the gain notification, and the election timer cleared its handle after claiming, losing an election that a listener started. The claim now stops when the tab no longer leads, and the timer clears its handle first. --- .changeset/web-locks-leader-takeover.md | 2 +- docs/contributing/oracle-coverage.md | 9 +- packages/db/tests/oracle-config.ts | 1 + packages/db/tests/oracle-replay-manifest.ts | 5 + .../db/tests/property-registry/adapters.ts | 6 - .../coordination/BroadcastChannelLeader.ts | 6 +- ...ast-channel-leader-oracle.property.test.ts | 392 ++++++++++++++++++ .../tests/broadcast-channel-leader.test.ts | 80 ++++ .../web-locks-leader-oracle.property.test.ts | 92 ---- 9 files changed, 489 insertions(+), 104 deletions(-) create mode 100644 packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts create mode 100644 packages/offline-transactions/tests/broadcast-channel-leader.test.ts diff --git a/.changeset/web-locks-leader-takeover.md b/.changeset/web-locks-leader-takeover.md index 593499ed9a..2ac084ef75 100644 --- a/.changeset/web-locks-leader-takeover.md +++ b/.changeset/web-locks-leader-takeover.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': patch --- -Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once (also with the BroadcastChannel fallback), and a leadership callback that throws no longer stops the takeover's replay. +Let a follower tab take over when the Web Locks leader releases or closes. A tab that finds the lock held now waits in its queue, then becomes leader and replays the outbox instead of staying online-only until it reloads. A request made right after a release starts a new acquisition, a listener that releases leadership as it is told the tab leads passes the lock on and can queue again at once; with the BroadcastChannel fallback, such a release also leaves no claim or heartbeat behind, and a leadership callback that throws no longer stops the takeover's replay. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index f07c1d0db0..896423312d 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4245,9 +4245,12 @@ The post-merge review added three missing domains to existing owners: checks FIFO takeover across three tabs that request, release and close over a controlled lock manager, including a request renewed after a release in one turn and a listener that releases, releases and requests again, or throws - when told its tab leads. A fixed property drives the BroadcastChannel - fallback through the same release and request. It does not cover real - browser contexts. + when told its tab leads. It does not cover real browser contexts. +- [BroadcastChannel leadership](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts) + checks the fallback elector's requests, releases, elections and heartbeats on + one tab against a timeline model, including a listener that releases, or + releases and requests again, when told its tab leads. It does not cover peer + tabs or a real BroadcastChannel. - [Leadership replay](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/leadership-replay-oracle.property.test.ts) holds real storage-read delivery across successful and permanently rejected durable removals, with bounded scans, concurrent loads, and unfinished peers. diff --git a/packages/db/tests/oracle-config.ts b/packages/db/tests/oracle-config.ts index 543b5fd923..daa5f3b367 100644 --- a/packages/db/tests/oracle-config.ts +++ b/packages/db/tests/oracle-config.ts @@ -437,6 +437,7 @@ const staticOracleProperties = [ `offline.leadership.stale-read`, `offline.leadership.storage-failure`, `offline.web-locks-leader`, + `offline.broadcast-channel-leader`, `offline.serializer.mutation-wire`, `offline.serializer.date-marker`, `offline.serializer.version-two`, diff --git a/packages/db/tests/oracle-replay-manifest.ts b/packages/db/tests/oracle-replay-manifest.ts index bea27af169..c646919ee8 100644 --- a/packages/db/tests/oracle-replay-manifest.ts +++ b/packages/db/tests/oracle-replay-manifest.ts @@ -1801,6 +1801,11 @@ const ownerGroups: ReadonlyArray< `offline`, `web-locks-leader`, ], + [ + `offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts`, + `offline`, + `broadcast-channel-leader`, + ], [ `offline-transactions/tests/transaction-serializer-oracle.property.test.ts`, `offline`, diff --git a/packages/db/tests/property-registry/adapters.ts b/packages/db/tests/property-registry/adapters.ts index f80b7ec082..1fc8e6c33f 100644 --- a/packages/db/tests/property-registry/adapters.ts +++ b/packages/db/tests/property-registry/adapters.ts @@ -51,7 +51,6 @@ export const properties: ReadonlyArray = [ `offline.settlement.restored`, `offline.settlement.started-peer`, `offline.connectivity-replay`, - `offline.leader-reentrant-reacquisition`, ] export const owners: ReadonlyArray = [ @@ -175,9 +174,4 @@ export const owners: ReadonlyArray = [ `offline`, `connectivity-replay`, ], - [ - `offline-transactions/tests/web-locks-leader-oracle.property.test.ts`, - `offline`, - `leader-reentrant-reacquisition`, - ], ] diff --git a/packages/offline-transactions/src/coordination/BroadcastChannelLeader.ts b/packages/offline-transactions/src/coordination/BroadcastChannelLeader.ts index 7f50d06459..be5df75690 100644 --- a/packages/offline-transactions/src/coordination/BroadcastChannelLeader.ts +++ b/packages/offline-transactions/src/coordination/BroadcastChannelLeader.ts @@ -96,13 +96,13 @@ export class BroadcastChannelLeader extends BaseLeaderElection { }) this.electionTimeout = window.setTimeout(() => { + // Cleared first: a listener told of the claim may start the next one. + this.electionTimeout = null const timeSinceLastHeartbeat = Date.now() - this.lastLeaderHeartbeat if (timeSinceLastHeartbeat > this.electionTimeoutMs) { this.claimLeadership() } - - this.electionTimeout = null }, this.electionTimeoutMs) } @@ -115,6 +115,8 @@ export class BroadcastChannelLeader extends BaseLeaderElection { private claimLeadership(): void { this.notifyLeadershipChange(true) + // A listener may have released already, leaving nothing to announce. + if (!this.isLeaderState) return this.sendMessage({ type: `leadership-claim`, tabId: this.tabId, diff --git a/packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts b/packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts new file mode 100644 index 0000000000..33706b74f4 --- /dev/null +++ b/packages/offline-transactions/tests/broadcast-channel-leader-oracle.property.test.ts @@ -0,0 +1,392 @@ +/** + * # Does the BroadcastChannel leader fallback follow its own requests and + * releases, including from inside its own gain notification? + * + * Law and source: one tab leads outbox processing, and a tab that releases + * stops leading (docs/guides/offline-transactions.md, "Storage and + * leadership"; issue #2463). Without Web Locks, BroadcastChannelLeader elects + * a tab: a request that does not lead starts an election unless one is + * pending, and reports after one second whether the tab leads. With no other + * tab answering, the election claims leadership ten seconds after it starts, + * announces the claim and sends a heartbeat at once and every five seconds. A + * release stops the heartbeat, cancels a pending election and, if the tab led, + * reports the loss. The leader state changes at once; listeners hear changes in + * order, so a release inside a gain notification is heard after the gain. + * + * Model: a timeline of the election, heartbeat and request timers, ordered by + * due time and then by creation, as the timer queue orders them. A listener + * armed to release, or to release and request again, acts when the tab gains + * leadership, before the claim is announced. + * + * History grammar: up to fourteen actions on one tab: request, release, arm a + * listener to release or to release and request again on the next gain, and + * advance time by one, five or ten seconds. Each history ends by disposing the + * leader. + * + * Production driver: the real BroadcastChannelLeader over a controlled channel + * that records posted message types, with fake timers. + * + * Refinement check: after every action, the posted messages, each listener + * notification, every request result and the leader state equal the model. + * + * Known omissions: no peer tab, so no competing heartbeats, elections or + * claims, and no real BroadcastChannel. + */ +import fc from 'fast-check' +import { expect, vi } from 'vitest' +import { BroadcastChannelLeader } from '../src/coordination/BroadcastChannelLeader' +import { + forwardAssertionJudgment, + recordAssertionJudgment, + recordedAssertionJudgment, +} from '../../db/tests/oracle-assertion-adapter' +import { oracleProperty } from '../../db/tests/oracle-property' + +const property = `offline.broadcast-channel-leader` +const MAX_ACTIONS = 14 +const ELECTION_MS = 10_000 +const HEARTBEAT_MS = 5_000 +const REQUEST_MS = 1_000 + +const reachStates = [ + // An election claimed leadership. + `claimed`, + // A leader sent a later heartbeat. + `heartbeat-repeated`, + // A request reported that the tab leads. + `request-true`, + // A request reported that the tab does not lead. + `request-false`, + // A request found the tab already leading. + `request-while-leading`, + // A release cancelled a pending election. + `election-cancelled`, + // A listener released when told the tab leads. + `released-on-gain`, + // A listener released and requested again when told the tab leads. + `rerequested-on-gain`, +] as const +type ReachState = (typeof reachStates)[number] + +type Action = + | { type: `request` } + | { type: `release` } + | { type: `release-on-gain` } + | { type: `rerequest-on-gain` } + | { type: `advance`; ms: number } +type History = { actions: Array } + +// --------------------------------------------------------------------------- +// Model +// --------------------------------------------------------------------------- + +type Timer = { at: number; seq: number } + +class FallbackModel { + now = 0 + private seq = 0 + leader = false + private election: Timer | undefined + private heartbeat: Timer | undefined + private readonly pending: Array = [] + readonly results: Array = [] + readonly posted: Array = [] + readonly notifications: Array = [] + armed: `release` | `rerequest` | undefined + readonly reached = new Set() + + private timer(delay: number): Timer { + return { at: this.now + delay, seq: this.seq++ } + } + + request(): void { + const index = this.results.length + if (this.leader) { + this.results.push(true) + this.reached.add(`request-while-leading`) + return + } + this.results.push(undefined) + if (!this.election) { + this.posted.push(`election`) + this.election = this.timer(ELECTION_MS) + } + this.pending.push({ ...this.timer(REQUEST_MS), index }) + } + + release(): void { + this.heartbeat = undefined + if (this.election) this.reached.add(`election-cancelled`) + this.election = undefined + if (!this.leader) return + this.leader = false + this.notifications.push(false) + } + + private claim(): void { + this.leader = true + this.notifications.push(true) + const armed = this.armed + this.armed = undefined + if (armed !== undefined) { + this.reached.add( + armed === `release` ? `released-on-gain` : `rerequested-on-gain`, + ) + this.release() + if (armed === `rerequest`) this.request() + // A listener that released leaves nothing to announce. + return + } + this.reached.add(`claimed`) + this.posted.push(`leadership-claim`, `heartbeat`) + this.heartbeat = this.timer(HEARTBEAT_MS) + } + + advance(ms: number): void { + const until = this.now + ms + for (;;) { + const due = [this.election, this.heartbeat, ...this.pending] + .filter((timer): timer is Timer => timer !== undefined) + .filter((timer) => timer.at <= until) + .sort((a, b) => a.at - b.at || a.seq - b.seq)[0] + if (!due) break + this.now = due.at + if (due === this.election) { + this.election = undefined + this.claim() + } else if (due === this.heartbeat) { + this.reached.add(`heartbeat-repeated`) + this.posted.push(`heartbeat`) + this.heartbeat = { at: this.now + HEARTBEAT_MS, seq: due.seq } + } else { + const request = due as Timer & { index: number } + this.pending.splice(this.pending.indexOf(request), 1) + this.results[request.index] = this.leader + this.reached.add(this.leader ? `request-true` : `request-false`) + } + } + this.now = until + } +} + +// --------------------------------------------------------------------------- +// History grammar +// --------------------------------------------------------------------------- + +const actionArbitrary: fc.Arbitrary = fc.oneof( + { + weight: 3, + arbitrary: fc.record({ type: fc.constant(`request` as const) }), + }, + { + weight: 2, + arbitrary: fc.record({ type: fc.constant(`release` as const) }), + }, + { + weight: 1, + arbitrary: fc.record({ type: fc.constant(`release-on-gain` as const) }), + }, + { + weight: 1, + arbitrary: fc.record({ type: fc.constant(`rerequest-on-gain` as const) }), + }, + { + weight: 4, + arbitrary: fc.record({ + type: fc.constant(`advance` as const), + ms: fc.constantFrom(REQUEST_MS, HEARTBEAT_MS, ELECTION_MS), + }), + }, +) +const historyArbitrary: fc.Arbitrary = fc.record({ + actions: fc.array(actionArbitrary, { minLength: 1, maxLength: MAX_ACTIONS }), +}) + +const request: Action = { type: `request` } +const release: Action = { type: `release` } +const advance = (ms: number): Action => ({ type: `advance`, ms }) + +// --------------------------------------------------------------------------- +// Production driver +// --------------------------------------------------------------------------- + +async function runHistory( + history: History, + reach: (state: ReachState) => void, +): Promise { + vi.useFakeTimers() + // The leader schedules elections and heartbeats through window, which fake + // timers leave alone in this environment. + const timers = [ + vi + .spyOn(window, `setTimeout`) + .mockImplementation(((callback: () => void, delay?: number) => + setTimeout(callback, delay)) as never), + vi + .spyOn(window, `setInterval`) + .mockImplementation(((callback: () => void, delay?: number) => + setInterval(callback, delay)) as never), + ] + const posted: Array = [] + class ControlledChannel { + constructor(readonly name: string) {} + addEventListener() {} + removeEventListener() {} + postMessage(message: { type: string }) { + posted.push(message.type) + } + close() {} + } + vi.stubGlobal(`BroadcastChannel`, ControlledChannel) + const leader = new BroadcastChannelLeader(`oracle-fallback`) + const model = new FallbackModel() + const notifications: Array = [] + const results: Array<{ value?: boolean }> = [] + let armed: `release` | `rerequest` | undefined + const observe = (promise: Promise) => { + const outcome: { value?: boolean } = {} + results.push(outcome) + void promise.then((value) => { + outcome.value = value + }) + } + // Registered first, so it acts before later listeners hear the gain. + leader.onLeadershipChange((isLeader) => { + if (!isLeader || !armed) return + const action = armed + armed = undefined + leader.releaseLeadership() + if (action === `rerequest`) observe(leader.requestLeadership()) + }) + leader.onLeadershipChange((isLeader) => { + notifications.push(isLeader) + }) + + const check = (label: string) => { + expect(posted, `${label}: posted messages`).toEqual(model.posted) + expect(notifications, `${label}: notifications`).toEqual( + model.notifications, + ) + expect( + results.map((outcome) => outcome.value), + `${label}: request results`, + ).toEqual(model.results) + expect(leader.isLeader(), `${label}: leader`).toBe(model.leader) + } + + try { + for (const [step, action] of history.actions.entries()) { + const label = `step ${step} ${action.type}` + if (action.type === `request`) { + model.request() + observe(leader.requestLeadership()) + } else if (action.type === `release`) { + model.release() + leader.releaseLeadership() + } else if (action.type === `advance`) { + model.advance(action.ms) + await vi.advanceTimersByTimeAsync(action.ms) + } else { + armed = action.type === `release-on-gain` ? `release` : `rerequest` + model.armed = armed + } + // Settle resolved requests without moving time. + await vi.advanceTimersByTimeAsync(0) + check(label) + } + model.release() + leader.dispose() + check(`dispose`) + for (const state of model.reached) reach(state) + } finally { + leader.dispose() + for (const timer of timers) timer.mockRestore() + vi.useRealTimers() + vi.unstubAllGlobals() + } +} + +oracleProperty({ + id: property, + law: { + statement: `Without Web Locks, a request that does not lead starts an election unless one is pending and reports after one second whether the tab leads; an unanswered election claims leadership ten seconds after it starts and announces it with a heartbeat that repeats every five seconds; a release stops the heartbeat, cancels a pending election and reports a loss once. The leader state changes at once, a release or a new request inside the gain notification is heard after the gain and leaves no claim announced, and a release while not leading notifies nothing.`, + authority: `Issue #2463, docs/guides/offline-transactions.md "Storage and leadership", and the LeaderElection contract in packages/offline-transactions/src/types.ts.`, + limits: `One tab over a controlled channel with fake timers; up to fourteen actions; no peer tab and no real BroadcastChannel.`, + }, + owns: [ + `src/coordination/BroadcastChannelLeader.ts`, + `src/coordination/LeaderElection.ts`, + ], + histories: { + arbitrary: historyArbitrary, + runs: 60, + fixedSeeds: [2463], + states: reachStates, + constructed: [ + { + name: `an election claims, heartbeats and is released`, + enters: [ + `claimed`, + `heartbeat-repeated`, + `request-true`, + `request-false`, + `request-while-leading`, + ], + build: (): History => ({ + actions: [ + request, + advance(HEARTBEAT_MS), + advance(REQUEST_MS), + advance(REQUEST_MS), + advance(REQUEST_MS), + advance(REQUEST_MS), + request, + advance(REQUEST_MS), + request, + advance(HEARTBEAT_MS), + release, + ], + }), + }, + { + name: `a release cancels a pending election`, + enters: [`election-cancelled`], + build: (): History => ({ + actions: [request, release, advance(ELECTION_MS)], + }), + }, + { + name: `a listener releases when told the tab leads`, + enters: [`released-on-gain`], + build: (): History => ({ + actions: [ + { type: `release-on-gain` }, + request, + advance(ELECTION_MS), + advance(ELECTION_MS), + ], + }), + }, + { + name: `a listener releases and requests again when told the tab leads`, + enters: [`rerequested-on-gain`, `request-false`, `claimed`], + build: (): History => ({ + actions: [ + { type: `rerequest-on-gain` }, + request, + advance(ELECTION_MS), + advance(REQUEST_MS), + advance(ELECTION_MS), + ], + }), + }, + ], + }, + resolve: (history: History) => ({ history }), + model: recordedAssertionJudgment, + driver: (plan: { history: History }, observe) => + recordAssertionJudgment(property, plan, observe, () => + runHistory(plan.history, (state) => observe(`reach`, state)), + ), + check: forwardAssertionJudgment, +}) diff --git a/packages/offline-transactions/tests/broadcast-channel-leader.test.ts b/packages/offline-transactions/tests/broadcast-channel-leader.test.ts new file mode 100644 index 0000000000..f4d4458717 --- /dev/null +++ b/packages/offline-transactions/tests/broadcast-channel-leader.test.ts @@ -0,0 +1,80 @@ +// Supplemental example for the BroadcastChannel fallback. The law-driven +// coverage is broadcast-channel-leader-oracle.property.test.ts. +import { describe, expect, it, vi } from 'vitest' +import { BroadcastChannelLeader } from '../src/coordination/BroadcastChannelLeader' + +const observed = (result: Promise) => { + const outcome: { value?: boolean } = {} + void result.then((value) => { + outcome.value = value + }) + return outcome +} + +describe(`BroadcastChannelLeader`, () => { + it(`releases and queues a new election when a gain listener releases and requests again`, async () => { + vi.useFakeTimers() + // The leader schedules through window, which fake timers leave alone here. + const timers = [ + vi + .spyOn(window, `setTimeout`) + .mockImplementation(((callback: () => void, delay?: number) => + setTimeout(callback, delay)) as never), + vi + .spyOn(window, `setInterval`) + .mockImplementation(((callback: () => void, delay?: number) => + setInterval(callback, delay)) as never), + ] + const posted: Array = [] + class ControlledChannel { + constructor(readonly name: string) {} + addEventListener() {} + removeEventListener() {} + postMessage(message: { type: string }) { + posted.push(message.type) + } + close() {} + } + vi.stubGlobal(`BroadcastChannel`, ControlledChannel) + const leader = new BroadcastChannelLeader(`oracle-reentrant`) + const heard: Array = [] + let armed = true + let outcome: { value?: boolean } = {} + let leaderAfterRelease: boolean | undefined + let electionsAfterRequest = 0 + leader.onLeadershipChange((isLeader) => { + if (!isLeader || !armed) return + armed = false + leader.releaseLeadership() + outcome = observed(leader.requestLeadership()) + leaderAfterRelease = leader.isLeader() + electionsAfterRequest = posted.filter( + (type) => type === `election`, + ).length + }) + leader.onLeadershipChange((isLeader) => { + heard.push(isLeader) + }) + try { + void leader.requestLeadership() + // No other tab answers, so the election claims leadership. + await vi.advanceTimersByTimeAsync(10_000) + expect(heard, `listeners heard the gain, then the loss`).toEqual([ + true, + false, + ]) + expect(leaderAfterRelease, `released at once`).toBe(false) + expect(electionsAfterRequest, `the request started an election`).toBe(2) + await vi.advanceTimersByTimeAsync(1_000) + expect(outcome.value, `the request result`).toBe(false) + // Disposing releases again; a tab that is not leading notifies nothing. + leader.dispose() + expect(heard, `a release while not leading`).toEqual([true, false]) + } finally { + leader.dispose() + for (const timer of timers) timer.mockRestore() + vi.useRealTimers() + vi.unstubAllGlobals() + } + }) +}) diff --git a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts index b44d2abd5d..5ebdf50254 100644 --- a/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts +++ b/packages/offline-transactions/tests/web-locks-leader-oracle.property.test.ts @@ -41,7 +41,6 @@ import { AsyncLocalStorage } from 'node:async_hooks' import fc from 'fast-check' import { expect, vi } from 'vitest' import { WebLocksLeader } from '../src/coordination/WebLocksLeader' -import { BroadcastChannelLeader } from '../src/coordination/BroadcastChannelLeader' import { forwardAssertionJudgment, recordAssertionJudgment, @@ -760,94 +759,3 @@ oracleProperty({ ), check: forwardAssertionJudgment, }) - -// The BroadcastChannel fallback shares the notification queue. A tab that -// releases and requests again while told it leads must not lead: its current -// state is cleared at once, the request starts a new election and reports -// false, and every listener hears the gain before the loss. -const reentrantProperty = `offline.leader-reentrant-reacquisition` - -async function runBroadcastReacquisition(): Promise { - vi.useFakeTimers() - // The leader schedules through window, which fake timers leave alone here. - const timers = [ - vi - .spyOn(window, `setTimeout`) - .mockImplementation(((callback: () => void, delay?: number) => - setTimeout(callback, delay)) as never), - vi - .spyOn(window, `setInterval`) - .mockImplementation(((callback: () => void, delay?: number) => - setInterval(callback, delay)) as never), - ] - const posted: Array = [] - class ControlledChannel { - constructor(readonly name: string) {} - addEventListener() {} - removeEventListener() {} - postMessage(message: { type: string }) { - posted.push(message.type) - } - close() {} - } - vi.stubGlobal(`BroadcastChannel`, ControlledChannel) - const leader = new BroadcastChannelLeader(`oracle-reentrant`) - const heard: Array = [] - let armed = true - let outcome: { value?: boolean } = {} - let leaderAfterRelease: boolean | undefined - let electionsAfterRequest = 0 - leader.onLeadershipChange((isLeader) => { - if (!isLeader || !armed) return - armed = false - leader.releaseLeadership() - outcome = observed(leader.requestLeadership()) - leaderAfterRelease = leader.isLeader() - electionsAfterRequest = posted.filter((type) => type === `election`).length - }) - leader.onLeadershipChange((isLeader) => { - heard.push(isLeader) - }) - try { - void leader.requestLeadership() - // No other tab answers, so the election claims leadership. - await vi.advanceTimersByTimeAsync(10_000) - expect(heard, `listeners heard the gain, then the loss`).toEqual([ - true, - false, - ]) - expect(leaderAfterRelease, `released at once`).toBe(false) - expect(electionsAfterRequest, `the request started an election`).toBe(2) - await vi.advanceTimersByTimeAsync(1_000) - expect(outcome.value, `the request result`).toBe(false) - // Disposing releases again; a tab that is not leading notifies nothing. - leader.dispose() - expect(heard, `a release while not leading`).toEqual([true, false]) - } finally { - leader.dispose() - for (const timer of timers) timer.mockRestore() - vi.useRealTimers() - vi.unstubAllGlobals() - } -} - -oracleProperty<{ name: string }, ReturnType>({ - id: reentrantProperty, - law: { - statement: `A BroadcastChannel leader that releases and requests leadership again inside its own gain notification stops leading at once, starts a new election, reports false, and its listeners hear the gain before the loss; a later release while not leading notifies nothing.`, - authority: `Issue #2463, docs/guides/offline-transactions.md "Storage and leadership", and the LeaderElection contract in packages/offline-transactions/src/types.ts.`, - limits: `One tab over a controlled channel with fake timers; no peer answers the election.`, - }, - owns: [ - `src/coordination/BroadcastChannelLeader.ts#BroadcastChannelLeader.requestLeadership`, - `src/coordination/LeaderElection.ts`, - ], - histories: [{ name: `release and request again while told it leads` }], - label: ({ name }) => name, - model: recordedAssertionJudgment, - driver: (history, observe) => - recordAssertionJudgment(reentrantProperty, history, observe, () => - runBroadcastReacquisition(), - ), - check: forwardAssertionJudgment, -}) From a2539c7a01146540ac4f96fb711f3b876d3ea118 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Thu, 26 Nov 2026 15:41:16 -0800 Subject: [PATCH 6/6] test(offline-transactions): dispose failover executors after each test An executor created by a failover test was disposed only on the success path, so a failed assertion left its retry timer running. Each executor is now registered when created and disposed in teardown; dispose tolerates a second call. --- .../tests/web-locks-failover.test.ts | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/offline-transactions/tests/web-locks-failover.test.ts b/packages/offline-transactions/tests/web-locks-failover.test.ts index fbeaaaed83..0293aa4989 100644 --- a/packages/offline-transactions/tests/web-locks-failover.test.ts +++ b/packages/offline-transactions/tests/web-locks-failover.test.ts @@ -56,15 +56,30 @@ const createLocks = () => { } } +// Disposed after each test too, so a failed assertion stops their retries. +const environments: Array> = [] +const createEnvironment = ( + options: Parameters[0], +) => { + const environment = createTestOfflineEnvironment(options) + environments.push(environment) + return environment +} + describe(`Web Locks failover through the executor`, () => { - afterEach(() => vi.unstubAllGlobals()) + afterEach(() => { + for (const environment of environments.splice(0)) { + environment.executor.dispose() + } + vi.unstubAllGlobals() + }) it(`a waiting executor takes over and replays the outbox`, async () => { vi.stubGlobal(`navigator`, { locks: createLocks() }) const storage = new FakeStorageAdapter() const leadership: Array = [] - const first = createTestOfflineEnvironment({ + const first = createEnvironment({ storage, config: { leaderElection: new WebLocksLeader(`failover`) }, mutationFn: () => { @@ -92,7 +107,7 @@ describe(`Web Locks failover through the executor`, () => { ) const replayed: Array = [] - const second = createTestOfflineEnvironment({ + const second = createEnvironment({ storage, config: { leaderElection: new WebLocksLeader(`failover`), @@ -124,7 +139,7 @@ describe(`Web Locks failover through the executor`, () => { vi.stubGlobal(`navigator`, { locks: createLocks() }) const warn = vi.spyOn(console, `warn`).mockImplementation(() => {}) const storage = new FakeStorageAdapter() - const first = createTestOfflineEnvironment({ + const first = createEnvironment({ storage, config: { leaderElection: new WebLocksLeader(`failover-callback`) }, mutationFn: () => { @@ -150,7 +165,7 @@ describe(`Web Locks failover through the executor`, () => { ) const replayed: Array = [] - const second = createTestOfflineEnvironment({ + const second = createEnvironment({ storage, config: { leaderElection: new WebLocksLeader(`failover-callback`),