From 68939e50462dac2384cd23e747f7c2c932544652 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Mon, 23 Nov 2026 05:50:52 -0800 Subject: [PATCH 01/16] feat(offline-transactions): add durable follower writes --- .changeset/durable-follower-writes.md | 5 + docs/contributing/oracle-coverage.md | 5 + docs/guides/offline-transactions.md | 2 + packages/db/tests/oracle-config.ts | 1 + packages/db/tests/oracle-replay-manifest.ts | 5 + packages/offline-transactions/README.md | 2 +- .../src/OfflineExecutor.ts | 136 ++- .../src/executor/TransactionExecutor.ts | 10 + packages/offline-transactions/src/types.ts | 8 + .../durable-follower-oracle.property.test.ts | 772 ++++++++++++++++++ 10 files changed, 939 insertions(+), 7 deletions(-) create mode 100644 .changeset/durable-follower-writes.md create mode 100644 packages/offline-transactions/tests/durable-follower-oracle.property.test.ts diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md new file mode 100644 index 0000000000..d9aab47064 --- /dev/null +++ b/.changeset/durable-follower-writes.md @@ -0,0 +1,5 @@ +--- +'@tanstack/offline-transactions': minor +--- + +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The default stays `'online'`. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index aa55120c43..5918bb99fa 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4245,6 +4245,11 @@ The post-merge review added three missing domains to existing owners: holds real storage-read delivery across successful and permanently rejected durable removals, with bounded scans, concurrent loads, and unfinished peers. This is distinct from exactly-once execution across independent owners. +- [Durable follower writes](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts) + checks delivery and settlement of `followerWrites: 'durable'` across three + tabs that write, close, reopen and hand over leadership, with controlled + election, connectivity and BroadcastChannel. It does not cover real browser + contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index d72ef8e82b..24d74a9beb 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,6 +189,8 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. If a leader closes between removing a row and reporting its result, the next leader reports that write as completed. + Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. ## React Native and Expo diff --git a/packages/db/tests/oracle-config.ts b/packages/db/tests/oracle-config.ts index f01a5b607f..6c47f88ee0 100644 --- a/packages/db/tests/oracle-config.ts +++ b/packages/db/tests/oracle-config.ts @@ -431,6 +431,7 @@ const staticOracleProperties = [ `offline.executor-connectivity-barrier`, `offline.executor-connectivity-query-db`, `offline.executor-environment`, + `offline.durable-follower-writes`, `offline.fifo-retry`, `offline.leadership.serial-work`, `offline.leadership.report`, diff --git a/packages/db/tests/oracle-replay-manifest.ts b/packages/db/tests/oracle-replay-manifest.ts index 40ba366459..464c81e635 100644 --- a/packages/db/tests/oracle-replay-manifest.ts +++ b/packages/db/tests/oracle-replay-manifest.ts @@ -1791,6 +1791,11 @@ const ownerGroups: ReadonlyArray< `executor-environment`, `offline-transactions/tests/executor-environment-oracle.ts`, ], + [ + `offline-transactions/tests/durable-follower-oracle.property.test.ts`, + `offline`, + `durable-follower-writes`, + ], [ `offline-transactions/tests/fifo-retry-oracle.property.test.ts`, `offline`, diff --git a/packages/offline-transactions/README.md b/packages/offline-transactions/README.md index b522c95246..5f583c92b0 100644 --- a/packages/offline-transactions/README.md +++ b/packages/offline-transactions/README.md @@ -109,7 +109,7 @@ An optimistic change does not prove that the outbox write succeeded. Handle tran Only one tab acts as the "leader" to safely manage the outbox: - **Leader tab**: Full offline support with outbox persistence -- **Non-leader tabs**: Online-only mode for safety +- **Non-leader tabs**: Online-only mode by default, or a shared durable outbox with `followerWrites: 'durable'` - **Leadership transfer**: Automatic failover when leader tab closes ### FIFO Sequential Processing diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 13ee818c9d..d3df5155ca 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -40,6 +40,21 @@ import type { } from './types' import type { Transaction } from '@tanstack/db' +/** Messages between tabs that share an outbox with durable follower writes. */ +type OutboxMessage = + | { type: `added`; id: string } + | { type: `settled`; id: string; error?: { name: string; message: string } } + | { type: `leader` } + +function outboxMessageError(error: { name: string; message: string }): Error { + const restored = + error.name === `NonRetriableError` + ? new NonRetriableError(error.message) + : new Error(error.message) + restored.name = error.name + return restored +} + /** How many settled ids an executor remembers to reject late waiters. */ const SETTLED_TRANSACTIONS_REMEMBERED = 1000 @@ -92,6 +107,8 @@ export class OfflineExecutor { promise: Promise resolve: (result: any) => void reject: (error: Error) => void + // Set once a follower's save starts; resolves to whether it succeeded. + saved?: Promise } > = new Map() @@ -104,6 +121,8 @@ export class OfflineExecutor { // Track restoration transactions for cleanup when offline transactions complete private restorationTransactions: Map = new Map() + // Carries follower writes to the leader and their outcomes back. + private outboxChannel: BroadcastChannel | null = null constructor(config: OfflineConfig) { this.config = config this.scheduler = new KeyScheduler() @@ -329,6 +348,7 @@ export class OfflineExecutor { this, ) this.leaderElection = this.createLeaderElection() + this.openOutboxChannel() // Request leadership first const isLeader = await this.leaderElection.requestLeadership() @@ -368,12 +388,86 @@ export class OfflineExecutor { // Startup must observe a failed read instead of reporting an empty outbox. await this.executor.loadPendingTransactions() + // A leader that closed can leave a removed row with an undelivered outcome. + if (this.outboxChannel) { + this.outboxChannel.postMessage({ + type: `leader`, + } satisfies OutboxMessage) + } + this.reconcileFollowerWrites() + // Replay completion is separate from initialization and durable admission. this.executor.executeAll().catch((error) => { console.warn(`Failed to execute transactions:`, error) }) } + private openOutboxChannel(): void { + if ( + this.config.followerWrites !== `durable` || + typeof BroadcastChannel === `undefined` + ) { + return + } + const collectionIds = Object.values(this.config.collections) + .map((collection) => collection.id) + .sort() + this.outboxChannel = new BroadcastChannel( + `tanstack-offline-outbox:${collectionIds.join(`,`)}`, + ) + this.outboxChannel.onmessage = (event: MessageEvent) => { + this.handleOutboxMessage(event.data) + } + } + + private handleOutboxMessage(message: OutboxMessage): void { + if (message.type === `leader`) { + this.reconcileFollowerWrites() + } else if (message.type === `added`) { + this.executor!.admitTransaction(message.id).catch((error) => { + console.warn(`Failed to run follower write:`, error) + }) + } else { + this.settleTransaction( + message.id, + undefined, + message.error && outboxMessageError(message.error), + ) + } + } + + private reconcileFollowerWrites(): void { + this.settleRemovedWrites().catch((error) => { + console.warn(`Failed to reconcile follower writes:`, error) + }) + } + + // A saved write that left the outbox was settled by a leader whose message + // never arrived. + private async settleRemovedWrites(): Promise { + for (const [id, waiter] of [...this.pendingTransactionPromises]) { + if (!(await waiter.saved)) continue + if (await this.outbox!.get(id)) continue + this.settleTransaction(id, undefined) + } + } + + private announceSettled(id: string, error?: Error): void { + if (this.outboxChannel) { + this.outboxChannel.postMessage({ + type: `settled`, + id, + ...(error + ? { error: { name: error.name, message: error.message } } + : {}), + } satisfies OutboxMessage) + } + } + + private get writesToSharedOutbox(): boolean { + return this.outboxChannel !== null + } + get isOfflineEnabled(): boolean { return !this.disposed && this.mode === `offline` && this.isLeaderState } @@ -396,7 +490,7 @@ export class OfflineExecutor { } // Check leadership immediately and use the appropriate primitive - if (!this.isOfflineEnabled) { + if (!this.isOfflineEnabled && !this.writesToSharedOutbox) { // Non-leader: use createTransaction directly with the resolved mutation function // We need to wrap it to add the idempotency key return createTransaction({ @@ -429,7 +523,7 @@ export class OfflineExecutor { // Return a wrapper that checks leadership status at call time return (variables: T) => { // Check leadership when action is called, not when it's created - if (!this.isOfflineEnabled) { + if (!this.isOfflineEnabled && !this.writesToSharedOutbox) { // Non-leader: use createOptimisticAction directly const action = createOptimisticAction({ mutationFn: (vars, params) => @@ -460,13 +554,30 @@ export class OfflineExecutor { // Wait for initialization to complete await this.initPromise - if (!this.isOfflineEnabled || !this.outbox || !this.executor) { + if ( + (!this.isOfflineEnabled && !this.writesToSharedOutbox) || + !this.outbox || + !this.executor + ) { throw new NonRetriableError(`Offline transaction was not admitted`) } try { this.executor.assertHealthy() - await this.outbox.add(transaction) + const saved = this.outbox.add(transaction) + // The transaction registered this waiter before it asked to persist. + this.pendingTransactionPromises.get(transaction.id)!.saved = saved.then( + () => true, + () => false, + ) + await saved + if (this.outboxChannel && !this.isOfflineEnabled) { + this.outboxChannel.postMessage({ + type: `added`, + id: transaction.id, + } satisfies OutboxMessage) + return + } // A shared queue error belongs to its execution, not every caller // that durably admitted a transaction. Per-ID signals settle callers. this.executor.execute(transaction).catch((error) => { @@ -518,12 +629,20 @@ export class OfflineExecutor { // Method for TransactionExecutor to signal completion resolveTransaction(transactionId: string, result: any): void { - this.settleTransaction(transactionId, result) + try { + this.settleTransaction(transactionId, result) + } finally { + this.announceSettled(transactionId) + } } // Method for TransactionExecutor to signal failure rejectTransaction(transactionId: string, error: Error): void { - this.settleTransaction(transactionId, undefined, error) + try { + this.settleTransaction(transactionId, undefined, error) + } finally { + this.announceSettled(transactionId, error) + } } private trackCompletion(): void { @@ -699,6 +818,11 @@ export class OfflineExecutor { } } + if (this.outboxChannel) { + this.outboxChannel.close() + this.outboxChannel = null + } + this.onlineDetector.dispose() } } diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index ff13791a6d..4909dcaa28 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -428,6 +428,16 @@ export class TransactionExecutor { } } + /** Runs one transaction that a follower tab saved to the shared outbox. */ + async admitTransaction(id: string): Promise { + const transaction = await this.outbox.get(id) + if (!transaction || !this.offlineExecutor.isOfflineEnabled) return + // A duplicate message is harmless: both steps ignore a known transaction. + this.scheduler.schedule(transaction) + this.restoreOptimisticState([transaction]) + await this.executeAll() + } + /** * Restore optimistic state from loaded transactions. * Creates internal transactions to hold the mutations so the collection's diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index 15f625ae83..369f64b4f6 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -129,6 +129,14 @@ export interface OfflineConfig { onLeadershipChange?: (isLeader: boolean) => void onStorageFailure?: (diagnostic: StorageDiagnostic) => void leaderElection?: LeaderElection + /** + * How a follower tab sends a write. `'online'` (default) calls the mutation + * function directly, with no outbox entry. `'durable'` saves the write to the + * shared outbox, and the current or next leader sends it. Requires + * BroadcastChannel, and falls back to `'online'` without it. A write made + * before the executor initializes uses the online path. + */ + followerWrites?: `online` | `durable` /** * Custom online detector implementation. * Defaults to WebOnlineDetector for browser environments. diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts new file mode 100644 index 0000000000..894ef765a4 --- /dev/null +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -0,0 +1,772 @@ +/** + * # Does a follower's write survive with `followerWrites: 'durable'`? + * + * Law and source: issue #2464 asks that a write from a follower tab not depend + * on which tab leads. With `followerWrites: 'durable'`, a follower saves its + * write to the shared outbox before the write can be lost, the current or next + * leader sends it, and the writing tab's transaction settles with its outcome. + * The default, `'online'`, keeps the documented follower path with no outbox + * entry and no channel. + * + * Model: in durable mode, every write made from an initialized tab is delivered + * once after some tab leads while online, whether or not its tab is still open. + * It stays pending until then, and the leader shows it optimistically. A write + * the server rejects permanently fails in its open tab with the server's error, + * and every other write completes. When a settlement message is lost, the next + * leader's outbox check settles the waiter. Stale and duplicate channel + * messages change nothing. In online mode, a follower's write made offline + * fails and is never sent. + * + * History grammar: a mode and up to twelve actions over three tabs: write, a + * write the server rejects, a write whose save is held or fails while a leader + * message arrives, close a tab, reopen a tab, go online or offline, + * lose the next successful settlement, deliver a stale or duplicate message, + * and fail the storage read of an admission or an outbox check. + * + * Production driver: real executors over one shared storage adapter, with a + * controlled leader election, online detector and BroadcastChannel. + * + * Refinement check: after every action, pending writes stay pending and shown + * by the leader, open channels match open tabs, and warnings match the injected + * failures. After the history ends online with a leader, each deliverable write + * reached the server exactly once, the outbox is empty, and each open tab's + * transaction has the model's outcome and error. + * + * Known omissions: writes made before a tab initializes use the online path; a + * reloaded follower does not show another tab's pending writes optimistically; + * a settlement lost for a permanently rejected write would report success; and + * no real browser contexts. + */ +import fc from 'fast-check' +import { expect, vi } from 'vitest' +import { NonRetriableError } from '../src/types' +import { + forwardAssertionJudgment, + recordAssertionJudgment, + recordedAssertionJudgment, +} from '../../db/tests/oracle-assertion-adapter' +import { oracleProperty } from '../../db/tests/oracle-property' +import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness' +import type { + LeaderElection, + OfflineMutationFnParams, + OnlineDetector, +} from '../src/types' + +const property = `offline.durable-follower-writes` +const TABS = 3 +const MAX_ACTIONS = 12 +const CHANNEL = `tanstack-offline-outbox:test-items` + +const reachStates = [ + // A follower's write reached the server through the leader. + `follower-write-delivered`, + // A follower wrote offline and closed before the write was sent. + `write-outlived-its-tab`, + // The leader closed while holding a follower's unsent write. + `leader-closed-with-follower-write`, + // The server rejected a follower's write and its tab saw the failure. + `follower-write-rejected`, + // A lost settlement message was recovered by the next leader. + `lost-settlement-recovered`, + // A tab that stayed a follower recovered a lost settlement. + `lost-settlement-recovered-by-follower`, + // A follower's write used the default online path while offline. + `online-mode-follower-write-failed`, + // A message named a write that is no longer in the outbox. + `stale-message-ignored`, + // A second message named a write that is still queued. + `duplicate-message-ignored`, + // An admission's storage read failed. + `admission-read-failed`, + // An outbox check's storage read failed. + `outbox-check-read-failed`, + // A leader message arrived while a write was still being saved. + `leader-message-during-save`, + // A follower's save failed after a leader message arrived. + `follower-save-failed`, + // A leader's write completed in the default mode. + `online-mode-leader-write-delivered`, +] as const +type ReachState = (typeof reachStates)[number] + +type TabActionType = + | `write` + | `write-rejected` + | `write-during-leader-message` + | `write-save-fails` + | `close` + | `open` +type SharedActionType = + | `online` + | `offline` + | `lose-settlement` + | `stale-added` + | `duplicate-added` + | `fail-admission-read` + | `fail-outbox-check` +type Action = { type: TabActionType; tab: number } | { type: SharedActionType } +type Mode = `durable` | `online` +type History = { mode: Mode; actions: Array } + +// --------------------------------------------------------------------------- +// History grammar +// --------------------------------------------------------------------------- + +const tabAction = (type: TabActionType) => + fc.record({ type: fc.constant(type), tab: fc.nat({ max: TABS - 1 }) }) +const sharedAction = (type: SharedActionType) => + fc.record({ type: fc.constant(type) }) +const actionArbitrary: fc.Arbitrary = fc.oneof( + { weight: 6, arbitrary: tabAction(`write`) }, + { weight: 1, arbitrary: tabAction(`write-rejected`) }, + { weight: 1, arbitrary: tabAction(`write-during-leader-message`) }, + { weight: 1, arbitrary: tabAction(`write-save-fails`) }, + { weight: 2, arbitrary: tabAction(`close`) }, + { weight: 2, arbitrary: tabAction(`open`) }, + { weight: 2, arbitrary: sharedAction(`offline`) }, + { weight: 2, arbitrary: sharedAction(`online`) }, + { weight: 1, arbitrary: sharedAction(`lose-settlement`) }, + { weight: 1, arbitrary: sharedAction(`stale-added`) }, + { weight: 1, arbitrary: sharedAction(`duplicate-added`) }, + { weight: 1, arbitrary: sharedAction(`fail-admission-read`) }, + { weight: 1, arbitrary: sharedAction(`fail-outbox-check`) }, +) +const historyArbitrary: fc.Arbitrary = fc.record({ + mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), + actions: fc.array(actionArbitrary, { maxLength: MAX_ACTIONS }), +}) +const spliced = ( + generated: History, + prefix: Array, + mode: Mode = `durable`, +): History => ({ + mode, + actions: [ + ...prefix, + ...generated.actions + .filter( + (action) => + action.type !== `lose-settlement` && + action.type !== `fail-admission-read` && + action.type !== `fail-outbox-check`, + ) + .slice(0, MAX_ACTIONS - prefix.length), + ], +}) + +// --------------------------------------------------------------------------- +// Controlled environment +// --------------------------------------------------------------------------- + +class ControlledElection { + holder: TabElection | undefined + readonly queue: Array = [] + + leave(tab: TabElection): void { + const index = this.queue.indexOf(tab) + if (index >= 0) this.queue.splice(index, 1) + if (this.holder !== tab) return + this.holder = this.queue.shift() + tab.set(false) + this.holder?.set(true) + } +} + +class TabElection implements LeaderElection { + private leader = false + private readonly listeners = new Set<(isLeader: boolean) => void>() + constructor(private readonly shared: ControlledElection) {} + + requestLeadership(): Promise { + if (!this.shared.holder) { + this.shared.holder = this + this.leader = true + } else if ( + this.shared.holder !== this && + !this.shared.queue.includes(this) + ) { + this.shared.queue.push(this) + } + return Promise.resolve(this.leader) + } + releaseLeadership(): void { + this.shared.leave(this) + } + isLeader(): boolean { + return this.leader + } + onLeadershipChange(callback: (isLeader: boolean) => void): () => void { + this.listeners.add(callback) + return () => this.listeners.delete(callback) + } + set(isLeader: boolean): void { + this.leader = isLeader + for (const listener of this.listeners) listener(isLeader) + } +} + +class ControlledOnline { + online = true + readonly listeners = new Set<() => void>() + + detector(): OnlineDetector { + const own = new Set<() => void>() + return { + subscribe: (callback) => { + own.add(callback) + this.listeners.add(callback) + return () => { + own.delete(callback) + this.listeners.delete(callback) + } + }, + notifyOnline: () => { + for (const listener of [...this.listeners]) listener() + }, + isOnline: () => this.online, + dispose: () => { + for (const callback of own) this.listeners.delete(callback) + own.clear() + }, + } + } + set(online: boolean): void { + this.online = online + if (online) for (const listener of [...this.listeners]) listener() + } +} + +class ReadFailingStorage extends FakeStorageAdapter { + failReads = 0 + private heldWrites: Array<(fail: boolean) => void> | null = null + + holdWrites(): void { + this.heldWrites = [] + } + releaseWrites(fail: boolean): void { + const held = this.heldWrites ?? [] + this.heldWrites = null + for (const release of held) release(fail) + } + override async set(key: string, value: string): Promise { + if (this.heldWrites) { + const held = this.heldWrites + const fail = await new Promise((resolve) => held.push(resolve)) + if (fail) throw new Error(`storage write failed`) + } + return super.set(key, value) + } + override async get(key: string): Promise { + if (this.failReads > 0) { + this.failReads -= 1 + throw new Error(`storage read failed`) + } + return super.get(key) + } +} + +type ChannelMessage = { type: string; id?: string; error?: unknown } + +function controlledChannels() { + const open = new Set() + const state = { loseSettlement: false, lost: 0, created: 0 } + const deliver = (from: ControlledChannel | null, data: ChannelMessage) => { + const copy = structuredClone(data) + for (const channel of open) { + if (channel === from) continue + setTimeout(() => { + if (open.has(channel)) channel.onmessage?.({ data: copy }) + }, 0) + } + } + class ControlledChannel { + onmessage: ((event: { data: ChannelMessage }) => void) | null = null + constructor(readonly name: string) { + expect(name, `channel name`).toBe(CHANNEL) + state.created += 1 + open.add(this) + } + postMessage(data: ChannelMessage): void { + if (state.loseSettlement && data.type === `settled` && !data.error) { + state.loseSettlement = false + state.lost += 1 + return + } + deliver(this, data) + } + close(): void { + open.delete(this) + } + } + return { + ControlledChannel, + state, + openCount: () => open.size, + inject: (data: ChannelMessage) => deliver(null, data), + } +} + +const settle = async () => { + for (let turn = 0; turn < 12; turn++) { + await new Promise((resolve) => setTimeout(resolve, 0)) + } +} + +// --------------------------------------------------------------------------- +// Production driver +// --------------------------------------------------------------------------- + +type Write = { + id: string + transactionId?: string + tab: number + rejected: boolean + deliverable: boolean + fromFollower: boolean + session: number + outcome?: `completed` | `failed` + error?: unknown +} + +const warningsFor = + (warn: { mock: { calls: Array> } }) => (text: string) => + warn.mock.calls.filter(([message]) => message === text).length + +async function runHistory( + history: History, + reach: (state: ReachState) => void, +): Promise { + const channels = controlledChannels() + vi.stubGlobal(`BroadcastChannel`, channels.ControlledChannel) + const warn = vi.spyOn(console, `warn`).mockImplementation(() => {}) + const consoleError = vi.spyOn(console, `error`).mockImplementation(() => {}) + const warnings = warningsFor(warn) + const durable = history.mode === `durable` + const storage = new ReadFailingStorage() + const election = new ControlledElection() + const online = new ControlledOnline() + const writes: Array = [] + const calls: Array = [] + const rejected = new Set() + const expectedWarnings = { admission: 0, check: 0 } + type Tab = { + env: ReturnType + election: TabElection + session: number + } + const tabs: Array = Array.from({ length: TABS }) + let sessions = 0 + + const openTab = async (index: number) => { + const tabElection = new TabElection(election) + const env = createTestOfflineEnvironment({ + storage, + mutationFn: (params: OfflineMutationFnParams) => { + const id = String(params.transaction.mutations[0].key) + // The server is unreachable while offline, whichever path sends it. + if (!online.online) throw new Error(`offline`) + calls.push(id) + if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) + return { ok: true } + }, + config: { + ...(durable ? { followerWrites: `durable` } : {}), + leaderElection: tabElection, + onlineDetector: online.detector(), + jitter: false, + } as never, + }) + tabs[index] = { env, election: tabElection, session: ++sessions } + await env.executor.waitForInit() + await settle() + } + const closeTab = async (index: number) => { + const tab = tabs[index] + if (!tab) return + tabs[index] = undefined + expect(() => tab.env.executor.dispose(), `close tab ${index}`).not.toThrow() + await settle() + } + const isUnsent = (write: Write) => + write.deliverable && !calls.includes(write.id) + const leaderIndex = () => + tabs.findIndex((tab) => tab && tab.election === election.holder) + const openSessions = () => new Set(tabs.flatMap((tab) => tab?.session ?? [])) + + const check = (label: string) => { + expect( + [...warn.mock.calls, ...consoleError.mock.calls] + .flat() + .filter((value) => value instanceof TypeError), + `${label}: no internal TypeError`, + ).toEqual([]) + expect(channels.openCount(), `${label}: open channels`).toBe( + durable ? tabs.filter(Boolean).length : 0, + ) + expect(warnings(`Failed to run follower write:`), `${label}: admit`).toBe( + expectedWarnings.admission, + ) + expect( + warnings(`Failed to reconcile follower writes:`), + `${label}: outbox check`, + ).toBe(expectedWarnings.check) + if (!durable) return + const sessionsOpen = openSessions() + const leader = tabs[leaderIndex()] + for (const write of writes) { + if (!isUnsent(write)) continue + if (sessionsOpen.has(write.session)) { + expect(write.outcome, `${label}: ${write.id} stays pending`).toBe( + undefined, + ) + } + if (leader) { + expect( + leader.env.collection.has(write.id), + `${label}: leader shows ${write.id}`, + ).toBe(true) + } + } + } + + try { + for (let index = 0; index < TABS; index++) await openTab(index) + expect(channels.state.created, `channels created`).toBe(durable ? TABS : 0) + + for (const [step, action] of history.actions.entries()) { + switch (action.type) { + case `write`: + case `write-rejected`: + case `write-during-leader-message`: + case `write-save-fails`: { + const tab = tabs[action.tab] + if (!tab) break + const fromFollower = leaderIndex() !== action.tab + const id = `write-${writes.length}` + const write: Write = { + id, + tab: action.tab, + rejected: action.type === `write-rejected`, + deliverable: durable || !fromFollower || online.online, + fromFollower, + session: tab.session, + } + writes.push(write) + if (write.rejected) rejected.add(id) + const saveFails = durable && action.type === `write-save-fails` + const heldSave = + saveFails || + (durable && action.type === `write-during-leader-message`) + if (saveFails) write.deliverable = false + if (heldSave) storage.holdWrites() + if (!durable && !fromFollower && online.online) { + reach(`online-mode-leader-write-delivered`) + } + if (!durable && fromFollower && !online.online) { + reach(`online-mode-follower-write-failed`) + } + const transaction = tab.env.executor.createOfflineTransaction({ + mutationFnName: tab.env.mutationFnName, + autoCommit: false, + }) + write.transactionId = transaction.id + const settled = transaction.mutate(() => { + tab.env.collection.insert({ + id, + value: id, + completed: false, + updatedAt: new Date(), + }) + }) + void transaction.commit().catch(() => undefined) + void settled.when(`settled`).then( + () => { + write.outcome = `completed` + }, + (error: unknown) => { + write.outcome = `failed` + write.error = error + }, + ) + await settle() + if (heldSave) { + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${id} waits for its save`).toBe(undefined) + reach(`leader-message-during-save`) + if (saveFails && fromFollower) reach(`follower-save-failed`) + storage.releaseWrites(saveFails) + await settle() + } + break + } + case `close`: { + const leader = leaderIndex() === action.tab + if ( + durable && + leader && + writes.some((write) => write.tab !== action.tab && isUnsent(write)) + ) { + reach(`leader-closed-with-follower-write`) + } + if ( + durable && + !leader && + writes.some( + (write) => + write.tab === action.tab && + write.session === tabs[action.tab]?.session && + isUnsent(write), + ) + ) { + reach(`write-outlived-its-tab`) + } + await closeTab(action.tab) + break + } + case `open`: + if (!tabs[action.tab]) await openTab(action.tab) + break + case `online`: + online.set(true) + await settle() + break + case `offline`: + online.set(false) + break + case `lose-settlement`: + if (durable) channels.state.loseSettlement = true + break + case `stale-added`: + if (!durable || !tabs.some(Boolean)) break + reach(`stale-message-ignored`) + channels.inject({ type: `added`, id: `not-in-outbox` }) + await settle() + break + case `duplicate-added`: { + const queued = writes.find(isUnsent) + if (!durable || !queued || leaderIndex() < 0) break + reach(`duplicate-message-ignored`) + channels.inject({ type: `added`, id: queued.transactionId }) + await settle() + break + } + case `fail-admission-read`: + if (!durable || !tabs.some(Boolean)) break + reach(`admission-read-failed`) + storage.failReads = 1 + expectedWarnings.admission += 1 + channels.inject({ type: `added`, id: `not-in-outbox` }) + await settle() + break + case `fail-outbox-check`: { + const sessionsOpen = openSessions() + const waiting = writes.some( + (write) => isUnsent(write) && sessionsOpen.has(write.session), + ) + if (!durable || !waiting) break + reach(`outbox-check-read-failed`) + storage.failReads = 1 + expectedWarnings.check += 1 + channels.inject({ type: `leader` }) + await settle() + break + } + } + check(`step ${step} ${action.type}`) + } + + // End online with a leader, handing over once if a settlement was lost. + channels.state.loseSettlement = false + online.set(true) + await settle() + if (channels.state.lost > 0) { + const holder = leaderIndex() + const stranded = writes.some( + (write) => + write.session !== tabs[holder]?.session && + openSessions().has(write.session) && + write.outcome === undefined, + ) + if (holder >= 0) await closeTab(holder) + reach(`lost-settlement-recovered`) + const nextLeader = tabs[leaderIndex()]?.session + if ( + stranded && + writes.some( + (write) => + write.session !== nextLeader && + openSessions().has(write.session) && + write.outcome !== undefined, + ) + ) { + reach(`lost-settlement-recovered-by-follower`) + } + } + if (tabs.every((tab) => !tab)) await openTab(0) + if (leaderIndex() < 0) await openTab(tabs.findIndex((tab) => !tab)) + online.set(true) + for (let round = 0; round < 8; round++) await settle() + + const sessionsOpen = openSessions() + for (const write of writes) { + if (!durable || !write.fromFollower) continue + if (!write.rejected) reach(`follower-write-delivered`) + else if (sessionsOpen.has(write.session)) { + reach(`follower-write-rejected`) + } + } + expect([...calls].sort(), `each write reached the server once`).toEqual( + writes + .filter((write) => write.deliverable) + .map((write) => write.id) + .sort(), + ) + const executor = tabs[leaderIndex()]!.env.executor + expect(await executor.peekOutbox(), `the outbox is empty`).toEqual([]) + for (const write of writes) { + if (!sessionsOpen.has(write.session)) continue + expect(write.outcome, `${write.id} outcome`).toBe( + write.rejected || !write.deliverable ? `failed` : `completed`, + ) + if (write.rejected && write.deliverable) { + const error = write.error as Error + expect(error, `${write.id} error type`).toBeInstanceOf( + NonRetriableError, + ) + expect(error.name, `${write.id} error name`).toBe(`NonRetriableError`) + expect(error.message, `${write.id} error message`).toBe( + `rejected ${write.id}`, + ) + } + } + } finally { + for (const tab of tabs) tab?.env.executor.dispose() + warn.mockRestore() + consoleError.mockRestore() + vi.unstubAllGlobals() + } +} + +const write = (tab: number): Action => ({ type: `write`, tab }) +const close = (tab: number): Action => ({ type: `close`, tab }) +const offline: Action = { type: `offline` } +const loseSettlement: Action = { type: `lose-settlement` } + +oracleProperty({ + id: property, + law: { + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until it reaches the server exactly once after some tab leads while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome. Stale and duplicate messages change nothing. The default mode keeps the online path with no channel.`, + authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, + limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts, and a lost settlement of a rejected write is not modeled.`, + }, + owns: [ + `src/OfflineExecutor.ts#OfflineExecutor.handleOutboxMessage`, + `src/OfflineExecutor.ts#OfflineExecutor.settleRemovedWrites`, + `src/OfflineExecutor.ts#OfflineExecutor.openOutboxChannel`, + `src/OfflineExecutor.ts#OfflineExecutor.announceSettled`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.admitTransaction`, + ], + histories: { + arbitrary: historyArbitrary, + runs: 30, + fixedSeeds: [2464], + states: reachStates, + constructed: [ + { + name: `a follower's online write goes through the leader`, + enters: [`follower-write-delivered`], + build: (generated: History): History => spliced(generated, [write(1)]), + }, + { + name: `a follower writes offline and closes`, + enters: [`write-outlived-its-tab`, `follower-write-delivered`], + build: (generated: History): History => + spliced(generated, [offline, write(1), close(1)]), + }, + { + name: `the leader closes holding a follower's write`, + enters: [`leader-closed-with-follower-write`], + build: (generated: History): History => + spliced(generated, [offline, write(1), close(0)]), + }, + { + name: `the server rejects a follower's write`, + enters: [`follower-write-rejected`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `write-rejected`, tab: 2 }], + }), + }, + { + name: `a lost settlement is recovered at handover`, + enters: [`lost-settlement-recovered`, `follower-write-delivered`], + build: (): History => ({ + mode: `durable`, + actions: [loseSettlement, write(1)], + }), + }, + { + name: `a tab that stays a follower recovers a lost settlement`, + enters: [`lost-settlement-recovered-by-follower`], + build: (): History => ({ + mode: `durable`, + actions: [loseSettlement, write(2)], + }), + }, + { + name: `the default mode keeps the online follower path`, + enters: [`online-mode-follower-write-failed`], + build: (generated: History): History => + spliced(generated, [offline, write(1)], `online`), + }, + { + name: `stale and duplicate messages change nothing`, + enters: [`stale-message-ignored`, `duplicate-message-ignored`], + build: (generated: History): History => + spliced(generated, [ + { type: `stale-added` }, + offline, + write(1), + { type: `duplicate-added` }, + ]), + }, + { + name: `a leader message arrives during a save`, + enters: [`leader-message-during-save`], + build: (generated: History): History => + spliced(generated, [{ type: `write-during-leader-message`, tab: 1 }]), + }, + { + name: `a follower's save fails`, + enters: [`follower-save-failed`], + build: (generated: History): History => + spliced(generated, [{ type: `write-save-fails`, tab: 1 }]), + }, + { + name: `a leader writes in the default mode`, + enters: [`online-mode-leader-write-delivered`], + build: (): History => ({ mode: `online`, actions: [write(0)] }), + }, + { + name: `failed storage reads are reported`, + enters: [`admission-read-failed`, `outbox-check-read-failed`], + build: (generated: History): History => + spliced(generated, [ + { type: `fail-admission-read` }, + offline, + write(1), + { type: `fail-outbox-check` }, + ]), + }, + ], + }, + 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 1684318f85fea4cda85b4dc89506c286d9a7fa44 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 00:17:06 -0800 Subject: [PATCH 02/16] fix(offline-transactions): address durable follower write review A follower settled a saved write as completed whenever its outbox row was gone, even when the server had rejected it. The leader now records each outcome before removing a row, and the writer settles from that record and removes it. Records of writers that never return are pruned after a day. A failed admission read left a saved write pending until leadership changed. The leader now retries it when connectivity changes. An admission read that the write's removal overtakes no longer schedules it again, so a completed write cannot reach the server twice. A write made before initialization keeps the online path. The oracle now checks which tab sends each durable write, recovers lost settlements for the same write without closing its writer, and covers lost rejections, retried and stale admission reads, pre-initialization writes and outcome records. --- .changeset/durable-follower-writes.md | 2 +- docs/contributing/oracle-coverage.md | 8 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 60 ++- .../src/executor/TransactionExecutor.ts | 13 +- .../src/outbox/OutboxManager.ts | 56 +++ .../durable-follower-oracle.property.test.ts | 454 ++++++++++++++---- 7 files changed, 476 insertions(+), 119 deletions(-) diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index d9aab47064..e16296d0aa 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The default stays `'online'`. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records the result before removing the row, so a follower that misses the report still settles correctly. The default stays `'online'`. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 5918bb99fa..7675244105 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4248,8 +4248,12 @@ The post-merge review added three missing domains to existing owners: - [Durable follower writes](https://github.com/TanStack/db/blob/main/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts) checks delivery and settlement of `followerWrites: 'durable'` across three tabs that write, close, reopen and hand over leadership, with controlled - election, connectivity and BroadcastChannel. It does not cover real browser - contexts. + election, connectivity and BroadcastChannel. It also checks that only the + leader sends a durable write, that a lost settlement (including a rejection) + is recovered for the same write, that a leader retries a saved write it could + not read, that a stale admission read cannot send a write twice, that a write + made before initialization takes the online path, and which outcome records + remain. It does not cover real browser contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 24d74a9beb..a7739ad5b1 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. If a leader closes between removing a row and reporting its result, the next leader reports that write as completed. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records each result before it removes the row, so a follower that misses the report still settles with the server's outcome, including a rejection. A recorded result whose tab never returns is removed after a day. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index d3df5155ca..d1b3413394 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -55,6 +55,9 @@ function outboxMessageError(error: { name: string; message: string }): Error { return restored } +/** How long a recorded outcome waits for a writer that never returns. */ +const OUTCOME_RETENTION_MS = 24 * 60 * 60 * 1000 + /** How many settled ids an executor remembers to reject late waiters. */ const SETTLED_TRANSACTIONS_REMEMBERED = 1000 @@ -101,6 +104,9 @@ export class OfflineExecutor { private initReject!: (error: Error) => void // Coordination mechanism for blocking transactions + // Follower writes this leader could not read; retried on connectivity. + private readonly unadmitted = new Set() + private initialized = false private pendingTransactionPromises: Map< string, { @@ -278,6 +284,7 @@ export class OfflineExecutor { this.unsubscribeOnline = this.onlineDetector.subscribe(() => { if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays() + this.retryAdmissions() if (this.scheduler.getPendingCount() > 0) { const barrierPromise = this.executor.executeAll() @@ -373,6 +380,7 @@ export class OfflineExecutor { if (isLeader) { await this.loadAndReplayTransactions() } + this.initialized = true this.initResolve() } catch (error) { console.warn(`Failed to initialize offline executor:`, error) @@ -393,6 +401,10 @@ export class OfflineExecutor { this.outboxChannel.postMessage({ type: `leader`, } satisfies OutboxMessage) + // Housekeeping only: a later leader prunes again. + this.outbox!.pruneOutcomes(Date.now() - OUTCOME_RETENTION_MS).catch( + () => {}, + ) } this.reconcileFollowerWrites() @@ -424,18 +436,37 @@ export class OfflineExecutor { if (message.type === `leader`) { this.reconcileFollowerWrites() } else if (message.type === `added`) { - this.executor!.admitTransaction(message.id).catch((error) => { - console.warn(`Failed to run follower write:`, error) - }) + this.admitFollowerWrite(message.id) } else { - this.settleTransaction( + this.settleFollowerWrite( message.id, - undefined, message.error && outboxMessageError(message.error), ) } } + private admitFollowerWrite(id: string): void { + this.unadmitted.delete(id) + this.executor!.admitTransaction(id).catch((error) => { + console.warn(`Failed to run follower write:`, error) + // The row is still saved. This leader tries again when connectivity + // changes, which is harmless if it was scheduled; a later leader loads + // it from the outbox. + this.unadmitted.add(id) + }) + } + + private retryAdmissions(): void { + for (const id of [...this.unadmitted]) this.admitFollowerWrite(id) + } + + // Every tab hears a settlement; only the writer removes its outcome record. + private settleFollowerWrite(id: string, error?: Error): void { + const own = this.pendingTransactionPromises.has(id) + this.settleTransaction(id, undefined, error) + if (own) this.outbox!.removeOutcome(id).catch(() => {}) + } + private reconcileFollowerWrites(): void { this.settleRemovedWrites().catch((error) => { console.warn(`Failed to reconcile follower writes:`, error) @@ -443,17 +474,21 @@ export class OfflineExecutor { } // A saved write that left the outbox was settled by a leader whose message - // never arrived. + // never arrived. The leader recorded the outcome before removing the row; a + // row removed with no record, such as by an older leader, completed. private async settleRemovedWrites(): Promise { for (const [id, waiter] of [...this.pendingTransactionPromises]) { if (!(await waiter.saved)) continue if (await this.outbox!.get(id)) continue - this.settleTransaction(id, undefined) + const error = (await this.outbox!.getOutcome(id))?.error + this.settleFollowerWrite(id, error && outboxMessageError(error)) } } - private announceSettled(id: string, error?: Error): void { + private announceSettled(id: string, own: boolean, error?: Error): void { if (this.outboxChannel) { + // This tab's own write needs no record for another tab. + if (own) this.outbox!.removeOutcome(id).catch(() => {}) this.outboxChannel.postMessage({ type: `settled`, id, @@ -464,8 +499,9 @@ export class OfflineExecutor { } } + // A write made before initialization keeps the online path. private get writesToSharedOutbox(): boolean { - return this.outboxChannel !== null + return this.outboxChannel !== null && this.initialized } get isOfflineEnabled(): boolean { @@ -629,19 +665,21 @@ export class OfflineExecutor { // Method for TransactionExecutor to signal completion resolveTransaction(transactionId: string, result: any): void { + const own = this.pendingTransactionPromises.has(transactionId) try { this.settleTransaction(transactionId, result) } finally { - this.announceSettled(transactionId) + this.announceSettled(transactionId, own) } } // Method for TransactionExecutor to signal failure rejectTransaction(transactionId: string, error: Error): void { + const own = this.pendingTransactionPromises.has(transactionId) try { this.settleTransaction(transactionId, undefined, error) } finally { - this.announceSettled(transactionId, error) + this.announceSettled(transactionId, own, error) } } diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 4909dcaa28..2773201f0a 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -325,6 +325,16 @@ export class TransactionExecutor { } } } + // A follower that wrote this transaction reads its outcome here when + // the settlement message never reaches it. + if (this.config.followerWrites === `durable`) { + await this.outbox.recordOutcome( + transaction.id, + transaction.outboxPhase === `rejection-pending` + ? this.getTerminalError(transaction) + : undefined, + ) + } await this.outbox.remove(transaction.id) this.scheduler.markCompleted(transaction) } catch (error) { @@ -430,7 +440,8 @@ export class TransactionExecutor { /** Runs one transaction that a follower tab saved to the shared outbox. */ async admitTransaction(id: string): Promise { - const transaction = await this.outbox.get(id) + // A read that the transaction's removal overtakes returns null. + const transaction = await this.outbox.getCurrent(id) if (!transaction || !this.offlineExecutor.isOfflineEnabled) return // A duplicate message is harmless: both steps ignore a known transaction. this.scheduler.schedule(transaction) diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index ade147717a..87572039af 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -12,10 +12,17 @@ import type { Collection } from '@tanstack/db' export class OutboxTransactionNotFoundError extends Error {} +/** How a removed transaction settled, kept for a writer in another tab. */ +export type OutboxOutcome = { + at: number + error?: { name: string; message: string } +} + export class OutboxManager { private storage: StorageAdapter private serializer: TransactionSerializer private keyPrefix = `tx:` + private outcomePrefix = `outcome:` private removalRevision = 0 private activeReads = new Set<{ revision: number }>() private removedAtRevision = new Map() @@ -79,6 +86,55 @@ export class OutboxManager { } } + /** + * Reads one transaction, or null if it was removed after this read began, + * so a stale read cannot bring back a transaction that already settled. + */ + async getCurrent(id: string): Promise { + const read = { revision: this.removalRevision } + this.activeReads.add(read) + try { + const transaction = await this.get(id) + return (this.removedAtRevision.get(id) ?? 0) <= read.revision + ? transaction + : null + } finally { + this.activeReads.delete(read) + this.pruneRemovalHistory() + } + } + + /** Records how a transaction settled before its row is removed. */ + async recordOutcome(id: string, error?: Error): Promise { + const outcome: OutboxOutcome = { + at: Date.now(), + ...(error ? { error: { name: error.name, message: error.message } } : {}), + } + await this.storage.set( + `${this.outcomePrefix}${id}`, + JSON.stringify(outcome), + ) + } + + async getOutcome(id: string): Promise { + const data = await this.storage.get(`${this.outcomePrefix}${id}`) + return data === null ? null : (JSON.parse(data) as OutboxOutcome) + } + + async removeOutcome(id: string): Promise { + await this.storage.delete(`${this.outcomePrefix}${id}`) + } + + /** Removes outcomes recorded before `before`, whose writers are gone. */ + async pruneOutcomes(before: number): Promise { + for (const key of await this.storage.keys()) { + if (!key.startsWith(this.outcomePrefix)) continue + const data = await this.storage.get(key) + if (data !== null && (JSON.parse(data) as OutboxOutcome).at < before) + await this.storage.delete(key) + } + } + async getAll(): Promise> { return this.withAll((transactions) => transactions) } diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 894ef765a4..6503cec9a4 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -12,34 +12,42 @@ * once after some tab leads while online, whether or not its tab is still open. * It stays pending until then, and the leader shows it optimistically. A write * the server rejects permanently fails in its open tab with the server's error, - * and every other write completes. When a settlement message is lost, the next - * leader's outbox check settles the waiter. Stale and duplicate channel - * messages change nothing. In online mode, a follower's write made offline - * fails and is never sent. + * and every other write completes. Only the leader sends a durable write. When + * a settlement message is lost, the outcome the leader recorded settles the + * waiter at the next leader's outbox check, with the server's error for a + * rejected write. A leader that cannot read a saved write tries again when + * connectivity changes. Stale and duplicate channel messages change nothing. + * A write made before its tab initializes, and in online mode a follower's + * write, uses the online path: the writing tab sends it, and offline it fails + * and is never sent. * * History grammar: a mode and up to twelve actions over three tabs: write, a * write the server rejects, a write whose save is held or fails while a leader - * message arrives, close a tab, reopen a tab, go online or offline, - * lose the next successful settlement, deliver a stale or duplicate message, - * and fail the storage read of an admission or an outbox check. + * message arrives, close a tab, reopen a tab, reopen a tab and write before it + * initializes, go online or offline, lose the next settlement, deliver a stale + * or duplicate message, fail the leader's admission read of a follower's saved + * write, fail an outbox check's storage read, and return a leader's admission + * read only after a duplicate message sent and removed its write. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. * * Refinement check: after every action, pending writes stay pending and shown - * by the leader, open channels match open tabs, and warnings match the injected - * failures. After the history ends online with a leader, each deliverable write - * reached the server exactly once, the outbox is empty, and each open tab's - * transaction has the model's outcome and error. + * by the leader once it read them, open channels match open tabs, and warnings + * match the injected failures. After the history ends online with a leader, + * each deliverable write reached the server exactly once from the tab the + * model names, the outbox is empty, and each open tab's transaction has the + * model's outcome and error. A lost settlement is recovered for the same write, + * by the writer itself if it became leader, or else after one handover. * - * Known omissions: writes made before a tab initializes use the online path; a - * reloaded follower does not show another tab's pending writes optimistically; - * a settlement lost for a permanently rejected write would report success; and - * no real browser contexts. + * Known omissions: a reloaded follower does not show another tab's pending + * writes optimistically; outcomes are pruned by age only for a record placed a + * day old before the tabs open; and no real browser contexts. */ import fc from 'fast-check' import { expect, vi } from 'vitest' import { NonRetriableError } from '../src/types' +import { OutboxManager } from '../src/outbox/OutboxManager' import { forwardAssertionJudgment, recordAssertionJudgment, @@ -87,6 +95,14 @@ const reachStates = [ `follower-save-failed`, // A leader's write completed in the default mode. `online-mode-leader-write-delivered`, + // A write made before its tab initialized used the online path. + `pre-initialization-write`, + // A lost settlement of a rejected write still failed with its error. + `lost-rejection-recovered`, + // A saved write the leader could not read was sent after connectivity changed. + `admission-retried`, + // An admission read returned after its write was sent and removed. + `stale-admission-ignored`, ] as const type ReachState = (typeof reachStates)[number] @@ -97,6 +113,7 @@ type TabActionType = | `write-save-fails` | `close` | `open` + | `open-and-write` type SharedActionType = | `online` | `offline` @@ -105,6 +122,7 @@ type SharedActionType = | `duplicate-added` | `fail-admission-read` | `fail-outbox-check` + | `stale-admission-read` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -124,6 +142,7 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: tabAction(`write-save-fails`) }, { weight: 2, arbitrary: tabAction(`close`) }, { weight: 2, arbitrary: tabAction(`open`) }, + { weight: 1, arbitrary: tabAction(`open-and-write`) }, { weight: 2, arbitrary: sharedAction(`offline`) }, { weight: 2, arbitrary: sharedAction(`online`) }, { weight: 1, arbitrary: sharedAction(`lose-settlement`) }, @@ -131,6 +150,7 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`duplicate-added`) }, { weight: 1, arbitrary: sharedAction(`fail-admission-read`) }, { weight: 1, arbitrary: sharedAction(`fail-outbox-check`) }, + { weight: 1, arbitrary: sharedAction(`stale-admission-read`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), @@ -149,7 +169,8 @@ const spliced = ( (action) => action.type !== `lose-settlement` && action.type !== `fail-admission-read` && - action.type !== `fail-outbox-check`, + action.type !== `fail-outbox-check` && + action.type !== `stale-admission-read`, ) .slice(0, MAX_ACTIONS - prefix.length), ], @@ -176,9 +197,13 @@ class ControlledElection { class TabElection implements LeaderElection { private leader = false private readonly listeners = new Set<(isLeader: boolean) => void>() - constructor(private readonly shared: ControlledElection) {} + constructor( + private readonly shared: ControlledElection, + private readonly hold?: Promise, + ) {} - requestLeadership(): Promise { + async requestLeadership(): Promise { + await this.hold if (!this.shared.holder) { this.shared.holder = this this.leader = true @@ -188,7 +213,7 @@ class TabElection implements LeaderElection { ) { this.shared.queue.push(this) } - return Promise.resolve(this.leader) + return this.leader } releaseLeadership(): void { this.shared.leave(this) @@ -239,6 +264,8 @@ class ControlledOnline { class ReadFailingStorage extends FakeStorageAdapter { failReads = 0 + // The next read captures its value at once and returns it on release. + private staleRead: { release: () => void } | null | undefined private heldWrites: Array<(fail: boolean) => void> | null = null holdWrites(): void { @@ -257,11 +284,25 @@ class ReadFailingStorage extends FakeStorageAdapter { } return super.set(key, value) } + holdNextRead(): void { + this.staleRead = null + } + releaseRead(): void { + this.staleRead?.release() + this.staleRead = undefined + } override async get(key: string): Promise { if (this.failReads > 0) { this.failReads -= 1 throw new Error(`storage read failed`) } + if (this.staleRead === null) { + const value = await super.get(key) + await new Promise((release) => { + this.staleRead = { release } + }) + return value + } return super.get(key) } } @@ -270,7 +311,12 @@ type ChannelMessage = { type: string; id?: string; error?: unknown } function controlledChannels() { const open = new Set() - const state = { loseSettlement: false, lost: 0, created: 0 } + const state = { + loseSettlement: false, + lost: 0, + lostIds: [] as Array, + created: 0, + } const deliver = (from: ControlledChannel | null, data: ChannelMessage) => { const copy = structuredClone(data) for (const channel of open) { @@ -288,9 +334,10 @@ function controlledChannels() { open.add(this) } postMessage(data: ChannelMessage): void { - if (state.loseSettlement && data.type === `settled` && !data.error) { + if (state.loseSettlement && data.type === `settled`) { state.loseSettlement = false state.lost += 1 + state.lostIds.push(data.id!) return } deliver(this, data) @@ -325,6 +372,10 @@ type Write = { deliverable: boolean fromFollower: boolean session: number + // Made before its tab initialized, so it took the online path. + preInit: boolean + // The leader's admission read failed and connectivity has not changed since. + unadmitted: boolean outcome?: `completed` | `failed` error?: unknown } @@ -348,6 +399,8 @@ async function runHistory( const online = new ControlledOnline() const writes: Array = [] const calls: Array = [] + // Which tab called the server for each write, and which tab led then. + const sends: Array<{ id: string; sender: number; leader?: number }> = [] const rejected = new Set() const expectedWarnings = { admission: 0, check: 0 } type Tab = { @@ -358,8 +411,13 @@ async function runHistory( const tabs: Array = Array.from({ length: TABS }) let sessions = 0 - const openTab = async (index: number) => { - const tabElection = new TabElection(election) + const openTab = async ( + index: number, + beforeInit?: () => Promise, + hold?: Promise, + ) => { + const tabElection = new TabElection(election, hold) + const session = ++sessions const env = createTestOfflineEnvironment({ storage, mutationFn: (params: OfflineMutationFnParams) => { @@ -367,6 +425,11 @@ async function runHistory( // The server is unreachable while offline, whichever path sends it. if (!online.online) throw new Error(`offline`) calls.push(id) + sends.push({ + id, + sender: session, + leader: tabs[leaderIndex()]?.session, + }) if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) return { ok: true } }, @@ -377,7 +440,8 @@ async function runHistory( jitter: false, } as never, }) - tabs[index] = { env, election: tabElection, session: ++sessions } + tabs[index] = { env, election: tabElection, session } + await beforeInit?.() await env.executor.waitForInit() await settle() } @@ -421,7 +485,7 @@ async function runHistory( undefined, ) } - if (leader) { + if (leader && !write.unadmitted) { expect( leader.env.collection.has(write.id), `${label}: leader shows ${write.id}`, @@ -430,7 +494,85 @@ async function runHistory( } } + type WriteType = + | `write` + | `write-rejected` + | `write-during-leader-message` + | `write-save-fails` + const doWrite = async ( + index: number, + type: WriteType, + preInit = false, + ): Promise => { + const tab = tabs[index] + if (!tab) return undefined + const fromFollower = leaderIndex() !== index + const id = `write-${writes.length}` + // Durable writes go through the shared outbox once the tab is ready. + const shared = durable && !preInit + const write: Write = { + id, + tab: index, + rejected: type === `write-rejected`, + deliverable: shared || (!preInit && !fromFollower) || online.online, + fromFollower, + session: tab.session, + preInit, + unadmitted: false, + } + writes.push(write) + if (write.rejected) rejected.add(id) + const saveFails = shared && type === `write-save-fails` + const heldSave = + saveFails || (shared && type === `write-during-leader-message`) + if (saveFails) write.deliverable = false + if (heldSave) storage.holdWrites() + if (!durable && !fromFollower && online.online) { + reach(`online-mode-leader-write-delivered`) + } + if (!durable && fromFollower && !online.online) { + reach(`online-mode-follower-write-failed`) + } + const transaction = tab.env.executor.createOfflineTransaction({ + mutationFnName: tab.env.mutationFnName, + autoCommit: false, + }) + write.transactionId = transaction.id + const settled = transaction.mutate(() => { + tab.env.collection.insert({ + id, + value: id, + completed: false, + updatedAt: new Date(), + }) + }) + void transaction.commit().catch(() => undefined) + void settled.when(`settled`).then( + () => { + write.outcome = `completed` + }, + (error: unknown) => { + write.outcome = `failed` + write.error = error + }, + ) + await settle() + if (heldSave) { + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${id} waits for its save`).toBe(undefined) + reach(`leader-message-during-save`) + if (saveFails && fromFollower) reach(`follower-save-failed`) + storage.releaseWrites(saveFails) + await settle() + } + return write + } + try { + // A day-old outcome of a writer that never returned; the first leader + // prunes it. + if (durable) await storage.set(`outcome:aged`, JSON.stringify({ at: 0 })) for (let index = 0; index < TABS; index++) await openTab(index) expect(channels.state.created, `channels created`).toBe(durable ? TABS : 0) @@ -439,68 +581,9 @@ async function runHistory( case `write`: case `write-rejected`: case `write-during-leader-message`: - case `write-save-fails`: { - const tab = tabs[action.tab] - if (!tab) break - const fromFollower = leaderIndex() !== action.tab - const id = `write-${writes.length}` - const write: Write = { - id, - tab: action.tab, - rejected: action.type === `write-rejected`, - deliverable: durable || !fromFollower || online.online, - fromFollower, - session: tab.session, - } - writes.push(write) - if (write.rejected) rejected.add(id) - const saveFails = durable && action.type === `write-save-fails` - const heldSave = - saveFails || - (durable && action.type === `write-during-leader-message`) - if (saveFails) write.deliverable = false - if (heldSave) storage.holdWrites() - if (!durable && !fromFollower && online.online) { - reach(`online-mode-leader-write-delivered`) - } - if (!durable && fromFollower && !online.online) { - reach(`online-mode-follower-write-failed`) - } - const transaction = tab.env.executor.createOfflineTransaction({ - mutationFnName: tab.env.mutationFnName, - autoCommit: false, - }) - write.transactionId = transaction.id - const settled = transaction.mutate(() => { - tab.env.collection.insert({ - id, - value: id, - completed: false, - updatedAt: new Date(), - }) - }) - void transaction.commit().catch(() => undefined) - void settled.when(`settled`).then( - () => { - write.outcome = `completed` - }, - (error: unknown) => { - write.outcome = `failed` - write.error = error - }, - ) - await settle() - if (heldSave) { - channels.inject({ type: `leader` }) - await settle() - expect(write.outcome, `${id} waits for its save`).toBe(undefined) - reach(`leader-message-during-save`) - if (saveFails && fromFollower) reach(`follower-save-failed`) - storage.releaseWrites(saveFails) - await settle() - } + case `write-save-fails`: + await doWrite(action.tab, action.type) break - } case `close`: { const leader = leaderIndex() === action.tab if ( @@ -528,9 +611,40 @@ async function runHistory( case `open`: if (!tabs[action.tab]) await openTab(action.tab) break + case `open-and-write`: { + if (tabs[action.tab]) break + // The write lands after the tab opens its channel, while its + // election is still pending. + let release!: () => void + const hold = new Promise((resolve) => { + release = resolve + }) + let made: Promise | undefined + const channelsBefore = channels.state.created + await openTab( + action.tab, + async () => { + for (let turn = 0; turn < 50; turn++) { + if (!durable || channels.state.created > channelsBefore) break + await new Promise((resolve) => setTimeout(resolve, 0)) + } + if (durable) + expect(channels.state.created, `channel opened`).toBe( + channelsBefore + 1, + ) + made = doWrite(action.tab, `write`, true) + await Promise.resolve() + release() + }, + hold, + ) + if (await made) reach(`pre-initialization-write`) + break + } case `online`: online.set(true) await settle() + for (const write of writes) write.unadmitted = false break case `offline`: online.set(false) @@ -552,14 +666,37 @@ async function runHistory( await settle() break } - case `fail-admission-read`: - if (!durable || !tabs.some(Boolean)) break + case `fail-admission-read`: { + // The leader's first read of a follower's saved write fails. + const follower = tabs.findIndex( + (tab, index) => tab && index !== leaderIndex(), + ) + if (!durable || leaderIndex() < 0 || follower < 0) break reach(`admission-read-failed`) storage.failReads = 1 expectedWarnings.admission += 1 - channels.inject({ type: `added`, id: `not-in-outbox` }) + const write = await doWrite(follower, `write`) + write!.unadmitted = true + break + } + case `stale-admission-read`: { + // The leader's admission read stalls with the saved row; a duplicate + // message sends and removes the write before the read returns. + const follower = tabs.findIndex( + (tab, index) => tab && index !== leaderIndex(), + ) + if (!durable || !online.online || leaderIndex() < 0 || follower < 0) + break + storage.holdNextRead() + const write = await doWrite(follower, `write`) + if (!write) break + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + storage.releaseRead() await settle() + if (calls.includes(write.id)) reach(`stale-admission-ignored`) break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const waiting = writes.some( @@ -577,31 +714,55 @@ async function runHistory( check(`step ${step} ${action.type}`) } - // End online with a leader, handing over once if a settlement was lost. + // End online with a leader. A lost settlement is recovered for its own + // write: by the writer itself if it became leader, or else after one + // handover to another tab. channels.state.loseSettlement = false online.set(true) await settle() - if (channels.state.lost > 0) { + const lostWrites = writes.filter( + (write) => + write.transactionId !== undefined && + channels.state.lostIds.includes(write.transactionId), + ) + if (lostWrites.length > 0) { + reach(`lost-settlement-recovered`) const holder = leaderIndex() - const stranded = writes.some( + const leaderSession = tabs[holder]?.session + for (const write of lostWrites) { + if (write.session === leaderSession) { + expect(write.outcome, `${write.id} recovered by its leader`).not.toBe( + undefined, + ) + } + } + const stranded = lostWrites.filter( (write) => - write.session !== tabs[holder]?.session && + write.session !== leaderSession && openSessions().has(write.session) && write.outcome === undefined, ) - if (holder >= 0) await closeTab(holder) - reach(`lost-settlement-recovered`) - const nextLeader = tabs[leaderIndex()]?.session + if (stranded.length > 0 && holder >= 0) { + await closeTab(holder) + const nextLeader = tabs[leaderIndex()]?.session + if ( + stranded.some( + (write) => + write.session !== nextLeader && write.outcome !== undefined, + ) + ) { + reach(`lost-settlement-recovered-by-follower`) + } + } if ( - stranded && - writes.some( + lostWrites.some( (write) => - write.session !== nextLeader && + write.rejected && openSessions().has(write.session) && - write.outcome !== undefined, + write.outcome === `failed`, ) ) { - reach(`lost-settlement-recovered-by-follower`) + reach(`lost-rejection-recovered`) } } if (tabs.every((tab) => !tab)) await openTab(0) @@ -617,6 +778,21 @@ async function runHistory( reach(`follower-write-rejected`) } } + if (writes.some((write) => write.unadmitted && calls.includes(write.id))) + reach(`admission-retried`) + for (const send of sends) { + const write = writes.find((candidate) => candidate.id === send.id)! + if (write.preInit || !durable) continue + // A durable write is sent only by the tab that leads at that moment. + expect(send.sender, `${send.id} sent by the leader`).toBe(send.leader) + } + for (const write of writes) { + if (!write.preInit) continue + for (const send of sends.filter((candidate) => candidate.id === write.id)) + expect(send.sender, `${write.id} sent by its own tab`).toBe( + write.session, + ) + } expect([...calls].sort(), `each write reached the server once`).toEqual( writes .filter((write) => write.deliverable) @@ -625,6 +801,32 @@ async function runHistory( ) const executor = tabs[leaderIndex()]!.env.executor expect(await executor.peekOutbox(), `the outbox is empty`).toEqual([]) + // An outcome record stays only for a sent durable write whose tab closed + // before it settled; a tab that settles its write removes the record. + const outcomes = (await storage.keys()) + .filter((key) => key.startsWith(`outcome:`)) + .map((key) => key.slice(`outcome:`.length)) + .sort() + expect(outcomes, `outcome records`).toEqual( + writes + .filter( + (write) => + durable && + !write.preInit && + write.deliverable && + write.outcome === undefined, + ) + .map((write) => write.transactionId) + .sort(), + ) + // Every recorded outcome carries its age, so a day later all are pruned. + await new OutboxManager(storage, {}).pruneOutcomes( + Date.now() + 2 * 24 * 60 * 60 * 1000, + ) + expect( + (await storage.keys()).filter((key) => key.startsWith(`outcome:`)), + `outcome records a day later`, + ).toEqual([]) for (const write of writes) { if (!sessionsOpen.has(write.session)) continue expect(write.outcome, `${write.id} outcome`).toBe( @@ -657,16 +859,26 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until it reaches the server exactly once after some tab leads while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome. Stale and duplicate messages change nothing. The default mode keeps the online path with no channel.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, - limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts, and a lost settlement of a rejected write is not modeled.`, + limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts, and no outcome old enough to be pruned.`, }, owns: [ + `src/OfflineExecutor.ts`, `src/OfflineExecutor.ts#OfflineExecutor.handleOutboxMessage`, `src/OfflineExecutor.ts#OfflineExecutor.settleRemovedWrites`, `src/OfflineExecutor.ts#OfflineExecutor.openOutboxChannel`, `src/OfflineExecutor.ts#OfflineExecutor.announceSettled`, `src/executor/TransactionExecutor.ts#TransactionExecutor.admitTransaction`, + `src/OfflineExecutor.ts#OfflineExecutor.admitFollowerWrite`, + `src/OfflineExecutor.ts#OfflineExecutor.retryAdmissions`, + `src/OfflineExecutor.ts#OfflineExecutor.settleFollowerWrite`, + `src/OfflineExecutor.ts#OfflineExecutor.writesToSharedOutbox`, + `src/outbox/OutboxManager.ts#OutboxManager.getCurrent`, + `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.getOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.removeOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.pruneOutcomes`, ], histories: { arbitrary: historyArbitrary, @@ -760,6 +972,42 @@ oracleProperty({ { type: `fail-outbox-check` }, ]), }, + { + name: `a leader retries a saved write it could not read`, + enters: [`admission-read-failed`, `admission-retried`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `fail-admission-read` }], + }), + }, + { + name: `a lost rejection still fails its writer`, + enters: [`lost-settlement-recovered`, `lost-rejection-recovered`], + build: (): History => ({ + mode: `durable`, + actions: [loseSettlement, { type: `write-rejected`, tab: 2 }], + }), + }, + { + name: `a stale admission read does not send a write again`, + enters: [`stale-admission-ignored`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `stale-admission-read` }], + }), + }, + { + name: `a write before initialization takes the online path`, + enters: [`pre-initialization-write`], + build: (generated: History): History => + spliced(generated, [ + close(1), + { type: `open-and-write`, tab: 1 }, + offline, + close(2), + { type: `open-and-write`, tab: 2 }, + ]), + }, ], }, resolve: (history: History) => ({ history }), From 7a3c3bd44f224f75db4eac54953043c46d5d630f Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 01:51:24 -0800 Subject: [PATCH 03/16] fix(offline-transactions): address second durable follower write review Only rejections are recorded now, so a failing success record cannot fault the queue, and a rejection record stays until its writer reads it instead of expiring into a success. A beforeRetry exclusion is recorded too. A failed row removal after a successful send is no longer announced as the write's outcome; the writer waits for a leader that finishes the removal. A follower's failed outbox check is handled per write and retried when connectivity changes. An admission read that spans a change of leadership is dropped, an undecodable saved row is reported instead of skipped, only the leader reads admissions, and a rejected row is not restored. The oracle scopes its unread exemption to the leader that failed the read, checks that the online path is sent by its own tab, and covers each of these cases; the direct pruning check is gone with pruning. --- .changeset/durable-follower-writes.md | 2 +- docs/contributing/oracle-coverage.md | 7 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 68 ++-- .../src/executor/TransactionExecutor.ts | 45 ++- .../src/outbox/OutboxManager.ts | 40 ++- packages/offline-transactions/src/types.ts | 11 +- .../durable-follower-oracle.property.test.ts | 312 +++++++++++++++--- 8 files changed, 379 insertions(+), 108 deletions(-) diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index e16296d0aa..5c955dc150 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records the result before removing the row, so a follower that misses the report still settles correctly. The default stays `'online'`. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. The default stays `'online'`. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 7675244105..b3d759624d 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4252,8 +4252,11 @@ The post-merge review added three missing domains to existing owners: leader sends a durable write, that a lost settlement (including a rejection) is recovered for the same write, that a leader retries a saved write it could not read, that a stale admission read cannot send a write twice, that a write - made before initialization takes the online path, and which outcome records - remain. It does not cover real browser contexts. + made before initialization takes the online path, and which rejection + records remain. It also covers a failed row removal after a successful send, + an undecodable saved row, a follower's failed outbox check, an admission read + across a change of leadership, and a `beforeRetry` exclusion whose settlement + is lost. It does not cover real browser contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index a7739ad5b1..4c8ee82f0e 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records each result before it removes the row, so a follower that misses the report still settles with the server's outcome, including a rejection. A recorded result whose tab never returns is removed after a day. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it. Every tab must register its collections under the same keys: a leader that cannot read a follower's saved write reports it and keeps the write pending. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index d1b3413394..17a33b761e 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -55,9 +55,6 @@ function outboxMessageError(error: { name: string; message: string }): Error { return restored } -/** How long a recorded outcome waits for a writer that never returns. */ -const OUTCOME_RETENTION_MS = 24 * 60 * 60 * 1000 - /** How many settled ids an executor remembers to reject late waiters. */ const SETTLED_TRANSACTIONS_REMEMBERED = 1000 @@ -106,7 +103,10 @@ export class OfflineExecutor { // Coordination mechanism for blocking transactions // Follower writes this leader could not read; retried on connectivity. private readonly unadmitted = new Set() + // A follower's outbox check failed; it runs again on connectivity. + private reconcileFailed = false private initialized = false + private term = 0 private pendingTransactionPromises: Map< string, { @@ -266,7 +266,8 @@ export class OfflineExecutor { // A custom elector may repeat the initial result while replay is active. if (this.disposed || isLeader === this.isLeaderState) return this.isLeaderState = isLeader - if (!isLeader) this.executor?.pause() + if (isLeader) this.term++ + else this.executor?.pause() if (this.config.onLeadershipChange) { this.config.onLeadershipChange(isLeader) @@ -282,6 +283,7 @@ export class OfflineExecutor { } this.unsubscribeOnline = this.onlineDetector.subscribe(() => { + if (this.reconcileFailed) this.reconcileFollowerWrites() if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays() this.retryAdmissions() @@ -401,10 +403,6 @@ export class OfflineExecutor { this.outboxChannel.postMessage({ type: `leader`, } satisfies OutboxMessage) - // Housekeeping only: a later leader prunes again. - this.outbox!.pruneOutcomes(Date.now() - OUTCOME_RETENTION_MS).catch( - () => {}, - ) } this.reconcileFollowerWrites() @@ -447,11 +445,12 @@ export class OfflineExecutor { private admitFollowerWrite(id: string): void { this.unadmitted.delete(id) + // Only the leader sends; a later leader loads the row from the outbox. + if (!this.isOfflineEnabled) return this.executor!.admitTransaction(id).catch((error) => { console.warn(`Failed to run follower write:`, error) - // The row is still saved. This leader tries again when connectivity - // changes, which is harmless if it was scheduled; a later leader loads - // it from the outbox. + // The row is still saved. This leader reads it again when + // connectivity changes. this.unadmitted.add(id) }) } @@ -468,26 +467,37 @@ export class OfflineExecutor { } private reconcileFollowerWrites(): void { - this.settleRemovedWrites().catch((error) => { - console.warn(`Failed to reconcile follower writes:`, error) - }) + void this.settleRemovedWrites() } // A saved write that left the outbox was settled by a leader whose message - // never arrived. The leader recorded the outcome before removing the row; a - // row removed with no record, such as by an older leader, completed. + // never arrived. The leader recorded a rejection before removing the row; a + // row removed with no record completed. A failed read leaves that write + // pending, and the check runs again when connectivity changes. private async settleRemovedWrites(): Promise { + let failed = false for (const [id, waiter] of [...this.pendingTransactionPromises]) { - if (!(await waiter.saved)) continue - if (await this.outbox!.get(id)) continue - const error = (await this.outbox!.getOutcome(id))?.error - this.settleFollowerWrite(id, error && outboxMessageError(error)) + try { + if (!(await waiter.saved)) continue + if (await this.outbox!.get(id)) continue + const error = (await this.outbox!.getOutcome(id))?.error + this.settleFollowerWrite(id, error && outboxMessageError(error)) + } catch (error) { + failed = true + console.warn(`Failed to reconcile follower writes:`, error) + } } + this.reconcileFailed = failed } - private announceSettled(id: string, own: boolean, error?: Error): void { + /** Counts later leadership gains, so work begun in an earlier term can tell. */ + get leadershipTerm(): number { + return this.term + } + + private announceSettled(id: string, error?: Error, own = false): void { if (this.outboxChannel) { - // This tab's own write needs no record for another tab. + // This tab's own rejected write needs no record for another tab. if (own) this.outbox!.removeOutcome(id).catch(() => {}) this.outboxChannel.postMessage({ type: `settled`, @@ -665,21 +675,25 @@ export class OfflineExecutor { // Method for TransactionExecutor to signal completion resolveTransaction(transactionId: string, result: any): void { - const own = this.pendingTransactionPromises.has(transactionId) try { this.settleTransaction(transactionId, result) } finally { - this.announceSettled(transactionId, own) + this.announceSettled(transactionId) } } - // Method for TransactionExecutor to signal failure - rejectTransaction(transactionId: string, error: Error): void { + // Method for TransactionExecutor to signal failure. A local fault that is + // not the write's outcome stays unannounced. + rejectTransaction( + transactionId: string, + error: Error, + announce = true, + ): void { const own = this.pendingTransactionPromises.has(transactionId) try { this.settleTransaction(transactionId, undefined, error) } finally { - this.announceSettled(transactionId, own, error) + if (announce) this.announceSettled(transactionId, error, own) } } diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 2773201f0a..1d4d95c58a 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -120,9 +120,12 @@ export class TransactionExecutor { ) } catch (error) { const storageError = error as Error + // A cleanup fault is not the write's outcome. Another tab's writer + // waits for a leader that finishes the removal. this.offlineExecutor.rejectTransaction( transaction.id, terminalError ?? storageError, + terminalError !== undefined, ) throw storageError } @@ -325,14 +328,15 @@ export class TransactionExecutor { } } } - // A follower that wrote this transaction reads its outcome here when - // the settlement message never reaches it. - if (this.config.followerWrites === `durable`) { - await this.outbox.recordOutcome( + // A follower that wrote this transaction and misses the settlement + // message reads a rejection here; a write with no record completed. + if ( + this.config.followerWrites === `durable` && + transaction.outboxPhase === `rejection-pending` + ) { + await this.outbox.recordRejection( transaction.id, - transaction.outboxPhase === `rejection-pending` - ? this.getTerminalError(transaction) - : undefined, + this.getTerminalError(transaction), ) } await this.outbox.remove(transaction.id) @@ -424,6 +428,8 @@ export class TransactionExecutor { await Promise.all( removedIds.map(async (id) => { try { + if (this.config.followerWrites === `durable`) + await this.outbox.recordRejection(id, error) await this.outbox.remove(id) this.offlineExecutor.rejectTransaction(id, error) } catch (cleanupError) { @@ -438,15 +444,30 @@ export class TransactionExecutor { } } - /** Runs one transaction that a follower tab saved to the shared outbox. */ + /** + * Schedules one transaction that a follower tab saved to the shared outbox. + * It rejects only when the read fails. + */ async admitTransaction(id: string): Promise { - // A read that the transaction's removal overtakes returns null. + // A read that the transaction's removal overtakes returns null. One that + // spans a change of leadership is dropped: another leader may have sent + // the write, and this term's outbox load already has it if it remains. + const term = this.offlineExecutor.leadershipTerm const transaction = await this.outbox.getCurrent(id) - if (!transaction || !this.offlineExecutor.isOfflineEnabled) return + if ( + !transaction || + !this.offlineExecutor.isOfflineEnabled || + term !== this.offlineExecutor.leadershipTerm + ) + return // A duplicate message is harmless: both steps ignore a known transaction. this.scheduler.schedule(transaction) - this.restoreOptimisticState([transaction]) - await this.executeAll() + if (transaction.outboxPhase !== `rejection-pending`) + this.restoreOptimisticState([transaction]) + // A queue error belongs to its execution, not to this admission. + this.executeAll().catch((error) => { + console.warn(`Failed to execute transactions:`, error) + }) } /** diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 87572039af..58915d2dab 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -12,11 +12,8 @@ import type { Collection } from '@tanstack/db' export class OutboxTransactionNotFoundError extends Error {} -/** How a removed transaction settled, kept for a writer in another tab. */ -export type OutboxOutcome = { - at: number - error?: { name: string; message: string } -} +/** A rejected transaction's error, kept for a writer in another tab. */ +export type OutboxOutcome = { error: { name: string; message: string } } export class OutboxManager { private storage: StorageAdapter @@ -88,13 +85,25 @@ export class OutboxManager { /** * Reads one transaction, or null if it was removed after this read began, - * so a stale read cannot bring back a transaction that already settled. + * so a stale read cannot bring back a transaction that already settled. A + * row this tab cannot decode, such as one saved under a collection key it + * does not register, throws instead of reading as absent. */ async getCurrent(id: string): Promise { const read = { revision: this.removalRevision } this.activeReads.add(read) try { - const transaction = await this.get(id) + const data = await this.storage.get(this.getStorageKey(id)) + let transaction: OfflineTransaction | null = null + if (data) { + try { + transaction = this.serializer.deserialize(data) + } catch (error) { + throw new Error( + `Cannot read outbox transaction ${id}: ${(error as Error).message}`, + ) + } + } return (this.removedAtRevision.get(id) ?? 0) <= read.revision ? transaction : null @@ -104,11 +113,10 @@ export class OutboxManager { } } - /** Records how a transaction settled before its row is removed. */ - async recordOutcome(id: string, error?: Error): Promise { + /** Records a rejection before its row is removed. */ + async recordRejection(id: string, error: Error): Promise { const outcome: OutboxOutcome = { - at: Date.now(), - ...(error ? { error: { name: error.name, message: error.message } } : {}), + error: { name: error.name, message: error.message }, } await this.storage.set( `${this.outcomePrefix}${id}`, @@ -125,16 +133,6 @@ export class OutboxManager { await this.storage.delete(`${this.outcomePrefix}${id}`) } - /** Removes outcomes recorded before `before`, whose writers are gone. */ - async pruneOutcomes(before: number): Promise { - for (const key of await this.storage.keys()) { - if (!key.startsWith(this.outcomePrefix)) continue - const data = await this.storage.get(key) - if (data !== null && (JSON.parse(data) as OutboxOutcome).at < before) - await this.storage.delete(key) - } - } - async getAll(): Promise> { return this.withAll((transactions) => transactions) } diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index 369f64b4f6..f451001ce5 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -132,7 +132,8 @@ export interface OfflineConfig { /** * How a follower tab sends a write. `'online'` (default) calls the mutation * function directly, with no outbox entry. `'durable'` saves the write to the - * shared outbox, and the current or next leader sends it. Requires + * shared outbox, and the current or next leader sends it. Every tab must + * register its collections under the same keys. Requires * BroadcastChannel, and falls back to `'online'` without it. A write made * before the executor initializes uses the online path. */ @@ -167,8 +168,14 @@ export interface LeaderElection { export interface TransactionSignaler { readonly isOfflineEnabled: boolean + /** Counts leadership gains; absent for a signaler that never changes. */ + readonly leadershipTerm?: number resolveTransaction: (transactionId: string, result: any) => void - rejectTransaction: (transactionId: string, error: Error) => void + rejectTransaction: ( + transactionId: string, + error: Error, + announce?: boolean, + ) => void registerRestorationTransaction: ( offlineTransactionId: string, restorationTransaction: Transaction, diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 6503cec9a4..0e64b89791 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -26,8 +26,12 @@ * message arrives, close a tab, reopen a tab, reopen a tab and write before it * initializes, go online or offline, lose the next settlement, deliver a stale * or duplicate message, fail the leader's admission read of a follower's saved - * write, fail an outbox check's storage read, and return a leader's admission - * read only after a duplicate message sent and removed its write. + * write, fail an outbox check's storage read, return a leader's admission read + * only after a duplicate message sent and removed its write, fail the removal + * of a sent follower write, announce a saved row the leader cannot decode, + * return an admission read after leadership moved away and back while another + * leader sent its write, and have the next leader's beforeRetry exclude a + * follower's write while its settlement is lost. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. @@ -40,14 +44,18 @@ * model's outcome and error. A lost settlement is recovered for the same write, * by the writer itself if it became leader, or else after one handover. * + * A failed row removal after a successful send is not the write's outcome: + * its writer waits, and the next leader finishes the removal. A row the leader + * cannot decode is reported, not dropped, and a follower's failed outbox check + * runs again when connectivity changes. + * * Known omissions: a reloaded follower does not show another tab's pending - * writes optimistically; outcomes are pruned by age only for a record placed a - * day old before the tabs open; and no real browser contexts. + * writes optimistically; rejection records of writers that never return are + * kept; and no real browser contexts. */ import fc from 'fast-check' import { expect, vi } from 'vitest' import { NonRetriableError } from '../src/types' -import { OutboxManager } from '../src/outbox/OutboxManager' import { forwardAssertionJudgment, recordAssertionJudgment, @@ -103,6 +111,18 @@ const reachStates = [ `admission-retried`, // An admission read returned after its write was sent and removed. `stale-admission-ignored`, + // A failed outbox check ran again on connectivity and settled a lost write. + `reconcile-retried`, + // A sent follower write's removal failed and its writer kept waiting. + `removal-failure-not-announced`, + // The leader reported a saved row it could not decode. + `unreadable-write-reported`, + // An admission read spanning a change of leadership was dropped. + `stale-admission-across-terms`, + // A lost exclusion by beforeRetry still failed its writer. + `exclusion-recovered`, + // A rejection whose writer had closed kept its record. + `orphan-rejection-kept`, ] as const type ReachState = (typeof reachStates)[number] @@ -123,6 +143,10 @@ type SharedActionType = | `fail-admission-read` | `fail-outbox-check` | `stale-admission-read` + | `fail-removal` + | `unreadable-added` + | `stale-admission-across-terms` + | `exclude-on-handover` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -151,6 +175,10 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`fail-admission-read`) }, { weight: 1, arbitrary: sharedAction(`fail-outbox-check`) }, { weight: 1, arbitrary: sharedAction(`stale-admission-read`) }, + { weight: 1, arbitrary: sharedAction(`fail-removal`) }, + { weight: 1, arbitrary: sharedAction(`unreadable-added`) }, + { weight: 1, arbitrary: sharedAction(`stale-admission-across-terms`) }, + { weight: 1, arbitrary: sharedAction(`exclude-on-handover`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), @@ -170,7 +198,11 @@ const spliced = ( action.type !== `lose-settlement` && action.type !== `fail-admission-read` && action.type !== `fail-outbox-check` && - action.type !== `stale-admission-read`, + action.type !== `stale-admission-read` && + action.type !== `fail-removal` && + action.type !== `unreadable-added` && + action.type !== `stale-admission-across-terms` && + action.type !== `exclude-on-handover`, ) .slice(0, MAX_ACTIONS - prefix.length), ], @@ -276,6 +308,14 @@ class ReadFailingStorage extends FakeStorageAdapter { this.heldWrites = null for (const release of held) release(fail) } + failDeletes = 0 + override async delete(key: string): Promise { + if (this.failDeletes > 0 && key.startsWith(`tx:`)) { + this.failDeletes -= 1 + throw new Error(`storage delete failed`) + } + return super.delete(key) + } override async set(key: string, value: string): Promise { if (this.heldWrites) { const held = this.heldWrites @@ -374,8 +414,15 @@ type Write = { session: number // Made before its tab initialized, so it took the online path. preInit: boolean - // The leader's admission read failed and connectivity has not changed since. - unadmitted: boolean + // The session of the leader whose admission read failed, until + // connectivity changes. + unadmittedBy?: number + // A failed outbox check found this lost write pending. + checkFailed: boolean + // Its admission read failed at some point in the history. + retried?: boolean + // The next leader's beforeRetry excluded it. + excluded?: boolean outcome?: `completed` | `failed` error?: unknown } @@ -402,6 +449,8 @@ async function runHistory( // Which tab called the server for each write, and which tab led then. const sends: Array<{ id: string; sender: number; leader?: number }> = [] const rejected = new Set() + // Writes a new leader's beforeRetry excludes, by write id. + const excluded = new Set() const expectedWarnings = { admission: 0, check: 0 } type Tab = { env: ReturnType @@ -437,6 +486,13 @@ async function runHistory( ...(durable ? { followerWrites: `durable` } : {}), leaderElection: tabElection, onlineDetector: online.detector(), + beforeRetry: ( + transactions: Array<{ mutations: Array<{ key: unknown }> }>, + ) => + transactions.filter( + (transaction) => + !excluded.has(String(transaction.mutations[0]!.key)), + ), jitter: false, } as never, }) @@ -485,7 +541,7 @@ async function runHistory( undefined, ) } - if (leader && !write.unadmitted) { + if (leader && write.unadmittedBy !== leader.session) { expect( leader.env.collection.has(write.id), `${label}: leader shows ${write.id}`, @@ -518,7 +574,7 @@ async function runHistory( fromFollower, session: tab.session, preInit, - unadmitted: false, + checkFailed: false, } writes.push(write) if (write.rejected) rejected.add(id) @@ -570,9 +626,6 @@ async function runHistory( } try { - // A day-old outcome of a writer that never returned; the first leader - // prunes it. - if (durable) await storage.set(`outcome:aged`, JSON.stringify({ at: 0 })) for (let index = 0; index < TABS; index++) await openTab(index) expect(channels.state.created, `channels created`).toBe(durable ? TABS : 0) @@ -644,7 +697,7 @@ async function runHistory( case `online`: online.set(true) await settle() - for (const write of writes) write.unadmitted = false + for (const write of writes) write.unadmittedBy = undefined break case `offline`: online.set(false) @@ -675,8 +728,10 @@ async function runHistory( reach(`admission-read-failed`) storage.failReads = 1 expectedWarnings.admission += 1 + const leaderSession = tabs[leaderIndex()]!.session const write = await doWrite(follower, `write`) - write!.unadmitted = true + write!.unadmittedBy = leaderSession + write!.retried = true break } case `stale-admission-read`: { @@ -697,12 +752,113 @@ async function runHistory( if (calls.includes(write.id)) reach(`stale-admission-ignored`) break } + case `fail-removal`: { + // The leader sends a follower's write, then fails to remove its row. + const follower = tabs.findIndex( + (tab, index) => tab && index !== leaderIndex(), + ) + if (!durable || !online.online || leaderIndex() < 0 || follower < 0) + break + storage.failDeletes = 1 + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) break + expect(write.outcome, `${write.id} waits after a cleanup fault`).toBe( + undefined, + ) + reach(`removal-failure-not-announced`) + // The faulted leader's executor stops; the next leader finishes the + // removal and settles the writer. + await closeTab(leaderIndex()) + break + } + case `unreadable-added`: { + // A saved row this leader cannot decode is reported, not dropped. + if (!durable || leaderIndex() < 0) break + await storage.set( + `tx:unreadable`, + JSON.stringify({ id: `unreadable` }), + ) + expectedWarnings.admission += 1 + channels.inject({ type: `added`, id: `unreadable` }) + await settle() + reach(`unreadable-write-reported`) + await storage.delete(`tx:unreadable`) + break + } + case `stale-admission-across-terms`: { + // The leader's admission read stalls. Leadership moves away, another + // leader sends and removes the write, and leadership comes back + // before the read returns. + const first = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== first) + if ( + !durable || + !online.online || + first < 0 || + writer < 0 || + tabs.filter(Boolean).length < 3 + ) + break + storage.holdNextRead() + const write = await doWrite(writer, `write`) + if (!write) break + const original = tabs[first]!.election + for (let turn = 0; turn < TABS + 1; turn++) { + const holder = election.holder! + if (turn > 0 && holder === original) break + holder.releaseLeadership() + await settle() + await holder.requestLeadership() + await settle() + } + storage.releaseRead() + await settle() + if (calls.includes(write.id)) reach(`stale-admission-across-terms`) + break + } + case `exclude-on-handover`: { + // An offline follower write waits; its settlement is lost when the + // next leader's beforeRetry excludes it. + // The writer stays a follower, so it learns the exclusion only + // from the record. In the default mode a follower's write is not + // saved, so the leader writes and closes, and no record is kept. + const leader = leaderIndex() + const next = election.queue[0] + const writer = durable + ? tabs.findIndex( + (tab, index) => + tab && index !== leader && tab.election !== next, + ) + : leader + if (leader < 0 || writer < 0 || tabs.filter(Boolean).length < 3) break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + excluded.add(write.id) + write.excluded = true + write.deliverable = false + channels.state.loseSettlement = true + await closeTab(leader) + channels.state.loseSettlement = false + if (write.outcome === `failed`) reach(`exclusion-recovered`) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() - const waiting = writes.some( - (write) => isUnsent(write) && sessionsOpen.has(write.session), + const pending = writes.filter( + (write) => + write.outcome === undefined && + write.deliverable && + !write.preInit && + sessionsOpen.has(write.session), ) - if (!durable || !waiting) break + if (!durable || pending.length === 0) break + for (const write of pending) + if ( + write.transactionId && + channels.state.lostIds.includes(write.transactionId) + ) + write.checkFailed = true reach(`outbox-check-read-failed`) storage.failReads = 1 expectedWarnings.check += 1 @@ -720,6 +876,15 @@ async function runHistory( channels.state.loseSettlement = false online.set(true) await settle() + if ( + writes.some( + (write) => + write.checkFailed && + openSessions().has(write.session) && + write.outcome !== undefined, + ) + ) + reach(`reconcile-retried`) const lostWrites = writes.filter( (write) => write.transactionId !== undefined && @@ -771,6 +936,16 @@ async function runHistory( for (let round = 0; round < 8; round++) await settle() const sessionsOpen = openSessions() + if ( + writes.some( + (write) => + durable && + write.rejected && + write.deliverable && + write.outcome === undefined, + ) + ) + reach(`orphan-rejection-kept`) for (const write of writes) { if (!durable || !write.fromFollower) continue if (!write.rejected) reach(`follower-write-delivered`) @@ -778,20 +953,19 @@ async function runHistory( reach(`follower-write-rejected`) } } - if (writes.some((write) => write.unadmitted && calls.includes(write.id))) + if (writes.some((write) => write.retried && calls.includes(write.id))) reach(`admission-retried`) for (const send of sends) { const write = writes.find((candidate) => candidate.id === send.id)! - if (write.preInit || !durable) continue - // A durable write is sent only by the tab that leads at that moment. - expect(send.sender, `${send.id} sent by the leader`).toBe(send.leader) - } - for (const write of writes) { - if (!write.preInit) continue - for (const send of sends.filter((candidate) => candidate.id === write.id)) - expect(send.sender, `${write.id} sent by its own tab`).toBe( + if (write.preInit || !durable) { + // The online path: the writing tab calls the server itself. + expect(send.sender, `${send.id} sent by its own tab`).toBe( write.session, ) + } else { + // A durable write is sent only by the tab that leads at that moment. + expect(send.sender, `${send.id} sent by the leader`).toBe(send.leader) + } } expect([...calls].sort(), `each write reached the server once`).toEqual( writes @@ -801,8 +975,8 @@ async function runHistory( ) const executor = tabs[leaderIndex()]!.env.executor expect(await executor.peekOutbox(), `the outbox is empty`).toEqual([]) - // An outcome record stays only for a sent durable write whose tab closed - // before it settled; a tab that settles its write removes the record. + // A rejection record stays only for a rejected durable write whose tab + // closed before it settled; a completed write leaves no record. const outcomes = (await storage.keys()) .filter((key) => key.startsWith(`outcome:`)) .map((key) => key.slice(`outcome:`.length)) @@ -813,25 +987,26 @@ async function runHistory( (write) => durable && !write.preInit && - write.deliverable && + (write.excluded || (write.deliverable && write.rejected)) && write.outcome === undefined, ) .map((write) => write.transactionId) .sort(), ) - // Every recorded outcome carries its age, so a day later all are pruned. - await new OutboxManager(storage, {}).pruneOutcomes( - Date.now() + 2 * 24 * 60 * 60 * 1000, - ) - expect( - (await storage.keys()).filter((key) => key.startsWith(`outcome:`)), - `outcome records a day later`, - ).toEqual([]) for (const write of writes) { if (!sessionsOpen.has(write.session)) continue expect(write.outcome, `${write.id} outcome`).toBe( write.rejected || !write.deliverable ? `failed` : `completed`, ) + if (write.excluded) { + const error = write.error as Error + expect(error, `${write.id} exclusion error`).toBeInstanceOf( + NonRetriableError, + ) + expect(error.message, `${write.id} exclusion message`).toBe( + `Transaction excluded by beforeRetry`, + ) + } if (write.rejected && write.deliverable) { const error = write.error as Error expect(error, `${write.id} error type`).toBeInstanceOf( @@ -859,9 +1034,9 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, - limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts, and no outcome old enough to be pruned.`, + limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, owns: [ `src/OfflineExecutor.ts`, @@ -875,10 +1050,9 @@ oracleProperty({ `src/OfflineExecutor.ts#OfflineExecutor.settleFollowerWrite`, `src/OfflineExecutor.ts#OfflineExecutor.writesToSharedOutbox`, `src/outbox/OutboxManager.ts#OutboxManager.getCurrent`, - `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.recordRejection`, `src/outbox/OutboxManager.ts#OutboxManager.getOutcome`, `src/outbox/OutboxManager.ts#OutboxManager.removeOutcome`, - `src/outbox/OutboxManager.ts#OutboxManager.pruneOutcomes`, ], histories: { arbitrary: historyArbitrary, @@ -996,6 +1170,60 @@ oracleProperty({ actions: [{ type: `stale-admission-read` }], }), }, + { + name: `a failed outbox check runs again on connectivity`, + enters: [`outbox-check-read-failed`, `reconcile-retried`], + build: (): History => ({ + mode: `durable`, + actions: [loseSettlement, write(2), { type: `fail-outbox-check` }], + }), + }, + { + name: `a cleanup fault is not a follower's outcome`, + enters: [`removal-failure-not-announced`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `fail-removal` }], + }), + }, + { + name: `an unreadable saved row is reported`, + enters: [`unreadable-write-reported`], + build: (generated: History): History => + spliced(generated, [{ type: `unreadable-added` }]), + }, + { + name: `an admission read across a change of leadership is dropped`, + enters: [`stale-admission-across-terms`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `stale-admission-across-terms` }], + }), + }, + { + name: `a rejection whose writer closed keeps its record`, + enters: [`orphan-rejection-kept`], + build: (): History => ({ + mode: `durable`, + actions: [offline, { type: `write-rejected`, tab: 1 }, close(1)], + }), + }, + { + name: `an exclusion in the default mode keeps no record`, + enters: [], + build: (): History => ({ + mode: `online`, + actions: [{ type: `exclude-on-handover` }], + }), + }, + { + name: `a lost exclusion still fails its writer`, + enters: [`exclusion-recovered`], + build: (): History => ({ + mode: `durable`, + actions: [{ type: `exclude-on-handover` }], + }), + }, { name: `a write before initialization takes the online path`, enters: [`pre-initialization-write`], From c84758e48dd903ad800c6dc3e329a8984837c4a7 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 13:59:47 -0800 Subject: [PATCH 04/16] fix(offline-transactions): address third durable follower write review A failed rejection record no longer faults the executor: the terminal row stays and its cleanup retries, and the rejection settles only once it is recorded. A write excluded by beforeRetry cannot be admitted while its cleanup runs. removeFromOutbox records a rejection for a saved follower write and drops an unstarted transaction from the queue. Only the newest outbox check sets the connectivity retry flag. A save acknowledged after a change of leadership is admitted by id, a follower's save ignores its own executor's fault, and a save that resumes after disposal still announces itself. The outbox channel is named by the registry keys the tabs share. A failed start closes the channel and releases leadership, and a tab that loses leadership drops its unstarted queue. The oracle covers each case, credits a failed outbox check to the writer whose read failed, and splices its constructed histories into generated ones. --- .changeset/durable-follower-writes.md | 2 +- docs/contributing/oracle-coverage.md | 7 +- docs/guides/offline-transactions.md | 2 +- packages/offline-transactions/README.md | 2 +- .../src/OfflineExecutor.ts | 68 ++- .../src/executor/TransactionExecutor.ts | 63 ++- .../durable-follower-oracle.property.test.ts | 479 +++++++++++++++--- .../offline-transactions/tests/harness.ts | 13 +- 8 files changed, 523 insertions(+), 113 deletions(-) diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index 5c955dc150..f59394f5d1 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. The default stays `'online'`. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. The default stays `'online'`. `removeFromOutbox()` now also stops a removed transaction that has not started. diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index b3d759624d..c3b8975a88 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4256,7 +4256,12 @@ The post-merge review added three missing domains to existing owners: records remain. It also covers a failed row removal after a successful send, an undecodable saved row, a follower's failed outbox check, an admission read across a change of leadership, and a `beforeRetry` exclusion whose settlement - is lost. It does not cover real browser contexts. + is lost. It also covers a failed rejection record, a late admission during an + exclusion, a write removed before it was sent, a save acknowledged after a + handover, a faulted former leader that saves for its successor, a failed + start, a save that ends after its tab closed, and tabs that name their + collections differently under one key. It does not cover real browser + contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 4c8ee82f0e..3b920b3f16 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it. Every tab must register its collections under the same keys: a leader that cannot read a follower's saved write reports it and keeps the write pending. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` before it is sent fails its writer's transaction. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/README.md b/packages/offline-transactions/README.md index 5f583c92b0..ff446f3831 100644 --- a/packages/offline-transactions/README.md +++ b/packages/offline-transactions/README.md @@ -223,7 +223,7 @@ mutation function after restart; an unmarked row may replay. - `createOfflineTransaction(options)` - Create a manual offline transaction - `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete. Call it before the transaction settles: a waiter for a transaction that this executor recently settled (one of its last 1,000) rejects. A waiter for an older settled id keeps waiting. A waiter for an id the executor does not know yet keeps waiting, because another tab can still queue that transaction. -- `removeFromOutbox(id)` - Manually remove transaction from outbox +- `removeFromOutbox(id)` - Manually remove transaction from outbox. A removed transaction that has not started does not run, and with `followerWrites: 'durable'` its writer's transaction fails - `clearOutbox()` - Manually remove all outbox transactions - `peekOutbox()` - View all pending transactions - `dispose()` - Stop new processing and release executor resources. Pending durable transactions and optimistic state on surviving Collections remain live. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 17a33b761e..f6b13a4242 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -105,6 +105,9 @@ export class OfflineExecutor { private readonly unadmitted = new Set() // A follower's outbox check failed; it runs again on connectivity. private reconcileFailed = false + // Only the newest outbox check sets or clears reconcileFailed. + private sweeps = 0 + private outboxChannelName: string | null = null private initialized = false private term = 0 private pendingTransactionPromises: Map< @@ -267,7 +270,10 @@ export class OfflineExecutor { if (this.disposed || isLeader === this.isLeaderState) return this.isLeaderState = isLeader if (isLeader) this.term++ - else this.executor?.pause() + else { + this.executor?.pause() + this.executor?.dropPending() + } if (this.config.onLeadershipChange) { this.config.onLeadershipChange(isLeader) @@ -386,6 +392,10 @@ export class OfflineExecutor { this.initResolve() } catch (error) { console.warn(`Failed to initialize offline executor:`, error) + // A failed start releases what it opened, without waiting for dispose(). + this.outboxChannel?.close() + this.outboxChannel = null + this.leaderElection?.releaseLeadership() this.initReject(error instanceof Error ? error : new Error(String(error))) } } @@ -419,12 +429,11 @@ export class OfflineExecutor { ) { return } - const collectionIds = Object.values(this.config.collections) - .map((collection) => collection.id) - .sort() - this.outboxChannel = new BroadcastChannel( - `tanstack-offline-outbox:${collectionIds.join(`,`)}`, - ) + // Tabs that share an outbox register the same keys; their collection + // ids may differ. + const registryKeys = Object.keys(this.config.collections).sort() + this.outboxChannelName = `tanstack-offline-outbox:${registryKeys.join(`,`)}` + this.outboxChannel = new BroadcastChannel(this.outboxChannelName) this.outboxChannel.onmessage = (event: MessageEvent) => { this.handleOutboxMessage(event.data) } @@ -475,6 +484,7 @@ export class OfflineExecutor { // row removed with no record completed. A failed read leaves that write // pending, and the check runs again when connectivity changes. private async settleRemovedWrites(): Promise { + const sweep = ++this.sweeps let failed = false for (const [id, waiter] of [...this.pendingTransactionPromises]) { try { @@ -487,7 +497,7 @@ export class OfflineExecutor { console.warn(`Failed to reconcile follower writes:`, error) } } - this.reconcileFailed = failed + if (sweep === this.sweeps) this.reconcileFailed = failed } /** Counts later leadership gains, so work begun in an earlier term can tell. */ @@ -495,6 +505,20 @@ export class OfflineExecutor { return this.term } + // Tells the leader about a saved write, even when this tab was disposed + // while the save ran. + private announceAdded(id: string): void { + const message = { type: `added`, id } satisfies OutboxMessage + if (this.outboxChannel) { + this.outboxChannel.postMessage(message) + return + } + if (this.outboxChannelName === null) return + const channel = new BroadcastChannel(this.outboxChannelName) + channel.postMessage(message) + channel.close() + } + private announceSettled(id: string, error?: Error, own = false): void { if (this.outboxChannel) { // This tab's own rejected write needs no record for another tab. @@ -609,7 +633,11 @@ export class OfflineExecutor { } try { - this.executor.assertHealthy() + const term = this.term + // A follower's save goes to the shared outbox for whichever tab leads; + // this executor's own faults only stop work it would run itself. + if (this.isOfflineEnabled || !this.writesToSharedOutbox) + this.executor.assertHealthy() const saved = this.outbox.add(transaction) // The transaction registered this waiter before it asked to persist. this.pendingTransactionPromises.get(transaction.id)!.saved = saved.then( @@ -617,11 +645,14 @@ export class OfflineExecutor { () => false, ) await saved - if (this.outboxChannel && !this.isOfflineEnabled) { - this.outboxChannel.postMessage({ - type: `added`, - id: transaction.id, - } satisfies OutboxMessage) + if (!this.isOfflineEnabled) { + this.announceAdded(transaction.id) + return + } + // Leadership changed while the row was saved: another leader may have + // sent and removed it, so admit it only if it is still there. + if (term !== this.term) { + this.admitFollowerWrite(transaction.id) return } // A shared queue error belongs to its execution, not every caller @@ -805,7 +836,16 @@ export class OfflineExecutor { if (!this.outbox) { return } + // A follower that saved this write and has not heard an outcome must not + // read the removal as success. + if (this.outboxChannelName !== null && (await this.outbox.get(id))) + await this.outbox.recordRejection( + id, + new NonRetriableError(`Transaction removed from the outbox`), + ) await this.outbox.remove(id) + // A removed transaction that has not started does not run. + this.scheduler.removePendingTransactions([id]) } async peekOutbox(): Promise> { diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 1d4d95c58a..408e6a545b 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -29,6 +29,8 @@ export class TransactionExecutor { private offlineExecutor: TransactionSignaler private retryTimer: ReturnType | null = null private fatalError: Error | null = null + // Writes beforeRetry excluded whose rejection cleanup has not finished. + private readonly excluding = new Set() constructor( scheduler: KeyScheduler, @@ -114,10 +116,14 @@ export class TransactionExecutor { ? transaction : { ...transaction, outboxPhase: `deletion-pending` } try { - await this.removeSettledTransaction( - deletionPending, - !transaction.outboxPhase, + // A rejection waits until it is recorded and its row removed. + if ( + !(await this.removeSettledTransaction( + deletionPending, + !transaction.outboxPhase, + )) ) + return } catch (error) { const storageError = error as Error // A cleanup fault is not the write's outcome. Another tab's writer @@ -247,7 +253,9 @@ export class TransactionExecutor { this.scheduler.getPendingCount() > 1, ) try { - await this.removeSettledTransaction(rejectionPending, true) + // A rejection waits until it is recorded and its row removed. + if (!(await this.removeSettledTransaction(rejectionPending, true))) + return } catch (storageError) { this.offlineExecutor.rejectTransaction(transaction.id, terminalError) throw storageError @@ -301,10 +309,11 @@ export class TransactionExecutor { } } + /** False when the row stays because its rejection could not be recorded. */ private async removeSettledTransaction( transaction: OfflineTransaction, persistMarker: boolean, - ): Promise { + ): Promise { // Read by this function's development-only oracle probes, as above. const probing = typeof process === `undefined` @@ -334,13 +343,31 @@ export class TransactionExecutor { this.config.followerWrites === `durable` && transaction.outboxPhase === `rejection-pending` ) { - await this.outbox.recordRejection( - transaction.id, - this.getTerminalError(transaction), - ) + try { + await this.outbox.recordRejection( + transaction.id, + this.getTerminalError(transaction), + ) + } catch (error) { + // The terminal row stays; a later attempt records the rejection and + // removes it without calling the provider. Other writes keep running. + console.warn( + `Failed to record rejection of transaction ${transaction.id}:`, + error, + ) + this.scheduler.updateTransaction({ + ...transaction, + nextAttemptAt: + Date.now() + + this.retryPolicy.calculateDelay(transaction.retryCount), + }) + this.scheduler.markFailed(transaction) + return false + } } await this.outbox.remove(transaction.id) this.scheduler.markCompleted(transaction) + return true } catch (error) { const storageError = toError(error) // Development-only oracle probe; a production build removes it. The @@ -407,6 +434,8 @@ export class TransactionExecutor { .filter(({ id }) => !selectedById.has(id)) .map(({ id }) => id) removedIds = this.scheduler.removePendingTransactions(removedIds) + // A late admission must not run a write this hook excluded. + for (const id of removedIds) this.excluding.add(id) // Restore optimistic state for loaded transactions // This ensures the UI shows the optimistic data while transactions are pending @@ -438,6 +467,8 @@ export class TransactionExecutor { id, cleanupError, ) + } finally { + this.excluding.delete(id) } }), ) @@ -457,7 +488,8 @@ export class TransactionExecutor { if ( !transaction || !this.offlineExecutor.isOfflineEnabled || - term !== this.offlineExecutor.leadershipTerm + term !== this.offlineExecutor.leadershipTerm || + this.excluding.has(id) ) return // A duplicate message is harmless: both steps ignore a known transaction. @@ -534,6 +566,17 @@ export class TransactionExecutor { this.clearRetryTimer() } + /** + * Drops queued work that has not started. Another leader may send and + * remove it; a later leadership gain loads what remains from the outbox. + */ + dropPending(): void { + this.scheduler.removePendingTransactions( + this.scheduler.getAllPendingTransactions().map(({ id }) => id), + ) + this.clearRetryTimer() + } + getPendingCount(): number { return this.scheduler.getPendingCount() } diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 0e64b89791..f461ca051b 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -121,6 +121,20 @@ const reachStates = [ `stale-admission-across-terms`, // A lost exclusion by beforeRetry still failed its writer. `exclusion-recovered`, + // A failed rejection record was retried while other writes kept running. + `outcome-record-retried`, + // A late admission during an exclusion's cleanup sent nothing. + `excluded-admission-ignored`, + // A saved write removed before any leader sent it failed its writer. + `removed-unsent-failed`, + // A save acknowledged after a change of leadership was admitted by id. + `save-acknowledged-after-handover`, + // A former leader with a faulted executor saved a write for its successor. + `faulted-former-leader-saved`, + // A tab whose start failed released its channel and leadership. + `failed-start-released`, + // A save that finished after its tab closed still reached the leader. + `save-announced-after-dispose`, // A rejection whose writer had closed kept its record. `orphan-rejection-kept`, ] as const @@ -147,6 +161,11 @@ type SharedActionType = | `unreadable-added` | `stale-admission-across-terms` | `exclude-on-handover` + | `fail-outcome-record` + | `remove-unsent` + | `ack-after-handover` + | `open-failing` + | `dispose-during-save` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -179,20 +198,37 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`unreadable-added`) }, { weight: 1, arbitrary: sharedAction(`stale-admission-across-terms`) }, { weight: 1, arbitrary: sharedAction(`exclude-on-handover`) }, + { weight: 1, arbitrary: sharedAction(`fail-outcome-record`) }, + { weight: 1, arbitrary: sharedAction(`remove-unsent`) }, + { weight: 1, arbitrary: sharedAction(`ack-after-handover`) }, + { weight: 1, arbitrary: sharedAction(`open-failing`) }, + { weight: 1, arbitrary: sharedAction(`dispose-during-save`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), actions: fc.array(actionArbitrary, { maxLength: MAX_ACTIONS }), }) +// Actions that leave the tabs, leadership and connectivity as they were. +const BENIGN = new Set([ + `write`, + `write-rejected`, + `open`, + `online`, + `stale-added`, + `duplicate-added`, +]) const spliced = ( generated: History, prefix: Array, mode: Mode = `durable`, + // A state judged when the history ends keeps the generated tail benign. + benign = false, ): History => ({ mode, actions: [ ...prefix, ...generated.actions + .filter((action) => !benign || BENIGN.has(action.type)) .filter( (action) => action.type !== `lose-settlement` && @@ -202,7 +238,12 @@ const spliced = ( action.type !== `fail-removal` && action.type !== `unreadable-added` && action.type !== `stale-admission-across-terms` && - action.type !== `exclude-on-handover`, + action.type !== `exclude-on-handover` && + action.type !== `fail-outcome-record` && + action.type !== `remove-unsent` && + action.type !== `ack-after-handover` && + action.type !== `open-failing` && + action.type !== `dispose-during-save`, ) .slice(0, MAX_ACTIONS - prefix.length), ], @@ -232,6 +273,8 @@ class TabElection implements LeaderElection { constructor( private readonly shared: ControlledElection, private readonly hold?: Promise, + // The request joins the election, then rejects. + private readonly fail = false, ) {} async requestLeadership(): Promise { @@ -245,6 +288,7 @@ class TabElection implements LeaderElection { ) { this.shared.queue.push(this) } + if (this.fail) throw new Error(`leadership request failed`) return this.leader } releaseLeadership(): void { @@ -296,6 +340,19 @@ class ControlledOnline { class ReadFailingStorage extends FakeStorageAdapter { failReads = 0 + // The next read of this key fails. + failReadKey: string | undefined + // The next outcome record write fails. + failOutcomeWrites = 0 + // The next write lands at once and acknowledges on release. + private heldAck: { release: () => void } | null | undefined + holdNextAck(): void { + this.heldAck = null + } + releaseAck(): void { + this.heldAck?.release() + this.heldAck = undefined + } // The next read captures its value at once and returns it on release. private staleRead: { release: () => void } | null | undefined private heldWrites: Array<(fail: boolean) => void> | null = null @@ -317,6 +374,17 @@ class ReadFailingStorage extends FakeStorageAdapter { return super.delete(key) } override async set(key: string, value: string): Promise { + if (this.failOutcomeWrites > 0 && key.startsWith(`outcome:`)) { + this.failOutcomeWrites -= 1 + throw new Error(`storage write failed`) + } + if (this.heldAck === null && key.startsWith(`tx:`)) { + await super.set(key, value) + await new Promise((release) => { + this.heldAck = { release } + }) + return + } if (this.heldWrites) { const held = this.heldWrites const fail = await new Promise((resolve) => held.push(resolve)) @@ -332,6 +400,10 @@ class ReadFailingStorage extends FakeStorageAdapter { this.staleRead = undefined } override async get(key: string): Promise { + if (this.failReadKey === key) { + this.failReadKey = undefined + throw new Error(`storage read failed`) + } if (this.failReads > 0) { this.failReads -= 1 throw new Error(`storage read failed`) @@ -423,6 +495,10 @@ type Write = { retried?: boolean // The next leader's beforeRetry excluded it. excluded?: boolean + // removeFromOutbox removed it before any leader sent it. + removed?: boolean + // Its rejection record failed once. + recordRetried?: boolean outcome?: `completed` | `failed` error?: unknown } @@ -464,11 +540,15 @@ async function runHistory( index: number, beforeInit?: () => Promise, hold?: Promise, + failStart = false, ) => { - const tabElection = new TabElection(election, hold) + const tabElection = new TabElection(election, hold, failStart) const session = ++sessions const env = createTestOfflineEnvironment({ storage, + // Each tab names its collection differently under the shared key. + collectionId: `items-${session}`, + registryKey: `test-items`, mutationFn: (params: OfflineMutationFnParams) => { const id = String(params.transaction.mutations[0].key) // The server is unreachable while offline, whichever path sends it. @@ -498,9 +578,22 @@ async function runHistory( }) tabs[index] = { env, election: tabElection, session } await beforeInit?.() - await env.executor.waitForInit() + if (failStart) { + await env.executor.waitForInit().catch(() => undefined) + } else await env.executor.waitForInit() await settle() } + // Leadership moves tab to tab until `target` leads, at least once. + const rotateTo = async (target: TabElection) => { + for (let turn = 0; turn < TABS + 1; turn++) { + const holder = election.holder! + if (turn > 0 && holder === target) return + holder.releaseLeadership() + await settle() + await holder.requestLeadership() + await settle() + } + } const closeTab = async (index: number) => { const tab = tabs[index] if (!tab) return @@ -761,14 +854,31 @@ async function runHistory( break storage.failDeletes = 1 const write = await doWrite(follower, `write`) - if (!write || !calls.includes(write.id)) break + // A queue still busy with earlier writes leaves the fault unused. + if (!write || !calls.includes(write.id)) { + storage.failDeletes = 0 + break + } expect(write.outcome, `${write.id} waits after a cleanup fault`).toBe( undefined, ) reach(`removal-failure-not-announced`) - // The faulted leader's executor stops; the next leader finishes the - // removal and settles the writer. - await closeTab(leaderIndex()) + // The faulted leader stays open as a follower; the next leader + // finishes the removal. A write from the faulted tab is saved for + // that leader, which sends it. + const faulted = leaderIndex() + const successor = tabs.findIndex( + (tab, index) => tab && index !== faulted, + ) + await rotateTo(tabs[successor]!.election) + const saved = await doWrite(faulted, `write`) + if (saved) { + expect(calls, `${saved.id} sent for the faulted tab`).toContain( + saved.id, + ) + reach(`faulted-former-leader-saved`) + } + await closeTab(faulted) break } case `unreadable-added`: { @@ -781,6 +891,10 @@ async function runHistory( expectedWarnings.admission += 1 channels.inject({ type: `added`, id: `unreadable` }) await settle() + expect( + await storage.get(`tx:unreadable`), + `the unreadable row is kept`, + ).toBe(JSON.stringify({ id: `unreadable` })) reach(`unreadable-write-reported`) await storage.delete(`tx:unreadable`) break @@ -803,14 +917,12 @@ async function runHistory( const write = await doWrite(writer, `write`) if (!write) break const original = tabs[first]!.election - for (let turn = 0; turn < TABS + 1; turn++) { - const holder = election.holder! - if (turn > 0 && holder === original) break - holder.releaseLeadership() - await settle() - await holder.requestLeadership() - await settle() - } + await rotateTo(original) + expect(election.holder, `the original tab leads again`).toBe(original) + expect( + await storage.get(`tx:${write.transactionId}`), + `another leader removed ${write.id}`, + ).toBe(null) storage.releaseRead() await settle() if (calls.includes(write.id)) reach(`stale-admission-across-terms`) @@ -838,11 +950,130 @@ async function runHistory( write.excluded = true write.deliverable = false channels.state.loseSettlement = true + // The exclusion's record stalls, and an admission arrives meanwhile. + if (durable) storage.holdWrites() await closeTab(leader) + if (durable) { + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + reach(`excluded-admission-ignored`) + storage.releaseWrites(false) + await settle() + } channels.state.loseSettlement = false if (write.outcome === `failed`) reach(`exclusion-recovered`) break } + case `fail-outcome-record`: { + // A follower's write is rejected, its rejection record fails, and + // another write after it still runs. + const follower = tabs.findIndex( + (tab, index) => tab && index !== leaderIndex(), + ) + if (!durable || !online.online || leaderIndex() < 0 || follower < 0) + break + storage.failOutcomeWrites = 1 + const rejectedWrite = await doWrite(follower, `write-rejected`) + const next = await doWrite(follower, `write`) + // The later write waits its turn behind the rejected one, which + // retries its cleanup; the history's end checks that both settle. + if (!rejectedWrite || !next || !calls.includes(rejectedWrite.id)) { + storage.failOutcomeWrites = 0 + break + } + rejectedWrite.recordRetried = true + break + } + case `remove-unsent`: { + // The leader removes a follower's saved write before sending it. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0) break + online.set(false) + const write = await doWrite(follower, `write`) + if (!write) break + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + channels.inject({ type: `leader` }) + await settle() + if (write.outcome === `failed`) reach(`removed-unsent-failed`) + break + } + case `ack-after-handover`: { + // A follower's row lands but its save acknowledges only after + // another leader sent and removed it and the writer then leads. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + !online.online || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 3 + ) + break + storage.holdNextAck() + const write = await doWrite(writer, `write`) + if (!write) { + storage.releaseAck() + break + } + await rotateTo(tabs[writer]!.election) + expect(calls, `${write.id} sent by another leader`).toContain( + write.id, + ) + storage.releaseAck() + await settle() + reach(`save-acknowledged-after-handover`) + break + } + case `open-failing`: { + // A tab whose start fails leaves no channel open and no claim on + // leadership, without being disposed. + const index = tabs.findIndex((tab) => !tab) + if (!durable || index < 0) break + const before = channels.openCount() + await openTab(index, undefined, undefined, true) + const failed = tabs[index]! + expect(channels.openCount(), `a failed start keeps no channel`).toBe( + before, + ) + expect( + election.holder !== failed.election && + !election.queue.includes(failed.election), + `a failed start keeps no leadership claim`, + ).toBe(true) + reach(`failed-start-released`) + tabs[index] = undefined + failed.env.executor.dispose() + await settle() + break + } + case `dispose-during-save`: { + // A follower closes while its save runs; the save still reaches + // the current leader, which sends it. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || !online.online || leader < 0 || follower < 0) break + storage.holdWrites() + const write = await doWrite(follower, `write`) + if (!write) break + await closeTab(follower) + storage.releaseWrites(false) + await settle() + expect(calls, `${write.id} sent after its tab closed`).toContain( + write.id, + ) + reach(`save-announced-after-dispose`) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const pending = writes.filter( @@ -853,14 +1084,17 @@ async function runHistory( sessionsOpen.has(write.session), ) if (!durable || pending.length === 0) break - for (const write of pending) - if ( - write.transactionId && - channels.state.lostIds.includes(write.transactionId) - ) - write.checkFailed = true + // The read that fails is this writer's check of its own row. + const target = + pending.find( + (write) => + write.transactionId && + channels.state.lostIds.includes(write.transactionId), + ) ?? pending[0]! + if (channels.state.lostIds.includes(target.transactionId!)) + target.checkFailed = true reach(`outbox-check-read-failed`) - storage.failReads = 1 + storage.failReadKey = `tx:${target.transactionId}` expectedWarnings.check += 1 channels.inject({ type: `leader` }) await settle() @@ -876,15 +1110,16 @@ async function runHistory( channels.state.loseSettlement = false online.set(true) await settle() - if ( - writes.some( - (write) => - write.checkFailed && - openSessions().has(write.session) && - write.outcome !== undefined, - ) - ) + // The writer whose check failed settles on connectivity, before any + // handover. + for (const write of writes) { + if (!write.checkFailed || !openSessions().has(write.session)) continue + expect( + write.outcome, + `${write.id} settled after its failed check`, + ).not.toBe(undefined) reach(`reconcile-retried`) + } const lostWrites = writes.filter( (write) => write.transactionId !== undefined && @@ -957,7 +1192,7 @@ async function runHistory( reach(`admission-retried`) for (const send of sends) { const write = writes.find((candidate) => candidate.id === send.id)! - if (write.preInit || !durable) { + if (write.preInit || (!durable && write.fromFollower)) { // The online path: the writing tab calls the server itself. expect(send.sender, `${send.id} sent by its own tab`).toBe( write.session, @@ -987,7 +1222,9 @@ async function runHistory( (write) => durable && !write.preInit && - (write.excluded || (write.deliverable && write.rejected)) && + (write.excluded || + write.removed || + (write.deliverable && write.rejected)) && write.outcome === undefined, ) .map((write) => write.transactionId) @@ -998,6 +1235,13 @@ async function runHistory( expect(write.outcome, `${write.id} outcome`).toBe( write.rejected || !write.deliverable ? `failed` : `completed`, ) + if (write.removed) { + expect((write.error as Error).message, `${write.id} removal`).toBe( + `Transaction removed from the outbox`, + ) + } + if (write.recordRetried && write.outcome === `failed`) + reach(`outcome-record-retried`) if (write.excluded) { const error = write.error as Error expect(error, `${write.id} exclusion error`).toBeInstanceOf( @@ -1080,26 +1324,25 @@ oracleProperty({ { name: `the server rejects a follower's write`, enters: [`follower-write-rejected`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `write-rejected`, tab: 2 }], - }), + build: (generated: History): History => + spliced( + generated, + [{ type: `write-rejected`, tab: 2 }], + `durable`, + true, + ), }, { name: `a lost settlement is recovered at handover`, enters: [`lost-settlement-recovered`, `follower-write-delivered`], - build: (): History => ({ - mode: `durable`, - actions: [loseSettlement, write(1)], - }), + build: (generated: History): History => + spliced(generated, [loseSettlement, write(1)], `durable`, true), }, { name: `a tab that stays a follower recovers a lost settlement`, enters: [`lost-settlement-recovered-by-follower`], - build: (): History => ({ - mode: `durable`, - actions: [loseSettlement, write(2)], - }), + build: (generated: History): History => + spliced(generated, [loseSettlement, write(2)], `durable`, true), }, { name: `the default mode keeps the online follower path`, @@ -1133,7 +1376,8 @@ oracleProperty({ { name: `a leader writes in the default mode`, enters: [`online-mode-leader-write-delivered`], - build: (): History => ({ mode: `online`, actions: [write(0)] }), + build: (generated: History): History => + spliced(generated, [write(0)], `online`, true), }, { name: `failed storage reads are reported`, @@ -1149,42 +1393,52 @@ oracleProperty({ { name: `a leader retries a saved write it could not read`, enters: [`admission-read-failed`, `admission-retried`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `fail-admission-read` }], - }), + build: (generated: History): History => + spliced( + generated, + [{ type: `fail-admission-read` }], + `durable`, + true, + ), }, { name: `a lost rejection still fails its writer`, enters: [`lost-settlement-recovered`, `lost-rejection-recovered`], - build: (): History => ({ - mode: `durable`, - actions: [loseSettlement, { type: `write-rejected`, tab: 2 }], - }), + build: (generated: History): History => + spliced( + generated, + [loseSettlement, { type: `write-rejected`, tab: 2 }], + `durable`, + true, + ), }, { name: `a stale admission read does not send a write again`, enters: [`stale-admission-ignored`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `stale-admission-read` }], - }), + build: (generated: History): History => + spliced( + generated, + [{ type: `stale-admission-read` }], + `durable`, + true, + ), }, { name: `a failed outbox check runs again on connectivity`, enters: [`outbox-check-read-failed`, `reconcile-retried`], - build: (): History => ({ - mode: `durable`, - actions: [loseSettlement, write(2), { type: `fail-outbox-check` }], - }), + build: (generated: History): History => + spliced( + generated, + [loseSettlement, write(2), { type: `fail-outbox-check` }], + `durable`, + true, + ), }, { name: `a cleanup fault is not a follower's outcome`, enters: [`removal-failure-not-announced`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `fail-removal` }], - }), + build: (generated: History): History => + spliced(generated, [{ type: `fail-removal` }], `durable`, true), }, { name: `an unreadable saved row is reported`, @@ -1195,34 +1449,97 @@ oracleProperty({ { name: `an admission read across a change of leadership is dropped`, enters: [`stale-admission-across-terms`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `stale-admission-across-terms` }], - }), + build: (generated: History): History => + spliced( + generated, + [{ type: `stale-admission-across-terms` }], + `durable`, + true, + ), }, { name: `a rejection whose writer closed keeps its record`, enters: [`orphan-rejection-kept`], - build: (): History => ({ - mode: `durable`, - actions: [offline, { type: `write-rejected`, tab: 1 }, close(1)], - }), + build: (generated: History): History => + spliced( + generated, + [offline, { type: `write-rejected`, tab: 1 }, close(1)], + `durable`, + true, + ), }, { name: `an exclusion in the default mode keeps no record`, enters: [], - build: (): History => ({ - mode: `online`, - actions: [{ type: `exclude-on-handover` }], - }), + build: (generated: History): History => + spliced(generated, [{ type: `exclude-on-handover` }], `online`, true), }, { name: `a lost exclusion still fails its writer`, enters: [`exclusion-recovered`], - build: (): History => ({ - mode: `durable`, - actions: [{ type: `exclude-on-handover` }], - }), + build: (generated: History): History => + spliced( + generated, + [{ type: `exclude-on-handover` }], + `durable`, + true, + ), + }, + { + name: `a failed rejection record is retried beside other writes`, + enters: [`outcome-record-retried`], + build: (generated: History): History => + spliced( + generated, + [{ type: `fail-outcome-record` }], + `durable`, + true, + ), + }, + { + name: `a late admission during an exclusion sends nothing`, + enters: [`excluded-admission-ignored`], + build: (generated: History): History => + spliced(generated, [{ type: `exclude-on-handover` }]), + }, + { + name: `a write removed before it was sent fails its writer`, + enters: [`removed-unsent-failed`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-unsent` }]), + }, + { + name: `a save acknowledged after a handover is admitted by id`, + enters: [`save-acknowledged-after-handover`], + build: (generated: History): History => + spliced(generated, [{ type: `ack-after-handover` }]), + }, + { + name: `a faulted former leader saves for its successor`, + enters: [`faulted-former-leader-saved`], + build: (generated: History): History => + spliced(generated, [{ type: `fail-removal` }]), + }, + { + name: `a failed start releases its channel and leadership`, + enters: [`failed-start-released`], + build: (generated: History): History => + spliced(generated, [close(2), { type: `open-failing` }]), + }, + { + name: `a save that ends after its tab closed reaches the leader`, + enters: [`save-announced-after-dispose`], + build: (generated: History): History => + spliced(generated, [{ type: `dispose-during-save` }]), + }, + { + name: `a former leader drops queued writes another leader sent`, + enters: [`stale-admission-across-terms`], + build: (generated: History): History => + spliced(generated, [ + { type: `fail-outcome-record` }, + { type: `stale-admission-across-terms` }, + ]), }, { name: `a write before initialization takes the online path`, diff --git a/packages/offline-transactions/tests/harness.ts b/packages/offline-transactions/tests/harness.ts index ba5737a628..7e3f84c64d 100644 --- a/packages/offline-transactions/tests/harness.ts +++ b/packages/offline-transactions/tests/harness.ts @@ -101,16 +101,19 @@ interface TestOfflineEnvironmentOptions { mutationFn?: TestMutationFn storage?: FakeStorageAdapter config?: Partial + // The collection's id, and the key the executor registers it under. + collectionId?: string + registryKey?: string } -function createDefaultCollection(): { +function createDefaultCollection(id = `test-items`): { collection: Collection controller: SyncController } { let controller!: SyncController const collection = createCollection({ - id: `test-items`, + id, getKey: (item) => item.id, startSync: true, sync: { @@ -147,7 +150,9 @@ export function createTestOfflineEnvironment( const mutationCalls: Array = [] const attemptCounter = new Map() - const { collection, controller } = createDefaultCollection() + const { collection, controller } = createDefaultCollection( + options.collectionId, + ) const serverState = new Map() const applyMutations = (mutations: ReadonlyArray) => { @@ -226,7 +231,7 @@ export function createTestOfflineEnvironment( ...options.config, collections: { ...(options.config?.collections ?? {}), - [collection.id]: collection, + [options.registryKey ?? collection.id]: collection, }, mutationFns: { ...(options.config?.mutationFns ?? {}), From 770284a4d38efc876e5d0373bb520c31a5a2e8fa Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 15:15:29 -0800 Subject: [PATCH 05/16] fix(offline-transactions): keep failed exclusions out of admission A beforeRetry exclusion whose rejection record or row removal fails keeps its row for a later replay, as before. Until a replay accepts it, an added message no longer schedules it. A tab that loses leadership drops its unstarted queue without a separate pause, and announceSettled takes explicit arguments. The durable follower oracle now records which outcome writes it failed, expects a kept exclusion to stay unsent until a later replay settles it, and pins that history with a benign tail. --- .../src/OfflineExecutor.ts | 14 +- .../src/executor/TransactionExecutor.ts | 10 +- .../durable-follower-oracle.property.test.ts | 124 +++++++++++++++++- 3 files changed, 134 insertions(+), 14 deletions(-) diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index f6b13a4242..c3127e5855 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -270,10 +270,8 @@ export class OfflineExecutor { if (this.disposed || isLeader === this.isLeaderState) return this.isLeaderState = isLeader if (isLeader) this.term++ - else { - this.executor?.pause() - this.executor?.dropPending() - } + // Its unstarted queue goes; the next leader loads the outbox. + else this.executor!.dropPending() if (this.config.onLeadershipChange) { this.config.onLeadershipChange(isLeader) @@ -519,7 +517,11 @@ export class OfflineExecutor { channel.close() } - private announceSettled(id: string, error?: Error, own = false): void { + private announceSettled( + id: string, + error: Error | undefined, + own: boolean, + ): void { if (this.outboxChannel) { // This tab's own rejected write needs no record for another tab. if (own) this.outbox!.removeOutcome(id).catch(() => {}) @@ -709,7 +711,7 @@ export class OfflineExecutor { try { this.settleTransaction(transactionId, result) } finally { - this.announceSettled(transactionId) + this.announceSettled(transactionId, undefined, false) } } diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 408e6a545b..7a380e072f 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -434,7 +434,10 @@ export class TransactionExecutor { .filter(({ id }) => !selectedById.has(id)) .map(({ id }) => id) removedIds = this.scheduler.removePendingTransactions(removedIds) - // A late admission must not run a write this hook excluded. + // A late admission must not run a write this hook excluded; one a + // later replay accepts is admissible again. + for (const id of this.excluding) + if (selectedById.has(id)) this.excluding.delete(id) for (const id of removedIds) this.excluding.add(id) // Restore optimistic state for loaded transactions @@ -460,15 +463,16 @@ export class TransactionExecutor { if (this.config.followerWrites === `durable`) await this.outbox.recordRejection(id, error) await this.outbox.remove(id) + this.excluding.delete(id) this.offlineExecutor.rejectTransaction(id, error) } catch (cleanupError) { + // The row stays for a later replay to decide; until then no + // admission runs it. console.warn( `Failed to remove transaction excluded by beforeRetry:`, id, cleanupError, ) - } finally { - this.excluding.delete(id) } }), ) diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index f461ca051b..97d2b42c05 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -125,6 +125,9 @@ const reachStates = [ `outcome-record-retried`, // A late admission during an exclusion's cleanup sent nothing. `excluded-admission-ignored`, + // An exclusion whose record failed kept its row for a later replay, and + // an admission meanwhile sent nothing. + `exclusion-cleanup-kept`, // A saved write removed before any leader sent it failed its writer. `removed-unsent-failed`, // A save acknowledged after a change of leadership was admitted by id. @@ -135,6 +138,8 @@ const reachStates = [ `failed-start-released`, // A save that finished after its tab closed still reached the leader. `save-announced-after-dispose`, + // A save that finished after its writer began to lead was sent. + `save-finished-after-gain`, // A rejection whose writer had closed kept its record. `orphan-rejection-kept`, ] as const @@ -166,6 +171,7 @@ type SharedActionType = | `ack-after-handover` | `open-failing` | `dispose-during-save` + | `save-after-gain` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -203,6 +209,7 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`ack-after-handover`) }, { weight: 1, arbitrary: sharedAction(`open-failing`) }, { weight: 1, arbitrary: sharedAction(`dispose-during-save`) }, + { weight: 1, arbitrary: sharedAction(`save-after-gain`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), @@ -243,7 +250,8 @@ const spliced = ( action.type !== `remove-unsent` && action.type !== `ack-after-handover` && action.type !== `open-failing` && - action.type !== `dispose-during-save`, + action.type !== `dispose-during-save` && + action.type !== `save-after-gain`, ) .slice(0, MAX_ACTIONS - prefix.length), ], @@ -344,6 +352,8 @@ class ReadFailingStorage extends FakeStorageAdapter { failReadKey: string | undefined // The next outcome record write fails. failOutcomeWrites = 0 + // Outcome keys whose write failed. + readonly failedOutcomeKeys = new Set() // The next write lands at once and acknowledges on release. private heldAck: { release: () => void } | null | undefined holdNextAck(): void { @@ -376,6 +386,7 @@ class ReadFailingStorage extends FakeStorageAdapter { override async set(key: string, value: string): Promise { if (this.failOutcomeWrites > 0 && key.startsWith(`outcome:`)) { this.failOutcomeWrites -= 1 + this.failedOutcomeKeys.add(key) throw new Error(`storage write failed`) } if (this.heldAck === null && key.startsWith(`tx:`)) { @@ -495,6 +506,8 @@ type Write = { retried?: boolean // The next leader's beforeRetry excluded it. excluded?: boolean + // That exclusion's rejection record failed, so its row stayed. + exclusionKept?: boolean // removeFromOutbox removed it before any leader sent it. removed?: boolean // Its rejection record failed once. @@ -606,6 +619,8 @@ async function runHistory( const leaderIndex = () => tabs.findIndex((tab) => tab && tab.election === election.holder) const openSessions = () => new Set(tabs.flatMap((tab) => tab?.session ?? [])) + // No earlier write is still queued, so a new one is sent at once. + const queueIdle = () => !writes.some(isUnsent) const check = (label: string) => { expect( @@ -852,6 +867,7 @@ async function runHistory( ) if (!durable || !online.online || leaderIndex() < 0 || follower < 0) break + if (!queueIdle()) break storage.failDeletes = 1 const write = await doWrite(follower, `write`) // A queue still busy with earlier writes leaves the fault unused. @@ -867,6 +883,14 @@ async function runHistory( // finishes the removal. A write from the faulted tab is saved for // that leader, which sends it. const faulted = leaderIndex() + // While it leads, its fault refuses its own writes. + const refused = await doWrite(faulted, `write`) + if (refused) { + refused.deliverable = false + expect(refused.outcome, `${refused.id} refused by a fault`).toBe( + `failed`, + ) + } const successor = tabs.findIndex( (tab, index) => tab && index !== faulted, ) @@ -959,6 +983,23 @@ async function runHistory( reach(`excluded-admission-ignored`) storage.releaseWrites(false) await settle() + // A leftover record fault: the row stays for a later replay to + // decide, and an admission meanwhile sends nothing. + if ( + storage.failedOutcomeKeys.has(`outcome:${write.transactionId}`) + ) { + write.exclusionKept = true + const holder = tabs[leaderIndex()] + if (holder) { + expect( + (await holder.env.executor.peekOutbox()).map(({ id }) => id), + `${write.id} kept for a later replay`, + ).toContain(write.transactionId) + } + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + reach(`exclusion-cleanup-kept`) + } } channels.state.loseSettlement = false if (write.outcome === `failed`) reach(`exclusion-recovered`) @@ -972,7 +1013,8 @@ async function runHistory( ) if (!durable || !online.online || leaderIndex() < 0 || follower < 0) break - storage.failOutcomeWrites = 1 + // The first retry fails too; a later one records the rejection. + storage.failOutcomeWrites = 2 const rejectedWrite = await doWrite(follower, `write-rejected`) const next = await doWrite(follower, `write`) // The later write waits its turn behind the rejected one, which @@ -997,6 +1039,17 @@ async function runHistory( await tabs[leader]!.env.executor.removeFromOutbox( write.transactionId!, ) + // Removing a row that is already gone records nothing. + const gone = writes.find( + (candidate) => + candidate !== write && + candidate.transactionId !== undefined && + calls.includes(candidate.id), + ) + if (gone) + await tabs[leader]!.env.executor.removeFromOutbox( + gone.transactionId!, + ) write.removed = true write.deliverable = false channels.inject({ type: `leader` }) @@ -1036,7 +1089,7 @@ async function runHistory( // A tab whose start fails leaves no channel open and no claim on // leadership, without being disposed. const index = tabs.findIndex((tab) => !tab) - if (!durable || index < 0) break + if (!durable || index < 0 || !queueIdle()) break const before = channels.openCount() await openTab(index, undefined, undefined, true) const failed = tabs[index]! @@ -1061,7 +1114,14 @@ async function runHistory( const follower = tabs.findIndex( (tab, index) => tab && index !== leader, ) - if (!durable || !online.online || leader < 0 || follower < 0) break + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !queueIdle() + ) + break storage.holdWrites() const write = await doWrite(follower, `write`) if (!write) break @@ -1074,6 +1134,32 @@ async function runHistory( reach(`save-announced-after-dispose`) break } + case `save-after-gain`: { + // A follower's save lands only after it began to lead, so its + // leadership load missed the row; the save still sends it. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + !online.online || + leader < 0 || + writer < 0 || + !queueIdle() + ) + break + storage.holdWrites() + const write = await doWrite(writer, `write`) + if (!write) { + storage.releaseWrites(false) + break + } + await rotateTo(tabs[writer]!.election) + storage.releaseWrites(false) + await settle() + expect(calls, `${write.id} sent after its save`).toContain(write.id) + reach(`save-finished-after-gain`) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const pending = writes.filter( @@ -1167,6 +1253,15 @@ async function runHistory( } if (tabs.every((tab) => !tab)) await openTab(0) if (leaderIndex() < 0) await openTab(tabs.findIndex((tab) => !tab)) + // A kept exclusion is decided by a later replay: hand over once, with + // no record fault left. + if (writes.some((write) => write.exclusionKept)) { + storage.failOutcomeWrites = 0 + if (tabs.filter(Boolean).length < 2) + await openTab(tabs.findIndex((tab) => !tab)) + await closeTab(leaderIndex()) + if (leaderIndex() < 0) await openTab(tabs.findIndex((tab) => !tab)) + } online.set(true) for (let round = 0; round < 8; round++) await settle() @@ -1278,7 +1373,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, its row stays for a later replay and nothing sends it meanwhile. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -1541,6 +1636,25 @@ oracleProperty({ { type: `stale-admission-across-terms` }, ]), }, + { + name: `a save that finishes after its writer leads is sent`, + enters: [`save-finished-after-gain`], + build: (generated: History): History => + spliced(generated, [{ type: `save-after-gain` }]), + }, + { + name: `a failed record before an exclusion sends nothing twice`, + enters: [`exclusion-cleanup-kept`], + // The benign tail keeps this leader, so the queue retries the failed + // exclusion cleanup rather than another leader's replay. + build: (generated: History): History => + spliced( + generated, + [{ type: `fail-outcome-record` }, { type: `exclude-on-handover` }], + `durable`, + true, + ), + }, { name: `a write before initialization takes the online path`, enters: [`pre-initialization-write`], From c89e7eb35b0d7fdec9dd64e68a0de405d76ac095 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 17:30:27 -0800 Subject: [PATCH 06/16] fix(offline-transactions): address fourth durable follower write review - Only a tab that saved a write owns it, so an observer from waitForTransactionCompletion() no longer deletes the writer's rejection record. Ownership covers executors in this runtime that settle the write directly. - removeFromOutbox() and clearOutbox() record the rejection and fail the writer of an unsent write at once; a started call keeps the server's outcome. A write removed while it is still being saved never runs. - An outbox load that spans a change of leadership schedules nothing. - A failed cleanup of an excluded write is retried on a timer and on reconnect, outside the queue, while the tab leads. - Rejections are recorded only where a writer in another tab can read them. Without a channel a saved write whose row another leader settled keeps waiting instead of reading the missing row as success. Records carry a time and are pruned after seven days, and a write saved longer ago keeps waiting. - A start that fails after setup unsubscribes its listeners. The durable follower oracle gains actions for each case, checks that another leader sends a write before its writer leads, and covers a leader whose outbox load fails. outcome-retention.test.ts checks pruning and the seven-day rule. --- .changeset/durable-follower-writes.md | 2 +- docs/guides/offline-transactions.md | 4 +- packages/offline-transactions/README.md | 7 +- .../src/OfflineExecutor.ts | 164 ++++++-- .../src/executor/KeyScheduler.ts | 4 + .../src/executor/TransactionExecutor.ts | 105 ++++- .../src/outbox/OutboxManager.ts | 37 +- packages/offline-transactions/src/types.ts | 7 + .../durable-follower-oracle.property.test.ts | 396 +++++++++++++++++- .../tests/outcome-retention.test.ts | 121 ++++++ 10 files changed, 758 insertions(+), 89 deletions(-) create mode 100644 packages/offline-transactions/tests/outcome-retention.test.ts diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index f59394f5d1..534d675e8a 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. The default stays `'online'`. `removeFromOutbox()` now also stops a removed transaction that has not started. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. A record no writer reads is pruned after seven days. The default stays `'online'`. `removeFromOutbox()` and `clearOutbox()` now also stop a removed transaction that has not started and fail its writer's transaction. diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 3b920b3f16..e938d91a19 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -175,7 +175,7 @@ Register `saveBatch` in `mutationFns` before you use this example. `commit()` ca On the web, the executor tests IndexedDB first. It uses localStorage if IndexedDB is unavailable. You can pass a `storage` adapter to choose a different store. -One tab leads outbox processing. The executor prefers Web Locks and then BroadcastChannel for leader election. A follower uses the normal online mutation path without an outbox entry. The same online-only path applies when durable storage is unavailable. +One tab leads outbox processing. The executor prefers Web Locks and then BroadcastChannel for leader election. By default, a follower uses the normal online mutation path without an outbox entry; with `followerWrites: 'durable'`, an initialized follower saves to the shared outbox instead, as described below. The same online-only path applies when durable storage is unavailable. If neither election API exists, the current fallback treats the tab as the leader. It does not coordinate multiple tabs. @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` before it is sent fails its writer's transaction. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it, or for seven days; a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/README.md b/packages/offline-transactions/README.md index ff446f3831..8a8b37c86a 100644 --- a/packages/offline-transactions/README.md +++ b/packages/offline-transactions/README.md @@ -138,6 +138,7 @@ interface OfflineConfig { onUnknownMutationFn?: (name: string, tx: OfflineTransaction) => void onLeadershipChange?: (isLeader: boolean) => void onlineDetector?: OnlineDetector + followerWrites?: 'online' | 'durable' } ``` @@ -217,14 +218,14 @@ mutation function after restart; an unmarked row may replay. #### Properties -- `isOfflineEnabled: boolean` - Whether this tab can persist offline transactions +- `isOfflineEnabled: boolean` - Whether this tab leads and processes the outbox. With `followerWrites: 'durable'`, an initialized follower can also save writes while this is `false` #### Methods - `createOfflineTransaction(options)` - Create a manual offline transaction - `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete. Call it before the transaction settles: a waiter for a transaction that this executor recently settled (one of its last 1,000) rejects. A waiter for an older settled id keeps waiting. A waiter for an id the executor does not know yet keeps waiting, because another tab can still queue that transaction. -- `removeFromOutbox(id)` - Manually remove transaction from outbox. A removed transaction that has not started does not run, and with `followerWrites: 'durable'` its writer's transaction fails -- `clearOutbox()` - Manually remove all outbox transactions +- `removeFromOutbox(id)` - Manually remove transaction from outbox. A removed transaction that has not started does not run, and its writer's transaction fails, also in another tab with `followerWrites: 'durable'` +- `clearOutbox()` - Manually remove all outbox transactions, with the same effect on each - `peekOutbox()` - View all pending transactions - `dispose()` - Stop new processing and release executor resources. Pending durable transactions and optimistic state on surviving Collections remain live. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index c3127e5855..f55d44a221 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -8,7 +8,7 @@ import { IndexedDBAdapter } from './storage/IndexedDBAdapter' import { LocalStorageAdapter } from './storage/LocalStorageAdapter' // Core components -import { OutboxManager } from './outbox/OutboxManager' +import { OUTCOME_RETENTION_MS, OutboxManager } from './outbox/OutboxManager' import { KeyScheduler } from './executor/KeyScheduler' import { TransactionExecutor } from './executor/TransactionExecutor' @@ -55,6 +55,10 @@ function outboxMessageError(error: { name: string; message: string }): Error { return restored } +function removedError(): Error { + return new NonRetriableError(`Transaction removed from the outbox`) +} + /** How many settled ids an executor remembers to reject late waiters. */ const SETTLED_TRANSACTIONS_REMEMBERED = 1000 @@ -110,14 +114,17 @@ export class OfflineExecutor { private outboxChannelName: string | null = null private initialized = false private term = 0 + // Saves in progress; true once removeFromOutbox or clearOutbox removed one. + private readonly saving = new Map() private pendingTransactionPromises: Map< string, { promise: Promise resolve: (result: any) => void reject: (error: Error) => void - // Set once a follower's save starts; resolves to whether it succeeded. + // Set once this tab's save starts; resolves to whether it succeeded. saved?: Promise + savedAt?: number } > = new Map() @@ -291,6 +298,7 @@ export class OfflineExecutor { if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays() this.retryAdmissions() + void this.executor.retryFailedCleanups() if (this.scheduler.getPendingCount() > 0) { const barrierPromise = this.executor.executeAll() @@ -391,6 +399,10 @@ export class OfflineExecutor { } catch (error) { console.warn(`Failed to initialize offline executor:`, error) // A failed start releases what it opened, without waiting for dispose(). + this.unsubscribeOnline?.() + this.unsubscribeOnline = null + this.unsubscribeLeadership?.() + this.unsubscribeLeadership = null this.outboxChannel?.close() this.outboxChannel = null this.leaderElection?.releaseLeadership() @@ -405,6 +417,13 @@ export class OfflineExecutor { // Startup must observe a failed read instead of reporting an empty outbox. await this.executor.loadPendingTransactions() + // Outcomes no writer read within the retention window go. + if (this.recordsOutcomes) + this.outbox!.pruneOutcomes(Date.now() - OUTCOME_RETENTION_MS).catch( + (error) => { + console.warn(`Failed to prune outcome records:`, error) + }, + ) // A leader that closed can leave a removed row with an undelivered outcome. if (this.outboxChannel) { @@ -468,11 +487,21 @@ export class OfflineExecutor { // Every tab hears a settlement; only the writer removes its outcome record. private settleFollowerWrite(id: string, error?: Error): void { - const own = this.pendingTransactionPromises.has(id) + const own = this.ownsWrite(id) this.settleTransaction(id, undefined, error) if (own) this.outbox!.removeOutcome(id).catch(() => {}) } + /** + * This executor, or one in this runtime that it settles, saved the + * transaction and waits for it; an observer does not. + */ + ownsWrite(id: string): boolean { + return this.settlementOwners(id).some( + (owner) => owner.pendingTransactionPromises.get(id)?.saved !== undefined, + ) + } + private reconcileFollowerWrites(): void { void this.settleRemovedWrites() } @@ -482,6 +511,9 @@ export class OfflineExecutor { // row removed with no record completed. A failed read leaves that write // pending, and the check runs again when connectivity changes. private async settleRemovedWrites(): Promise { + // Without recorded outcomes a missing row could be either outcome, so the + // waiter keeps waiting for this tab's own settlement. + if (!this.recordsOutcomes) return const sweep = ++this.sweeps let failed = false for (const [id, waiter] of [...this.pendingTransactionPromises]) { @@ -489,6 +521,10 @@ export class OfflineExecutor { if (!(await waiter.saved)) continue if (await this.outbox!.get(id)) continue const error = (await this.outbox!.getOutcome(id))?.error + // A record older than the retention window may have been pruned, so + // no record cannot mean success. + if (!error && Date.now() - waiter.savedAt! > OUTCOME_RETENTION_MS) + continue this.settleFollowerWrite(id, error && outboxMessageError(error)) } catch (error) { failed = true @@ -498,6 +534,11 @@ export class OfflineExecutor { if (sweep === this.sweeps) this.reconcileFailed = failed } + /** Rejections are recorded for writers in other tabs. */ + get recordsOutcomes(): boolean { + return this.outboxChannelName !== null + } + /** Counts later leadership gains, so work begun in an earlier term can tell. */ get leadershipTerm(): number { return this.term @@ -522,9 +563,10 @@ export class OfflineExecutor { error: Error | undefined, own: boolean, ): void { + // This tab's own rejected write needs no record for another tab. + if (own && this.recordsOutcomes) + this.outbox?.removeOutcome(id).catch(() => {}) if (this.outboxChannel) { - // This tab's own rejected write needs no record for another tab. - if (own) this.outbox!.removeOutcome(id).catch(() => {}) this.outboxChannel.postMessage({ type: `settled`, id, @@ -642,11 +684,27 @@ export class OfflineExecutor { this.executor.assertHealthy() const saved = this.outbox.add(transaction) // The transaction registered this waiter before it asked to persist. - this.pendingTransactionPromises.get(transaction.id)!.saved = saved.then( + const waiter = this.pendingTransactionPromises.get(transaction.id)! + waiter.savedAt = Date.now() + waiter.saved = saved.then( () => true, () => false, ) - await saved + this.saving.set(transaction.id, false) + let removed: boolean | undefined + try { + await saved + } finally { + removed = this.saving.get(transaction.id) + this.saving.delete(transaction.id) + } + if (removed) { + // Removed while it was saved: a row that landed after the removal + // goes too, and the write never runs. + await this.outbox.remove(transaction.id) + this.rejectTransaction(transaction.id, removedError()) + return + } if (!this.isOfflineEnabled) { this.announceAdded(transaction.id) return @@ -722,7 +780,7 @@ export class OfflineExecutor { error: Error, announce = true, ): void { - const own = this.pendingTransactionPromises.has(transactionId) + const own = this.ownsWrite(transactionId) try { this.settleTransaction(transactionId, undefined, error) } finally { @@ -748,28 +806,8 @@ export class OfflineExecutor { result: unknown, error?: Error, ): void { - const candidates = new Set([this]) - for (const collection of Object.values(this.config.collections)) { - for (const owner of completionOwners.get(collection) ?? []) - candidates.add(owner) - } // Select every recipient before publication can reenter this executor. - const owners = [...candidates].filter( - (owner) => - owner === this || - ((owner.pendingTransactionPromises.has(transactionId) || - owner.restorationTransactions.has(transactionId)) && - // Either executor may deliver the outcome: a retired issued call or - // its successor's replay. An ancillary overlap alone is insufficient. - (retainsCollections( - this.config.collections, - owner.config.collections, - ) || - retainsCollections( - owner.config.collections, - this.config.collections, - ))), - ) + const owners = this.settlementOwners(transactionId) const cleanupErrors: Array = [] for (const owner of owners) { @@ -797,6 +835,31 @@ export class OfflineExecutor { if (cleanupErrors.length > 0) throw cleanupErrors[0] } + /** The executors in this runtime that receive this transaction's outcome. */ + private settlementOwners(transactionId: string): Array { + const candidates = new Set([this]) + for (const collection of Object.values(this.config.collections)) { + for (const owner of completionOwners.get(collection) ?? []) + candidates.add(owner) + } + return [...candidates].filter( + (owner) => + owner === this || + ((owner.pendingTransactionPromises.has(transactionId) || + owner.restorationTransactions.has(transactionId)) && + // Either executor may deliver the outcome: a retired issued call or + // its successor's replay. An ancillary overlap alone is insufficient. + (retainsCollections( + this.config.collections, + owner.config.collections, + ) || + retainsCollections( + owner.config.collections, + this.config.collections, + ))), + ) + } + // Method for TransactionExecutor to register restoration transactions registerRestorationTransaction( offlineTransactionId: string, @@ -838,16 +901,39 @@ export class OfflineExecutor { if (!this.outbox) { return } - // A follower that saved this write and has not heard an outcome must not - // read the removal as success. - if (this.outboxChannelName !== null && (await this.outbox.get(id))) - await this.outbox.recordRejection( - id, - new NonRetriableError(`Transaction removed from the outbox`), - ) - await this.outbox.remove(id) + await this.removeSaved([id]) + } + + /** + * Removes saved transactions. A write that has not started fails with a + * removal error, which a writer in another tab also reads from its record; + * a started call keeps the provider's outcome. + */ + private async removeSaved(ids: Array): Promise { + const outbox = this.outbox! + const error = removedError() + const present = new Set( + ( + await Promise.all( + ids.map(async (id) => ((await outbox.has(id)) ? id : null)), + ) + ).filter((id): id is string => id !== null), + ) + await Promise.all( + [...present].map(async (id) => { + if ( + this.recordsOutcomes && + !this.ownsWrite(id) && + !this.scheduler.isRunning(id) + ) + await outbox.recordRejection(id, error) + }), + ) + await outbox.removeMany(ids) + for (const id of ids) if (this.saving.has(id)) this.saving.set(id, true) // A removed transaction that has not started does not run. - this.scheduler.removePendingTransactions([id]) + for (const id of this.scheduler.removePendingTransactions(ids)) + if (present.has(id)) this.rejectTransaction(id, error) } async peekOutbox(): Promise> { @@ -861,7 +947,7 @@ export class OfflineExecutor { if (!this.outbox || !this.executor) { return } - await this.outbox.clear() + await this.removeSaved(await this.outbox.ids()) this.executor.clear() } diff --git a/packages/offline-transactions/src/executor/KeyScheduler.ts b/packages/offline-transactions/src/executor/KeyScheduler.ts index 6edd95cadc..30f3497345 100644 --- a/packages/offline-transactions/src/executor/KeyScheduler.ts +++ b/packages/offline-transactions/src/executor/KeyScheduler.ts @@ -78,6 +78,10 @@ export class KeyScheduler { return this.pendingTransactions.length } + isRunning(transactionId: string): boolean { + return this.activeTransactionId === transactionId + } + getRunningCount(): number { return this.activeTransactionId === undefined ? 0 : 1 } diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 7a380e072f..6d16302a2e 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -31,6 +31,12 @@ export class TransactionExecutor { private fatalError: Error | null = null // Writes beforeRetry excluded whose rejection cleanup has not finished. private readonly excluding = new Set() + // Excluded writes whose cleanup failed, with their rejection. Retried on a + // timer and on connectivity, outside the queue, while this tab leads. + private readonly failedCleanups = new Map() + private cleanupTimer: ReturnType | null = null + private cleanupAttempts = 0 + private cleaning = false constructor( scheduler: KeyScheduler, @@ -337,11 +343,11 @@ export class TransactionExecutor { } } } - // A follower that wrote this transaction and misses the settlement - // message reads a rejection here; a write with no record completed. + // A writer in another tab that misses the settlement message reads a + // rejection here; a write with no record completed. if ( - this.config.followerWrites === `durable` && - transaction.outboxPhase === `rejection-pending` + transaction.outboxPhase === `rejection-pending` && + this.recordsFor(transaction.id) ) { try { await this.outbox.recordRejection( @@ -407,9 +413,13 @@ export class TransactionExecutor { async loadPendingTransactions(): Promise { let removedIds: Array = [] + const term = this.offlineExecutor.leadershipTerm await this.outbox.withAll((transactions) => { const { isOfflineEnabled } = this.offlineExecutor - if (!isOfflineEnabled) return + // A read that spans a change of leadership is stale: another leader + // may have sent its rows, and this term's own load reads them again. + if (!isOfflineEnabled || term !== this.offlineExecutor.leadershipTerm) + return const providerPending = transactions.filter( (transaction) => !transaction.outboxPhase, ) @@ -459,26 +469,77 @@ export class TransactionExecutor { const error = new NonRetriableError(`Transaction excluded by beforeRetry`) await Promise.all( removedIds.map(async (id) => { - try { - if (this.config.followerWrites === `durable`) - await this.outbox.recordRejection(id, error) - await this.outbox.remove(id) - this.excluding.delete(id) - this.offlineExecutor.rejectTransaction(id, error) - } catch (cleanupError) { - // The row stays for a later replay to decide; until then no - // admission runs it. - console.warn( - `Failed to remove transaction excluded by beforeRetry:`, - id, - cleanupError, - ) - } + if (await this.cleanUpExcluded(id, error)) return + // Until the retry succeeds, no admission runs it. + this.failedCleanups.set(id, error) + this.scheduleCleanupRetry() }), ) } } + /** Records and removes one excluded write; false when that failed. */ + private async cleanUpExcluded(id: string, error: Error): Promise { + try { + if (this.recordsFor(id)) await this.outbox.recordRejection(id, error) + await this.outbox.remove(id) + this.excluding.delete(id) + this.offlineExecutor.rejectTransaction(id, error) + return true + } catch (cleanupError) { + console.warn( + `Failed to remove transaction excluded by beforeRetry:`, + id, + cleanupError, + ) + return false + } + } + + // Only a writer in another tab, which shares the channel, reads a record. + private recordsFor(id: string): boolean { + return ( + this.offlineExecutor.recordsOutcomes === true && + !this.offlineExecutor.ownsWrite?.(id) + ) + } + + private scheduleCleanupRetry(): void { + if (this.cleanupTimer || this.failedCleanups.size === 0) return + this.cleanupTimer = setTimeout(() => { + this.cleanupTimer = null + this.cleanupAttempts++ + void this.retryFailedCleanups() + }, this.retryPolicy.calculateDelay(this.cleanupAttempts)) + } + + /** Retries the cleanups of excluded writes, without calling the provider. */ + async retryFailedCleanups(): Promise { + if (this.cleaning || !this.offlineExecutor.isOfflineEnabled) return + this.cleaning = true + try { + for (const [id, error] of [...this.failedCleanups]) { + // A change of leadership drops the rest; the next replay owns them. + if (!this.failedCleanups.has(id)) continue + if (!(await this.cleanUpExcluded(id, error))) continue + // A change of leadership during the attempt already dropped it. + this.failedCleanups.delete(id) + } + } finally { + this.cleaning = false + } + // A change of leadership or a disposal emptied the map. + if (this.failedCleanups.size === 0) this.cleanupAttempts = 0 + else this.scheduleCleanupRetry() + } + + private dropFailedCleanups(): void { + this.failedCleanups.clear() + this.cleanupAttempts = 0 + if (this.cleanupTimer) clearTimeout(this.cleanupTimer) + this.cleanupTimer = null + } + /** * Schedules one transaction that a follower tab saved to the shared outbox. * It rejects only when the read fails. @@ -563,11 +624,13 @@ export class TransactionExecutor { clear(): void { this.scheduler.clear() this.clearRetryTimer() + this.dropFailedCleanups() } pause(): void { // Retain queued work and let the issued call finish its acknowledgment. this.clearRetryTimer() + this.dropFailedCleanups() } /** @@ -579,6 +642,8 @@ export class TransactionExecutor { this.scheduler.getAllPendingTransactions().map(({ id }) => id), ) this.clearRetryTimer() + // The next leader's replay excludes these writes again. + this.dropFailedCleanups() } getPendingCount(): number { diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 58915d2dab..a598630219 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -13,7 +13,17 @@ import type { Collection } from '@tanstack/db' export class OutboxTransactionNotFoundError extends Error {} /** A rejected transaction's error, kept for a writer in another tab. */ -export type OutboxOutcome = { error: { name: string; message: string } } +export type OutboxOutcome = { + error: { name: string; message: string } + // When it was recorded, so an outcome no writer reads can be pruned. + at: number +} + +/** + * How long an outcome record outlives its row. A writer that saved its write + * longer ago than this cannot read a missing record as success. + */ +export const OUTCOME_RETENTION_MS = 7 * 24 * 60 * 60 * 1000 export class OutboxManager { private storage: StorageAdapter @@ -117,6 +127,7 @@ export class OutboxManager { async recordRejection(id: string, error: Error): Promise { const outcome: OutboxOutcome = { error: { name: error.name, message: error.message }, + at: Date.now(), } await this.storage.set( `${this.outcomePrefix}${id}`, @@ -133,6 +144,30 @@ export class OutboxManager { await this.storage.delete(`${this.outcomePrefix}${id}`) } + /** Removes outcome records made before `before`. */ + async pruneOutcomes(before: number): Promise { + const keys = (await this.storage.keys()).filter((key) => + key.startsWith(this.outcomePrefix), + ) + for (const key of keys) { + const data = await this.storage.get(key) + if (data !== null && (JSON.parse(data) as OutboxOutcome).at < before) + await this.storage.delete(key) + } + } + + /** Whether a row is saved, without decoding it. */ + async has(id: string): Promise { + return (await this.storage.get(this.getStorageKey(id))) !== null + } + + /** Ids of the saved transactions, without reading them. */ + async ids(): Promise> { + return (await this.storage.keys()) + .filter((key) => key.startsWith(this.keyPrefix)) + .map((key) => key.slice(this.keyPrefix.length)) + } + async getAll(): Promise> { return this.withAll((transactions) => transactions) } diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index f451001ce5..2f03a493f1 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -170,6 +170,13 @@ export interface TransactionSignaler { readonly isOfflineEnabled: boolean /** Counts leadership gains; absent for a signaler that never changes. */ readonly leadershipTerm?: number + /** Rejections are recorded for writers in other tabs. */ + readonly recordsOutcomes?: boolean + /** + * Whether this tab made the transaction and waits for it. Another tab's + * writer needs a recorded rejection; this tab's own does not. + */ + ownsWrite?: (transactionId: string) => boolean resolveTransaction: (transactionId: string, result: any) => void rejectTransaction: ( transactionId: string, diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 97d2b42c05..f9792d9001 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -31,7 +31,12 @@ * of a sent follower write, announce a saved row the leader cannot decode, * return an admission read after leadership moved away and back while another * leader sent its write, and have the next leader's beforeRetry exclude a - * follower's write while its settlement is lost. + * follower's write while its settlement is lost. Further actions observe a + * follower's rejected write from the leader, clear or remove unsent and + * still-saving writes, stall an outbox load across a change of leadership, + * fail a leader's start after setup, remove a write while its server call + * runs, and, in the default mode, let another + * leader reject a former leader's saved write. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. @@ -51,7 +56,8 @@ * * Known omissions: a reloaded follower does not show another tab's pending * writes optimistically; rejection records of writers that never return are - * kept; and no real browser contexts. + * pruned after seven days, which moves the clock and is checked in + * outcome-retention.test.ts instead; and no real browser contexts. */ import fc from 'fast-check' import { expect, vi } from 'vitest' @@ -142,6 +148,19 @@ const reachStates = [ `save-finished-after-gain`, // A rejection whose writer had closed kept its record. `orphan-rejection-kept`, + // A tab that only observed a write left its rejection record in place. + `observer-left-record`, + // Clearing the outbox failed the writer of an unsent write. + `cleared-unsent-failed`, + // A write removed while its save was pending never ran. + `removed-during-save`, + // An outbox load that spanned a change of leadership scheduled nothing. + `stale-load-dropped`, + // A write removed while its server call ran kept the server's outcome. + `removed-while-running-completed`, + // In the default mode, a write another leader rejected stayed pending in + // its former leader, which cannot tell a rejection from a success. + `former-leader-write-unresolved`, ] as const type ReachState = (typeof reachStates)[number] @@ -172,6 +191,12 @@ type SharedActionType = | `open-failing` | `dispose-during-save` | `save-after-gain` + | `observe-rejection` + | `clear-unsent` + | `remove-during-save` + | `stale-load-across-terms` + | `handover-rejection` + | `remove-running` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -210,6 +235,12 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`open-failing`) }, { weight: 1, arbitrary: sharedAction(`dispose-during-save`) }, { weight: 1, arbitrary: sharedAction(`save-after-gain`) }, + { weight: 1, arbitrary: sharedAction(`observe-rejection`) }, + { weight: 1, arbitrary: sharedAction(`clear-unsent`) }, + { weight: 1, arbitrary: sharedAction(`remove-during-save`) }, + { weight: 1, arbitrary: sharedAction(`stale-load-across-terms`) }, + { weight: 1, arbitrary: sharedAction(`handover-rejection`) }, + { weight: 1, arbitrary: sharedAction(`remove-running`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), @@ -251,7 +282,13 @@ const spliced = ( action.type !== `ack-after-handover` && action.type !== `open-failing` && action.type !== `dispose-during-save` && - action.type !== `save-after-gain`, + action.type !== `save-after-gain` && + action.type !== `observe-rejection` && + action.type !== `clear-unsent` && + action.type !== `remove-during-save` && + action.type !== `stale-load-across-terms` && + action.type !== `handover-rejection` && + action.type !== `remove-running`, ) .slice(0, MAX_ACTIONS - prefix.length), ], @@ -313,6 +350,9 @@ class TabElection implements LeaderElection { this.leader = isLeader for (const listener of this.listeners) listener(isLeader) } + listenerCount(): number { + return this.listeners.size + } } class ControlledOnline { @@ -375,6 +415,15 @@ class ReadFailingStorage extends FakeStorageAdapter { this.heldWrites = null for (const release of held) release(fail) } + // The next key listing fails. + failKeys = 0 + override async keys(): Promise> { + if (this.failKeys > 0) { + this.failKeys -= 1 + throw new Error(`storage keys failed`) + } + return super.keys() + } failDeletes = 0 override async delete(key: string): Promise { if (this.failDeletes > 0 && key.startsWith(`tx:`)) { @@ -512,6 +561,8 @@ type Write = { removed?: boolean // Its rejection record failed once. recordRetried?: boolean + // Another leader settled it in the default mode; its tab cannot tell how. + unresolved?: boolean outcome?: `completed` | `failed` error?: unknown } @@ -548,14 +599,17 @@ async function runHistory( } const tabs: Array = Array.from({ length: TABS }) let sessions = 0 + // The next server call waits for this before it answers. + let callGate: Promise | null = null const openTab = async ( index: number, beforeInit?: () => Promise, hold?: Promise, - failStart = false, + // `load`: it leads, then its outbox load fails. + failStart: boolean | `load` = false, ) => { - const tabElection = new TabElection(election, hold, failStart) + const tabElection = new TabElection(election, hold, failStart === true) const session = ++sessions const env = createTestOfflineEnvironment({ storage, @@ -573,6 +627,11 @@ async function runHistory( leader: tabs[leaderIndex()]?.session, }) if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) + if (callGate) { + const gate = callGate + callGate = null + return gate.then(() => ({ ok: true })) + } return { ok: true } }, config: { @@ -998,6 +1057,27 @@ async function runHistory( } channels.inject({ type: `added`, id: write.transactionId }) await settle() + // The leader retries the cleanup without a handover: at once on + // reconnecting, which fails again here, then on its timer. + channels.state.loseSettlement = false + storage.failOutcomeWrites = 1 + online.set(true) + await settle() + expect( + storage.failOutcomeWrites, + `the reconnect retried ${write.id}'s cleanup`, + ).toBe(0) + await new Promise((resolve) => setTimeout(resolve, 1100)) + await settle() + if (holder) { + expect( + (await holder.env.executor.peekOutbox()).map(({ id }) => id), + `${write.id} removed by the retried cleanup`, + ).not.toContain(write.transactionId) + } + expect(write.outcome, `${write.id} fails after the retry`).toBe( + `failed`, + ) reach(`exclusion-cleanup-kept`) } } @@ -1052,16 +1132,22 @@ async function runHistory( ) write.removed = true write.deliverable = false - channels.inject({ type: `leader` }) await settle() - if (write.outcome === `failed`) reach(`removed-unsent-failed`) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`removed-unsent-failed`) break } case `ack-after-handover`: { // A follower's row lands but its save acknowledges only after // another leader sent and removed it and the writer then leads. + // The writer waits behind the next leader, which sends the write. const leader = leaderIndex() - const writer = tabs.findIndex((tab, index) => tab && index !== leader) + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) if ( !durable || !online.online || @@ -1077,25 +1163,45 @@ async function runHistory( break } await rotateTo(tabs[writer]!.election) - expect(calls, `${write.id} sent by another leader`).toContain( - write.id, + const send = sends.find((candidate) => candidate.id === write.id) + expect(send?.sender, `${write.id} sent by another leader`).not.toBe( + undefined, + ) + expect(send?.sender, `${write.id} not sent by its writer`).not.toBe( + write.session, ) + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id} removed before its acknowledgment`, + ).toBe(null) storage.releaseAck() await settle() reach(`save-acknowledged-after-handover`) break } case `open-failing`: { - // A tab whose start fails leaves no channel open and no claim on - // leadership, without being disposed. + // A tab whose start fails leaves no channel open, no claim on + // leadership and no listener, without being disposed. With no + // leader it leads, and its outbox load fails after setup. const index = tabs.findIndex((tab) => !tab) if (!durable || index < 0 || !queueIdle()) break const before = channels.openCount() - await openTab(index, undefined, undefined, true) + const listenersBefore = online.listeners.size + const failLoad = leaderIndex() < 0 + if (failLoad) storage.failKeys = 1 + await openTab(index, undefined, undefined, failLoad ? `load` : true) const failed = tabs[index]! expect(channels.openCount(), `a failed start keeps no channel`).toBe( before, ) + expect( + online.listeners.size, + `a failed start keeps no connectivity listener`, + ).toBe(listenersBefore) + expect( + failed.election.listenerCount(), + `a failed start keeps no leadership listener`, + ).toBe(0) expect( election.holder !== failed.election && !election.queue.includes(failed.election), @@ -1160,6 +1266,194 @@ async function runHistory( reach(`save-finished-after-gain`) break } + case `observe-rejection`: { + // The leader also waits on a follower's rejected write. The writer + // misses the settlement and learns the rejection from its record. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !queueIdle()) break + online.set(false) + const write = await doWrite(writer, `write-rejected`) + if (!write) break + const observed = tabs[ + leader + ]!.env.executor.waitForTransactionCompletion( + write.transactionId!, + ).catch(() => undefined) + channels.state.loseSettlement = true + online.set(true) + await settle() + await observed + channels.state.loseSettlement = false + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} fails from its record`).toBe( + `failed`, + ) + reach(`observer-left-record`) + break + } + case `clear-unsent`: { + // The leader clears the outbox while a follower's write is unsent. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !queueIdle()) break + const executor = tabs[leader]!.env.executor + if ((await executor.peekOutbox()).length > 0) break + online.set(false) + const write = await doWrite(follower, `write`) + if (!write) break + await executor.clearOutbox() + write.removed = true + write.deliverable = false + await settle() + expect(write.outcome, `${write.id} fails when cleared`).toBe(`failed`) + reach(`cleared-unsent-failed`) + break + } + case `remove-during-save`: { + // The leader's own row lands, the leader removes it, and only then + // does its save acknowledge. + const leader = leaderIndex() + if (leader < 0 || !online.online || !queueIdle()) break + storage.holdNextAck() + const write = await doWrite(leader, `write`) + if (!write) { + storage.releaseAck() + break + } + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + storage.releaseAck() + await settle() + expect(calls, `${write.id} never runs`).not.toContain(write.id) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`removed-during-save`) + break + } + case `stale-load-across-terms`: { + // The next leader's outbox load stalls with a follower's row in it. + // Leadership moves on, another leader sends and removes the write, + // and the stalled tab leads again before its load returns. + const first = leaderIndex() + const target = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== first && tab.election !== target, + ) + if ( + !durable || + first < 0 || + !target || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !queueIdle() + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + const firstElection = tabs[first]!.election + storage.holdNextRead() + firstElection.releaseLeadership() + await settle() + await firstElection.requestLeadership() + online.set(true) + await settle() + target.releaseLeadership() + await settle() + await target.requestLeadership() + await settle() + expect(calls, `${write.id} sent by another leader`).toContain( + write.id, + ) + await rotateTo(target) + expect(election.holder, `the stalled tab leads again`).toBe(target) + storage.releaseRead() + await settle() + reach(`stale-load-dropped`) + break + } + case `handover-rejection`: { + // In the default mode the leader saves its own write offline, loses + // leadership, and another leader's server call rejects it. + const leader = leaderIndex() + if ( + durable || + leader < 0 || + tabs.filter(Boolean).length < 2 || + !queueIdle() + ) + break + online.set(false) + const write = await doWrite(leader, `write-rejected`) + if (!write) break + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} sent by another leader`).toContain( + write.id, + ) + expect(write.outcome, `${write.id} waits for its tab to lead`).toBe( + undefined, + ) + await rotateTo(original) + // No record tells a rejection from a success, so it keeps waiting. + expect(write.outcome, `${write.id} stays pending`).toBe(undefined) + write.unresolved = true + reach(`former-leader-write-unresolved`) + break + } + case `remove-running`: { + // The leader removes a follower's write while its server call runs, + // and the success message is lost. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !queueIdle() + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + channels.state.loseSettlement = true + release() + await settle() + channels.state.loseSettlement = false + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} keeps the server's outcome`).toBe( + `completed`, + ) + reach(`removed-while-running-completed`) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const pending = writes.filter( @@ -1253,15 +1547,6 @@ async function runHistory( } if (tabs.every((tab) => !tab)) await openTab(0) if (leaderIndex() < 0) await openTab(tabs.findIndex((tab) => !tab)) - // A kept exclusion is decided by a later replay: hand over once, with - // no record fault left. - if (writes.some((write) => write.exclusionKept)) { - storage.failOutcomeWrites = 0 - if (tabs.filter(Boolean).length < 2) - await openTab(tabs.findIndex((tab) => !tab)) - await closeTab(leaderIndex()) - if (leaderIndex() < 0) await openTab(tabs.findIndex((tab) => !tab)) - } online.set(true) for (let round = 0; round < 8; round++) await settle() @@ -1327,6 +1612,10 @@ async function runHistory( ) for (const write of writes) { if (!sessionsOpen.has(write.session)) continue + if (write.unresolved) { + expect(write.outcome, `${write.id} stays pending`).toBe(undefined) + continue + } expect(write.outcome, `${write.id} outcome`).toBe( write.rejected || !write.deliverable ? `failed` : `completed`, ) @@ -1373,7 +1662,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, its row stays for a later replay and nothing sends it meanwhile. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -1392,6 +1681,14 @@ oracleProperty({ `src/outbox/OutboxManager.ts#OutboxManager.recordRejection`, `src/outbox/OutboxManager.ts#OutboxManager.getOutcome`, `src/outbox/OutboxManager.ts#OutboxManager.removeOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.has`, + `src/outbox/OutboxManager.ts#OutboxManager.ids`, + `src/OfflineExecutor.ts#OfflineExecutor.ownsWrite`, + `src/OfflineExecutor.ts#OfflineExecutor.recordsOutcomes`, + `src/OfflineExecutor.ts#OfflineExecutor.removeSaved`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.cleanUpExcluded`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.retryFailedCleanups`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.recordsFor`, ], histories: { arbitrary: historyArbitrary, @@ -1621,6 +1918,17 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [close(2), { type: `open-failing` }]), }, + { + name: `a leader whose outbox load fails releases its listeners`, + enters: [`failed-start-released`], + build: (generated: History): History => + spliced(generated, [ + close(0), + close(1), + close(2), + { type: `open-failing` }, + ]), + }, { name: `a save that ends after its tab closed reaches the leader`, enters: [`save-announced-after-dispose`], @@ -1642,6 +1950,48 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `save-after-gain` }]), }, + { + name: `an observer leaves the writer's rejection record`, + enters: [`observer-left-record`], + build: (generated: History): History => + spliced(generated, [{ type: `observe-rejection` }]), + }, + { + name: `clearing the outbox fails an unsent write's writer`, + enters: [`cleared-unsent-failed`], + build: (generated: History): History => + spliced(generated, [{ type: `clear-unsent` }]), + }, + { + name: `a write removed during its save never runs`, + enters: [`removed-during-save`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-during-save` }]), + }, + { + name: `a default-mode write removed during its save never runs`, + enters: [`removed-during-save`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-during-save` }], `online`), + }, + { + name: `a write removed while its call runs keeps the server's outcome`, + enters: [`removed-while-running-completed`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-running` }]), + }, + { + name: `an outbox load from an earlier term schedules nothing`, + enters: [`stale-load-dropped`], + build: (generated: History): History => + spliced(generated, [{ type: `stale-load-across-terms` }]), + }, + { + name: `a default-mode write another leader rejected stays pending`, + enters: [`former-leader-write-unresolved`], + build: (generated: History): History => + spliced(generated, [{ type: `handover-rejection` }], `online`), + }, { name: `a failed record before an exclusion sends nothing twice`, enters: [`exclusion-cleanup-kept`], diff --git a/packages/offline-transactions/tests/outcome-retention.test.ts b/packages/offline-transactions/tests/outcome-retention.test.ts new file mode 100644 index 0000000000..d64776bad9 --- /dev/null +++ b/packages/offline-transactions/tests/outcome-retention.test.ts @@ -0,0 +1,121 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { OUTCOME_RETENTION_MS } from '../src/outbox/OutboxManager' +import { NonRetriableError } from '../src/types' +import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness' +import type { OnlineDetector } from '../src/types' + +// Rejection records for writers in other tabs live for a bounded time. These +// checks move the clock, which the durable follower oracle does not. + +const offline = (): OnlineDetector => ({ + subscribe: () => () => {}, + notifyOnline: () => {}, + isOnline: () => false, + dispose: () => {}, +}) + +const record = (message: string, at: number) => + JSON.stringify({ error: { name: `NonRetriableError`, message }, at }) + +// A tab alone: its channel carries nothing. +class SilentChannel { + onmessage: unknown = null + postMessage(): void {} + close(): void {} +} + +beforeEach(() => { + vi.stubGlobal(`BroadcastChannel`, SilentChannel) +}) + +afterEach(() => { + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +it(`prunes outcome records older than the retention window when a tab leads`, async () => { + const storage = new FakeStorageAdapter() + const now = Date.now() + await storage.set( + `outcome:old`, + record(`old`, now - OUTCOME_RETENTION_MS - 1), + ) + await storage.set( + `outcome:recent`, + record(`recent`, now - OUTCOME_RETENTION_MS + 60_000), + ) + const env = createTestOfflineEnvironment({ + storage, + config: { followerWrites: `durable`, onlineDetector: offline() }, + }) + try { + await env.waitForLeader() + await vi.waitFor(async () => { + expect(await storage.get(`outcome:old`)).toBe(null) + }) + expect(await storage.get(`outcome:recent`)).toBe( + record(`recent`, now - OUTCOME_RETENTION_MS + 60_000), + ) + } finally { + env.executor.dispose() + } +}) + +it.each([false, true])( + `a saved write whose row left with no record completes only within the retention window, aged=%s`, + async (aged) => { + vi.useFakeTimers({ toFake: [`Date`] }) + const storage = new FakeStorageAdapter() + const env = createTestOfflineEnvironment({ + storage, + config: { followerWrites: `durable`, onlineDetector: offline() }, + }) + let status: unknown = `pending` + let observed: Promise | undefined + let id = `` + try { + await env.waitForLeader() + const transaction = env.executor.createOfflineTransaction({ + mutationFnName: env.mutationFnName, + autoCommit: false, + }) + id = transaction.id + observed = env.executor.waitForTransactionCompletion(id).then( + () => { + status = `completed` + }, + (error: unknown) => { + status = error + }, + ) + transaction.mutate(() => { + env.collection.insert({ + id: `saved`, + value: `saved`, + completed: false, + updatedAt: new Date(), + }) + }) + void transaction.commit().catch(() => undefined) + await vi.waitFor(async () => { + expect(await storage.get(`tx:${id}`)).not.toBe(null) + }) + + env.leader.setLeader(false) + // Another leader sent and removed the row; a success records nothing. + await storage.delete(`tx:${id}`) + if (aged) vi.setSystemTime(Date.now() + OUTCOME_RETENTION_MS + 1) + env.leader.setLeader(true) + for (let turn = 0; turn < 10; turn++) + await new Promise((resolve) => setTimeout(resolve, 0)) + + // A pruned record would look the same, so an aged write keeps waiting. + expect(status).toBe(aged ? `pending` : `completed`) + } finally { + if (status === `pending` && id) + env.executor.rejectTransaction(id, new NonRetriableError(`cleanup`)) + await observed + env.executor.dispose() + } + }, +) From eb6e5e373808f1e8ba3684cb56ddb179d5d4aac2 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 19:21:02 -0800 Subject: [PATCH 07/16] fix(offline-transactions): address fifth durable follower write review - An exclusion cleanup that resumes after its leadership ended neither removes nor settles the write. It withdraws its own record while the row remains, and keeps it once the next leader settled the row, since it may have replaced that leader's record. - A durable follower's removeFromOutbox() and clearOutbox() ask the leader, which alone knows whether the call started, and ask again when a new leader appears; a follower that becomes leader makes its pending removals itself. - Reconciliation also settles saved writes left by a predecessor this executor settles, and a follower reconciles when it starts. - The retention tests state the seven-day boundary themselves. The durable follower oracle varies the removing tab, loses a removal request across a handover, stalls an exclusion record across a handover to a tab that accepts or excludes the write, replaces a disposed writer, and runs actions that expect an immediate outcome only when nothing is queued, retrying or armed to fail. --- .changeset/durable-follower-writes.md | 2 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 123 +++++- .../src/executor/TransactionExecutor.ts | 28 +- .../src/outbox/OutboxManager.ts | 16 +- .../durable-follower-oracle.property.test.ts | 384 ++++++++++++++++-- .../offline-transactions/tests/harness.ts | 12 +- .../tests/outcome-retention.test.ts | 31 +- 8 files changed, 522 insertions(+), 76 deletions(-) diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index 534d675e8a..9c26153ce5 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. A record no writer reads is pruned after seven days. The default stays `'online'`. `removeFromOutbox()` and `clearOutbox()` now also stop a removed transaction that has not started and fail its writer's transaction. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. A record no writer reads is pruned after seven days. The default stays `'online'`. `removeFromOutbox()` and `clearOutbox()` now also stop a removed transaction that has not started and fail its writer's transaction; in a durable follower they ask the leader, so a call that already started keeps the server's outcome. diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index e938d91a19..082229af5f 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it, or for seven days; a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it, or for seven days; a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index f55d44a221..541c351072 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -45,6 +45,13 @@ type OutboxMessage = | { type: `added`; id: string } | { type: `settled`; id: string; error?: { name: string; message: string } } | { type: `leader` } + // A follower asks the leader to remove saved writes, and hears back. + | { type: `remove`; request: string; ids: Array } + | { + type: `removed` + request: string + error?: { name: string; message: string } + } function outboxMessageError(error: { name: string; message: string }): Error { const restored = @@ -116,6 +123,15 @@ export class OfflineExecutor { private term = 0 // Saves in progress; true once removeFromOutbox or clearOutbox removed one. private readonly saving = new Map() + // Removals this follower asked the leader for, by request. + private readonly removals = new Map< + string, + { + ids: Array + resolve: () => void + reject: (error: Error) => void + } + >() private pendingTransactionPromises: Map< string, { @@ -395,6 +411,8 @@ export class OfflineExecutor { await this.loadAndReplayTransactions() } this.initialized = true + // A replacement executor settles saved writes its predecessor left. + if (!isLeader) this.reconcileFollowerWrites() this.initResolve() } catch (error) { console.warn(`Failed to initialize offline executor:`, error) @@ -432,6 +450,11 @@ export class OfflineExecutor { } satisfies OutboxMessage) } this.reconcileFollowerWrites() + // Removals this tab asked a former leader for are now its own to make. + for (const [request, removal] of [...this.removals]) { + this.removals.delete(request) + this.removeSaved(removal.ids).then(removal.resolve, removal.reject) + } // Replay completion is separate from initialization and durable admission. this.executor.executeAll().catch((error) => { @@ -459,6 +482,17 @@ export class OfflineExecutor { private handleOutboxMessage(message: OutboxMessage): void { if (message.type === `leader`) { this.reconcileFollowerWrites() + // A new leader may not have heard earlier removal requests. + for (const [request, removal] of this.removals) + this.postRemoval(request, removal.ids) + } else if (message.type === `remove`) { + this.removeForFollower(message.request, message.ids) + } else if (message.type === `removed`) { + const removal = this.removals.get(message.request) + if (!removal) return + this.removals.delete(message.request) + if (message.error) removal.reject(outboxMessageError(message.error)) + else removal.resolve() } else if (message.type === `added`) { this.admitFollowerWrite(message.id) } else { @@ -469,6 +503,51 @@ export class OfflineExecutor { } } + // Only the leader knows whether a write's call started, so it removes. + private removeForFollower(request: string, ids: Array): void { + if (!this.isOfflineEnabled) return + this.removeSaved(ids).then( + () => { + this.outboxChannel?.postMessage({ + type: `removed`, + request, + } satisfies OutboxMessage) + }, + (error: unknown) => { + console.warn(`Failed to remove transactions for a follower:`, error) + const failure = + error instanceof Error ? error : new Error(String(error)) + this.outboxChannel?.postMessage({ + type: `removed`, + request, + error: { name: failure.name, message: failure.message }, + } satisfies OutboxMessage) + }, + ) + } + + private postRemoval(request: string, ids: Array): void { + this.outboxChannel?.postMessage({ + type: `remove`, + request, + ids, + } satisfies OutboxMessage) + } + + // An initialized follower that shares the outbox asks the leader. + private get forwardsRemovals(): boolean { + return this.writesToSharedOutbox && !this.isOfflineEnabled + } + + private forwardRemoval(ids: Array): Promise { + for (const id of ids) if (this.saving.has(id)) this.saving.set(id, true) + const request = safeRandomUUID() + return new Promise((resolve, reject) => { + this.removals.set(request, { ids, resolve, reject }) + this.postRemoval(request, ids) + }) + } + private admitFollowerWrite(id: string): void { this.unadmitted.delete(id) // Only the leader sends; a later leader loads the row from the outbox. @@ -516,7 +595,11 @@ export class OfflineExecutor { if (!this.recordsOutcomes) return const sweep = ++this.sweeps let failed = false - for (const [id, waiter] of [...this.pendingTransactionPromises]) { + // A predecessor this executor settles may have left saved writes. + const waiters = this.relatedExecutors().flatMap((owner) => [ + ...owner.pendingTransactionPromises, + ]) + for (const [id, waiter] of waiters) { try { if (!(await waiter.saved)) continue if (await this.outbox!.get(id)) continue @@ -837,6 +920,16 @@ export class OfflineExecutor { /** The executors in this runtime that receive this transaction's outcome. */ private settlementOwners(transactionId: string): Array { + return this.relatedExecutors().filter( + (owner) => + owner === this || + owner.pendingTransactionPromises.has(transactionId) || + owner.restorationTransactions.has(transactionId), + ) + } + + /** This executor and those in this runtime whose outcomes it delivers. */ + private relatedExecutors(): Array { const candidates = new Set([this]) for (const collection of Object.values(this.config.collections)) { for (const owner of completionOwners.get(collection) ?? []) @@ -845,18 +938,10 @@ export class OfflineExecutor { return [...candidates].filter( (owner) => owner === this || - ((owner.pendingTransactionPromises.has(transactionId) || - owner.restorationTransactions.has(transactionId)) && - // Either executor may deliver the outcome: a retired issued call or - // its successor's replay. An ancillary overlap alone is insufficient. - (retainsCollections( - this.config.collections, - owner.config.collections, - ) || - retainsCollections( - owner.config.collections, - this.config.collections, - ))), + // Either executor may deliver the outcome: a retired issued call or + // its successor's replay. An ancillary overlap alone is insufficient. + retainsCollections(this.config.collections, owner.config.collections) || + retainsCollections(owner.config.collections, this.config.collections), ) } @@ -901,7 +986,8 @@ export class OfflineExecutor { if (!this.outbox) { return } - await this.removeSaved([id]) + if (this.forwardsRemovals) await this.forwardRemoval([id]) + else await this.removeSaved([id]) } /** @@ -947,7 +1033,9 @@ export class OfflineExecutor { if (!this.outbox || !this.executor) { return } - await this.removeSaved(await this.outbox.ids()) + const ids = await this.outbox.ids() + if (this.forwardsRemovals) await this.forwardRemoval(ids) + else await this.removeSaved(ids) this.executor.clear() } @@ -975,6 +1063,11 @@ export class OfflineExecutor { dispose(): void { this.disposed = true + for (const removal of this.removals.values()) + removal.reject( + new Error(`Offline executor disposed before the leader removed it`), + ) + this.removals.clear() this.executor?.pause() for (const collection of Object.values(this.config.collections)) { collection.deferDataRefresh = null diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 6d16302a2e..64c96726ba 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -469,7 +469,7 @@ export class TransactionExecutor { const error = new NonRetriableError(`Transaction excluded by beforeRetry`) await Promise.all( removedIds.map(async (id) => { - if (await this.cleanUpExcluded(id, error)) return + if (await this.cleanUpExcluded(id, error, term)) return // Until the retry succeeds, no admission runs it. this.failedCleanups.set(id, error) this.scheduleCleanupRetry() @@ -479,9 +479,28 @@ export class TransactionExecutor { } /** Records and removes one excluded write; false when that failed. */ - private async cleanUpExcluded(id: string, error: Error): Promise { + private async cleanUpExcluded( + id: string, + error: Error, + term: number | undefined, + ): Promise { try { - if (this.recordsFor(id)) await this.outbox.recordRejection(id, error) + const recorded = this.recordsFor(id) + ? await this.outbox.recordRejection(id, error) + : undefined + // A later leader decides the write once this term ends: this tab + // neither removes it nor settles it. While the row remains, that + // leader has not settled it, so this tab withdraws its own record. A + // row already gone was rejected by that leader, whose record this one + // may have replaced, or completed before this record landed. + if ( + !this.offlineExecutor.isOfflineEnabled || + term !== this.offlineExecutor.leadershipTerm + ) { + if (recorded !== undefined && (await this.outbox.has(id))) + await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) + return true + } await this.outbox.remove(id) this.excluding.delete(id) this.offlineExecutor.rejectTransaction(id, error) @@ -517,11 +536,12 @@ export class TransactionExecutor { async retryFailedCleanups(): Promise { if (this.cleaning || !this.offlineExecutor.isOfflineEnabled) return this.cleaning = true + const term = this.offlineExecutor.leadershipTerm try { for (const [id, error] of [...this.failedCleanups]) { // A change of leadership drops the rest; the next replay owns them. if (!this.failedCleanups.has(id)) continue - if (!(await this.cleanUpExcluded(id, error))) continue + if (!(await this.cleanUpExcluded(id, error, term))) continue // A change of leadership during the attempt already dropped it. this.failedCleanups.delete(id) } diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index a598630219..68c47cf5e6 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -17,6 +17,8 @@ export type OutboxOutcome = { error: { name: string; message: string } // When it was recorded, so an outcome no writer reads can be pruned. at: number + // Who recorded it, so that recorder can withdraw only its own record. + by?: string } /** @@ -123,16 +125,26 @@ export class OutboxManager { } } - /** Records a rejection before its row is removed. */ - async recordRejection(id: string, error: Error): Promise { + /** Records a rejection before its row is removed; returns its token. */ + async recordRejection(id: string, error: Error): Promise { + const by = `${Date.now()}:${Math.random()}` const outcome: OutboxOutcome = { error: { name: error.name, message: error.message }, at: Date.now(), + by, } await this.storage.set( `${this.outcomePrefix}${id}`, JSON.stringify(outcome), ) + return by + } + + /** Removes the record only if the recording with token `by` made it. */ + async withdrawOutcome(id: string, by: string): Promise { + const data = await this.storage.get(`${this.outcomePrefix}${id}`) + if (data !== null && (JSON.parse(data) as OutboxOutcome).by === by) + await this.storage.delete(`${this.outcomePrefix}${id}`) } async getOutcome(id: string): Promise { diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index f9792d9001..6302ab85ac 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -35,7 +35,9 @@ * follower's rejected write from the leader, clear or remove unsent and * still-saving writes, stall an outbox load across a change of leadership, * fail a leader's start after setup, remove a write while its server call - * runs, and, in the default mode, let another + * runs, from any tab, resume an exclusion cleanup after its leadership ended, + * replace a disposed writer's executor over the same collection, and, in the + * default mode, let another * leader reject a former leader's saved write. * * Production driver: real executors over one shared storage adapter, with a @@ -158,6 +160,22 @@ const reachStates = [ `stale-load-dropped`, // A write removed while its server call ran kept the server's outcome. `removed-while-running-completed`, + // A follower asked the leader to remove a write. + `removal-forwarded`, + // An exclusion cleanup that resumed after its leadership ended changed + // nothing, and the next leader's send settled the write. + `fenced-cleanup-yielded`, + // The next leader also excluded the write, and the stalled record that + // landed after its own still failed the writer. + `fenced-cleanup-kept-rejection`, + // A removal the leader never heard was made under the next leader, by that + // leader itself or after the follower asked it again. + `removal-made-by-new-leader`, + `removal-resent-to-new-leader`, + // A replacement executor settled its predecessor's write that another tab + // completed or rejected meanwhile. + `replacement-settled-success`, + `replacement-settled-rejection`, // In the default mode, a write another leader rejected stayed pending in // its former leader, which cannot tell a rejection from a success. `former-leader-write-unresolved`, @@ -172,6 +190,10 @@ type TabActionType = | `close` | `open` | `open-and-write` + | `remove-unsent` + | `clear-unsent` + | `remove-running` + | `removal-across-handover` type SharedActionType = | `online` | `offline` @@ -186,17 +208,18 @@ type SharedActionType = | `stale-admission-across-terms` | `exclude-on-handover` | `fail-outcome-record` - | `remove-unsent` | `ack-after-handover` | `open-failing` | `dispose-during-save` | `save-after-gain` | `observe-rejection` - | `clear-unsent` | `remove-during-save` | `stale-load-across-terms` | `handover-rejection` - | `remove-running` + | `exclusion-retry-across-handover` + | `exclusion-retry-excluded-again` + | `replace-writer` + | `replace-rejected-writer` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -230,17 +253,22 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`stale-admission-across-terms`) }, { weight: 1, arbitrary: sharedAction(`exclude-on-handover`) }, { weight: 1, arbitrary: sharedAction(`fail-outcome-record`) }, - { weight: 1, arbitrary: sharedAction(`remove-unsent`) }, + { weight: 1, arbitrary: tabAction(`remove-unsent`) }, { weight: 1, arbitrary: sharedAction(`ack-after-handover`) }, { weight: 1, arbitrary: sharedAction(`open-failing`) }, { weight: 1, arbitrary: sharedAction(`dispose-during-save`) }, { weight: 1, arbitrary: sharedAction(`save-after-gain`) }, { weight: 1, arbitrary: sharedAction(`observe-rejection`) }, - { weight: 1, arbitrary: sharedAction(`clear-unsent`) }, + { weight: 1, arbitrary: tabAction(`clear-unsent`) }, { weight: 1, arbitrary: sharedAction(`remove-during-save`) }, { weight: 1, arbitrary: sharedAction(`stale-load-across-terms`) }, { weight: 1, arbitrary: sharedAction(`handover-rejection`) }, - { weight: 1, arbitrary: sharedAction(`remove-running`) }, + { weight: 1, arbitrary: sharedAction(`exclusion-retry-across-handover`) }, + { weight: 1, arbitrary: sharedAction(`exclusion-retry-excluded-again`) }, + { weight: 1, arbitrary: tabAction(`removal-across-handover`) }, + { weight: 1, arbitrary: sharedAction(`replace-writer`) }, + { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, + { weight: 1, arbitrary: tabAction(`remove-running`) }, ) const historyArbitrary: fc.Arbitrary = fc.record({ mode: fc.constantFrom(`durable`, `durable`, `durable`, `online`), @@ -288,6 +316,11 @@ const spliced = ( action.type !== `remove-during-save` && action.type !== `stale-load-across-terms` && action.type !== `handover-rejection` && + action.type !== `exclusion-retry-across-handover` && + action.type !== `exclusion-retry-excluded-again` && + action.type !== `removal-across-handover` && + action.type !== `replace-writer` && + action.type !== `replace-rejected-writer` && action.type !== `remove-running`, ) .slice(0, MAX_ACTIONS - prefix.length), @@ -394,6 +427,15 @@ class ReadFailingStorage extends FakeStorageAdapter { failOutcomeWrites = 0 // Outcome keys whose write failed. readonly failedOutcomeKeys = new Set() + // The next outcome write waits for release, then lands. + private heldOutcome: { release: () => void } | null | undefined + holdOutcomeWrite(): void { + this.heldOutcome = null + } + releaseOutcomeWrite(): void { + this.heldOutcome?.release() + this.heldOutcome = undefined + } // The next write lands at once and acknowledges on release. private heldAck: { release: () => void } | null | undefined holdNextAck(): void { @@ -438,6 +480,11 @@ class ReadFailingStorage extends FakeStorageAdapter { this.failedOutcomeKeys.add(key) throw new Error(`storage write failed`) } + if (this.heldOutcome === null && key.startsWith(`outcome:`)) { + await new Promise((release) => { + this.heldOutcome = { release } + }) + } if (this.heldAck === null && key.startsWith(`tx:`)) { await super.set(key, value) await new Promise((release) => { @@ -485,6 +532,8 @@ function controlledChannels() { const open = new Set() const state = { loseSettlement: false, + loseRemoval: false, + loseLeader: false, lost: 0, lostIds: [] as Array, created: 0, @@ -506,6 +555,14 @@ function controlledChannels() { open.add(this) } postMessage(data: ChannelMessage): void { + if (state.loseLeader && data.type === `leader`) { + state.loseLeader = false + return + } + if (state.loseRemoval && data.type === `remove`) { + state.loseRemoval = false + return + } if (state.loseSettlement && data.type === `settled`) { state.loseSettlement = false state.lost += 1 @@ -608,6 +665,8 @@ async function runHistory( hold?: Promise, // `load`: it leads, then its outbox load fails. failStart: boolean | `load` = false, + // A replacement keeps its predecessor's collection. + collection?: ReturnType[`collection`], ) => { const tabElection = new TabElection(election, hold, failStart === true) const session = ++sessions @@ -615,6 +674,7 @@ async function runHistory( storage, // Each tab names its collection differently under the shared key. collectionId: `items-${session}`, + collection, registryKey: `test-items`, mutationFn: (params: OfflineMutationFnParams) => { const id = String(params.transaction.mutations[0].key) @@ -678,8 +738,19 @@ async function runHistory( const leaderIndex = () => tabs.findIndex((tab) => tab && tab.election === election.holder) const openSessions = () => new Set(tabs.flatMap((tab) => tab?.session ?? [])) - // No earlier write is still queued, so a new one is sent at once. - const queueIdle = () => !writes.some(isUnsent) + // No earlier write is queued or retrying a cleanup, nothing is armed to + // fail or be lost, so an action's writes are sent at once and its + // outcome is its own. + const quiet = async () => { + if ( + writes.some(isUnsent) || + storage.failOutcomeWrites > 0 || + channels.state.loseSettlement + ) + return false + const leader = tabs[leaderIndex()] + return !leader || (await leader.env.executor.peekOutbox()).length === 0 + } const check = (label: string) => { expect( @@ -926,7 +997,7 @@ async function runHistory( ) if (!durable || !online.online || leaderIndex() < 0 || follower < 0) break - if (!queueIdle()) break + if (!(await quiet())) break storage.failDeletes = 1 const write = await doWrite(follower, `write`) // A queue still busy with earlier writes leaves the fault unused. @@ -1107,16 +1178,18 @@ async function runHistory( break } case `remove-unsent`: { - // The leader removes a follower's saved write before sending it. + // A tab removes a follower's saved write before any leader sent it. const leader = leaderIndex() const follower = tabs.findIndex( (tab, index) => tab && index !== leader, ) - if (!durable || leader < 0 || follower < 0) break + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + const remover = tabs[action.tab] ? action.tab : leader online.set(false) const write = await doWrite(follower, `write`) if (!write) break - await tabs[leader]!.env.executor.removeFromOutbox( + if (remover !== leaderIndex()) reach(`removal-forwarded`) + await tabs[remover]!.env.executor.removeFromOutbox( write.transactionId!, ) // Removing a row that is already gone records nothing. @@ -1127,7 +1200,7 @@ async function runHistory( calls.includes(candidate.id), ) if (gone) - await tabs[leader]!.env.executor.removeFromOutbox( + await tabs[remover]!.env.executor.removeFromOutbox( gone.transactionId!, ) write.removed = true @@ -1153,7 +1226,8 @@ async function runHistory( !online.online || leader < 0 || writer < 0 || - tabs.filter(Boolean).length < 3 + tabs.filter(Boolean).length < 3 || + !(await quiet()) ) break storage.holdNextAck() @@ -1184,7 +1258,7 @@ async function runHistory( // leadership and no listener, without being disposed. With no // leader it leads, and its outbox load fails after setup. const index = tabs.findIndex((tab) => !tab) - if (!durable || index < 0 || !queueIdle()) break + if (!durable || index < 0 || !(await quiet())) break const before = channels.openCount() const listenersBefore = online.listeners.size const failLoad = leaderIndex() < 0 @@ -1225,7 +1299,7 @@ async function runHistory( !online.online || leader < 0 || follower < 0 || - !queueIdle() + !(await quiet()) ) break storage.holdWrites() @@ -1250,7 +1324,7 @@ async function runHistory( !online.online || leader < 0 || writer < 0 || - !queueIdle() + !(await quiet()) ) break storage.holdWrites() @@ -1271,7 +1345,7 @@ async function runHistory( // misses the settlement and learns the rejection from its record. const leader = leaderIndex() const writer = tabs.findIndex((tab, index) => tab && index !== leader) - if (!durable || leader < 0 || writer < 0 || !queueIdle()) break + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break online.set(false) const write = await doWrite(writer, `write-rejected`) if (!write) break @@ -1294,14 +1368,16 @@ async function runHistory( break } case `clear-unsent`: { - // The leader clears the outbox while a follower's write is unsent. + // A tab clears the outbox while a follower's write is unsent. const leader = leaderIndex() const follower = tabs.findIndex( (tab, index) => tab && index !== leader, ) - if (!durable || leader < 0 || follower < 0 || !queueIdle()) break - const executor = tabs[leader]!.env.executor + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + const remover = tabs[action.tab] ? action.tab : leader + const executor = tabs[remover]!.env.executor if ((await executor.peekOutbox()).length > 0) break + if (remover !== leader) reach(`removal-forwarded`) online.set(false) const write = await doWrite(follower, `write`) if (!write) break @@ -1317,7 +1393,7 @@ async function runHistory( // The leader's own row lands, the leader removes it, and only then // does its save acknowledge. const leader = leaderIndex() - if (leader < 0 || !online.online || !queueIdle()) break + if (leader < 0 || !online.online || !(await quiet())) break storage.holdNextAck() const write = await doWrite(leader, `write`) if (!write) { @@ -1353,7 +1429,7 @@ async function runHistory( !target || writer < 0 || tabs.filter(Boolean).length < 3 || - !queueIdle() + !(await quiet()) ) break online.set(false) @@ -1388,7 +1464,7 @@ async function runHistory( durable || leader < 0 || tabs.filter(Boolean).length < 2 || - !queueIdle() + !(await quiet()) ) break online.set(false) @@ -1414,8 +1490,8 @@ async function runHistory( break } case `remove-running`: { - // The leader removes a follower's write while its server call runs, - // and the success message is lost. + // A tab removes a follower's write while the leader's server call + // runs, and the success message is lost. const leader = leaderIndex() const follower = tabs.findIndex( (tab, index) => tab && index !== leader, @@ -1425,7 +1501,7 @@ async function runHistory( !online.online || leader < 0 || follower < 0 || - !queueIdle() + !(await quiet()) ) break let release!: () => void @@ -1439,9 +1515,14 @@ async function runHistory( await settle() break } - await tabs[leader]!.env.executor.removeFromOutbox( + const remover = tabs[action.tab] ? action.tab : leader + if (remover !== leader) reach(`removal-forwarded`) + await tabs[remover]!.env.executor.removeFromOutbox( write.transactionId!, ) + expect(write.outcome, `${write.id} waits for its call`).toBe( + undefined, + ) channels.state.loseSettlement = true release() await settle() @@ -1454,6 +1535,179 @@ async function runHistory( reach(`removed-while-running-completed`) break } + case `exclusion-retry-across-handover`: + case `exclusion-retry-excluded-again`: { + // The next leader excludes a follower's write and its record fails. + // Its retry stalls on the record while leadership moves on. The + // tab that leads next accepts the write, and the retry resumes + // during that send; or it excludes the write too, and the retry + // resumes after it settled. + const again = action.type === `exclusion-retry-excluded-again` + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + excluded.add(write.id) + storage.failOutcomeWrites = 1 + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + await settle() + storage.failOutcomeWrites = 0 + expect( + storage.failedOutcomeKeys.has(`outcome:${write.transactionId}`), + `${write.id}'s exclusion record failed`, + ).toBe(true) + storage.holdOutcomeWrite() + if (again) { + // The original tab leads next, so the writer stays a follower. + const writerElection = tabs[writer]!.election + writerElection.releaseLeadership() + await writerElection.requestLeadership() + online.set(true) + await settle() + write.excluded = true + write.deliverable = false + // The writer misses the rejection and the new leader's message, + // so it reads the outbox only after the stalled record lands. + channels.state.loseSettlement = true + channels.state.loseLeader = true + next.releaseLeadership() + await settle() + storage.releaseOutcomeWrite() + await settle() + channels.state.loseSettlement = false + channels.state.loseLeader = false + await next.requestLeadership() + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} fails from a record`).toBe( + `failed`, + ) + reach(`fenced-cleanup-kept-rejection`) + break + } + excluded.delete(write.id) + online.set(true) + await settle() + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + next.releaseLeadership() + await settle() + expect(calls, `${write.id} sent by the next leader`).toContain( + write.id, + ) + storage.releaseOutcomeWrite() + await settle() + expect(write.outcome, `${write.id} waits for its call`).toBe( + undefined, + ) + release() + await settle() + await next.requestLeadership() + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`fenced-cleanup-yielded`) + break + } + case `removal-across-handover`: { + // A follower asks to remove a follower's unsent write, the leader + // never hears it, and the leader closes. + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + const remover = action.tab + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + !tabs[remover] || + remover === leader || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + channels.state.loseRemoval = true + let done = false + const removal = tabs[remover].env.executor.removeFromOutbox( + write.transactionId!, + ) + void removal.then(() => { + done = true + }) + await settle() + expect(done, `the leader never heard the removal`).toBe(false) + const nextLeads = tabs[remover].election === next + await closeTab(leader) + await settle() + expect(done, `the removal finished under the next leader`).toBe(true) + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach( + nextLeads + ? `removal-made-by-new-leader` + : `removal-resent-to-new-leader`, + ) + break + } + case `replace-writer`: + case `replace-rejected-writer`: { + // A follower's executor is disposed with its write saved; another + // tab settles the write, then a replacement over the same + // collection starts. + const rejectedWrite = action.type === `replace-rejected-writer` + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite( + writer, + rejectedWrite ? `write-rejected` : `write`, + ) + if (!write) break + const collection = tabs[writer]!.env.collection + await closeTab(writer) + online.set(true) + await settle() + expect(calls, `${write.id} sent by the leader`).toContain(write.id) + expect(write.outcome, `${write.id} waits for a replacement`).toBe( + undefined, + ) + await openTab(writer, undefined, undefined, false, collection) + expect(write.outcome, `${write.id} settled by the replacement`).toBe( + rejectedWrite ? `failed` : `completed`, + ) + reach( + rejectedWrite + ? `replacement-settled-rejection` + : `replacement-settled-success`, + ) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const pending = writes.filter( @@ -1662,7 +1916,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -1689,6 +1943,10 @@ oracleProperty({ `src/executor/TransactionExecutor.ts#TransactionExecutor.cleanUpExcluded`, `src/executor/TransactionExecutor.ts#TransactionExecutor.retryFailedCleanups`, `src/executor/TransactionExecutor.ts#TransactionExecutor.recordsFor`, + `src/outbox/OutboxManager.ts#OutboxManager.withdrawOutcome`, + `src/OfflineExecutor.ts#OfflineExecutor.removeForFollower`, + `src/OfflineExecutor.ts#OfflineExecutor.forwardRemoval`, + `src/OfflineExecutor.ts#OfflineExecutor.relatedExecutors`, ], histories: { arbitrary: historyArbitrary, @@ -1898,7 +2156,13 @@ oracleProperty({ name: `a write removed before it was sent fails its writer`, enters: [`removed-unsent-failed`], build: (generated: History): History => - spliced(generated, [{ type: `remove-unsent` }]), + spliced(generated, [{ type: `remove-unsent`, tab: 0 }]), + }, + { + name: `a writer that removes its own unsent write fails`, + enters: [`removed-unsent-failed`, `removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-unsent`, tab: 1 }]), }, { name: `a save acknowledged after a handover is admitted by id`, @@ -1960,7 +2224,13 @@ oracleProperty({ name: `clearing the outbox fails an unsent write's writer`, enters: [`cleared-unsent-failed`], build: (generated: History): History => - spliced(generated, [{ type: `clear-unsent` }]), + spliced(generated, [{ type: `clear-unsent`, tab: 0 }]), + }, + { + name: `a follower that clears the outbox fails an unsent write`, + enters: [`cleared-unsent-failed`, `removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `clear-unsent`, tab: 2 }]), }, { name: `a write removed during its save never runs`, @@ -1978,7 +2248,55 @@ oracleProperty({ name: `a write removed while its call runs keeps the server's outcome`, enters: [`removed-while-running-completed`], build: (generated: History): History => - spliced(generated, [{ type: `remove-running` }]), + spliced(generated, [{ type: `remove-running`, tab: 0 }]), + }, + { + name: `a writer that removes its running write keeps the server's outcome`, + enters: [`removed-while-running-completed`, `removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-running`, tab: 1 }]), + }, + { + name: `a bystander that removes a running write keeps the server's outcome`, + enters: [`removed-while-running-completed`, `removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-running`, tab: 2 }]), + }, + { + name: `an exclusion cleanup after its leadership ended changes nothing`, + enters: [`fenced-cleanup-yielded`], + build: (generated: History): History => + spliced(generated, [{ type: `exclusion-retry-across-handover` }]), + }, + { + name: `a stalled exclusion record keeps the next leader's rejection`, + enters: [`fenced-cleanup-kept-rejection`], + build: (generated: History): History => + spliced(generated, [{ type: `exclusion-retry-excluded-again` }]), + }, + { + name: `a follower that becomes leader makes its own lost removal`, + enters: [`removal-made-by-new-leader`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-across-handover`, tab: 1 }]), + }, + { + name: `a follower asks the next leader again for a lost removal`, + enters: [`removal-resent-to-new-leader`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-across-handover`, tab: 2 }]), + }, + { + name: `a replacement settles its predecessor's completed write`, + enters: [`replacement-settled-success`], + build: (generated: History): History => + spliced(generated, [{ type: `replace-writer` }]), + }, + { + name: `a replacement settles its predecessor's rejected write`, + enters: [`replacement-settled-rejection`], + build: (generated: History): History => + spliced(generated, [{ type: `replace-rejected-writer` }]), }, { name: `an outbox load from an earlier term schedules nothing`, diff --git a/packages/offline-transactions/tests/harness.ts b/packages/offline-transactions/tests/harness.ts index 7e3f84c64d..e649f65db6 100644 --- a/packages/offline-transactions/tests/harness.ts +++ b/packages/offline-transactions/tests/harness.ts @@ -103,6 +103,8 @@ interface TestOfflineEnvironmentOptions { config?: Partial // The collection's id, and the key the executor registers it under. collectionId?: string + // An existing collection to register, as a replacement executor does. + collection?: Collection registryKey?: string } @@ -150,12 +152,16 @@ export function createTestOfflineEnvironment( const mutationCalls: Array = [] const attemptCounter = new Map() - const { collection, controller } = createDefaultCollection( - options.collectionId, - ) + const created = options.collection + ? undefined + : createDefaultCollection(options.collectionId) + const collection = options.collection ?? created!.collection + const controller = created?.controller const serverState = new Map() const applyMutations = (mutations: ReadonlyArray) => { + // A reused collection keeps the sync of the environment that made it. + if (!controller) return controller.begin() for (const mutation of mutations) { diff --git a/packages/offline-transactions/tests/outcome-retention.test.ts b/packages/offline-transactions/tests/outcome-retention.test.ts index d64776bad9..649f56a67c 100644 --- a/packages/offline-transactions/tests/outcome-retention.test.ts +++ b/packages/offline-transactions/tests/outcome-retention.test.ts @@ -1,11 +1,13 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { OUTCOME_RETENTION_MS } from '../src/outbox/OutboxManager' import { NonRetriableError } from '../src/types' import { FakeStorageAdapter, createTestOfflineEnvironment } from './harness' import type { OnlineDetector } from '../src/types' -// Rejection records for writers in other tabs live for a bounded time. These -// checks move the clock, which the durable follower oracle does not. +// Rejection records for writers in other tabs live for seven days, as the +// guide documents. These checks move the clock, which the durable follower +// oracle does not, and state the duration on their own. + +const DAY = 24 * 60 * 60 * 1000 const offline = (): OnlineDetector => ({ subscribe: () => () => {}, @@ -33,17 +35,11 @@ afterEach(() => { vi.unstubAllGlobals() }) -it(`prunes outcome records older than the retention window when a tab leads`, async () => { +it(`prunes outcome records older than seven days when a tab leads`, async () => { const storage = new FakeStorageAdapter() const now = Date.now() - await storage.set( - `outcome:old`, - record(`old`, now - OUTCOME_RETENTION_MS - 1), - ) - await storage.set( - `outcome:recent`, - record(`recent`, now - OUTCOME_RETENTION_MS + 60_000), - ) + await storage.set(`outcome:old`, record(`old`, now - 9 * DAY)) + await storage.set(`outcome:recent`, record(`recent`, now - 6 * DAY)) const env = createTestOfflineEnvironment({ storage, config: { followerWrites: `durable`, onlineDetector: offline() }, @@ -54,16 +50,17 @@ it(`prunes outcome records older than the retention window when a tab leads`, as expect(await storage.get(`outcome:old`)).toBe(null) }) expect(await storage.get(`outcome:recent`)).toBe( - record(`recent`, now - OUTCOME_RETENTION_MS + 60_000), + record(`recent`, now - 6 * DAY), ) } finally { env.executor.dispose() } }) -it.each([false, true])( - `a saved write whose row left with no record completes only within the retention window, aged=%s`, - async (aged) => { +it.each([6, 9])( + `a saved write whose row left with no record completes only within seven days, after %i days`, + async (days) => { + const aged = days > 7 vi.useFakeTimers({ toFake: [`Date`] }) const storage = new FakeStorageAdapter() const env = createTestOfflineEnvironment({ @@ -104,7 +101,7 @@ it.each([false, true])( env.leader.setLeader(false) // Another leader sent and removed the row; a success records nothing. await storage.delete(`tx:${id}`) - if (aged) vi.setSystemTime(Date.now() + OUTCOME_RETENTION_MS + 1) + vi.setSystemTime(Date.now() + days * DAY) env.leader.setLeader(true) for (let turn = 0; turn < 10; turn++) await new Promise((resolve) => setTimeout(resolve, 0)) From 25b5e5da3899203248a0761757822efdc23fec5b Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 20:33:45 -0800 Subject: [PATCH 08/16] fix(offline-transactions): address sixth durable follower write review - Each outcome recording has its own key, so a leader withdraws only its own record and never removes another leader's. - A leader takes removed writes off its queue before any storage step, settles each by its own deletion, and queues again one whose deletion failed. A removed write whose call is running leaves a marker, so its writer waits for the server's outcome. clearOutbox() leaves writes saved after its snapshot queued. - A follower marks its own save removed only once the leader confirms. - A failed exclusion cleanup is retried only while that exclusion still stands in the same term. - Reconciliation reads a predecessor's writes from the outbox they were saved to, and a row that cannot be decoded keeps its writer waiting. - The guide says every tab that can lead needs durable mode, and that a leader's write during startup waits for initialization. The durable follower oracle checks a removed write during its call and with a server rejection, an unreadable row, a partly failed clear, a clear across a handover with a later write, a replacement over another store or a new adapter, a failed removal during a save, a removal racing a reconnect, and a failed cleanup across terms. A failed start must reject, and a replaced writer's rejection keeps the server's error. --- .changeset/durable-follower-writes.md | 2 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 102 ++-- .../src/executor/TransactionExecutor.ts | 25 +- .../src/outbox/OutboxManager.ts | 67 ++- packages/offline-transactions/src/types.ts | 2 + .../durable-follower-oracle.property.test.ts | 441 +++++++++++++++++- .../tests/outcome-retention.test.ts | 8 +- 8 files changed, 569 insertions(+), 80 deletions(-) diff --git a/.changeset/durable-follower-writes.md b/.changeset/durable-follower-writes.md index 9c26153ce5..69202fd4cd 100644 --- a/.changeset/durable-follower-writes.md +++ b/.changeset/durable-follower-writes.md @@ -2,4 +2,4 @@ '@tanstack/offline-transactions': minor --- -Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. A record no writer reads is pruned after seven days. The default stays `'online'`. `removeFromOutbox()` and `clearOutbox()` now also stop a removed transaction that has not started and fail its writer's transaction; in a durable follower they ask the leader, so a call that already started keeps the server's outcome. +Add `followerWrites: 'durable'`. A follower tab can now save a write to the shared outbox, so it survives going offline or closing the tab. The current or next leader sends it and reports the result back over BroadcastChannel. The leader also records a rejection before removing the row, so a follower that misses the report still fails with the server's error. A writer deletes its record when it reads it, and a leader's replay prunes records older than seven days. The default stays `'online'`. `removeFromOutbox()` and `clearOutbox()` now also stop a removed transaction that has not started and fail its writer's transaction; in a durable follower they ask the leader, so a call that already started keeps the server's outcome. diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 082229af5f..9b861d8808 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. A write made before `waitForInit()` resolves also uses the online path. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it, or for seven days; a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. Every tab that can lead must also set `followerWrites: 'durable'`: a leader in the default mode opens no channel and never hears a follower's saved write. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 541c351072..c5afb70b91 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -123,6 +123,8 @@ export class OfflineExecutor { private term = 0 // Saves in progress; true once removeFromOutbox or clearOutbox removed one. private readonly saving = new Map() + // Running markers this leader recorded for removed writes, by id. + private readonly runningRemovals = new Map() // Removals this follower asked the leader for, by request. private readonly removals = new Map< string, @@ -540,10 +542,18 @@ export class OfflineExecutor { } private forwardRemoval(ids: Array): Promise { - for (const id of ids) if (this.saving.has(id)) this.saving.set(id, true) const request = safeRandomUUID() return new Promise((resolve, reject) => { - this.removals.set(request, { ids, resolve, reject }) + this.removals.set(request, { + ids, + // Only a confirmed removal stops a save of this tab that lands late. + resolve: () => { + for (const id of ids) + if (this.saving.has(id)) this.saving.set(id, true) + resolve() + }, + reject, + }) this.postRemoval(request, ids) }) } @@ -595,20 +605,28 @@ export class OfflineExecutor { if (!this.recordsOutcomes) return const sweep = ++this.sweeps let failed = false - // A predecessor this executor settles may have left saved writes. - const waiters = this.relatedExecutors().flatMap((owner) => [ - ...owner.pendingTransactionPromises, - ]) - for (const [id, waiter] of waiters) { + // A predecessor this executor settles may have left saved writes; each is + // checked against the outbox its executor saved it to. + const waiters = this.relatedExecutors().flatMap((owner) => + [...owner.pendingTransactionPromises].map( + ([id, waiter]) => [owner, id, waiter] as const, + ), + ) + for (const [owner, id, waiter] of waiters) { try { if (!(await waiter.saved)) continue - if (await this.outbox!.get(id)) continue - const error = (await this.outbox!.getOutcome(id))?.error + const outbox = owner.outbox! + // A row that cannot be decoded is still there. + if (await outbox.has(id)) continue + const outcome = await outbox.getOutcome(id) + // Its call is still running after a removal. + if (outcome?.pending) continue + const error = outcome?.error // A record older than the retention window may have been pruned, so // no record cannot mean success. if (!error && Date.now() - waiter.savedAt! > OUTCOME_RETENTION_MS) continue - this.settleFollowerWrite(id, error && outboxMessageError(error)) + owner.settleFollowerWrite(id, error && outboxMessageError(error)) } catch (error) { failed = true console.warn(`Failed to reconcile follower writes:`, error) @@ -998,28 +1016,51 @@ export class OfflineExecutor { private async removeSaved(ids: Array): Promise { const outbox = this.outbox! const error = removedError() - const present = new Set( - ( - await Promise.all( - ids.map(async (id) => ((await outbox.has(id)) ? id : null)), - ) - ).filter((id): id is string => id !== null), - ) + // Off the queue before any await, so this tab cannot start them + // meanwhile; the one already running keeps the provider's outcome. + const queued = this.scheduler + .getAllPendingTransactions() + .filter(({ id }) => ids.includes(id)) + const unstarted = new Set(this.scheduler.removePendingTransactions(ids)) + const failures: Array = [] + // Each id settles by its own deletion. await Promise.all( - [...present].map(async (id) => { - if ( - this.recordsOutcomes && - !this.ownsWrite(id) && - !this.scheduler.isRunning(id) - ) - await outbox.recordRejection(id, error) + ids.map(async (id) => { + let token: string | undefined + try { + if (!(await outbox.has(id))) { + if (this.saving.has(id)) this.saving.set(id, true) + return + } + // A writer in another tab reads a rejection, or that the call it + // cannot see is still running. + if (this.recordsOutcomes && !this.ownsWrite(id)) + token = unstarted.has(id) + ? await outbox.recordRejection(id, error) + : await outbox.recordPending(id) + await outbox.remove(id) + } catch (removalError) { + failures.push(removalError) + // Its row stays, so it is queued again and its record withdrawn. + if (token !== undefined) + await outbox.withdrawOutcome(id, token).catch(() => {}) + this.executor!.requeue(queued.filter((tx) => tx.id === id)) + return + } + if (this.saving.has(id)) this.saving.set(id, true) + if (unstarted.has(id)) this.rejectTransaction(id, error) + else if (token !== undefined) this.runningRemovals.set(id, token) }), ) - await outbox.removeMany(ids) - for (const id of ids) if (this.saving.has(id)) this.saving.set(id, true) - // A removed transaction that has not started does not run. - for (const id of this.scheduler.removePendingTransactions(ids)) - if (present.has(id)) this.rejectTransaction(id, error) + if (failures.length > 0) throw failures[0] + } + + /** Withdraws the running marker of a removed write whose call finished. */ + async finishRunningRemoval(id: string): Promise { + const token = this.runningRemovals.get(id) + if (token === undefined) return + this.runningRemovals.delete(id) + await this.outbox!.withdrawOutcome(id, token).catch(() => {}) } async peekOutbox(): Promise> { @@ -1033,10 +1074,11 @@ export class OfflineExecutor { if (!this.outbox || !this.executor) { return } + // Only the ids it removes leave the queue; a write saved after the + // snapshot stays queued. const ids = await this.outbox.ids() if (this.forwardsRemovals) await this.forwardRemoval(ids) else await this.removeSaved(ids) - this.executor.clear() } getPendingCount(): number { diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 64c96726ba..551fac038e 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -372,6 +372,7 @@ export class TransactionExecutor { } } await this.outbox.remove(transaction.id) + await this.offlineExecutor.finishRunningRemoval?.(transaction.id) this.scheduler.markCompleted(transaction) return true } catch (error) { @@ -470,7 +471,14 @@ export class TransactionExecutor { await Promise.all( removedIds.map(async (id) => { if (await this.cleanUpExcluded(id, error, term)) return - // Until the retry succeeds, no admission runs it. + // Retried only while this decision stands: a later term's replay + // may have accepted the write. Until then no admission runs it. + if ( + !this.offlineExecutor.isOfflineEnabled || + term !== this.offlineExecutor.leadershipTerm || + !this.excluding.has(id) + ) + return this.failedCleanups.set(id, error) this.scheduleCleanupRetry() }), @@ -489,15 +497,13 @@ export class TransactionExecutor { ? await this.outbox.recordRejection(id, error) : undefined // A later leader decides the write once this term ends: this tab - // neither removes it nor settles it. While the row remains, that - // leader has not settled it, so this tab withdraws its own record. A - // row already gone was rejected by that leader, whose record this one - // may have replaced, or completed before this record landed. + // neither removes it nor settles it, and withdraws its own record, + // which leaves any record that leader made. if ( !this.offlineExecutor.isOfflineEnabled || term !== this.offlineExecutor.leadershipTerm ) { - if (recorded !== undefined && (await this.outbox.has(id))) + if (recorded !== undefined) await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) return true } @@ -553,6 +559,13 @@ export class TransactionExecutor { else this.scheduleCleanupRetry() } + /** Queues writes again whose removal failed. */ + requeue(transactions: Array): void { + if (!this.offlineExecutor.isOfflineEnabled) return + for (const transaction of transactions) this.scheduler.schedule(transaction) + this.scheduleNextRetry() + } + private dropFailedCleanups(): void { this.failedCleanups.clear() this.cleanupAttempts = 0 diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 68c47cf5e6..a3ea37a392 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -12,13 +12,16 @@ import type { Collection } from '@tanstack/db' export class OutboxTransactionNotFoundError extends Error {} -/** A rejected transaction's error, kept for a writer in another tab. */ +/** + * A write's outcome, kept for a writer in another tab: a rejection, or a + * marker that the write's call is still running after its row was removed. + * Each recording has its own key, so a recorder withdraws only its own. + */ export type OutboxOutcome = { - error: { name: string; message: string } + error?: { name: string; message: string } + pending?: true // When it was recorded, so an outcome no writer reads can be pruned. at: number - // Who recorded it, so that recorder can withdraw only its own record. - by?: string } /** @@ -127,33 +130,51 @@ export class OutboxManager { /** Records a rejection before its row is removed; returns its token. */ async recordRejection(id: string, error: Error): Promise { - const by = `${Date.now()}:${Math.random()}` - const outcome: OutboxOutcome = { + return this.recordOutcome(id, { error: { name: error.name, message: error.message }, at: Date.now(), - by, - } + }) + } + + /** Records that a removed write's call is still running. */ + async recordPending(id: string): Promise { + return this.recordOutcome(id, { pending: true, at: Date.now() }) + } + + private async recordOutcome( + id: string, + outcome: OutboxOutcome, + ): Promise { + const token = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}` await this.storage.set( - `${this.outcomePrefix}${id}`, + `${this.outcomeKeyPrefix(id)}${token}`, JSON.stringify(outcome), ) - return by + return token } - /** Removes the record only if the recording with token `by` made it. */ - async withdrawOutcome(id: string, by: string): Promise { - const data = await this.storage.get(`${this.outcomePrefix}${id}`) - if (data !== null && (JSON.parse(data) as OutboxOutcome).by === by) - await this.storage.delete(`${this.outcomePrefix}${id}`) + /** Removes one recording, leaving any another recorder made. */ + async withdrawOutcome(id: string, token: string): Promise { + await this.storage.delete(`${this.outcomeKeyPrefix(id)}${token}`) } + /** A rejection if any recording holds one, else a running marker. */ async getOutcome(id: string): Promise { - const data = await this.storage.get(`${this.outcomePrefix}${id}`) - return data === null ? null : (JSON.parse(data) as OutboxOutcome) + let found: OutboxOutcome | null = null + for (const key of await this.outcomeKeys(id)) { + const data = await this.storage.get(key) + if (data === null) continue + const outcome = JSON.parse(data) as OutboxOutcome + if (outcome.error) return outcome + found = outcome + } + return found } async removeOutcome(id: string): Promise { - await this.storage.delete(`${this.outcomePrefix}${id}`) + await Promise.all( + (await this.outcomeKeys(id)).map((key) => this.storage.delete(key)), + ) } /** Removes outcome records made before `before`. */ @@ -168,6 +189,16 @@ export class OutboxManager { } } + // An encoded id contains no `:`, so one id's prefix never matches another. + private outcomeKeyPrefix(id: string): string { + return `${this.outcomePrefix}${encodeURIComponent(id)}:` + } + + private async outcomeKeys(id: string): Promise> { + const prefix = this.outcomeKeyPrefix(id) + return (await this.storage.keys()).filter((key) => key.startsWith(prefix)) + } + /** Whether a row is saved, without decoding it. */ async has(id: string): Promise { return (await this.storage.get(this.getStorageKey(id))) !== null diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index 2f03a493f1..4aa5ab3dec 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -177,6 +177,8 @@ export interface TransactionSignaler { * writer needs a recorded rejection; this tab's own does not. */ ownsWrite?: (transactionId: string) => boolean + /** A removed write's call finished: its running marker goes. */ + finishRunningRemoval?: (transactionId: string) => Promise resolveTransaction: (transactionId: string, result: any) => void rejectTransaction: ( transactionId: string, diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 6302ab85ac..8821231815 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -75,6 +75,7 @@ import type { LeaderElection, OfflineMutationFnParams, OnlineDetector, + StorageAdapter, } from '../src/types' const property = `offline.durable-follower-writes` @@ -176,6 +177,24 @@ const reachStates = [ // completed or rejected meanwhile. `replacement-settled-success`, `replacement-settled-rejection`, + // A replacement over another store left its predecessor's unsent write + // pending. + `replacement-other-store-waited`, + // A write removed while its call ran stayed pending at a check made during + // the call, then took the server's rejection. + `removed-while-running-rejected`, + // A writer whose saved row could not be decoded kept waiting. + `unreadable-row-kept-waiting`, + // A clear whose deletion of one row failed settled the other. + `partial-clear-settled`, + // A clear made under the next leader kept a write saved after it began. + `clear-kept-later-write`, + // A removal that failed during a save left the save to finish and send. + `failed-removal-kept-save`, + // A reconnect during a removal did not start the removed write. + `removal-held-off-reconnect`, + // A cleanup that failed after its leadership ended was not retried later. + `stale-cleanup-not-retried`, // In the default mode, a write another leader rejected stayed pending in // its former leader, which cannot tell a rejection from a success. `former-leader-write-unresolved`, @@ -194,6 +213,8 @@ type TabActionType = | `clear-unsent` | `remove-running` | `removal-across-handover` + | `remove-rejected-running` + | `clear-across-handover` type SharedActionType = | `online` | `offline` @@ -220,6 +241,12 @@ type SharedActionType = | `exclusion-retry-excluded-again` | `replace-writer` | `replace-rejected-writer` + | `replace-writer-other-store` + | `unreadable-saved-row` + | `clear-partially-fails` + | `failed-removal-during-save` + | `remove-before-reconnect` + | `failed-cleanup-across-terms` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -266,6 +293,14 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`exclusion-retry-across-handover`) }, { weight: 1, arbitrary: sharedAction(`exclusion-retry-excluded-again`) }, { weight: 1, arbitrary: tabAction(`removal-across-handover`) }, + { weight: 1, arbitrary: tabAction(`remove-rejected-running`) }, + { weight: 1, arbitrary: tabAction(`clear-across-handover`) }, + { weight: 1, arbitrary: sharedAction(`replace-writer-other-store`) }, + { weight: 1, arbitrary: sharedAction(`unreadable-saved-row`) }, + { weight: 1, arbitrary: sharedAction(`clear-partially-fails`) }, + { weight: 1, arbitrary: sharedAction(`failed-removal-during-save`) }, + { weight: 1, arbitrary: sharedAction(`remove-before-reconnect`) }, + { weight: 1, arbitrary: sharedAction(`failed-cleanup-across-terms`) }, { weight: 1, arbitrary: sharedAction(`replace-writer`) }, { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, { weight: 1, arbitrary: tabAction(`remove-running`) }, @@ -319,6 +354,14 @@ const spliced = ( action.type !== `exclusion-retry-across-handover` && action.type !== `exclusion-retry-excluded-again` && action.type !== `removal-across-handover` && + action.type !== `remove-rejected-running` && + action.type !== `clear-across-handover` && + action.type !== `replace-writer-other-store` && + action.type !== `unreadable-saved-row` && + action.type !== `clear-partially-fails` && + action.type !== `failed-removal-during-save` && + action.type !== `remove-before-reconnect` && + action.type !== `failed-cleanup-across-terms` && action.type !== `replace-writer` && action.type !== `replace-rejected-writer` && action.type !== `remove-running`, @@ -428,14 +471,19 @@ class ReadFailingStorage extends FakeStorageAdapter { // Outcome keys whose write failed. readonly failedOutcomeKeys = new Set() // The next outcome write waits for release, then lands. - private heldOutcome: { release: () => void } | null | undefined + private heldOutcome: { release: (fail: boolean) => void } | null | undefined holdOutcomeWrite(): void { this.heldOutcome = null } - releaseOutcomeWrite(): void { - this.heldOutcome?.release() + releaseOutcomeWrite(fail = false): void { + this.heldOutcome?.release(fail) this.heldOutcome = undefined } + // Whether a write of any of this transaction's outcome records failed. + outcomeFailed(transactionId: string): boolean { + const prefix = `outcome:${encodeURIComponent(transactionId)}:` + return [...this.failedOutcomeKeys].some((key) => key.startsWith(prefix)) + } // The next write lands at once and acknowledges on release. private heldAck: { release: () => void } | null | undefined holdNextAck(): void { @@ -481,9 +529,13 @@ class ReadFailingStorage extends FakeStorageAdapter { throw new Error(`storage write failed`) } if (this.heldOutcome === null && key.startsWith(`outcome:`)) { - await new Promise((release) => { + const fail = await new Promise((release) => { this.heldOutcome = { release } }) + if (fail) { + this.failedOutcomeKeys.add(key) + throw new Error(`storage write failed`) + } } if (this.heldAck === null && key.startsWith(`tx:`)) { await super.set(key, value) @@ -526,6 +578,26 @@ class ReadFailingStorage extends FakeStorageAdapter { } } +// Another adapter object over the same stored data. +class StorageView implements StorageAdapter { + constructor(private readonly target: StorageAdapter) {} + get(key: string) { + return this.target.get(key) + } + set(key: string, value: string) { + return this.target.set(key, value) + } + delete(key: string) { + return this.target.delete(key) + } + keys() { + return this.target.keys() + } + clear() { + return this.target.clear() + } +} + type ChannelMessage = { type: string; id?: string; error?: unknown } function controlledChannels() { @@ -667,11 +739,13 @@ async function runHistory( failStart: boolean | `load` = false, // A replacement keeps its predecessor's collection. collection?: ReturnType[`collection`], + // A replacement may reach the outbox through another adapter. + tabStorage: StorageAdapter = storage, ) => { const tabElection = new TabElection(election, hold, failStart === true) const session = ++sessions const env = createTestOfflineEnvironment({ - storage, + storage: tabStorage as FakeStorageAdapter, // Each tab names its collection differently under the shared key. collectionId: `items-${session}`, collection, @@ -686,12 +760,15 @@ async function runHistory( sender: session, leader: tabs[leaderIndex()]?.session, }) - if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) if (callGate) { const gate = callGate callGate = null - return gate.then(() => ({ ok: true })) + return gate.then(() => { + if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) + return { ok: true } + }) } + if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) return { ok: true } }, config: { @@ -711,7 +788,10 @@ async function runHistory( tabs[index] = { env, election: tabElection, session } await beforeInit?.() if (failStart) { - await env.executor.waitForInit().catch(() => undefined) + await expect( + env.executor.waitForInit(), + `a failed start rejects`, + ).rejects.toBeInstanceOf(Error) } else await env.executor.waitForInit() await settle() } @@ -1115,9 +1195,7 @@ async function runHistory( await settle() // A leftover record fault: the row stays for a later replay to // decide, and an admission meanwhile sends nothing. - if ( - storage.failedOutcomeKeys.has(`outcome:${write.transactionId}`) - ) { + if (storage.outcomeFailed(write.transactionId!)) { write.exclusionKept = true const holder = tabs[leaderIndex()] if (holder) { @@ -1489,9 +1567,12 @@ async function runHistory( reach(`former-leader-write-unresolved`) break } - case `remove-running`: { + case `remove-running`: + case `remove-rejected-running`: { // A tab removes a follower's write while the leader's server call - // runs, and the success message is lost. + // runs, a check runs during the call, and the settlement message + // is lost. + const rejectedRun = action.type === `remove-rejected-running` const leader = leaderIndex() const follower = tabs.findIndex( (tab, index) => tab && index !== leader, @@ -1508,7 +1589,10 @@ async function runHistory( callGate = new Promise((resolve) => { release = resolve }) - const write = await doWrite(follower, `write`) + const write = await doWrite( + follower, + rejectedRun ? `write-rejected` : `write`, + ) if (!write || !calls.includes(write.id)) { callGate = null release() @@ -1523,6 +1607,12 @@ async function runHistory( expect(write.outcome, `${write.id} waits for its call`).toBe( undefined, ) + // A check during the call finds no row, and still waits. + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} waits during its call`).toBe( + undefined, + ) channels.state.loseSettlement = true release() await settle() @@ -1530,9 +1620,13 @@ async function runHistory( channels.inject({ type: `leader` }) await settle() expect(write.outcome, `${write.id} keeps the server's outcome`).toBe( - `completed`, + rejectedRun ? `failed` : `completed`, + ) + reach( + rejectedRun + ? `removed-while-running-rejected` + : `removed-while-running-completed`, ) - reach(`removed-while-running-completed`) break } case `exclusion-retry-across-handover`: @@ -1569,7 +1663,7 @@ async function runHistory( await settle() storage.failOutcomeWrites = 0 expect( - storage.failedOutcomeKeys.has(`outcome:${write.transactionId}`), + storage.outcomeFailed(write.transactionId!), `${write.id}'s exclusion record failed`, ).toBe(true) storage.holdOutcomeWrite() @@ -1697,10 +1791,26 @@ async function runHistory( expect(write.outcome, `${write.id} waits for a replacement`).toBe( undefined, ) - await openTab(writer, undefined, undefined, false, collection) + // The replacement reaches the same outbox through a new adapter. + await openTab( + writer, + undefined, + undefined, + false, + collection, + new StorageView(storage), + ) expect(write.outcome, `${write.id} settled by the replacement`).toBe( rejectedWrite ? `failed` : `completed`, ) + if (rejectedWrite) { + expect(write.error, `${write.id} error type`).toBeInstanceOf( + NonRetriableError, + ) + expect((write.error as Error).message, `${write.id} error`).toBe( + `rejected ${write.id}`, + ) + } reach( rejectedWrite ? `replacement-settled-rejection` @@ -1708,6 +1818,243 @@ async function runHistory( ) break } + case `replace-writer-other-store`: { + // A disposed follower's write is unsent; its replacement keeps the + // collection but uses another store, then gives way to a tab over + // the shared one. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + const collection = tabs[writer]!.env.collection + await closeTab(writer) + await openTab( + writer, + undefined, + undefined, + false, + collection, + new FakeStorageAdapter(), + ) + expect(write.outcome, `${write.id} waits for its own outbox`).toBe( + undefined, + ) + reach(`replacement-other-store-waited`) + await closeTab(writer) + await openTab(writer) + break + } + case `unreadable-saved-row`: { + // A follower's saved row cannot be decoded while a check runs. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + const key = `tx:${write.transactionId}` + const saved = (await storage.get(key))! + await storage.set(key, `{not json`) + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} waits on its unreadable row`).toBe( + undefined, + ) + await storage.set(key, saved) + reach(`unreadable-row-kept-waiting`) + break + } + case `clear-partially-fails`: { + // The leader clears two unsent writes and one deletion fails. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + online.set(false) + const first = await doWrite(follower, `write`) + const second = await doWrite(follower, `write`) + if (!first || !second) break + storage.failDeletes = 1 + await expect( + tabs[leader]!.env.executor.clearOutbox(), + `the clear reports its failed deletion`, + ).rejects.toThrow(`storage delete failed`) + await settle() + // Which deletion failed is the injected fault's effect. + let kept = 0 + for (const write of [first, second]) { + if (await storage.get(`tx:${write.transactionId}`)) { + kept += 1 + expect(write.outcome, `${write.id} stays pending`).toBe(undefined) + } else { + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails when cleared`).toBe( + `failed`, + ) + } + } + expect(kept, `one row stays`).toBe(1) + reach(`partial-clear-settled`) + break + } + case `failed-removal-during-save`: { + // A follower's row lands, the follower asks to remove it, the + // leader's deletion fails, and the save then acknowledges. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + !online.online || + leader < 0 || + writer < 0 || + !(await quiet()) + ) + break + storage.holdNextAck() + const write = await doWrite(writer, `write`) + if (!write) { + storage.releaseAck() + break + } + storage.failDeletes = 1 + await expect( + tabs[writer]!.env.executor.removeFromOutbox(write.transactionId!), + `the failed removal is reported`, + ).rejects.toThrow(`storage delete failed`) + storage.failDeletes = 0 + storage.releaseAck() + await settle() + expect(calls, `${write.id} still sent`).toContain(write.id) + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`failed-removal-kept-save`) + break + } + case `remove-before-reconnect`: { + // The leader removes a queued follower write and reconnects while + // the removal's record is still being written. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(follower, `write`) + if (!write) break + storage.holdOutcomeWrite() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + online.set(true) + await settle() + expect(calls, `${write.id} not started`).not.toContain(write.id) + storage.releaseOutcomeWrite() + await removal + await settle() + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`removal-held-off-reconnect`) + break + } + case `failed-cleanup-across-terms`: { + // The next leader excludes a follower's write; its record stalls, + // it loses leadership to a tab that accepts the write, and the + // record then fails. It leads again later and accepts the write. + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + excluded.add(write.id) + storage.holdOutcomeWrite() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + excluded.delete(write.id) + next.releaseLeadership() + await settle() + storage.releaseOutcomeWrite(true) + await settle() + await next.requestLeadership() + await rotateTo(next) + await new Promise((resolve) => setTimeout(resolve, 1100)) + await settle() + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id} stays saved`, + ).not.toBe(null) + expect(write.outcome, `${write.id} stays pending`).toBe(undefined) + reach(`stale-cleanup-not-retried`) + break + } + case `clear-across-handover`: { + // The next leader-to-be asks to clear the outbox, the leader never + // hears it, another write lands, and the leader closes. + const leader = leaderIndex() + const next = election.queue[0] + const remover = action.tab + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && index !== remover, + ) + if ( + !durable || + leader < 0 || + !next || + !tabs[remover] || + tabs[remover].election !== next || + writer < 0 || + !(await quiet()) + ) + break + online.set(false) + const cleared = await doWrite(writer, `write`) + if (!cleared) break + channels.state.loseRemoval = true + let done = false + void tabs[remover].env.executor.clearOutbox().then(() => { + done = true + }) + await settle() + const later = await doWrite(writer, `write`) + if (!later) break + await closeTab(leader) + await settle() + expect(done, `the clear finished under the next leader`).toBe(true) + cleared.removed = true + cleared.deliverable = false + expect(cleared.outcome, `${cleared.id} fails when cleared`).toBe( + `failed`, + ) + expect(later.outcome, `${later.id} stays queued`).toBe(undefined) + // The new leader still sends it once online. + online.set(true) + await settle() + expect(calls, `${later.id} sent by the new leader`).toContain( + later.id, + ) + reach(`clear-kept-later-write`) + break + } case `fail-outbox-check`: { const sessionsOpen = openSessions() const pending = writes.filter( @@ -1848,7 +2195,8 @@ async function runHistory( // closed before it settled; a completed write leaves no record. const outcomes = (await storage.keys()) .filter((key) => key.startsWith(`outcome:`)) - .map((key) => key.slice(`outcome:`.length)) + .map((key) => decodeURIComponent(key.split(`:`)[1]!)) + .filter((id, index, ids) => ids.indexOf(id) === index) .sort() expect(outcomes, `outcome records`).toEqual( writes @@ -1916,7 +2264,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removed write whose call is running stays pending until the call settles, an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -1947,6 +2295,11 @@ oracleProperty({ `src/OfflineExecutor.ts#OfflineExecutor.removeForFollower`, `src/OfflineExecutor.ts#OfflineExecutor.forwardRemoval`, `src/OfflineExecutor.ts#OfflineExecutor.relatedExecutors`, + `src/OfflineExecutor.ts#OfflineExecutor.finishRunningRemoval`, + `src/outbox/OutboxManager.ts#OutboxManager.recordPending`, + `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, + `src/outbox/OutboxManager.ts#OutboxManager.outcomeKeys`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.requeue`, ], histories: { arbitrary: historyArbitrary, @@ -2286,6 +2639,54 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `removal-across-handover`, tab: 2 }]), }, + { + name: `a write removed while its call runs takes the server's rejection`, + enters: [`removed-while-running-rejected`, `removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-rejected-running`, tab: 2 }]), + }, + { + name: `a replacement over another store leaves an unsent write pending`, + enters: [`replacement-other-store-waited`], + build: (generated: History): History => + spliced(generated, [{ type: `replace-writer-other-store` }]), + }, + { + name: `a writer waits while its saved row cannot be decoded`, + enters: [`unreadable-row-kept-waiting`], + build: (generated: History): History => + spliced(generated, [{ type: `unreadable-saved-row` }]), + }, + { + name: `a partly failed clear settles the row it deleted`, + enters: [`partial-clear-settled`], + build: (generated: History): History => + spliced(generated, [{ type: `clear-partially-fails` }]), + }, + { + name: `a clear under the next leader keeps a later write queued`, + enters: [`clear-kept-later-write`], + build: (generated: History): History => + spliced(generated, [{ type: `clear-across-handover`, tab: 1 }]), + }, + { + name: `a failed removal during a save leaves the write to send`, + enters: [`failed-removal-kept-save`], + build: (generated: History): History => + spliced(generated, [{ type: `failed-removal-during-save` }]), + }, + { + name: `a reconnect during a removal does not start the write`, + enters: [`removal-held-off-reconnect`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-before-reconnect` }]), + }, + { + name: `a cleanup that failed after its leadership ended is dropped`, + enters: [`stale-cleanup-not-retried`], + build: (generated: History): History => + spliced(generated, [{ type: `failed-cleanup-across-terms` }]), + }, { name: `a replacement settles its predecessor's completed write`, enters: [`replacement-settled-success`], diff --git a/packages/offline-transactions/tests/outcome-retention.test.ts b/packages/offline-transactions/tests/outcome-retention.test.ts index 649f56a67c..84f1ef0487 100644 --- a/packages/offline-transactions/tests/outcome-retention.test.ts +++ b/packages/offline-transactions/tests/outcome-retention.test.ts @@ -38,8 +38,8 @@ afterEach(() => { it(`prunes outcome records older than seven days when a tab leads`, async () => { const storage = new FakeStorageAdapter() const now = Date.now() - await storage.set(`outcome:old`, record(`old`, now - 9 * DAY)) - await storage.set(`outcome:recent`, record(`recent`, now - 6 * DAY)) + await storage.set(`outcome:old:a`, record(`old`, now - 9 * DAY)) + await storage.set(`outcome:recent:a`, record(`recent`, now - 6 * DAY)) const env = createTestOfflineEnvironment({ storage, config: { followerWrites: `durable`, onlineDetector: offline() }, @@ -47,9 +47,9 @@ it(`prunes outcome records older than seven days when a tab leads`, async () => try { await env.waitForLeader() await vi.waitFor(async () => { - expect(await storage.get(`outcome:old`)).toBe(null) + expect(await storage.get(`outcome:old:a`)).toBe(null) }) - expect(await storage.get(`outcome:recent`)).toBe( + expect(await storage.get(`outcome:recent:a`)).toBe( record(`recent`, now - 6 * DAY), ) } finally { From a6927b0e6c1183859ebb5177839e0dfd72b70dfa Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 21:29:17 -0800 Subject: [PATCH 09/16] fix(offline-transactions): address seventh durable follower write review - A removal or exclusion is written to its row as a rejection before the row is deleted, so a later leader's replay settles it as decided rather than send it. A replay settles such rows without waiting for the network or blocking startup. - A leader's removal or exclusion checks that it still leads right after writing its decision, not only that its term is unchanged; otherwise it leaves the write to the next leader. - A removal that fails before its decision is written reads the row again before queueing it, instead of reusing its snapshot. - Reconciliation skips a write whose call this runtime still runs, and a predecessor whose mode records no outcomes. The durable follower oracle hands leadership over while an exclusion's decision or deletion, or a removal's decision, is pending, removes a leader's own running write across a handover, and replaces a default-mode executor with a durable one. --- .../src/OfflineExecutor.ts | 60 ++- .../src/executor/TransactionExecutor.ts | 77 ++-- .../src/outbox/OutboxManager.ts | 30 ++ .../durable-follower-oracle.property.test.ts | 376 +++++++++++++++++- 4 files changed, 492 insertions(+), 51 deletions(-) diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index c5afb70b91..717525d6ab 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -615,6 +615,14 @@ export class OfflineExecutor { for (const [owner, id, waiter] of waiters) { try { if (!(await waiter.saved)) continue + // Absence means success only where rejections are recorded, and not + // while this runtime still runs the write's call. + if ( + !owner.recordsOutcomes || + owner.scheduler.isRunning(id) || + this.scheduler.isRunning(id) + ) + continue const outbox = owner.outbox! // A row that cannot be decoded is still there. if (await outbox.has(id)) continue @@ -1018,34 +1026,56 @@ export class OfflineExecutor { const error = removedError() // Off the queue before any await, so this tab cannot start them // meanwhile; the one already running keeps the provider's outcome. - const queued = this.scheduler - .getAllPendingTransactions() - .filter(({ id }) => ids.includes(id)) const unstarted = new Set(this.scheduler.removePendingTransactions(ids)) + // A leader's removal yields if it stops leading before its decision is + // written; the term only counts gains. + const term = this.term + const leading = this.isOfflineEnabled + const stillLeads = () => + // Leadership can end during the awaits this check follows. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + !leading || (this.isOfflineEnabled && term === this.term) const failures: Array = [] // Each id settles by its own deletion. await Promise.all( ids.map(async (id) => { let token: string | undefined + let decided = false try { if (!(await outbox.has(id))) { if (this.saving.has(id)) this.saving.set(id, true) return } - // A writer in another tab reads a rejection, or that the call it - // cannot see is still running. - if (this.recordsOutcomes && !this.ownsWrite(id)) - token = unstarted.has(id) - ? await outbox.recordRejection(id, error) - : await outbox.recordPending(id) + if (unstarted.has(id)) { + if (this.recordsOutcomes && !this.ownsWrite(id)) + token = await outbox.recordRejection(id, error) + // The removal is persisted on the row first, so a later leader's + // replay rejects it rather than send it. A row this term has not + // marked belongs to the next leader. + const mark = await outbox.markRejected(id, error) + if (mark === `gone` || !stillLeads()) { + if (token !== undefined) + await outbox.withdrawOutcome(id, token).catch(() => {}) + return + } + decided = mark === `marked` + } else if (this.recordsOutcomes && !this.ownsWrite(id)) { + // A writer in another tab reads that the call it cannot see is + // still running. + token = await outbox.recordPending(id) + } await outbox.remove(id) } catch (removalError) { - failures.push(removalError) - // Its row stays, so it is queued again and its record withdrawn. - if (token !== undefined) - await outbox.withdrawOutcome(id, token).catch(() => {}) - this.executor!.requeue(queued.filter((tx) => tx.id === id)) - return + // A persisted decision stands: the queue finishes its deletion. + if (!decided) { + failures.push(removalError) + if (token !== undefined) + await outbox.withdrawOutcome(id, token).catch(() => {}) + } + // The row is read again, so a write another leader settled meanwhile + // is not queued again. + this.executor!.admitTransaction(id).catch(() => {}) + if (!decided) return } if (this.saving.has(id)) this.saving.set(id, true) if (unstarted.has(id)) this.rejectTransaction(id, error) diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 551fac038e..ca09120262 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -414,6 +414,8 @@ export class TransactionExecutor { async loadPendingTransactions(): Promise { let removedIds: Array = [] + // Rows a former leader decided to reject: settled here, never sent. + let decided: Array = [] const term = this.offlineExecutor.leadershipTerm await this.outbox.withAll((transactions) => { const { isOfflineEnabled } = this.offlineExecutor @@ -428,7 +430,13 @@ export class TransactionExecutor { ? this.config.beforeRetry(providerPending) : providerPending const selectedById = new Map(selectedProvider.map((tx) => [tx.id, tx])) + decided = transactions.filter( + (transaction) => + transaction.outboxPhase === `rejection-pending` && + !this.scheduler.isRunning(transaction.id), + ) const filteredTransactions = transactions.flatMap((transaction) => { + if (decided.includes(transaction)) return [] if (transaction.outboxPhase) return [transaction] const selected = selectedById.get(transaction.id) return selected ? [selected] : [] @@ -450,6 +458,7 @@ export class TransactionExecutor { for (const id of this.excluding) if (selectedById.has(id)) this.excluding.delete(id) for (const id of removedIds) this.excluding.add(id) + for (const { id } of decided) this.excluding.add(id) // Restore optimistic state for loaded transactions // This ensures the UI shows the optimistic data while transactions are pending @@ -466,24 +475,30 @@ export class TransactionExecutor { this.scheduleNextRetry() }) - if (removedIds.length > 0) { - const error = new NonRetriableError(`Transaction excluded by beforeRetry`) - await Promise.all( - removedIds.map(async (id) => { - if (await this.cleanUpExcluded(id, error, term)) return - // Retried only while this decision stands: a later term's replay - // may have accepted the write. Until then no admission runs it. - if ( - !this.offlineExecutor.isOfflineEnabled || - term !== this.offlineExecutor.leadershipTerm || - !this.excluding.has(id) - ) - return - this.failedCleanups.set(id, error) - this.scheduleCleanupRetry() - }), + const cleanUp = async (id: string, error: Error, marked: boolean) => { + if (await this.cleanUpExcluded(id, error, term, marked)) return + // Retried only while this decision stands: a later term's replay may + // have accepted the write. Until then no admission runs it. + if ( + !this.offlineExecutor.isOfflineEnabled || + term !== this.offlineExecutor.leadershipTerm || + !this.excluding.has(id) ) + return + this.failedCleanups.set(id, error) + this.scheduleCleanupRetry() } + // A former leader's decision settles without the network, and startup + // does not wait for it. + void Promise.all( + decided.map((transaction) => + cleanUp(transaction.id, this.getTerminalError(transaction), true), + ), + ) + const exclusion = new NonRetriableError( + `Transaction excluded by beforeRetry`, + ) + await Promise.all(removedIds.map((id) => cleanUp(id, exclusion, false))) } /** Records and removes one excluded write; false when that failed. */ @@ -491,22 +506,35 @@ export class TransactionExecutor { id: string, error: Error, term: number | undefined, + marked = false, ): Promise { + const leads = () => + this.offlineExecutor.isOfflineEnabled && + term === this.offlineExecutor.leadershipTerm + let recorded: string | undefined try { - const recorded = this.recordsFor(id) + recorded = this.recordsFor(id) ? await this.outbox.recordRejection(id, error) : undefined // A later leader decides the write once this term ends: this tab // neither removes it nor settles it, and withdraws its own record, // which leaves any record that leader made. - if ( - !this.offlineExecutor.isOfflineEnabled || - term !== this.offlineExecutor.leadershipTerm - ) { + if (!leads()) { if (recorded !== undefined) await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) return true } + // The decision is persisted before the row goes, so a later leader's + // replay rejects the row rather than send it. Once it is persisted in + // this term, the deletion and settlement follow even across a handover. + if (!marked) { + const mark = await this.outbox.markRejected(id, error) + if (mark === `gone` || !leads()) { + if (recorded !== undefined) + await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) + return true + } + } await this.outbox.remove(id) this.excluding.delete(id) this.offlineExecutor.rejectTransaction(id, error) @@ -559,13 +587,6 @@ export class TransactionExecutor { else this.scheduleCleanupRetry() } - /** Queues writes again whose removal failed. */ - requeue(transactions: Array): void { - if (!this.offlineExecutor.isOfflineEnabled) return - for (const transaction of transactions) this.scheduler.schedule(transaction) - this.scheduleNextRetry() - } - private dropFailedCleanups(): void { this.failedCleanups.clear() this.cleanupAttempts = 0 diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index a3ea37a392..3d22e0af38 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -199,6 +199,36 @@ export class OutboxManager { return (await this.storage.keys()).filter((key) => key.startsWith(prefix)) } + /** + * Persists a decision to reject a saved row, so any later leader's replay + * settles it as rejected instead of sending it. A row that already carries + * a phase keeps it; one that cannot be read is left as it is. + */ + async markRejected( + id: string, + error: Error, + ): Promise<`marked` | `gone` | `unreadable`> { + const data = await this.storage.get(this.getStorageKey(id)) + if (data === null) return `gone` + let transaction: OfflineTransaction + try { + transaction = this.serializer.deserialize(data) + } catch { + return `unreadable` + } + if (transaction.outboxPhase) return `marked` + await this.add({ + ...transaction, + outboxPhase: `rejection-pending`, + lastError: { + name: error.name, + message: error.message, + stack: error.stack, + }, + }) + return `marked` + } + /** Whether a row is saved, without decoding it. */ async has(id: string): Promise { return (await this.storage.get(this.getStorageKey(id))) !== null diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 8821231815..2d4ddb713e 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -195,6 +195,22 @@ const reachStates = [ `removal-held-off-reconnect`, // A cleanup that failed after its leadership ended was not retried later. `stale-cleanup-not-retried`, + // An exclusion whose deletion was still pending at a handover stayed an + // exclusion under the next leader. + `exclusion-decision-survived-handover`, + // An exclusion whose decision had not landed at a handover gave way to the + // next leader's send. + `exclusion-yielded-to-successor`, + // A removal decided before a handover was settled by the next leader, and + // one not yet decided gave way to the next leader's send. + `removal-decision-survived-handover`, + `removal-yielded-to-successor`, + // A leader's own write removed while its call ran stayed pending across a + // handover, then took the server's outcome. + `own-running-removal-completed`, + `own-running-removal-rejected`, + // A durable replacement left a default-mode predecessor's write pending. + `default-predecessor-unresolved`, // In the default mode, a write another leader rejected stayed pending in // its former leader, which cannot tell a rejection from a success. `former-leader-write-unresolved`, @@ -247,6 +263,13 @@ type SharedActionType = | `failed-removal-during-save` | `remove-before-reconnect` | `failed-cleanup-across-terms` + | `exclusion-across-handover-mid-delete` + | `exclusion-across-handover-mid-mark` + | `removal-mark-landed-handover` + | `removal-mark-held-handover` + | `remove-own-running` + | `remove-own-rejected-running` + | `replace-default-with-durable` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -301,6 +324,19 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`failed-removal-during-save`) }, { weight: 1, arbitrary: sharedAction(`remove-before-reconnect`) }, { weight: 1, arbitrary: sharedAction(`failed-cleanup-across-terms`) }, + { + weight: 1, + arbitrary: sharedAction(`exclusion-across-handover-mid-delete`), + }, + { + weight: 1, + arbitrary: sharedAction(`exclusion-across-handover-mid-mark`), + }, + { weight: 1, arbitrary: sharedAction(`removal-mark-landed-handover`) }, + { weight: 1, arbitrary: sharedAction(`removal-mark-held-handover`) }, + { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, + { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, + { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, { weight: 1, arbitrary: sharedAction(`replace-writer`) }, { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, { weight: 1, arbitrary: tabAction(`remove-running`) }, @@ -362,6 +398,13 @@ const spliced = ( action.type !== `failed-removal-during-save` && action.type !== `remove-before-reconnect` && action.type !== `failed-cleanup-across-terms` && + action.type !== `exclusion-across-handover-mid-delete` && + action.type !== `exclusion-across-handover-mid-mark` && + action.type !== `removal-mark-landed-handover` && + action.type !== `removal-mark-held-handover` && + action.type !== `remove-own-running` && + action.type !== `remove-own-rejected-running` && + action.type !== `replace-default-with-durable` && action.type !== `replace-writer` && action.type !== `replace-rejected-writer` && action.type !== `remove-running`, @@ -515,11 +558,35 @@ class ReadFailingStorage extends FakeStorageAdapter { return super.keys() } failDeletes = 0 + // The next row deletion waits for release. + private heldDelete: { release: () => void } | null | undefined + holdNextDelete(): void { + this.heldDelete = null + } + releaseDelete(): void { + this.heldDelete?.release() + this.heldDelete = undefined + } + // The next row write fails, or waits for release before it lands. + failTxWrites = 0 + private heldTx: { release: () => void } | null | undefined + holdNextTxWrite(): void { + this.heldTx = null + } + releaseTxWrite(): void { + this.heldTx?.release() + this.heldTx = undefined + } override async delete(key: string): Promise { if (this.failDeletes > 0 && key.startsWith(`tx:`)) { this.failDeletes -= 1 throw new Error(`storage delete failed`) } + if (this.heldDelete === null && key.startsWith(`tx:`)) { + await new Promise((release) => { + this.heldDelete = { release } + }) + } return super.delete(key) } override async set(key: string, value: string): Promise { @@ -537,6 +604,15 @@ class ReadFailingStorage extends FakeStorageAdapter { throw new Error(`storage write failed`) } } + if (this.failTxWrites > 0 && key.startsWith(`tx:`)) { + this.failTxWrites -= 1 + throw new Error(`storage write failed`) + } + if (this.heldTx === null && key.startsWith(`tx:`)) { + await new Promise((release) => { + this.heldTx = { release } + }) + } if (this.heldAck === null && key.startsWith(`tx:`)) { await super.set(key, value) await new Promise((release) => { @@ -741,6 +817,8 @@ async function runHistory( collection?: ReturnType[`collection`], // A replacement may reach the outbox through another adapter. tabStorage: StorageAdapter = storage, + // A durable tab in a default-mode history. + durableTab = durable, ) => { const tabElection = new TabElection(election, hold, failStart === true) const session = ++sessions @@ -772,7 +850,7 @@ async function runHistory( return { ok: true } }, config: { - ...(durable ? { followerWrites: `durable` } : {}), + ...(durableTab ? { followerWrites: `durable` } : {}), leaderElection: tabElection, onlineDetector: online.detector(), beforeRetry: ( @@ -1877,11 +1955,13 @@ async function runHistory( const first = await doWrite(follower, `write`) const second = await doWrite(follower, `write`) if (!first || !second) break - storage.failDeletes = 1 + // The first removal decision fails to persist. + storage.failTxWrites = 1 await expect( tabs[leader]!.env.executor.clearOutbox(), - `the clear reports its failed deletion`, - ).rejects.toThrow(`storage delete failed`) + `the clear reports its failed removal`, + ).rejects.toThrow(`storage write failed`) + storage.failTxWrites = 0 await settle() // Which deletion failed is the injected fault's effect. let kept = 0 @@ -1920,12 +2000,12 @@ async function runHistory( storage.releaseAck() break } - storage.failDeletes = 1 + storage.failTxWrites = 1 await expect( tabs[writer]!.env.executor.removeFromOutbox(write.transactionId!), `the failed removal is reported`, - ).rejects.toThrow(`storage delete failed`) - storage.failDeletes = 0 + ).rejects.toThrow(`storage write failed`) + storage.failTxWrites = 0 storage.releaseAck() await settle() expect(calls, `${write.id} still sent`).toContain(write.id) @@ -2007,6 +2087,238 @@ async function runHistory( reach(`stale-cleanup-not-retried`) break } + case `exclusion-across-handover-mid-delete`: + case `exclusion-across-handover-mid-mark`: { + // The next leader excludes a follower's write and its deletion, or + // the write of its decision, stalls; leadership moves to a tab + // that would accept the write. + const midMark = action.type === `exclusion-across-handover-mid-mark` + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + excluded.add(write.id) + if (midMark) storage.holdNextTxWrite() + else storage.holdNextDelete() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + excluded.delete(write.id) + if (midMark) { + // The next leader sends the unmarked row; the stalled decision + // then lands and changes nothing. + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + online.set(true) + await settle() + next.releaseLeadership() + await settle() + expect(calls, `${write.id} sent by the next leader`).toContain( + write.id, + ) + storage.releaseTxWrite() + await settle() + expect(write.outcome, `${write.id} waits for that send`).toBe( + undefined, + ) + release() + await settle() + await next.requestLeadership() + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`exclusion-yielded-to-successor`) + break + } + write.excluded = true + write.deliverable = false + online.set(true) + await settle() + next.releaseLeadership() + await settle() + storage.releaseDelete() + await settle() + await next.requestLeadership() + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} stays excluded`).toBe(`failed`) + reach(`exclusion-decision-survived-handover`) + break + } + case `removal-mark-landed-handover`: + case `removal-mark-held-handover`: { + // The leader removes a queued follower write and loses leadership + // while its removal decision is written: after it landed, or + // before. + const landed = action.type === `removal-mark-landed-handover` + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + if (landed) storage.holdNextAck() + else storage.holdNextTxWrite() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + let release = () => {} + if (!landed) + callGate = new Promise((resolve) => { + release = resolve + }) + online.set(true) + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + if (landed) { + storage.releaseAck() + await removal + await settle() + await original.requestLeadership() + await settle() + write.removed = true + write.deliverable = false + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`removal-decision-survived-handover`) + break + } + expect(calls, `${write.id} sent by the next leader`).toContain( + write.id, + ) + storage.releaseTxWrite() + await removal + await settle() + expect(write.outcome, `${write.id} waits for that send`).toBe( + undefined, + ) + release() + await settle() + await original.requestLeadership() + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`removal-yielded-to-successor`) + break + } + case `remove-own-running`: + case `remove-own-rejected-running`: { + // The leader removes its own write while its call runs, then loses + // leadership; the next leader's check runs during the call. + const rejectedRun = action.type === `remove-own-rejected-running` + const leader = leaderIndex() + if ( + !durable || + !online.online || + leader < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite( + leader, + rejectedRun ? `write-rejected` : `write`, + ) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + await settle() + expect(write.outcome, `${write.id} waits during its call`).toBe( + undefined, + ) + release() + await settle() + expect(write.outcome, `${write.id} keeps the server's outcome`).toBe( + rejectedRun ? `failed` : `completed`, + ) + reach( + rejectedRun + ? `own-running-removal-rejected` + : `own-running-removal-completed`, + ) + break + } + case `replace-default-with-durable`: { + // In the default mode the leader saves its own write offline, + // another leader rejects it, and a durable executor replaces the + // writer over the same collection. + const leader = leaderIndex() + if ( + durable || + leader < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(leader, `write-rejected`) + if (!write) break + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} sent by another leader`).toContain( + write.id, + ) + const collection = tabs[leader]!.env.collection + await closeTab(leader) + await openTab( + leader, + undefined, + undefined, + false, + collection, + storage, + true, + ) + // No record tells a rejection from a success. + expect(write.outcome, `${write.id} stays pending`).toBe(undefined) + reach(`default-predecessor-unresolved`) + await closeTab(leader) + await openTab(leader) + break + } case `clear-across-handover`: { // The next leader-to-be asks to clear the outbox, the leader never // hears it, another write lands, and the leader closes. @@ -2264,7 +2576,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removed write whose call is running stays pending until the call settles, an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is written to its row before the row goes, so a later leader settles it as decided rather than send it. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -2687,6 +2999,54 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `failed-cleanup-across-terms` }]), }, + { + name: `an exclusion pending deletion at a handover stays an exclusion`, + enters: [`exclusion-decision-survived-handover`], + build: (generated: History): History => + spliced(generated, [ + { type: `exclusion-across-handover-mid-delete` }, + ]), + }, + { + name: `an exclusion not yet decided at a handover gives way to the send`, + enters: [`exclusion-yielded-to-successor`], + build: (generated: History): History => + spliced(generated, [{ type: `exclusion-across-handover-mid-mark` }]), + }, + { + name: `a removal decided before a handover is settled by the next leader`, + enters: [`removal-decision-survived-handover`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-mark-landed-handover` }]), + }, + { + name: `a removal not yet decided at a handover gives way to the send`, + enters: [`removal-yielded-to-successor`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-mark-held-handover` }]), + }, + { + name: `a leader's own running write removed keeps the server's outcome`, + enters: [`own-running-removal-completed`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-own-running` }]), + }, + { + name: `a leader's own running write removed takes the server's rejection`, + enters: [`own-running-removal-rejected`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-own-rejected-running` }]), + }, + { + name: `a durable replacement leaves a default-mode write pending`, + enters: [`default-predecessor-unresolved`], + build: (generated: History): History => + spliced( + generated, + [{ type: `replace-default-with-durable` }], + `online`, + ), + }, { name: `a replacement settles its predecessor's completed write`, enters: [`replacement-settled-success`], From 8d3508845af1c699e3e573c4c94fd276774218d0 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 22:38:03 -0800 Subject: [PATCH 10/16] fix(offline-transactions): address eighth durable follower write review - A removal or exclusion records its decision under its own key beside the row, instead of rewriting the row, so a decision that lands late never recreates a settled row. A replay settles a row with a decision rather than send it, and drops decisions whose row is gone. - The rejection record follows the committed decision, so a writer never reads a provisional exclusion or removal. - A removed row whose call already settled keeps that outcome. - A removal that yields at a handover is made by the next leader: a follower's request is answered with a retry, and a local caller asks the leader. - A cleanup retry clears its entry only in the term that attempted it, and a leader that retries a write removes any stale decision for it. - Decisions exist only where outcomes are recorded; the default mode keeps its direct deletion. The guide requires one followerWrites mode for every tab that shares an outbox. The durable follower oracle holds decision writes rather than records, lets a writer reconcile while a stalled decision is pending, releases a decision after the next leader settled the write, removes a row whose call succeeded, and yields removals at a handover from the leader and from a follower. --- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 109 +++++-- .../src/executor/TransactionExecutor.ts | 193 +++++++----- .../src/outbox/OutboxManager.ts | 56 ++-- .../durable-follower-oracle.property.test.ts | 283 +++++++++++++++--- 5 files changed, 458 insertions(+), 185 deletions(-) diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 9b861d8808..1cb127a251 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. Every tab that can lead must also set `followerWrites: 'durable'`: a leader in the default mode opens no channel and never hears a follower's saved write. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 717525d6ab..5c60f36ce5 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -51,6 +51,8 @@ type OutboxMessage = type: `removed` request: string error?: { name: string; message: string } + // The leader stopped leading before it decided; ask again. + retry?: true } function outboxMessageError(error: { name: string; message: string }): Error { @@ -455,7 +457,7 @@ export class OfflineExecutor { // Removals this tab asked a former leader for are now its own to make. for (const [request, removal] of [...this.removals]) { this.removals.delete(request) - this.removeSaved(removal.ids).then(removal.resolve, removal.reject) + this.removeOrForward(removal.ids).then(removal.resolve, removal.reject) } // Replay completion is separate from initialization and durable admission. @@ -492,6 +494,10 @@ export class OfflineExecutor { } else if (message.type === `removed`) { const removal = this.removals.get(message.request) if (!removal) return + if (message.retry) { + this.postRemoval(message.request, removal.ids) + return + } this.removals.delete(message.request) if (message.error) removal.reject(outboxMessageError(message.error)) else removal.resolve() @@ -509,10 +515,11 @@ export class OfflineExecutor { private removeForFollower(request: string, ids: Array): void { if (!this.isOfflineEnabled) return this.removeSaved(ids).then( - () => { + (yielded) => { this.outboxChannel?.postMessage({ type: `removed`, request, + ...(yielded.length > 0 ? { retry: true as const } : {}), } satisfies OutboxMessage) }, (error: unknown) => { @@ -1013,7 +1020,15 @@ export class OfflineExecutor { return } if (this.forwardsRemovals) await this.forwardRemoval([id]) - else await this.removeSaved([id]) + else await this.removeOrForward([id]) + } + + /** Removes here, or asks the leader for removals this tab yielded. */ + private async removeOrForward(ids: Array): Promise { + const yielded = await this.removeSaved(ids) + if (yielded.length === 0) return + if (this.forwardsRemovals) return this.forwardRemoval(yielded) + throw new Error(`Leadership moved before the removal was decided`) } /** @@ -1021,68 +1036,96 @@ export class OfflineExecutor { * removal error, which a writer in another tab also reads from its record; * a started call keeps the provider's outcome. */ - private async removeSaved(ids: Array): Promise { + /** + * Removes saved transactions; returns those it left to the next leader + * because it stopped leading before deciding them. + */ + private async removeSaved(ids: Array): Promise> { const outbox = this.outbox! const error = removedError() // Off the queue before any await, so this tab cannot start them // meanwhile; the one already running keeps the provider's outcome. const unstarted = new Set(this.scheduler.removePendingTransactions(ids)) // A leader's removal yields if it stops leading before its decision is - // written; the term only counts gains. + // recorded; the term only counts gains. const term = this.term const leading = this.isOfflineEnabled const stillLeads = () => // Leadership can end during the awaits this check follows. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition !leading || (this.isOfflineEnabled && term === this.term) + // A writer in another tab reads a record; this tab's own needs none. + const records = (id: string) => this.recordsOutcomes && !this.ownsWrite(id) const failures: Array = [] + const yielded: Array = [] // Each id settles by its own deletion. await Promise.all( ids.map(async (id) => { - let token: string | undefined - let decided = false + let committed = false try { if (!(await outbox.has(id))) { if (this.saving.has(id)) this.saving.set(id, true) return } - if (unstarted.has(id)) { - if (this.recordsOutcomes && !this.ownsWrite(id)) - token = await outbox.recordRejection(id, error) - // The removal is persisted on the row first, so a later leader's - // replay rejects it rather than send it. A row this term has not - // marked belongs to the next leader. - const mark = await outbox.markRejected(id, error) - if (mark === `gone` || !stillLeads()) { - if (token !== undefined) - await outbox.withdrawOutcome(id, token).catch(() => {}) - return - } - decided = mark === `marked` - } else if (this.recordsOutcomes && !this.ownsWrite(id)) { + if (!unstarted.has(id)) { // A writer in another tab reads that the call it cannot see is // still running. - token = await outbox.recordPending(id) + const token = records(id) + ? await outbox.recordPending(id) + : undefined + await outbox.remove(id) + if (this.saving.has(id)) this.saving.set(id, true) + if (token !== undefined) this.runningRemovals.set(id, token) + return + } + // A row whose call already settled keeps that outcome. + const row = await outbox.get(id).catch(() => null) + if (row?.outboxPhase) { + const outcome = + row.outboxPhase === `rejection-pending` && row.lastError + ? outboxMessageError(row.lastError) + : undefined + if (outcome && records(id)) + await outbox.recordRejection(id, outcome) + await outbox.remove(id) + if (outcome) this.rejectTransaction(id, outcome) + else this.resolveTransaction(id, undefined) + return } + // The decision is recorded beside the row first, so a later + // leader's replay settles the row rather than send it. One that + // does not commit while this tab leads is withdrawn. Without + // recorded outcomes there are no decisions, and a write the next + // leader now decides is left to it. + if (this.recordsOutcomes) await outbox.recordDecision(id, error) + if (!stillLeads()) { + if (this.recordsOutcomes) + await outbox.removeDecision(id).catch(() => {}) + yielded.push(id) + return + } + committed = true + if (records(id)) await outbox.recordRejection(id, error) await outbox.remove(id) + if (this.recordsOutcomes) + await outbox.removeDecision(id).catch(() => {}) } catch (removalError) { - // A persisted decision stands: the queue finishes its deletion. - if (!decided) { + if (!committed) { failures.push(removalError) - if (token !== undefined) - await outbox.withdrawOutcome(id, token).catch(() => {}) + // The row is read again, so a write another leader settled + // meanwhile is not queued again. + this.executor!.admitTransaction(id).catch(() => {}) + return } - // The row is read again, so a write another leader settled meanwhile - // is not queued again. - this.executor!.admitTransaction(id).catch(() => {}) - if (!decided) return + // A committed removal stands; its deletion is retried. + this.executor!.retryDecided(id, error) } if (this.saving.has(id)) this.saving.set(id, true) - if (unstarted.has(id)) this.rejectTransaction(id, error) - else if (token !== undefined) this.runningRemovals.set(id, token) + this.rejectTransaction(id, error) }), ) if (failures.length > 0) throw failures[0] + return yielded } /** Withdraws the running marker of a removed write whose call finished. */ @@ -1108,7 +1151,7 @@ export class OfflineExecutor { // snapshot stays queued. const ids = await this.outbox.ids() if (this.forwardsRemovals) await this.forwardRemoval(ids) - else await this.removeSaved(ids) + else await this.removeOrForward(ids) } getPendingCount(): number { diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index ca09120262..995896430a 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -300,6 +300,10 @@ export class TransactionExecutor { try { await this.outbox.update(transaction.id, updatedTransaction) + // This leader accepted and sent the write; a former leader's decision + // that landed meanwhile must not settle it at a later replay. + if (this.offlineExecutor.recordsOutcomes) + await this.outbox.removeDecision(transaction.id).catch(() => {}) } catch (persistError) { // Public removal can finish while the named mutation function runs. // The removed row cannot be retried, but its caller still owns the @@ -416,67 +420,81 @@ export class TransactionExecutor { let removedIds: Array = [] // Rows a former leader decided to reject: settled here, never sent. let decided: Array = [] + // Decisions whose row is gone. + let orphaned: Array = [] const term = this.offlineExecutor.leadershipTerm - await this.outbox.withAll((transactions) => { - const { isOfflineEnabled } = this.offlineExecutor - // A read that spans a change of leadership is stale: another leader - // may have sent its rows, and this term's own load reads them again. - if (!isOfflineEnabled || term !== this.offlineExecutor.leadershipTerm) - return - const providerPending = transactions.filter( - (transaction) => !transaction.outboxPhase, - ) - const selectedProvider = this.config.beforeRetry - ? this.config.beforeRetry(providerPending) - : providerPending - const selectedById = new Map(selectedProvider.map((tx) => [tx.id, tx])) - decided = transactions.filter( - (transaction) => - transaction.outboxPhase === `rejection-pending` && - !this.scheduler.isRunning(transaction.id), - ) - const filteredTransactions = transactions.flatMap((transaction) => { - if (decided.includes(transaction)) return [] - if (transaction.outboxPhase) return [transaction] - const selected = selectedById.get(transaction.id) - return selected ? [selected] : [] - }) + // Decisions exist only where outcomes are recorded. + const decisions = new Map() + await this.outbox.withAll( + (transactions) => { + const { isOfflineEnabled } = this.offlineExecutor + // A read that spans a change of leadership is stale: another leader + // may have sent its rows, and this term's own load reads them again. + if (!isOfflineEnabled || term !== this.offlineExecutor.leadershipTerm) + return + decided = transactions.filter( + (transaction) => + !transaction.outboxPhase && + decisions.has(transaction.id) && + !this.scheduler.isRunning(transaction.id), + ) + orphaned = [...decisions.keys()].filter( + (id) => !transactions.some((transaction) => transaction.id === id), + ) + const providerPending = transactions.filter( + (transaction) => + !transaction.outboxPhase && !decided.includes(transaction), + ) + const selectedProvider = this.config.beforeRetry + ? this.config.beforeRetry(providerPending) + : providerPending + const selectedById = new Map(selectedProvider.map((tx) => [tx.id, tx])) + const filteredTransactions = transactions.flatMap((transaction) => { + if (decided.includes(transaction)) return [] + if (transaction.outboxPhase) return [transaction] + const selected = selectedById.get(transaction.id) + return selected ? [selected] : [] + }) - // The retry hook is user code and may synchronously revoke replay rights. - if (!this.offlineExecutor.isOfflineEnabled) return + // The retry hook is user code and may synchronously revoke replay rights. + if (!this.offlineExecutor.isOfflineEnabled) return - const newlyLoaded = filteredTransactions.filter((transaction) => - this.scheduler.schedule(transaction), - ) + const newlyLoaded = filteredTransactions.filter((transaction) => + this.scheduler.schedule(transaction), + ) - removedIds = providerPending - .filter(({ id }) => !selectedById.has(id)) - .map(({ id }) => id) - removedIds = this.scheduler.removePendingTransactions(removedIds) - // A late admission must not run a write this hook excluded; one a - // later replay accepts is admissible again. - for (const id of this.excluding) - if (selectedById.has(id)) this.excluding.delete(id) - for (const id of removedIds) this.excluding.add(id) - for (const { id } of decided) this.excluding.add(id) - - // Restore optimistic state for loaded transactions - // This ensures the UI shows the optimistic data while transactions are pending - this.restoreOptimisticState( - newlyLoaded.filter( - (transaction) => transaction.outboxPhase !== `rejection-pending`, - ), - ) + removedIds = providerPending + .filter(({ id }) => !selectedById.has(id)) + .map(({ id }) => id) + removedIds = this.scheduler.removePendingTransactions(removedIds) + // A late admission must not run a write this hook excluded; one a + // later replay accepts is admissible again. + for (const id of this.excluding) + if (selectedById.has(id)) this.excluding.delete(id) + for (const id of removedIds) this.excluding.add(id) + for (const { id } of decided) this.excluding.add(id) + + // Restore optimistic state for loaded transactions + // This ensures the UI shows the optimistic data while transactions are pending + this.restoreOptimisticState( + newlyLoaded.filter( + (transaction) => transaction.outboxPhase !== `rejection-pending`, + ), + ) - // Reset retry delays for all loaded transactions so they can run immediately - this.resetRetryDelays() + // Reset retry delays for all loaded transactions so they can run immediately + this.resetRetryDelays() - // Schedule retry timer for loaded transactions - this.scheduleNextRetry() - }) + // Schedule retry timer for loaded transactions + this.scheduleNextRetry() + }, + this.offlineExecutor.recordsOutcomes ? decisions : undefined, + ) - const cleanUp = async (id: string, error: Error, marked: boolean) => { - if (await this.cleanUpExcluded(id, error, term, marked)) return + for (const id of orphaned) + void this.outbox.removeDecision(id).catch(() => {}) + const cleanUp = async (id: string, error: Error, committed: boolean) => { + if (await this.cleanUpExcluded(id, error, term, committed)) return // Retried only while this decision stands: a later term's replay may // have accepted the write. Until then no admission runs it. if ( @@ -491,9 +509,15 @@ export class TransactionExecutor { // A former leader's decision settles without the network, and startup // does not wait for it. void Promise.all( - decided.map((transaction) => - cleanUp(transaction.id, this.getTerminalError(transaction), true), - ), + decided.map((transaction) => { + const { name, message } = decisions.get(transaction.id)! + const error = + name === `NonRetriableError` + ? new NonRetriableError(message) + : new Error(message) + error.name = name + return cleanUp(transaction.id, error, true) + }), ) const exclusion = new NonRetriableError( `Transaction excluded by beforeRetry`, @@ -506,36 +530,30 @@ export class TransactionExecutor { id: string, error: Error, term: number | undefined, - marked = false, + committed = false, ): Promise { - const leads = () => - this.offlineExecutor.isOfflineEnabled && - term === this.offlineExecutor.leadershipTerm - let recorded: string | undefined try { - recorded = this.recordsFor(id) - ? await this.outbox.recordRejection(id, error) - : undefined - // A later leader decides the write once this term ends: this tab - // neither removes it nor settles it, and withdraws its own record, - // which leaves any record that leader made. - if (!leads()) { - if (recorded !== undefined) - await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) - return true - } - // The decision is persisted before the row goes, so a later leader's - // replay rejects the row rather than send it. Once it is persisted in - // this term, the deletion and settlement follow even across a handover. - if (!marked) { - const mark = await this.outbox.markRejected(id, error) - if (mark === `gone` || !leads()) { - if (recorded !== undefined) - await this.outbox.withdrawOutcome(id, recorded).catch(() => {}) + // The decision is recorded before anything else, so a later leader's + // replay settles the row rather than send it. One that does not commit + // within this term is withdrawn: the next leader decides the write. + const leads = () => + this.offlineExecutor.isOfflineEnabled && + term === this.offlineExecutor.leadershipTerm + const decides = this.offlineExecutor.recordsOutcomes === true + if (!committed && decides) { + await this.outbox.recordDecision(id, error) + if (!leads()) { + await this.outbox.removeDecision(id).catch(() => {}) return true } } + // Without decisions, a write the next leader now decides is left. + if (!committed && !decides && !leads()) return true + // Only a committed decision reaches a writer in another tab, and the + // deletion and settlement follow even across a handover. + if (this.recordsFor(id)) await this.outbox.recordRejection(id, error) await this.outbox.remove(id) + if (decides) await this.outbox.removeDecision(id).catch(() => {}) this.excluding.delete(id) this.offlineExecutor.rejectTransaction(id, error) return true @@ -576,8 +594,9 @@ export class TransactionExecutor { // A change of leadership drops the rest; the next replay owns them. if (!this.failedCleanups.has(id)) continue if (!(await this.cleanUpExcluded(id, error, term))) continue - // A change of leadership during the attempt already dropped it. - this.failedCleanups.delete(id) + // Only the term that made the attempt may clear its entry. + if (term === this.offlineExecutor.leadershipTerm) + this.failedCleanups.delete(id) } } finally { this.cleaning = false @@ -587,6 +606,14 @@ export class TransactionExecutor { else this.scheduleCleanupRetry() } + /** Finishes a committed removal whose deletion failed, outside the queue. */ + retryDecided(id: string, error: Error): void { + if (!this.offlineExecutor.isOfflineEnabled) return + this.excluding.add(id) + this.failedCleanups.set(id, error) + this.scheduleCleanupRetry() + } + private dropFailedCleanups(): void { this.failedCleanups.clear() this.cleanupAttempts = 0 diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 3d22e0af38..677d9ebd8a 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -35,6 +35,7 @@ export class OutboxManager { private serializer: TransactionSerializer private keyPrefix = `tx:` private outcomePrefix = `outcome:` + private decisionPrefix = `decision:` private removalRevision = 0 private activeReads = new Set<{ revision: number }>() private removedAtRevision = new Map() @@ -200,33 +201,22 @@ export class OutboxManager { } /** - * Persists a decision to reject a saved row, so any later leader's replay - * settles it as rejected instead of sending it. A row that already carries - * a phase keeps it; one that cannot be read is left as it is. + * Records a decision to reject a saved write, beside its row, which it + * never rewrites. A replay settles a row that has one instead of sending + * it; a decision whose row is gone means nothing. */ - async markRejected( - id: string, - error: Error, - ): Promise<`marked` | `gone` | `unreadable`> { - const data = await this.storage.get(this.getStorageKey(id)) - if (data === null) return `gone` - let transaction: OfflineTransaction - try { - transaction = this.serializer.deserialize(data) - } catch { - return `unreadable` - } - if (transaction.outboxPhase) return `marked` - await this.add({ - ...transaction, - outboxPhase: `rejection-pending`, - lastError: { - name: error.name, - message: error.message, - stack: error.stack, - }, - }) - return `marked` + async recordDecision(id: string, error: Error): Promise { + await this.storage.set( + `${this.decisionPrefix}${encodeURIComponent(id)}`, + JSON.stringify({ + error: { name: error.name, message: error.message }, + at: Date.now(), + }), + ) + } + + async removeDecision(id: string): Promise { + await this.storage.delete(`${this.decisionPrefix}${encodeURIComponent(id)}`) } /** Whether a row is saved, without decoding it. */ @@ -247,11 +237,25 @@ export class OutboxManager { async withAll( consume: (transactions: Array) => T, + // Filled from the same key listing with every recorded decision. + decisions?: Map, ): Promise { const read = { revision: this.removalRevision } this.activeReads.add(read) try { const keys = await this.storage.keys() + if (decisions) { + for (const key of keys) { + if (!key.startsWith(this.decisionPrefix)) continue + const data = await this.storage.get(key) + if (data === null) continue + decisions.set( + decodeURIComponent(key.slice(this.decisionPrefix.length)), + (JSON.parse(data) as { error: { name: string; message: string } }) + .error, + ) + } + } const transactionKeys = keys.filter((key) => key.startsWith(this.keyPrefix), ) diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 2d4ddb713e..b29d30d501 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -205,6 +205,16 @@ const reachStates = [ // one not yet decided gave way to the next leader's send. `removal-decision-survived-handover`, `removal-yielded-to-successor`, + // A removal decision that landed after the next leader settled the write + // left no row for a later replay to reject. + `stale-decision-left-no-row`, + // A removal that yielded at a handover was made by the next leader. + `yielded-removal-forwarded`, + // A follower's removal that the leader yielded was asked again of the + // next leader, which made it. + `follower-removal-asked-again`, + // Removing a write whose call succeeded but whose row stayed completed it. + `removed-after-success-completed`, // A leader's own write removed while its call ran stayed pending across a // handover, then took the server's outcome. `own-running-removal-completed`, @@ -267,6 +277,10 @@ type SharedActionType = | `exclusion-across-handover-mid-mark` | `removal-mark-landed-handover` | `removal-mark-held-handover` + | `removal-mark-held-late` + | `removal-mark-held-offline` + | `remove-deletion-pending` + | `forwarded-removal-yields` | `remove-own-running` | `remove-own-rejected-running` | `replace-default-with-durable` @@ -334,6 +348,10 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( }, { weight: 1, arbitrary: sharedAction(`removal-mark-landed-handover`) }, { weight: 1, arbitrary: sharedAction(`removal-mark-held-handover`) }, + { weight: 1, arbitrary: sharedAction(`removal-mark-held-late`) }, + { weight: 1, arbitrary: sharedAction(`removal-mark-held-offline`) }, + { weight: 1, arbitrary: sharedAction(`remove-deletion-pending`) }, + { weight: 1, arbitrary: sharedAction(`forwarded-removal-yields`) }, { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, @@ -402,6 +420,10 @@ const spliced = ( action.type !== `exclusion-across-handover-mid-mark` && action.type !== `removal-mark-landed-handover` && action.type !== `removal-mark-held-handover` && + action.type !== `removal-mark-held-late` && + action.type !== `removal-mark-held-offline` && + action.type !== `remove-deletion-pending` && + action.type !== `forwarded-removal-yields` && action.type !== `remove-own-running` && action.type !== `remove-own-rejected-running` && action.type !== `replace-default-with-durable` && @@ -567,15 +589,20 @@ class ReadFailingStorage extends FakeStorageAdapter { this.heldDelete?.release() this.heldDelete = undefined } - // The next row write fails, or waits for release before it lands. - failTxWrites = 0 - private heldTx: { release: () => void } | null | undefined - holdNextTxWrite(): void { - this.heldTx = null + // The next removal decision write fails, or waits for release: before it + // lands, or after. + failDecisionWrites = 0 + private heldDecision: + | { release: (fail: boolean) => void; landed: boolean } + | { landFirst: boolean } + | undefined + holdNextDecision(landFirst = false): void { + this.heldDecision = { landFirst } } - releaseTxWrite(): void { - this.heldTx?.release() - this.heldTx = undefined + releaseDecision(fail = false): void { + if (this.heldDecision && `release` in this.heldDecision) + this.heldDecision.release(fail) + this.heldDecision = undefined } override async delete(key: string): Promise { if (this.failDeletes > 0 && key.startsWith(`tx:`)) { @@ -604,14 +631,22 @@ class ReadFailingStorage extends FakeStorageAdapter { throw new Error(`storage write failed`) } } - if (this.failTxWrites > 0 && key.startsWith(`tx:`)) { - this.failTxWrites -= 1 + if (this.failDecisionWrites > 0 && key.startsWith(`decision:`)) { + this.failDecisionWrites -= 1 throw new Error(`storage write failed`) } - if (this.heldTx === null && key.startsWith(`tx:`)) { - await new Promise((release) => { - this.heldTx = { release } + if ( + this.heldDecision && + `landFirst` in this.heldDecision && + key.startsWith(`decision:`) + ) { + const { landFirst } = this.heldDecision + if (landFirst) await super.set(key, value) + const fail = await new Promise((release) => { + this.heldDecision = { release, landed: landFirst } }) + if (landFirst) return + if (fail) throw new Error(`storage write failed`) } if (this.heldAck === null && key.startsWith(`tx:`)) { await super.set(key, value) @@ -1733,18 +1768,18 @@ async function runHistory( const write = await doWrite(writer, `write`) if (!write) break excluded.add(write.id) - storage.failOutcomeWrites = 1 + // Its first cleanup fails before its decision commits. + storage.failDecisionWrites = 1 const original = tabs[leader]!.election original.releaseLeadership() await settle() await original.requestLeadership() await settle() - storage.failOutcomeWrites = 0 expect( - storage.outcomeFailed(write.transactionId!), - `${write.id}'s exclusion record failed`, - ).toBe(true) - storage.holdOutcomeWrite() + storage.failDecisionWrites, + `${write.id}'s exclusion decision failed`, + ).toBe(0) + storage.holdNextDecision() if (again) { // The original tab leads next, so the writer stays a follower. const writerElection = tabs[writer]!.election @@ -1760,7 +1795,7 @@ async function runHistory( channels.state.loseLeader = true next.releaseLeadership() await settle() - storage.releaseOutcomeWrite() + storage.releaseDecision() await settle() channels.state.loseSettlement = false channels.state.loseLeader = false @@ -1785,16 +1820,20 @@ async function runHistory( expect(calls, `${write.id} sent by the next leader`).toContain( write.id, ) - storage.releaseOutcomeWrite() - await settle() - expect(write.outcome, `${write.id} waits for its call`).toBe( - undefined, - ) + // The send completes and its message is lost; the writer checks + // the outbox while the stalled decision is still pending. + channels.state.loseSettlement = true release() await settle() - await next.requestLeadership() + channels.state.loseSettlement = false + channels.inject({ type: `leader` }) await settle() expect(write.outcome, `${write.id} completes`).toBe(`completed`) + storage.releaseDecision() + await settle() + await next.requestLeadership() + await settle() + expect(write.outcome, `${write.id} stays completed`).toBe(`completed`) reach(`fenced-cleanup-yielded`) break } @@ -1956,12 +1995,12 @@ async function runHistory( const second = await doWrite(follower, `write`) if (!first || !second) break // The first removal decision fails to persist. - storage.failTxWrites = 1 + storage.failDecisionWrites = 1 await expect( tabs[leader]!.env.executor.clearOutbox(), `the clear reports its failed removal`, ).rejects.toThrow(`storage write failed`) - storage.failTxWrites = 0 + storage.failDecisionWrites = 0 await settle() // Which deletion failed is the injected fault's effect. let kept = 0 @@ -2000,12 +2039,12 @@ async function runHistory( storage.releaseAck() break } - storage.failTxWrites = 1 + storage.failDecisionWrites = 1 await expect( tabs[writer]!.env.executor.removeFromOutbox(write.transactionId!), `the failed removal is reported`, ).rejects.toThrow(`storage write failed`) - storage.failTxWrites = 0 + storage.failDecisionWrites = 0 storage.releaseAck() await settle() expect(calls, `${write.id} still sent`).toContain(write.id) @@ -2065,7 +2104,7 @@ async function runHistory( const write = await doWrite(writer, `write`) if (!write) break excluded.add(write.id) - storage.holdOutcomeWrite() + storage.holdNextDecision() const original = tabs[leader]!.election original.releaseLeadership() await settle() @@ -2073,7 +2112,7 @@ async function runHistory( excluded.delete(write.id) next.releaseLeadership() await settle() - storage.releaseOutcomeWrite(true) + storage.releaseDecision(true) await settle() await next.requestLeadership() await rotateTo(next) @@ -2111,7 +2150,7 @@ async function runHistory( const write = await doWrite(writer, `write`) if (!write) break excluded.add(write.id) - if (midMark) storage.holdNextTxWrite() + if (midMark) storage.holdNextDecision() else storage.holdNextDelete() const original = tabs[leader]!.election original.releaseLeadership() @@ -2132,7 +2171,7 @@ async function runHistory( expect(calls, `${write.id} sent by the next leader`).toContain( write.id, ) - storage.releaseTxWrite() + storage.releaseDecision() await settle() expect(write.outcome, `${write.id} waits for that send`).toBe( undefined, @@ -2161,11 +2200,18 @@ async function runHistory( break } case `removal-mark-landed-handover`: - case `removal-mark-held-handover`: { + case `removal-mark-held-handover`: + case `removal-mark-held-late`: + case `removal-mark-held-offline`: { // The leader removes a queued follower write and loses leadership // while its removal decision is written: after it landed, or // before. const landed = action.type === `removal-mark-landed-handover` + // The stalled decision lands only after the next leader settled + // the write and its row is gone. + const late = action.type === `removal-mark-held-late` + // Offline, the next leader queues the write without sending it. + const offlineHandover = action.type === `removal-mark-held-offline` const leader = leaderIndex() const writer = tabs.findIndex((tab, index) => tab && index !== leader) if ( @@ -2179,23 +2225,38 @@ async function runHistory( online.set(false) const write = await doWrite(writer, `write`) if (!write) break - if (landed) storage.holdNextAck() - else storage.holdNextTxWrite() + storage.holdNextDecision(landed) const removal = tabs[leader]!.env.executor.removeFromOutbox( write.transactionId!, ) await settle() let release = () => {} - if (!landed) + if (!landed && !offlineHandover) callGate = new Promise((resolve) => { release = resolve }) - online.set(true) + if (!offlineHandover) online.set(true) const original = tabs[leader]!.election original.releaseLeadership() await settle() + if (offlineHandover) { + // The removal that yielded is made by the next leader. + storage.releaseDecision() + await removal + await settle() + await original.requestLeadership() + await settle() + write.removed = true + write.deliverable = false + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`yielded-removal-forwarded`) + break + } if (landed) { - storage.releaseAck() + storage.releaseDecision() await removal await settle() await original.requestLeadership() @@ -2212,7 +2273,33 @@ async function runHistory( expect(calls, `${write.id} sent by the next leader`).toContain( write.id, ) - storage.releaseTxWrite() + if (late) { + release() + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + storage.releaseDecision() + await removal + await settle() + await original.requestLeadership() + // A later replay finds nothing to settle. + await rotateTo(original) + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id} stays removed`, + ).toBe(null) + expect( + await storage.get( + `decision:${encodeURIComponent(write.transactionId!)}`, + ), + `the stale decision is gone`, + ).toBe(null) + expect(write.outcome, `${write.id} stays completed`).toBe( + `completed`, + ) + reach(`stale-decision-left-no-row`) + break + } + storage.releaseDecision() await removal await settle() expect(write.outcome, `${write.id} waits for that send`).toBe( @@ -2226,6 +2313,94 @@ async function runHistory( reach(`removal-yielded-to-successor`) break } + case `forwarded-removal-yields`: { + // A follower behind the next leader asks to remove its queued + // write; the leader's decision stalls while leadership moves on. + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.holdNextDecision() + let done = false + void tabs[writer]!.env.executor.removeFromOutbox( + write.transactionId!, + ).then(() => { + done = true + }) + await settle() + // The follower misses the next leader's message, so only the reply + // to its request can send it there. + channels.state.loseLeader = true + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + channels.state.loseLeader = false + storage.releaseDecision() + await settle() + await original.requestLeadership() + await settle() + expect(done, `the removal finished under the next leader`).toBe(true) + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`follower-removal-asked-again`) + break + } + case `remove-deletion-pending`: { + // The leader sends a follower's write and fails to delete its row. + // Offline, the next leader loads that row, and it is removed. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + storage.failDeletes = 1 + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + storage.failDeletes = 0 + break + } + online.set(false) + const successor = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + await rotateTo(tabs[successor]!.election) + await tabs[successor]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id} removed`, + ).toBe(null) + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`removed-after-success-completed`) + await closeTab(leader) + break + } case `remove-own-running`: case `remove-own-rejected-running`: { // The leader removes its own write while its call runs, then loses @@ -2576,7 +2751,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is written to its row before the row goes, so a later leader settles it as decided rather than send it. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -3025,6 +3200,30 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `removal-mark-held-handover` }]), }, + { + name: `a removal decision landing after the send leaves no row`, + enters: [`stale-decision-left-no-row`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-mark-held-late` }]), + }, + { + name: `a removal that yields at a handover is made by the next leader`, + enters: [`yielded-removal-forwarded`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-mark-held-offline` }]), + }, + { + name: `a follower's removal the leader yielded is asked again`, + enters: [`follower-removal-asked-again`], + build: (generated: History): History => + spliced(generated, [{ type: `forwarded-removal-yields` }]), + }, + { + name: `removing a write whose call succeeded completes it`, + enters: [`removed-after-success-completed`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-deletion-pending` }]), + }, { name: `a leader's own running write removed keeps the server's outcome`, enters: [`own-running-removal-completed`], From d92677d320d453d08d710bb08f4a1ff7132ce4bb Mon Sep 17 00:00:00 2001 From: daveycodez Date: Tue, 24 Nov 2026 23:57:55 -0800 Subject: [PATCH 11/16] fix(offline-transactions): address ninth durable follower write review - A committed removal keeps its write out of direct admission while its deletion is pending, as a decided row loaded at replay already is. - Decisions have one key per recorder. A successor adopts a former leader's decision under its own key before cleanup, so the former leader withdrawing its key cannot expose the row to a third leader. - An executor registers by Collection while it runs a call, so reconciliation sees a call an intermediate replacement issued. - A removed running write's marker is registered before its row goes, and withdrawn at once if the call already finished. The durable follower oracle sends an added message during a committed removal, hands leadership over twice while an adopted cleanup is pending, replaces an executor twice while an issued call runs, and lets a call finish before its removal's deletion acknowledges. --- .../src/OfflineExecutor.ts | 71 ++++- .../src/executor/TransactionExecutor.ts | 34 ++- .../src/outbox/OutboxManager.ts | 35 ++- packages/offline-transactions/src/types.ts | 2 + .../durable-follower-oracle.property.test.ts | 247 +++++++++++++++++- 5 files changed, 358 insertions(+), 31 deletions(-) diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 5c60f36ce5..62cadca66b 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -79,6 +79,13 @@ const completionOwners = new WeakMap< Set >() +// Executors with a call running, by Collection, so a later replacement can +// tell a write is still being sent after its row went. +const callIssuers = new WeakMap< + OfflineConfig[`collections`][string], + Set +>() + /** A replacement may add Collections while retaining every prior registry entry. */ function retainsCollections( configured: OfflineConfig[`collections`], @@ -125,6 +132,8 @@ export class OfflineExecutor { private term = 0 // Saves in progress; true once removeFromOutbox or clearOutbox removed one. private readonly saving = new Map() + // Ids whose call this executor is running. + private readonly issued = new Set() // Running markers this leader recorded for removed writes, by id. private readonly runningRemovals = new Map() // Removals this follower asked the leader for, by request. @@ -624,12 +633,7 @@ export class OfflineExecutor { if (!(await waiter.saved)) continue // Absence means success only where rejections are recorded, and not // while this runtime still runs the write's call. - if ( - !owner.recordsOutcomes || - owner.scheduler.isRunning(id) || - this.scheduler.isRunning(id) - ) - continue + if (!owner.recordsOutcomes || this.callRunning(id)) continue const outbox = owner.outbox! // A row that cannot be decoded is still there. if (await outbox.has(id)) continue @@ -961,6 +965,38 @@ export class OfflineExecutor { ) } + trackIssued(id: string, active: boolean): void { + if (active) this.issued.add(id) + else this.issued.delete(id) + for (const collection of Object.values(this.config.collections)) { + let issuers = callIssuers.get(collection) + if (!issuers) callIssuers.set(collection, (issuers = new Set())) + if (this.issued.size > 0) issuers.add(this) + else issuers.delete(this) + } + } + + /** Whether an executor over these Collections in this runtime runs its call. */ + private callRunning(id: string): boolean { + if (this.issued.has(id)) return true + for (const collection of Object.values(this.config.collections)) { + for (const issuer of callIssuers.get(collection) ?? []) + if ( + issuer.issued.has(id) && + (retainsCollections( + this.config.collections, + issuer.config.collections, + ) || + retainsCollections( + issuer.config.collections, + this.config.collections, + )) + ) + return true + } + return false + } + /** This executor and those in this runtime whose outcomes it delivers. */ private relatedExecutors(): Array { const candidates = new Set([this]) @@ -1069,13 +1105,18 @@ export class OfflineExecutor { } if (!unstarted.has(id)) { // A writer in another tab reads that the call it cannot see is - // still running. + // still running. The marker is registered before the row goes, + // and withdrawn at once if the call already finished. const token = records(id) ? await outbox.recordPending(id) : undefined + if (token !== undefined) { + if (this.scheduler.isRunning(id)) + this.runningRemovals.set(id, token) + else await outbox.withdrawOutcome(id, token).catch(() => {}) + } await outbox.remove(id) if (this.saving.has(id)) this.saving.set(id, true) - if (token !== undefined) this.runningRemovals.set(id, token) return } // A row whose call already settled keeps that outcome. @@ -1097,18 +1138,22 @@ export class OfflineExecutor { // does not commit while this tab leads is withdrawn. Without // recorded outcomes there are no decisions, and a write the next // leader now decides is left to it. - if (this.recordsOutcomes) await outbox.recordDecision(id, error) + const decision = this.recordsOutcomes + ? await outbox.recordDecision(id, error) + : undefined if (!stillLeads()) { - if (this.recordsOutcomes) - await outbox.removeDecision(id).catch(() => {}) + if (decision !== undefined) + await outbox.removeDecision(id, decision).catch(() => {}) yielded.push(id) return } committed = true + // No admission runs it while its deletion is pending. + this.executor!.exclude(id) if (records(id)) await outbox.recordRejection(id, error) await outbox.remove(id) - if (this.recordsOutcomes) - await outbox.removeDecision(id).catch(() => {}) + if (decision !== undefined) + await outbox.removeDecision(id, decision).catch(() => {}) } catch (removalError) { if (!committed) { failures.push(removalError) diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 995896430a..d12c3ae0d4 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -97,6 +97,16 @@ export class TransactionExecutor { private async executeTransaction( transaction: OfflineTransaction, ): Promise { + // Another executor over the same Collections reads that this call runs. + this.offlineExecutor.trackIssued?.(transaction.id, true) + try { + await this.runTransaction(transaction) + } finally { + this.offlineExecutor.trackIssued?.(transaction.id, false) + } + } + + private async runTransaction(transaction: OfflineTransaction): Promise { try { const terminalError = transaction.outboxPhase === `rejection-pending` @@ -303,7 +313,7 @@ export class TransactionExecutor { // This leader accepted and sent the write; a former leader's decision // that landed meanwhile must not settle it at a later replay. if (this.offlineExecutor.recordsOutcomes) - await this.outbox.removeDecision(transaction.id).catch(() => {}) + await this.outbox.removeDecisions(transaction.id).catch(() => {}) } catch (persistError) { // Public removal can finish while the named mutation function runs. // The removed row cannot be retried, but its caller still owns the @@ -492,7 +502,7 @@ export class TransactionExecutor { ) for (const id of orphaned) - void this.outbox.removeDecision(id).catch(() => {}) + void this.outbox.removeDecisions(id).catch(() => {}) const cleanUp = async (id: string, error: Error, committed: boolean) => { if (await this.cleanUpExcluded(id, error, term, committed)) return // Retried only while this decision stands: a later term's replay may @@ -540,10 +550,14 @@ export class TransactionExecutor { this.offlineExecutor.isOfflineEnabled && term === this.offlineExecutor.leadershipTerm const decides = this.offlineExecutor.recordsOutcomes === true - if (!committed && decides) { - await this.outbox.recordDecision(id, error) + // A decision a former leader made is adopted under this tab's own key, + // so it survives that leader withdrawing its own until this cleanup + // finishes. + let token: string | undefined + if (decides) { + token = await this.outbox.recordDecision(id, error) if (!leads()) { - await this.outbox.removeDecision(id).catch(() => {}) + await this.outbox.removeDecision(id, token).catch(() => {}) return true } } @@ -553,7 +567,8 @@ export class TransactionExecutor { // deletion and settlement follow even across a handover. if (this.recordsFor(id)) await this.outbox.recordRejection(id, error) await this.outbox.remove(id) - if (decides) await this.outbox.removeDecision(id).catch(() => {}) + if (token !== undefined) + await this.outbox.removeDecision(id, token).catch(() => {}) this.excluding.delete(id) this.offlineExecutor.rejectTransaction(id, error) return true @@ -606,6 +621,11 @@ export class TransactionExecutor { else this.scheduleCleanupRetry() } + /** Keeps a write a committed removal is deleting out of admission. */ + exclude(id: string): void { + this.excluding.add(id) + } + /** Finishes a committed removal whose deletion failed, outside the queue. */ retryDecided(id: string, error: Error): void { if (!this.offlineExecutor.isOfflineEnabled) return @@ -631,6 +651,8 @@ export class TransactionExecutor { // the write, and this term's outbox load already has it if it remains. const term = this.offlineExecutor.leadershipTerm const transaction = await this.outbox.getCurrent(id) + // A row this leader decided to reject, or loaded with a decision, is in + // `excluding` and is settled, never sent. if ( !transaction || !this.offlineExecutor.isOfflineEnabled || diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 677d9ebd8a..9ab3baf62a 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -202,21 +202,40 @@ export class OutboxManager { /** * Records a decision to reject a saved write, beside its row, which it - * never rewrites. A replay settles a row that has one instead of sending - * it; a decision whose row is gone means nothing. + * never rewrites; returns its token. A replay settles a row that has any + * decision instead of sending it; a decision whose row is gone means + * nothing. Each recorder has its own key, so one that withdraws its + * decision leaves any other tab's, such as a successor's adoption. */ - async recordDecision(id: string, error: Error): Promise { + async recordDecision(id: string, error: Error): Promise { + const token = `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}` await this.storage.set( - `${this.decisionPrefix}${encodeURIComponent(id)}`, + `${this.decisionKeyPrefix(id)}${token}`, JSON.stringify({ error: { name: error.name, message: error.message }, at: Date.now(), }), ) + return token + } + + /** Withdraws one recorder's decision. */ + async removeDecision(id: string, token: string): Promise { + await this.storage.delete(`${this.decisionKeyPrefix(id)}${token}`) + } + + /** Removes every decision for a write. */ + async removeDecisions(id: string): Promise { + const prefix = this.decisionKeyPrefix(id) + await Promise.all( + (await this.storage.keys()) + .filter((key) => key.startsWith(prefix)) + .map((key) => this.storage.delete(key)), + ) } - async removeDecision(id: string): Promise { - await this.storage.delete(`${this.decisionPrefix}${encodeURIComponent(id)}`) + private decisionKeyPrefix(id: string): string { + return `${this.decisionPrefix}${encodeURIComponent(id)}:` } /** Whether a row is saved, without decoding it. */ @@ -250,7 +269,9 @@ export class OutboxManager { const data = await this.storage.get(key) if (data === null) continue decisions.set( - decodeURIComponent(key.slice(this.decisionPrefix.length)), + decodeURIComponent( + key.slice(this.decisionPrefix.length).split(`:`)[0]!, + ), (JSON.parse(data) as { error: { name: string; message: string } }) .error, ) diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index 4aa5ab3dec..dfae4ac649 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -177,6 +177,8 @@ export interface TransactionSignaler { * writer needs a recorded rejection; this tab's own does not. */ ownsWrite?: (transactionId: string) => boolean + /** A call for this transaction starts or ends in this executor. */ + trackIssued?: (transactionId: string, active: boolean) => void /** A removed write's call finished: its running marker goes. */ finishRunningRemoval?: (transactionId: string) => Promise resolveTransaction: (transactionId: string, result: any) => void diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index b29d30d501..c6052a0ffb 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -213,6 +213,18 @@ const reachStates = [ // A follower's removal that the leader yielded was asked again of the // next leader, which made it. `follower-removal-asked-again`, + // An added message while a committed removal's deletion was pending sent + // nothing. + `committed-removal-not-admitted`, + // A decision a successor adopted survived its first recorder withdrawing + // its own, through a second handover. + `adopted-decision-survived`, + // A write whose call an intermediate replacement issued stayed pending at + // a later replacement, then took the server's outcome. + `issued-call-across-replacements`, + // A call that finished before its removal's deletion acknowledged left no + // running marker behind. + `running-marker-retired`, // Removing a write whose call succeeded but whose row stayed completed it. `removed-after-success-completed`, // A leader's own write removed while its call ran stayed pending across a @@ -281,6 +293,10 @@ type SharedActionType = | `removal-mark-held-offline` | `remove-deletion-pending` | `forwarded-removal-yields` + | `added-during-committed-removal` + | `adopted-decision-second-handover` + | `replaced-twice-during-call` + | `running-removal-completes-first` | `remove-own-running` | `remove-own-rejected-running` | `replace-default-with-durable` @@ -352,6 +368,10 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`removal-mark-held-offline`) }, { weight: 1, arbitrary: sharedAction(`remove-deletion-pending`) }, { weight: 1, arbitrary: sharedAction(`forwarded-removal-yields`) }, + { weight: 1, arbitrary: sharedAction(`added-during-committed-removal`) }, + { weight: 1, arbitrary: sharedAction(`adopted-decision-second-handover`) }, + { weight: 1, arbitrary: sharedAction(`replaced-twice-during-call`) }, + { weight: 1, arbitrary: sharedAction(`running-removal-completes-first`) }, { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, @@ -424,6 +444,10 @@ const spliced = ( action.type !== `removal-mark-held-offline` && action.type !== `remove-deletion-pending` && action.type !== `forwarded-removal-yields` && + action.type !== `added-during-committed-removal` && + action.type !== `adopted-decision-second-handover` && + action.type !== `replaced-twice-during-call` && + action.type !== `running-removal-completes-first` && action.type !== `remove-own-running` && action.type !== `remove-own-rejected-running` && action.type !== `replace-default-with-durable` && @@ -2288,11 +2312,13 @@ async function runHistory( `${write.id} stays removed`, ).toBe(null) expect( - await storage.get( - `decision:${encodeURIComponent(write.transactionId!)}`, + (await storage.keys()).filter((key) => + key.startsWith( + `decision:${encodeURIComponent(write.transactionId!)}:`, + ), ), `the stale decision is gone`, - ).toBe(null) + ).toEqual([]) expect(write.outcome, `${write.id} stays completed`).toBe( `completed`, ) @@ -2361,6 +2387,186 @@ async function runHistory( reach(`follower-removal-asked-again`) break } + case `added-during-committed-removal`: { + // The leader removes a queued follower write; while its deletion + // stalls, a duplicate added message arrives online. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(follower, `write`) + if (!write) break + storage.holdNextDelete() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + online.set(true) + await settle() + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + expect(calls, `${write.id} not admitted`).not.toContain(write.id) + storage.releaseDelete() + await removal + await settle() + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`committed-removal-not-admitted`) + break + } + case `adopted-decision-second-handover`: { + // The leader's removal decision lands but its acknowledgment + // stalls. The next leader adopts it and its deletion stalls. The + // first leader then withdraws its own, and leadership moves again. + const leader = leaderIndex() + const next = election.queue[0] + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && tab.election !== next, + ) + if ( + !durable || + leader < 0 || + !next || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.holdNextDecision(true) + storage.holdNextDelete() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + await settle() + // The first leader's request to the next one is lost. + channels.state.loseRemoval = true + storage.releaseDecision() + await settle() + channels.state.loseRemoval = false + online.set(true) + next.releaseLeadership() + await settle() + storage.releaseDelete() + await settle() + await next.requestLeadership() + await removal + await settle() + write.removed = true + write.deliverable = false + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`adopted-decision-survived`) + break + } + case `replaced-twice-during-call`: { + // A follower's executor is replaced; the replacement leads and + // issues the write's rejected call; the row is removed and that + // replacement is replaced in turn while the call runs. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write-rejected`) + if (!write) break + const collection = tabs[writer]!.env.collection + await closeTab(writer) + await openTab(writer, undefined, undefined, false, collection) + await rotateTo(tabs[writer]!.election) + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + online.set(true) + await settle() + if (!calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + await tabs[writer]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await closeTab(writer) + await openTab(writer, undefined, undefined, false, collection) + expect(write.outcome, `${write.id} waits for its issued call`).toBe( + undefined, + ) + release() + await settle() + expect(write.outcome, `${write.id} takes the server's outcome`).toBe( + `failed`, + ) + reach(`issued-call-across-replacements`) + break + } + case `running-removal-completes-first`: { + // The leader removes a follower's running write; the call finishes + // before the removal's deletion acknowledges, and its message is + // lost. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + storage.holdNextDelete() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + channels.state.loseSettlement = true + release() + await settle() + channels.state.loseSettlement = false + storage.releaseDelete() + await removal + await settle() + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`running-marker-retired`) + break + } case `remove-deletion-pending`: { // The leader sends a follower's write and fails to delete its row. // Offline, the next leader loads that row, and it is removed. @@ -2751,7 +2957,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -2783,10 +2989,17 @@ oracleProperty({ `src/OfflineExecutor.ts#OfflineExecutor.forwardRemoval`, `src/OfflineExecutor.ts#OfflineExecutor.relatedExecutors`, `src/OfflineExecutor.ts#OfflineExecutor.finishRunningRemoval`, + `src/OfflineExecutor.ts#OfflineExecutor.callRunning`, + `src/OfflineExecutor.ts#OfflineExecutor.trackIssued`, + `src/OfflineExecutor.ts#OfflineExecutor.removeOrForward`, + `src/outbox/OutboxManager.ts#OutboxManager.recordDecision`, + `src/outbox/OutboxManager.ts#OutboxManager.removeDecision`, + `src/outbox/OutboxManager.ts#OutboxManager.removeDecisions`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.exclude`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.retryDecided`, `src/outbox/OutboxManager.ts#OutboxManager.recordPending`, `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, `src/outbox/OutboxManager.ts#OutboxManager.outcomeKeys`, - `src/executor/TransactionExecutor.ts#TransactionExecutor.requeue`, ], histories: { arbitrary: historyArbitrary, @@ -3218,6 +3431,30 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `forwarded-removal-yields` }]), }, + { + name: `an added message during a committed removal sends nothing`, + enters: [`committed-removal-not-admitted`], + build: (generated: History): History => + spliced(generated, [{ type: `added-during-committed-removal` }]), + }, + { + name: `an adopted decision survives a second handover`, + enters: [`adopted-decision-survived`], + build: (generated: History): History => + spliced(generated, [{ type: `adopted-decision-second-handover` }]), + }, + { + name: `an issued call is tracked across two replacements`, + enters: [`issued-call-across-replacements`], + build: (generated: History): History => + spliced(generated, [{ type: `replaced-twice-during-call` }]), + }, + { + name: `a call finishing before its removal leaves no marker`, + enters: [`running-marker-retired`], + build: (generated: History): History => + spliced(generated, [{ type: `running-removal-completes-first` }]), + }, { name: `removing a write whose call succeeded completes it`, enters: [`removed-after-success-completed`], From 5ec1262a81235fe8e7a1da7e29b1dac7ae6412e5 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Wed, 25 Nov 2026 01:25:07 -0800 Subject: [PATCH 12/16] fix(offline-transactions): address tenth durable follower write review - A replay reads decisions only for stored rows, so a row this tab cannot decode keeps its decision; an unreadable decision still rejects its row, and one whose row is gone is deleted unread. - An admission that arrives during this term's replay waits for it, so a decided row cannot be scheduled before replay excludes it. - A follower that stops leading during its replay leaves its pending removals with the current leader and asks it again. - Without a persisted decision, a failed deletion is reported and the write stays eligible, as before this feature. - Retried cleanups remember whether their decision committed, and a writer removes a record a later cleanup writes for a write it settled. The durable follower oracle checks a decision whose row one leader cannot decode, an added message during replay, a pending removal after a lost replay, a failed default-mode deletion and an unreadable orphan decision, and asserts the stalled decision before a forwarded retry. --- .../src/OfflineExecutor.ts | 38 ++- .../src/executor/TransactionExecutor.ts | 40 ++- .../src/outbox/OutboxManager.ts | 36 ++- .../durable-follower-oracle.property.test.ts | 271 ++++++++++++++++++ 4 files changed, 358 insertions(+), 27 deletions(-) diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 62cadca66b..24e5ddba30 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -446,6 +446,7 @@ export class OfflineExecutor { return } + const term = this.term // Startup must observe a failed read instead of reporting an empty outbox. await this.executor.loadPendingTransactions() // Outcomes no writer read within the retention window go. @@ -463,11 +464,18 @@ export class OfflineExecutor { } satisfies OutboxMessage) } this.reconcileFollowerWrites() - // Removals this tab asked a former leader for are now its own to make. - for (const [request, removal] of [...this.removals]) { - this.removals.delete(request) - this.removeOrForward(removal.ids).then(removal.resolve, removal.reject) - } + // Removals this tab asked a former leader for are now its own to make, + // unless it stopped leading during the replay; they then stay with the + // current leader. + + if (this.isOfflineEnabled && term === this.term) + for (const [request, removal] of [...this.removals]) { + this.removals.delete(request) + this.removeOrForward(removal.ids).then(removal.resolve, removal.reject) + } + else + for (const [request, removal] of this.removals) + this.postRemoval(request, removal.ids) // Replay completion is separate from initialization and durable admission. this.executor.executeAll().catch((error) => { @@ -602,6 +610,9 @@ export class OfflineExecutor { * transaction and waits for it; an observer does not. */ ownsWrite(id: string): boolean { + // One it settled as the writer stays its own, so a later cleanup leaves + // no record for it. + if (this.ownSettled.has(id)) return true return this.settlementOwners(id).some( (owner) => owner.pendingTransactionPromises.get(id)?.saved !== undefined, ) @@ -849,6 +860,16 @@ export class OfflineExecutor { } } + // Ids this executor settled as their writer, oldest first: a record a + // later leader writes for one again is still its own to remove. + private readonly ownSettled = new Set() + + private rememberOwnSettled(transactionId: string): void { + this.ownSettled.add(transactionId) + if (this.ownSettled.size > SETTLED_TRANSACTIONS_REMEMBERED) + this.ownSettled.delete(this.ownSettled.values().next().value!) + } + private rememberSettled(transactionId: string): void { this.settledTransactions.add(transactionId) if (this.settledTransactions.size > SETTLED_TRANSACTIONS_REMEMBERED) @@ -933,6 +954,7 @@ export class OfflineExecutor { for (const owner of owners) { owner.rememberSettled(transactionId) const deferred = owner.pendingTransactionPromises.get(transactionId) + if (deferred?.saved !== undefined) owner.rememberOwnSettled(transactionId) owner.pendingTransactionPromises.delete(transactionId) if (error) deferred?.reject(error) else deferred?.resolve(result) @@ -1147,9 +1169,11 @@ export class OfflineExecutor { yielded.push(id) return } - committed = true + // Only a persisted decision commits a removal; without one, a failed + // deletion is reported and the write stays eligible. + committed = decision !== undefined // No admission runs it while its deletion is pending. - this.executor!.exclude(id) + if (committed) this.executor!.exclude(id) if (records(id)) await outbox.recordRejection(id, error) await outbox.remove(id) if (decision !== undefined) diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index d12c3ae0d4..e21eb12d66 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -33,7 +33,13 @@ export class TransactionExecutor { private readonly excluding = new Set() // Excluded writes whose cleanup failed, with their rejection. Retried on a // timer and on connectivity, outside the queue, while this tab leads. - private readonly failedCleanups = new Map() + // Each with whether its decision is already persisted. + private readonly failedCleanups = new Map< + string, + { error: Error; committed: boolean } + >() + // The replay of the current term, which admissions wait for. + private replay: Promise | null = null private cleanupTimer: ReturnType | null = null private cleanupAttempts = 0 private cleaning = false @@ -427,11 +433,25 @@ export class TransactionExecutor { } async loadPendingTransactions(): Promise { + // An admission waits for this replay, which settles decided rows and + // fills `excluding` before any of them can be scheduled. + let finish!: () => void + const replay = new Promise((resolve) => { + finish = resolve + }) + this.replay = replay + try { + await this.loadPending() + } finally { + if (this.replay === replay) this.replay = null + finish() + } + } + + private async loadPending(): Promise { let removedIds: Array = [] // Rows a former leader decided to reject: settled here, never sent. let decided: Array = [] - // Decisions whose row is gone. - let orphaned: Array = [] const term = this.offlineExecutor.leadershipTerm // Decisions exist only where outcomes are recorded. const decisions = new Map() @@ -448,9 +468,6 @@ export class TransactionExecutor { decisions.has(transaction.id) && !this.scheduler.isRunning(transaction.id), ) - orphaned = [...decisions.keys()].filter( - (id) => !transactions.some((transaction) => transaction.id === id), - ) const providerPending = transactions.filter( (transaction) => !transaction.outboxPhase && !decided.includes(transaction), @@ -501,8 +518,6 @@ export class TransactionExecutor { this.offlineExecutor.recordsOutcomes ? decisions : undefined, ) - for (const id of orphaned) - void this.outbox.removeDecisions(id).catch(() => {}) const cleanUp = async (id: string, error: Error, committed: boolean) => { if (await this.cleanUpExcluded(id, error, term, committed)) return // Retried only while this decision stands: a later term's replay may @@ -513,7 +528,7 @@ export class TransactionExecutor { !this.excluding.has(id) ) return - this.failedCleanups.set(id, error) + this.failedCleanups.set(id, { error, committed }) this.scheduleCleanupRetry() } // A former leader's decision settles without the network, and startup @@ -605,10 +620,10 @@ export class TransactionExecutor { this.cleaning = true const term = this.offlineExecutor.leadershipTerm try { - for (const [id, error] of [...this.failedCleanups]) { + for (const [id, { error, committed }] of [...this.failedCleanups]) { // A change of leadership drops the rest; the next replay owns them. if (!this.failedCleanups.has(id)) continue - if (!(await this.cleanUpExcluded(id, error, term))) continue + if (!(await this.cleanUpExcluded(id, error, term, committed))) continue // Only the term that made the attempt may clear its entry. if (term === this.offlineExecutor.leadershipTerm) this.failedCleanups.delete(id) @@ -630,7 +645,7 @@ export class TransactionExecutor { retryDecided(id: string, error: Error): void { if (!this.offlineExecutor.isOfflineEnabled) return this.excluding.add(id) - this.failedCleanups.set(id, error) + this.failedCleanups.set(id, { error, committed: true }) this.scheduleCleanupRetry() } @@ -649,6 +664,7 @@ export class TransactionExecutor { // A read that the transaction's removal overtakes returns null. One that // spans a change of leadership is dropped: another leader may have sent // the write, and this term's outbox load already has it if it remains. + await this.replay const term = this.offlineExecutor.leadershipTerm const transaction = await this.outbox.getCurrent(id) // A row this leader decided to reject, or loaded with a decision, is in diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 9ab3baf62a..08fd29ec35 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -264,17 +264,37 @@ export class OutboxManager { try { const keys = await this.storage.keys() if (decisions) { + // Only a decision whose row is stored is read; one that cannot be + // read still blocks its row. One whose row is gone is deleted + // unread, whether or not this tab can decode that row. + const stored = new Set( + keys + .filter((key) => key.startsWith(this.keyPrefix)) + .map((key) => key.slice(this.keyPrefix.length)), + ) for (const key of keys) { if (!key.startsWith(this.decisionPrefix)) continue - const data = await this.storage.get(key) - if (data === null) continue - decisions.set( - decodeURIComponent( - key.slice(this.decisionPrefix.length).split(`:`)[0]!, - ), - (JSON.parse(data) as { error: { name: string; message: string } }) - .error, + const id = decodeURIComponent( + key.slice(this.decisionPrefix.length).split(`:`)[0]!, ) + if (!stored.has(id)) { + this.storage.delete(key).catch(() => {}) + continue + } + let error = { + name: `NonRetriableError`, + message: `Transaction rejected by a recorded decision`, + } + try { + const data = await this.storage.get(key) + if (data === null) continue + error = ( + JSON.parse(data) as { error: { name: string; message: string } } + ).error + } catch { + // The unread decision still rejects its row. + } + decisions.set(id, error) } } const transactionKeys = keys.filter((key) => diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index c6052a0ffb..ac19ce3718 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -225,6 +225,20 @@ const reachStates = [ // A call that finished before its removal's deletion acknowledged left no // running marker behind. `running-marker-retired`, + // A committed decision whose row one leader could not decode survived + // that leader's replay. + `decision-kept-for-unreadable-row`, + // An added message during a new leader's replay waited for it and sent + // nothing decided. + `admission-waited-for-replay`, + // A follower that lost leadership during its replay left its pending + // removal with the current leader. + `pending-removal-left-to-leader`, + // A default-mode removal whose deletion failed reported it and left the + // write to send. + `default-removal-failure-reported`, + // An unreadable decision with no row did not stop a replay. + `orphan-decision-ignored`, // Removing a write whose call succeeded but whose row stayed completed it. `removed-after-success-completed`, // A leader's own write removed while its call ran stayed pending across a @@ -297,6 +311,11 @@ type SharedActionType = | `adopted-decision-second-handover` | `replaced-twice-during-call` | `running-removal-completes-first` + | `decision-row-undecodable` + | `added-during-replay` + | `removal-pending-replay-lost` + | `default-removal-delete-fails` + | `unreadable-orphan-decision` | `remove-own-running` | `remove-own-rejected-running` | `replace-default-with-durable` @@ -372,6 +391,11 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`adopted-decision-second-handover`) }, { weight: 1, arbitrary: sharedAction(`replaced-twice-during-call`) }, { weight: 1, arbitrary: sharedAction(`running-removal-completes-first`) }, + { weight: 1, arbitrary: sharedAction(`decision-row-undecodable`) }, + { weight: 1, arbitrary: sharedAction(`added-during-replay`) }, + { weight: 1, arbitrary: sharedAction(`removal-pending-replay-lost`) }, + { weight: 1, arbitrary: sharedAction(`default-removal-delete-fails`) }, + { weight: 1, arbitrary: sharedAction(`unreadable-orphan-decision`) }, { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, @@ -448,6 +472,11 @@ const spliced = ( action.type !== `adopted-decision-second-handover` && action.type !== `replaced-twice-during-call` && action.type !== `running-removal-completes-first` && + action.type !== `decision-row-undecodable` && + action.type !== `added-during-replay` && + action.type !== `removal-pending-replay-lost` && + action.type !== `default-removal-delete-fails` && + action.type !== `unreadable-orphan-decision` && action.type !== `remove-own-running` && action.type !== `remove-own-rejected-running` && action.type !== `replace-default-with-durable` && @@ -623,6 +652,10 @@ class ReadFailingStorage extends FakeStorageAdapter { holdNextDecision(landFirst = false): void { this.heldDecision = { landFirst } } + // Whether a held decision write reached the gate. + decisionHeld(): boolean { + return this.heldDecision !== undefined && `release` in this.heldDecision + } releaseDecision(fail = false): void { if (this.heldDecision && `release` in this.heldDecision) this.heldDecision.release(fail) @@ -2367,6 +2400,11 @@ async function runHistory( done = true }) await settle() + expect(storage.decisionHeld(), `the leader's decision stalls`).toBe( + true, + ) + expect(done, `the removal waits for that decision`).toBe(false) + expect(write.outcome, `${write.id} still pending`).toBe(undefined) // The follower misses the next leader's message, so only the reply // to its request can send it there. channels.state.loseLeader = true @@ -2379,6 +2417,10 @@ async function runHistory( await original.requestLeadership() await settle() expect(done, `the removal finished under the next leader`).toBe(true) + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id} removed`, + ).toBe(null) write.removed = true write.deliverable = false expect(write.outcome, `${write.id} fails on its removal`).toBe( @@ -2567,6 +2609,201 @@ async function runHistory( reach(`running-marker-retired`) break } + case `decision-row-undecodable`: { + // A committed removal's deletion fails; the next leader cannot + // decode the row, and the leader after it can. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.failDeletes = 1 + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + const key = `tx:${write.transactionId}` + const saved = await storage.get(key) + if (saved === null) break + await storage.set(key, `{not json`) + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + await storage.set(key, saved) + const second = election.holder! + second.releaseLeadership() + await settle() + await second.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`decision-kept-for-unreadable-row`) + break + } + case `added-during-replay`: { + // A committed removal's deletion fails; the next leader's replay + // stalls while an added message for the row arrives online. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.failDeletes = 1 + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + storage.holdNextRead() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + online.set(true) + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + expect(calls, `${write.id} not admitted`).not.toContain(write.id) + storage.releaseRead() + await settle() + await original.requestLeadership() + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + reach(`admission-waited-for-replay`) + break + } + case `removal-pending-replay-lost`: { + // The next leader-to-be asks to remove a follower's write and the + // request is lost. Its replay stalls when it leads, it loses + // leadership, and the tab after it sends the write. + const leader = leaderIndex() + const next = election.queue[0] + const remover = tabs.findIndex((tab) => tab?.election === next) + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && index !== remover, + ) + if ( + !durable || + leader < 0 || + !next || + remover < 0 || + writer < 0 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + channels.state.loseRemoval = true + let done = false + void tabs[remover]!.env.executor.removeFromOutbox( + write.transactionId!, + ).then(() => { + done = true + }) + await settle() + channels.state.loseRemoval = false + storage.holdNextRead() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + online.set(true) + // The remover misses the next leader's message, so only its own + // replay's continuation can act on the request. + channels.state.loseLeader = true + next.releaseLeadership() + await settle() + channels.state.loseLeader = false + expect(calls, `${write.id} sent by the tab after`).toContain(write.id) + storage.releaseRead() + await settle() + expect(write.outcome, `${write.id} waits for that send`).toBe( + undefined, + ) + release() + await settle() + await next.requestLeadership() + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + expect(done, `the removal finished`).toBe(true) + reach(`pending-removal-left-to-leader`) + break + } + case `default-removal-delete-fails`: { + // In the default mode the leader removes its own queued write and + // the deletion fails. + const leader = leaderIndex() + if (durable || leader < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(leader, `write`) + if (!write) break + storage.failDeletes = 1 + await expect( + tabs[leader]!.env.executor.removeFromOutbox(write.transactionId!), + `the failed removal is reported`, + ).rejects.toThrow(`storage delete failed`) + expect(write.outcome, `${write.id} still pending`).toBe(undefined) + online.set(true) + await settle() + expect(calls, `${write.id} still sent`).toContain(write.id) + reach(`default-removal-failure-reported`) + break + } + case `unreadable-orphan-decision`: { + // A decision with no row cannot be read; a follower's write is + // queued, and another tab leads and replays. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 2 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + await storage.set(`decision:orphan:unread`, `{not json`) + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} sent after the replay`).toContain(write.id) + expect( + await storage.get(`decision:orphan:unread`), + `the orphan decision is gone`, + ).toBe(null) + reach(`orphan-decision-ignored`) + break + } case `remove-deletion-pending`: { // The leader sends a follower's write and fails to delete its row. // Offline, the next leader loads that row, and it is removed. @@ -3455,6 +3692,40 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `running-removal-completes-first` }]), }, + { + name: `a decision outlives a leader that cannot decode its row`, + enters: [`decision-kept-for-unreadable-row`], + build: (generated: History): History => + spliced(generated, [{ type: `decision-row-undecodable` }]), + }, + { + name: `an added message during a replay waits for it`, + enters: [`admission-waited-for-replay`], + build: (generated: History): History => + spliced(generated, [{ type: `added-during-replay` }]), + }, + { + name: `a removal stays with the leader after a lost replay`, + enters: [`pending-removal-left-to-leader`], + build: (generated: History): History => + spliced(generated, [{ type: `removal-pending-replay-lost` }]), + }, + { + name: `a default-mode removal reports a failed deletion`, + enters: [`default-removal-failure-reported`], + build: (generated: History): History => + spliced( + generated, + [{ type: `default-removal-delete-fails` }], + `online`, + ), + }, + { + name: `an unreadable orphan decision does not stop a replay`, + enters: [`orphan-decision-ignored`], + build: (generated: History): History => + spliced(generated, [{ type: `unreadable-orphan-decision` }]), + }, { name: `removing a write whose call succeeded completes it`, enters: [`removed-after-success-completed`], From 1b086c28b07fe23cde5394f17f28890902dcf82a Mon Sep 17 00:00:00 2001 From: daveycodez Date: Wed, 25 Nov 2026 03:44:59 -0800 Subject: [PATCH 13/16] fix(offline-transactions): address eleventh durable follower write review - An admission waits for every replay in flight and goes ahead only after this term's replay succeeded; otherwise it fails, so the leader retries it on connectivity. - A completed call stops counting as running before its removal marker is looked up, so a marker registered at any point is either withdrawn or never kept. - Issued calls are checked against the waiter owner's Collections, so replacements that each add a Collection still see one another's call. The durable follower oracle gives each tab its own storage view, routes channel messages by name, and checks an added message after a failed replay and across a newer replay of the same tab, and two replacements that each add a Collection. --- .../src/OfflineExecutor.ts | 17 +- .../src/executor/TransactionExecutor.ts | 22 +- .../durable-follower-oracle.property.test.ts | 218 +++++++++++++++++- 3 files changed, 236 insertions(+), 21 deletions(-) diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 24e5ddba30..4ed885e8c3 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -467,7 +467,7 @@ export class OfflineExecutor { // Removals this tab asked a former leader for are now its own to make, // unless it stopped leading during the replay; they then stay with the // current leader. - + if (this.isOfflineEnabled && term === this.term) for (const [request, removal] of [...this.removals]) { this.removals.delete(request) @@ -644,7 +644,7 @@ export class OfflineExecutor { if (!(await waiter.saved)) continue // Absence means success only where rejections are recorded, and not // while this runtime still runs the write's call. - if (!owner.recordsOutcomes || this.callRunning(id)) continue + if (!owner.recordsOutcomes || this.callRunning(id, owner)) continue const outbox = owner.outbox! // A row that cannot be decoded is still there. if (await outbox.has(id)) continue @@ -998,20 +998,23 @@ export class OfflineExecutor { } } - /** Whether an executor over these Collections in this runtime runs its call. */ - private callRunning(id: string): boolean { + /** + * Whether an executor in this runtime over the waiter owner's Collections + * runs the write's call; replacements may each add other Collections. + */ + private callRunning(id: string, owner: OfflineExecutor): boolean { if (this.issued.has(id)) return true - for (const collection of Object.values(this.config.collections)) { + for (const collection of Object.values(owner.config.collections)) { for (const issuer of callIssuers.get(collection) ?? []) if ( issuer.issued.has(id) && (retainsCollections( - this.config.collections, issuer.config.collections, + owner.config.collections, ) || retainsCollections( + owner.config.collections, issuer.config.collections, - this.config.collections, )) ) return true diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index e21eb12d66..eaf357404b 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -40,6 +40,8 @@ export class TransactionExecutor { >() // The replay of the current term, which admissions wait for. private replay: Promise | null = null + // The leadership term whose replay last completed. + private replayedTerm: number | undefined | null = null private cleanupTimer: ReturnType | null = null private cleanupAttempts = 0 private cleaning = false @@ -392,8 +394,10 @@ export class TransactionExecutor { } } await this.outbox.remove(transaction.id) - await this.offlineExecutor.finishRunningRemoval?.(transaction.id) + // The call stops counting as running before its marker is looked up, + // so a removal that registers a marker afterwards sees it finished. this.scheduler.markCompleted(transaction) + await this.offlineExecutor.finishRunningRemoval?.(transaction.id) return true } catch (error) { const storageError = toError(error) @@ -440,15 +444,18 @@ export class TransactionExecutor { finish = resolve }) this.replay = replay + const term = this.offlineExecutor.leadershipTerm try { - await this.loadPending() + if (await this.loadPending()) this.replayedTerm = term } finally { if (this.replay === replay) this.replay = null finish() } } - private async loadPending(): Promise { + /** False when the read was stale for this term and changed nothing. */ + private async loadPending(): Promise { + let reconciled = false let removedIds: Array = [] // Rows a former leader decided to reject: settled here, never sent. let decided: Array = [] @@ -514,6 +521,7 @@ export class TransactionExecutor { // Schedule retry timer for loaded transactions this.scheduleNextRetry() + reconciled = true }, this.offlineExecutor.recordsOutcomes ? decisions : undefined, ) @@ -548,6 +556,7 @@ export class TransactionExecutor { `Transaction excluded by beforeRetry`, ) await Promise.all(removedIds.map((id) => cleanUp(id, exclusion, false))) + return reconciled } /** Records and removes one excluded write; false when that failed. */ @@ -664,8 +673,13 @@ export class TransactionExecutor { // A read that the transaction's removal overtakes returns null. One that // spans a change of leadership is dropped: another leader may have sent // the write, and this term's outbox load already has it if it remains. - await this.replay + // Every replay in flight finishes first, a newer one included. + while (this.replay) await this.replay const term = this.offlineExecutor.leadershipTerm + // Only a successful replay of this term has loaded its decisions; the + // admission is retried after a failed one. + if (this.offlineExecutor.isOfflineEnabled && this.replayedTerm !== term) + throw new Error(`The outbox replay for this leadership has not completed`) const transaction = await this.outbox.getCurrent(id) // A row this leader decided to reject, or loaded with a decision, is in // `excluding` and is settled, never sent. diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index ac19ce3718..c78dff3002 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -63,6 +63,7 @@ */ import fc from 'fast-check' import { expect, vi } from 'vitest' +import { createCollection } from '@tanstack/db' import { NonRetriableError } from '../src/types' import { forwardAssertionJudgment, @@ -239,6 +240,12 @@ const reachStates = [ `default-removal-failure-reported`, // An unreadable decision with no row did not stop a replay. `orphan-decision-ignored`, + // An added message after a failed replay was refused, not sent. + `admission-refused-after-failed-replay`, + // An added message waited for a newer replay of the same tab. + `admission-waited-for-newer-replay`, + // Replacements that each added a Collection still saw an issued call. + `issued-call-across-extended-replacements`, // Removing a write whose call succeeded but whose row stayed completed it. `removed-after-success-completed`, // A leader's own write removed while its call ran stayed pending across a @@ -316,6 +323,9 @@ type SharedActionType = | `removal-pending-replay-lost` | `default-removal-delete-fails` | `unreadable-orphan-decision` + | `added-after-failed-replay` + | `added-across-replays` + | `replaced-twice-extended` | `remove-own-running` | `remove-own-rejected-running` | `replace-default-with-durable` @@ -396,6 +406,9 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`removal-pending-replay-lost`) }, { weight: 1, arbitrary: sharedAction(`default-removal-delete-fails`) }, { weight: 1, arbitrary: sharedAction(`unreadable-orphan-decision`) }, + { weight: 1, arbitrary: sharedAction(`added-after-failed-replay`) }, + { weight: 1, arbitrary: sharedAction(`added-across-replays`) }, + { weight: 1, arbitrary: sharedAction(`replaced-twice-extended`) }, { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, @@ -477,6 +490,9 @@ const spliced = ( action.type !== `removal-pending-replay-lost` && action.type !== `default-removal-delete-fails` && action.type !== `unreadable-orphan-decision` && + action.type !== `added-after-failed-replay` && + action.type !== `added-across-replays` && + action.type !== `replaced-twice-extended` && action.type !== `remove-own-running` && action.type !== `remove-own-rejected-running` && action.type !== `replace-default-with-durable` && @@ -749,8 +765,21 @@ class ReadFailingStorage extends FakeStorageAdapter { // Another adapter object over the same stored data. class StorageView implements StorageAdapter { constructor(private readonly target: StorageAdapter) {} - get(key: string) { - return this.target.get(key) + // Reads of this tab only that capture their value, then wait for release. + private readHolds = 0 + private readonly heldReads: Array<() => void> = [] + holdNextRead(): void { + this.readHolds += 1 + } + releaseRead(): void { + this.heldReads.shift()?.() + } + async get(key: string) { + if (this.readHolds === 0) return this.target.get(key) + this.readHolds -= 1 + const value = await this.target.get(key) + await new Promise((release) => this.heldReads.push(release)) + return value } set(key: string, value: string) { return this.target.set(key, value) @@ -766,6 +795,16 @@ class StorageView implements StorageAdapter { } } +// A Collection a replacement executor registers in addition. +function extraCollection(id: string) { + return createCollection<{ id: string }, string, {}>({ + id, + getKey: (item) => item.id, + startSync: true, + sync: { sync: ({ markReady }) => markReady() }, + }) +} + type ChannelMessage = { type: string; id?: string; error?: unknown } function controlledChannels() { @@ -778,10 +817,12 @@ function controlledChannels() { lostIds: [] as Array, created: 0, } + // Only channels with the sender's name hear it, as with BroadcastChannel. const deliver = (from: ControlledChannel | null, data: ChannelMessage) => { const copy = structuredClone(data) + const name = from?.name ?? CHANNEL for (const channel of open) { - if (channel === from) continue + if (channel === from || channel.name !== name) continue setTimeout(() => { if (open.has(channel)) channel.onmessage?.({ data: copy }) }, 0) @@ -790,7 +831,8 @@ function controlledChannels() { class ControlledChannel { onmessage: ((event: { data: ChannelMessage }) => void) | null = null constructor(readonly name: string) { - expect(name, `channel name`).toBe(CHANNEL) + // A tab that registers more Collections names a longer channel. + expect(name.startsWith(CHANNEL), `channel name`).toBe(true) state.created += 1 open.add(this) } @@ -893,6 +935,8 @@ async function runHistory( env: ReturnType election: TabElection session: number + // This tab's own way to the stored data. + view: StorageView } const tabs: Array = Array.from({ length: TABS }) let sessions = 0 @@ -911,11 +955,14 @@ async function runHistory( tabStorage: StorageAdapter = storage, // A durable tab in a default-mode history. durableTab = durable, + // Collections a replacement registers beyond the shared one. + extra?: Record>, ) => { + const view = new StorageView(tabStorage) const tabElection = new TabElection(election, hold, failStart === true) const session = ++sessions const env = createTestOfflineEnvironment({ - storage: tabStorage as FakeStorageAdapter, + storage: view as unknown as FakeStorageAdapter, // Each tab names its collection differently under the shared key. collectionId: `items-${session}`, collection, @@ -943,6 +990,7 @@ async function runHistory( }, config: { ...(durableTab ? { followerWrites: `durable` } : {}), + ...(extra ? { collections: extra } : {}), leaderElection: tabElection, onlineDetector: online.detector(), beforeRetry: ( @@ -955,7 +1003,7 @@ async function runHistory( jitter: false, } as never, }) - tabs[index] = { env, election: tabElection, session } + tabs[index] = { env, election: tabElection, session, view } await beforeInit?.() if (failStart) { await expect( @@ -2515,7 +2563,10 @@ async function runHistory( reach(`adopted-decision-survived`) break } - case `replaced-twice-during-call`: { + case `replaced-twice-during-call`: + case `replaced-twice-extended`: { + // Each replacement may also add a Collection of its own. + const extended = action.type === `replaced-twice-extended` // A follower's executor is replaced; the replacement leads and // issues the write's rejected call; the row is removed and that // replacement is replaced in turn while the call runs. @@ -2534,7 +2585,16 @@ async function runHistory( if (!write) break const collection = tabs[writer]!.env.collection await closeTab(writer) - await openTab(writer, undefined, undefined, false, collection) + await openTab( + writer, + undefined, + undefined, + false, + collection, + storage, + durable, + extended ? { zfirst: extraCollection(`first-extra`) } : undefined, + ) await rotateTo(tabs[writer]!.election) let release!: () => void callGate = new Promise((resolve) => { @@ -2552,7 +2612,16 @@ async function runHistory( write.transactionId!, ) await closeTab(writer) - await openTab(writer, undefined, undefined, false, collection) + await openTab( + writer, + undefined, + undefined, + false, + collection, + storage, + durable, + extended ? { zsecond: extraCollection(`second-extra`) } : undefined, + ) expect(write.outcome, `${write.id} waits for its issued call`).toBe( undefined, ) @@ -2561,7 +2630,17 @@ async function runHistory( expect(write.outcome, `${write.id} takes the server's outcome`).toBe( `failed`, ) - reach(`issued-call-across-replacements`) + reach( + extended + ? `issued-call-across-extended-replacements` + : `issued-call-across-replacements`, + ) + // A tab over more Collections names its own channel; a tab over + // the shared one takes its place. + if (extended) { + await closeTab(writer) + await openTab(writer) + } break } case `running-removal-completes-first`: { @@ -2804,6 +2883,107 @@ async function runHistory( reach(`orphan-decision-ignored`) break } + case `added-after-failed-replay`: { + // A committed removal's deletion fails; the next leader's replay + // fails to read the row, and an added message for it arrives. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if ( + !durable || + leader < 0 || + writer < 0 || + tabs.filter(Boolean).length < 3 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.failDeletes = 1 + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + storage.failReadKey = `tx:${write.transactionId}` + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + const failed = election.holder! + online.set(true) + expectedWarnings.admission += 1 + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + expect(calls, `${write.id} not admitted`).not.toContain(write.id) + // Another leader's replay settles the row. + failed.releaseLeadership() + await settle() + await failed.requestLeadership() + await original.requestLeadership() + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + reach(`admission-refused-after-failed-replay`) + break + } + case `added-across-replays`: { + // A committed removal's deletion fails. The next leader's replay + // stalls while an added message waits on it; that tab loses and + // regains leadership, and its newer replay stalls too. + const leader = leaderIndex() + const next = election.queue[0] + const nextTab = tabs.findIndex((tab) => tab?.election === next) + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && index !== nextTab, + ) + if ( + !durable || + leader < 0 || + nextTab < 0 || + writer < 0 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.failDeletes = 1 + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + write.removed = true + write.deliverable = false + const view = tabs[nextTab]!.view + view.holdNextRead() + // The first leader steps out of the election meanwhile. + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + online.set(true) + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + // The tab in between adopts the decision; its deletion stalls. + storage.holdNextDelete() + next!.releaseLeadership() + await settle() + view.holdNextRead() + await next!.requestLeadership() + tabs[writer]!.election.releaseLeadership() + await settle() + await tabs[writer]!.election.requestLeadership() + expect(election.holder, `the stalled tab leads again`).toBe(next) + view.releaseRead() + await settle() + expect(calls, `${write.id} not admitted`).not.toContain(write.id) + view.releaseRead() + await settle() + storage.releaseDelete() + await settle() + await original.requestLeadership() + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + reach(`admission-waited-for-newer-replay`) + break + } case `remove-deletion-pending`: { // The leader sends a follower's write and fails to delete its row. // Offline, the next leader loads that row, and it is removed. @@ -3726,6 +3906,24 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `unreadable-orphan-decision` }]), }, + { + name: `an added message after a failed replay is refused`, + enters: [`admission-refused-after-failed-replay`], + build: (generated: History): History => + spliced(generated, [{ type: `added-after-failed-replay` }]), + }, + { + name: `an added message waits for a newer replay`, + enters: [`admission-waited-for-newer-replay`], + build: (generated: History): History => + spliced(generated, [{ type: `added-across-replays` }]), + }, + { + name: `replacements that add Collections still see an issued call`, + enters: [`issued-call-across-extended-replacements`], + build: (generated: History): History => + spliced(generated, [{ type: `replaced-twice-extended` }]), + }, { name: `removing a write whose call succeeded completes it`, enters: [`removed-after-success-completed`], From e693616d495ff8c1f442781818cbaa4631061301 Mon Sep 17 00:00:00 2001 From: daveycodez Date: Thu, 26 Nov 2026 15:57:08 -0800 Subject: [PATCH 14/16] fix(offline-transactions): address twelfth durable follower write review - A leader whose replay failed replays again when connectivity changes, before it retries the admissions the failed replay refused. - A replay that outlives its leadership term no longer marks that older term as replayed, so admission stays open for the newer one. - Overlapping removals of a running write each keep their running marker, and the call's completion withdraws all of them. - An outcome lookup lists the records again when one it listed was withdrawn meanwhile, so a rejection recorded after the listing is read. An unreadable record no longer aborts the lookup: an intact rejection still wins, and otherwise the writer keeps waiting. Pruning skips unreadable records. - A decision whose stored error is missing or malformed keeps the fallback error instead of breaking the replay. - A removed running write whose call fails with a retryable error records that error for its writer and withdraws its running marker; a failed record is retried without calling the provider again. - The guide limits the no-BroadcastChannel fallback to followers. The durable follower oracle fails a replay and then reconnects, lets a replay outlive its term, removes a running write twice, records a rejection after its writer listed the records, stores an unreadable record or a decision with no error, and fails a removed running write's call retryably. It also checks that a running marker exists before the call is released and is gone afterwards, that a removed row is gone before the call settles, that a kept record holds the expected rejection, and that a failed cleanup's decision actually stalled. The test harness refuses a reused collection without its own provider. --- docs/contributing/oracle-coverage.md | 8 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 30 +- .../src/executor/TransactionExecutor.ts | 29 +- .../src/outbox/OutboxManager.ts | 66 ++- .../durable-follower-oracle.property.test.ts | 518 +++++++++++++++++- .../offline-transactions/tests/harness.ts | 3 + 7 files changed, 606 insertions(+), 50 deletions(-) diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index c3b8975a88..e3edf33d5e 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4260,8 +4260,12 @@ The post-merge review added three missing domains to existing owners: exclusion, a write removed before it was sent, a save acknowledged after a handover, a faulted former leader that saves for its successor, a failed start, a save that ends after its tab closed, and tabs that name their - collections differently under one key. It does not cover real browser - contexts. + collections differently under one key. It also covers a failed replay + that runs again on connectivity, a replay that outlives its term, + overlapping removals of a running write, a rejection recorded after its + writer listed the outcome records, unreadable outcome records and + decisions, and a removed running write whose call fails with a retryable + error. It does not cover real browser contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 1cb127a251..9400a7ad11 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel, and a tab without it uses the online path. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel: a follower without it uses the online path, while a tab that leads still saves its own writes to the outbox. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending, and a leader whose outbox replay failed replays again when connectivity changes. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 4ed885e8c3..70706884d8 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -134,8 +134,9 @@ export class OfflineExecutor { private readonly saving = new Map() // Ids whose call this executor is running. private readonly issued = new Set() - // Running markers this leader recorded for removed writes, by id. - private readonly runningRemovals = new Map() + // Running markers this leader recorded for removed writes, by id; each + // overlapping removal leaves its own. + private readonly runningRemovals = new Map>() // Removals this follower asked the leader for, by request. private readonly removals = new Map< string, @@ -326,6 +327,11 @@ export class OfflineExecutor { if (this.reconcileFailed) this.reconcileFollowerWrites() if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays() + // A failed replay of this term runs again; admissions wait for it. + if (this.executor.replayFailed) + this.loadAndReplayTransactions().catch((error) => { + console.warn(`Failed to load and replay transactions:`, error) + }) this.retryAdmissions() void this.executor.retryFailedCleanups() @@ -1136,9 +1142,11 @@ export class OfflineExecutor { ? await outbox.recordPending(id) : undefined if (token !== undefined) { - if (this.scheduler.isRunning(id)) - this.runningRemovals.set(id, token) - else await outbox.withdrawOutcome(id, token).catch(() => {}) + if (this.scheduler.isRunning(id)) { + let tokens = this.runningRemovals.get(id) + if (!tokens) this.runningRemovals.set(id, (tokens = new Set())) + tokens.add(token) + } else await outbox.withdrawOutcome(id, token).catch(() => {}) } await outbox.remove(id) if (this.saving.has(id)) this.saving.set(id, true) @@ -1200,12 +1208,16 @@ export class OfflineExecutor { return yielded } - /** Withdraws the running marker of a removed write whose call finished. */ + /** Withdraws the running markers of a removed write whose call finished. */ async finishRunningRemoval(id: string): Promise { - const token = this.runningRemovals.get(id) - if (token === undefined) return + const tokens = this.runningRemovals.get(id) + if (!tokens) return this.runningRemovals.delete(id) - await this.outbox!.withdrawOutcome(id, token).catch(() => {}) + await Promise.all( + [...tokens].map((token) => + this.outbox!.withdrawOutcome(id, token).catch(() => {}), + ), + ) } async peekOutbox(): Promise> { diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index eaf357404b..cebfa86d84 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -326,9 +326,17 @@ export class TransactionExecutor { // Public removal can finish while the named mutation function runs. // The removed row cannot be retried, but its caller still owns the // provider failure and later queued work must be able to run. + // A writer in another tab reads the error from its record, as for a + // rejection, and the running marker goes; a failed record is retried + // without calling the provider again. if (persistError instanceof OutboxTransactionNotFoundError) { - this.scheduler.markCompleted(transaction) - this.offlineExecutor.rejectTransaction(transaction.id, error) + const failed: OfflineTransaction = { + ...updatedTransaction, + outboxPhase: `rejection-pending`, + } + this.scheduler.updateTransaction(failed) + if (await this.removeSettledTransaction(failed, false)) + this.offlineExecutor.rejectTransaction(transaction.id, error) return } throw persistError @@ -446,13 +454,28 @@ export class TransactionExecutor { this.replay = replay const term = this.offlineExecutor.leadershipTerm try { - if (await this.loadPending()) this.replayedTerm = term + // A replay that outlived its term must not reopen admission for an + // older one. + if ( + (await this.loadPending()) && + term === this.offlineExecutor.leadershipTerm + ) + this.replayedTerm = term } finally { if (this.replay === replay) this.replay = null finish() } } + /** Whether this term's replay failed and none is running. */ + get replayFailed(): boolean { + return ( + this.offlineExecutor.isOfflineEnabled && + this.replay === null && + this.replayedTerm !== this.offlineExecutor.leadershipTerm + ) + } + /** False when the read was stale for this term and changed nothing. */ private async loadPending(): Promise { let reconciled = false diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index 08fd29ec35..c2548fec82 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -30,6 +30,33 @@ export type OutboxOutcome = { */ export const OUTCOME_RETENTION_MS = 7 * 24 * 60 * 60 * 1000 +/** A stored error, or undefined when the value does not hold one. */ +function readError( + value: unknown, +): { name: string; message: string } | undefined { + if (typeof value !== `object` || value === null) return undefined + const { name, message } = value as Record + return typeof name === `string` && typeof message === `string` + ? { name, message } + : undefined +} + +/** A stored outcome, or undefined when it cannot be read. */ +function readOutcome(data: string): OutboxOutcome | undefined { + let value: unknown + try { + value = JSON.parse(data) + } catch { + return undefined + } + if (typeof value !== `object` || value === null) return undefined + const { error, pending, at } = value as Record + if (typeof at !== `number`) return undefined + const recorded = readError(error) + if (recorded) return { error: recorded, at } + return pending === true ? { pending: true, at } : undefined +} + export class OutboxManager { private storage: StorageAdapter private serializer: TransactionSerializer @@ -159,17 +186,28 @@ export class OutboxManager { await this.storage.delete(`${this.outcomeKeyPrefix(id)}${token}`) } - /** A rejection if any recording holds one, else a running marker. */ + /** + * A rejection if any recording holds one, else a running marker. A record + * that cannot be read leaves the outcome unknown, so it reads as running. + */ async getOutcome(id: string): Promise { - let found: OutboxOutcome | null = null - for (const key of await this.outcomeKeys(id)) { - const data = await this.storage.get(key) - if (data === null) continue - const outcome = JSON.parse(data) as OutboxOutcome - if (outcome.error) return outcome - found = outcome + for (;;) { + let found: OutboxOutcome | null = null + let withdrawn = false + for (const key of await this.outcomeKeys(id)) { + const data = await this.storage.get(key) + // A marker is withdrawn only after any rejection that replaces it + // is recorded, so a listing that lost a record is taken again. + if (data === null) { + withdrawn = true + continue + } + const outcome = readOutcome(data) ?? { pending: true, at: 0 } + if (outcome.error) return outcome + found = outcome + } + if (!withdrawn) return found } - return found } async removeOutcome(id: string): Promise { @@ -185,8 +223,8 @@ export class OutboxManager { ) for (const key of keys) { const data = await this.storage.get(key) - if (data !== null && (JSON.parse(data) as OutboxOutcome).at < before) - await this.storage.delete(key) + const outcome = data === null ? undefined : readOutcome(data) + if (outcome && outcome.at < before) await this.storage.delete(key) } } @@ -288,9 +326,9 @@ export class OutboxManager { try { const data = await this.storage.get(key) if (data === null) continue - error = ( - JSON.parse(data) as { error: { name: string; message: string } } - ).error + error = + readError((JSON.parse(data) as { error?: unknown }).error) ?? + error } catch { // The unread decision still rejects its row. } diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index c78dff3002..c05565877b 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -15,8 +15,8 @@ * and every other write completes. Only the leader sends a durable write. When * a settlement message is lost, the outcome the leader recorded settles the * waiter at the next leader's outbox check, with the server's error for a - * rejected write. A leader that cannot read a saved write tries again when - * connectivity changes. Stale and duplicate channel messages change nothing. + * rejected write. A leader that cannot read a saved write, or whose replay + * failed, tries again when connectivity changes. Stale and duplicate channel messages change nothing. * A write made before its tab initializes, and in online mode a follower's * write, uses the online path: the writing tab sends it, and offline it fails * and is never sent. @@ -38,7 +38,11 @@ * runs, from any tab, resume an exclusion cleanup after its leadership ended, * replace a disposed writer's executor over the same collection, and, in the * default mode, let another - * leader reject a former leader's saved write. + * leader reject a former leader's saved write. Others fail a new leader's + * replay and then reconnect, let a replay outlive its term, remove a running + * write twice, record a rejection after its writer listed the outcome + * records, store an unreadable outcome record or a decision with no error, + * and fail a removed running write's call with a retryable error. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. @@ -257,6 +261,26 @@ const reachStates = [ // In the default mode, a write another leader rejected stayed pending in // its former leader, which cannot tell a rejection from a success. `former-leader-write-unresolved`, + // A leader whose replay failed replayed again on connectivity and sent a + // saved write without a handover. + `replay-retried-on-connectivity`, + // A replay that finished after a newer replay of the same tab left + // admission open for the newer term. + `stale-replay-kept-newer-term`, + // Two removals of one running write each left a marker, and the call's + // completion withdrew both. + `overlapping-markers-retired`, + // A rejection recorded after a writer listed the outcome records still + // failed that writer. + `rejection-recorded-after-listing`, + // An unreadable outcome record before an intact rejection still failed + // the writer. + `rejection-read-past-unreadable-record`, + // A decision with no readable error still settled its row. + `decision-without-error-settled`, + // A removed running write whose call failed with a retryable error failed + // its writer through the recorded error. + `removed-retryable-failure-recorded`, ] as const type ReachState = (typeof reachStates)[number] @@ -329,6 +353,13 @@ type SharedActionType = | `remove-own-running` | `remove-own-rejected-running` | `replace-default-with-durable` + | `replay-fails-then-reconnects` + | `stale-replay-across-terms` + | `overlapping-running-removals` + | `rejection-after-outcome-listing` + | `unreadable-outcome-before-rejection` + | `decision-without-error` + | `remove-running-retryable` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -412,6 +443,13 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`remove-own-running`) }, { weight: 1, arbitrary: sharedAction(`remove-own-rejected-running`) }, { weight: 1, arbitrary: sharedAction(`replace-default-with-durable`) }, + { weight: 1, arbitrary: sharedAction(`replay-fails-then-reconnects`) }, + { weight: 1, arbitrary: sharedAction(`stale-replay-across-terms`) }, + { weight: 1, arbitrary: sharedAction(`overlapping-running-removals`) }, + { weight: 1, arbitrary: sharedAction(`rejection-after-outcome-listing`) }, + { weight: 1, arbitrary: sharedAction(`unreadable-outcome-before-rejection`) }, + { weight: 1, arbitrary: sharedAction(`decision-without-error`) }, + { weight: 1, arbitrary: sharedAction(`remove-running-retryable`) }, { weight: 1, arbitrary: sharedAction(`replace-writer`) }, { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, { weight: 1, arbitrary: tabAction(`remove-running`) }, @@ -498,6 +536,13 @@ const spliced = ( action.type !== `replace-default-with-durable` && action.type !== `replace-writer` && action.type !== `replace-rejected-writer` && + action.type !== `replay-fails-then-reconnects` && + action.type !== `stale-replay-across-terms` && + action.type !== `overlapping-running-removals` && + action.type !== `rejection-after-outcome-listing` && + action.type !== `unreadable-outcome-before-rejection` && + action.type !== `decision-without-error` && + action.type !== `remove-running-retryable` && action.type !== `remove-running`, ) .slice(0, MAX_ACTIONS - prefix.length), @@ -658,6 +703,10 @@ class ReadFailingStorage extends FakeStorageAdapter { this.heldDelete?.release() this.heldDelete = undefined } + // Whether a held row deletion reached its gate. + deleteHeld(): boolean { + return this.heldDelete !== null && this.heldDelete !== undefined + } // The next removal decision write fails, or waits for release: before it // lands, or after. failDecisionWrites = 0 @@ -787,8 +836,25 @@ class StorageView implements StorageAdapter { delete(key: string) { return this.target.delete(key) } - keys() { - return this.target.keys() + // Key listings of this tab only that are taken at once, then wait for + // release. + private keyHolds = 0 + private readonly heldKeys: Array<() => void> = [] + holdNextKeys(): void { + this.keyHolds += 1 + } + keysHeld(): boolean { + return this.heldKeys.length > 0 + } + releaseKeys(): void { + this.heldKeys.shift()?.() + } + async keys() { + if (this.keyHolds === 0) return this.target.keys() + this.keyHolds -= 1 + const listed = await this.target.keys() + await new Promise((release) => this.heldKeys.push(release)) + return listed } clear() { return this.target.clear() @@ -902,6 +968,8 @@ type Write = { recordRetried?: boolean // Another leader settled it in the default mode; its tab cannot tell how. unresolved?: boolean + // It fails with this error rather than a rejection from the server. + failure?: string outcome?: `completed` | `failed` error?: unknown } @@ -928,6 +996,8 @@ async function runHistory( // Which tab called the server for each write, and which tab led then. const sends: Array<{ id: string; sender: number; leader?: number }> = [] const rejected = new Set() + // Writes whose next server call fails with a retryable error. + const retryable = new Set() // Writes a new leader's beforeRetry excludes, by write id. const excluded = new Set() const expectedWarnings = { admission: 0, check: 0 } @@ -982,6 +1052,7 @@ async function runHistory( callGate = null return gate.then(() => { if (rejected.has(id)) throw new NonRetriableError(`rejected ${id}`) + if (retryable.delete(id)) throw new Error(`retry ${id}`) return { ok: true } }) } @@ -1031,6 +1102,21 @@ async function runHistory( expect(() => tab.env.executor.dispose(), `close tab ${index}`).not.toThrow() await settle() } + // The outcome records stored for a transaction. + const outcomesOf = async (transactionId: string) => { + const prefix = `outcome:${encodeURIComponent(transactionId)}:` + return Promise.all( + (await storage.keys()) + .filter((key) => key.startsWith(prefix)) + .map( + async (key) => + JSON.parse((await storage.get(key))!) as { + error?: { name: string; message: string } + pending?: true + }, + ), + ) + } const isUnsent = (write: Write) => write.deliverable && !calls.includes(write.id) const leaderIndex = () => @@ -1822,6 +1908,10 @@ async function runHistory( await tabs[remover]!.env.executor.removeFromOutbox( write.transactionId!, ) + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id}'s row is gone`, + ).toBe(null) expect(write.outcome, `${write.id} waits for its call`).toBe( undefined, ) @@ -2213,6 +2303,10 @@ async function runHistory( const original = tabs[leader]!.election original.releaseLeadership() await settle() + expect( + storage.decisionHeld(), + `the exclusion's decision stalls`, + ).toBe(true) await original.requestLeadership() excluded.delete(write.id) next.releaseLeadership() @@ -2671,17 +2765,38 @@ async function runHistory( break } storage.holdNextDelete() + let removed = false const removal = tabs[leader]!.env.executor.removeFromOutbox( write.transactionId!, - ) + ).then(() => { + removed = true + }) await settle() + expect(storage.deleteHeld(), `${write.id}'s deletion stalls`).toBe( + true, + ) + expect(removed, `the removal waits for its deletion`).toBe(false) + expect( + (await outcomesOf(write.transactionId!)).some( + ({ pending }) => pending, + ), + `${write.id} has a running marker`, + ).toBe(true) channels.state.loseSettlement = true release() await settle() channels.state.loseSettlement = false + expect( + channels.state.lostIds, + `${write.id}'s settlement was lost`, + ).toContain(write.transactionId) storage.releaseDelete() await removal await settle() + expect( + await outcomesOf(write.transactionId!), + `${write.id}'s marker is gone`, + ).toEqual([]) channels.inject({ type: `leader` }) await settle() expect(write.outcome, `${write.id} completes`).toBe(`completed`) @@ -2910,11 +3025,14 @@ async function runHistory( original.releaseLeadership() await settle() const failed = election.holder! - online.set(true) expectedWarnings.admission += 1 channels.inject({ type: `added`, id: write.transactionId }) await settle() expect(calls, `${write.id} not admitted`).not.toContain(write.id) + // Connectivity runs the failed replay again before the admission. + online.set(true) + await settle() + expect(calls, `${write.id} still not sent`).not.toContain(write.id) // Another leader's replay settles the row. failed.releaseLeadership() await settle() @@ -2984,6 +3102,302 @@ async function runHistory( reach(`admission-waited-for-newer-replay`) break } + case `replay-fails-then-reconnects`: { + // The next leader's replay fails to read a follower's saved write, + // an added message for it is refused, and connectivity returns + // while the same tab leads. + const leader = leaderIndex() + const next = election.queue[0] + const nextTab = tabs.findIndex((tab) => tab?.election === next) + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && index !== nextTab, + ) + if ( + !durable || + leader < 0 || + nextTab < 0 || + writer < 0 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + storage.failReadKey = `tx:${write.transactionId}` + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + expect(storage.failReadKey, `the replay read failed`).toBe(undefined) + // The new leader has not read the write, so it does not show it. + write.unadmittedBy = tabs[nextTab]!.session + expectedWarnings.admission += 1 + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + expect(calls, `${write.id} refused before a replay`).not.toContain( + write.id, + ) + online.set(true) + await settle() + write.unadmittedBy = undefined + expect(election.holder, `the same tab leads`).toBe(next) + expect(calls, `${write.id} sent after reconnecting`).toContain( + write.id, + ) + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`replay-retried-on-connectivity`) + await original.requestLeadership() + await settle() + break + } + case `stale-replay-across-terms`: { + // The next leader's replay stalls on an exclusion's decision; that + // tab loses and regains leadership, and its newer replay finishes + // first. The stalled replay then finishes, and a follower writes. + const leader = leaderIndex() + const next = election.queue[0] + const nextTab = tabs.findIndex((tab) => tab?.election === next) + const writer = tabs.findIndex( + (tab, index) => tab && index !== leader && index !== nextTab, + ) + if ( + !durable || + leader < 0 || + nextTab < 0 || + writer < 0 || + !(await quiet()) + ) + break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + excluded.add(write.id) + write.excluded = true + write.deliverable = false + storage.holdNextDecision() + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + expect( + storage.decisionHeld(), + `the exclusion's decision stalls`, + ).toBe(true) + await original.requestLeadership() + // Leadership goes round to the stalled tab again; a tab in between + // settles the exclusion. + await rotateTo(next!) + expect(write.outcome, `${write.id} excluded`).toBe(`failed`) + online.set(true) + await settle() + storage.releaseDecision() + await settle() + const later = await doWrite(writer, `write`) + expect(calls, `${later?.id} sent in the newer term`).toContain( + later?.id, + ) + reach(`stale-replay-kept-newer-term`) + break + } + case `overlapping-running-removals`: { + // The leader removes a follower's running write twice. The first + // removal's deletion stalls, the call succeeds, and its message is + // lost. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + const executor = tabs[leader]!.env.executor + storage.holdNextDelete() + const first = executor.removeFromOutbox(write.transactionId!) + await settle() + expect(storage.deleteHeld(), `the first deletion stalls`).toBe(true) + await executor.removeFromOutbox(write.transactionId!) + expect( + (await outcomesOf(write.transactionId!)).filter( + ({ pending }) => pending, + ), + `${write.id} has a marker per removal`, + ).toHaveLength(2) + channels.state.loseSettlement = true + release() + await settle() + channels.state.loseSettlement = false + storage.releaseDelete() + await first + await settle() + expect( + await outcomesOf(write.transactionId!), + `${write.id}'s markers are gone`, + ).toEqual([]) + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`overlapping-markers-retired`) + break + } + case `rejection-after-outcome-listing`: { + // The leader removes a follower's running write that the server + // rejects. The writer lists the outcome records; the rejection then + // lands, the running marker goes, and the writer reads its listing. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write-rejected`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + const view = tabs[follower]!.view + view.holdNextKeys() + channels.inject({ type: `leader` }) + await settle() + expect(view.keysHeld(), `the writer listed the records`).toBe(true) + channels.state.loseSettlement = true + release() + await settle() + channels.state.loseSettlement = false + view.releaseKeys() + await settle() + expect(write.outcome, `${write.id} takes the rejection`).toBe( + `failed`, + ) + reach(`rejection-recorded-after-listing`) + break + } + case `unreadable-outcome-before-rejection`: { + // An unreadable outcome record precedes the rejection of a + // follower's write, whose settlement message is lost. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(follower, `write-rejected`) + if (!write) break + await storage.set( + `outcome:${encodeURIComponent(write.transactionId!)}:0`, + `{not json`, + ) + channels.state.loseSettlement = true + online.set(true) + await settle() + channels.state.loseSettlement = false + expect(calls, `${write.id} sent`).toContain(write.id) + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} takes the rejection`).toBe( + `failed`, + ) + reach(`rejection-read-past-unreadable-record`) + break + } + case `decision-without-error`: { + // A follower's saved write has a decision that holds no error, and + // another tab leads and replays. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + await storage.set( + `decision:${encodeURIComponent(write.transactionId!)}:empty`, + `{}`, + ) + write.deliverable = false + write.failure = `Transaction rejected by a recorded decision` + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} settled as decided`).toBe(`failed`) + reach(`decision-without-error-settled`) + break + } + case `remove-running-retryable`: { + // The leader removes a follower's running write; the call then + // fails with a retryable error, and its message is lost. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + retryable.add(write.id) + write.rejected = true + write.failure = `retry ${write.id}` + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + channels.state.loseSettlement = true + release() + await settle() + channels.state.loseSettlement = false + channels.inject({ type: `leader` }) + await settle() + expect(write.outcome, `${write.id} takes the call's error`).toBe( + `failed`, + ) + reach(`removed-retryable-failure-recorded`) + break + } case `remove-deletion-pending`: { // The leader sends a follower's write and fails to delete its row. // Offline, the next leader loads that row, and it is removed. @@ -3308,20 +3722,33 @@ async function runHistory( .map((key) => decodeURIComponent(key.split(`:`)[1]!)) .filter((id, index, ids) => ids.indexOf(id) === index) .sort() + const orphans = writes.filter( + (write) => + durable && + !write.preInit && + (write.excluded || + write.removed || + (write.deliverable && write.rejected)) && + write.outcome === undefined, + ) expect(outcomes, `outcome records`).toEqual( - writes - .filter( - (write) => - durable && - !write.preInit && - (write.excluded || - write.removed || - (write.deliverable && write.rejected)) && - write.outcome === undefined, - ) - .map((write) => write.transactionId) - .sort(), + orphans.map((write) => write.transactionId).sort(), ) + // Each kept record holds the rejection its writer will read; a running + // marker alone would leave that writer waiting. + for (const write of orphans) { + const errors = (await outcomesOf(write.transactionId!)).map( + ({ error }) => error, + ) + expect(errors, `${write.id} kept rejection`).toContainEqual({ + name: `NonRetriableError`, + message: write.removed + ? `Transaction removed from the outbox` + : write.excluded + ? `Transaction excluded by beforeRetry` + : `rejected ${write.id}`, + }) + } for (const write of writes) { if (!sessionsOpen.has(write.session)) continue if (write.unresolved) { @@ -3347,7 +3774,11 @@ async function runHistory( `Transaction excluded by beforeRetry`, ) } - if (write.rejected && write.deliverable) { + if (write.failure !== undefined) { + expect((write.error as Error).message, `${write.id} failure`).toBe( + write.failure, + ) + } else if (write.rejected && write.deliverable) { const error = write.error as Error expect(error, `${write.id} error type`).toBeInstanceOf( NonRetriableError, @@ -3374,7 +3805,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. A failed replay runs again on connectivity before a refused admission, a replay that outlives its term leaves admission to the newer one, every running marker of overlapping removals is withdrawn, a writer reads a rejection recorded after it listed the records, an unreadable record or decision never hides or blocks a rejection, and a removed running write whose call fails retryably fails its writer with that error. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -3417,6 +3848,9 @@ oracleProperty({ `src/outbox/OutboxManager.ts#OutboxManager.recordPending`, `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, `src/outbox/OutboxManager.ts#OutboxManager.outcomeKeys`, + `src/outbox/OutboxManager.ts#OutboxManager.pruneOutcomes`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.loadPendingTransactions`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.replayFailed`, ], histories: { arbitrary: historyArbitrary, @@ -3989,6 +4423,48 @@ oracleProperty({ true, ), }, + { + name: `a failed replay runs again on connectivity`, + enters: [`replay-retried-on-connectivity`], + build: (generated: History): History => + spliced(generated, [{ type: `replay-fails-then-reconnects` }]), + }, + { + name: `a stale replay leaves the newer term's admission open`, + enters: [`stale-replay-kept-newer-term`], + build: (generated: History): History => + spliced(generated, [{ type: `stale-replay-across-terms` }]), + }, + { + name: `overlapping removals of a running write retire both markers`, + enters: [`overlapping-markers-retired`], + build: (generated: History): History => + spliced(generated, [{ type: `overlapping-running-removals` }]), + }, + { + name: `a rejection recorded after the listing still fails its writer`, + enters: [`rejection-recorded-after-listing`], + build: (generated: History): History => + spliced(generated, [{ type: `rejection-after-outcome-listing` }]), + }, + { + name: `an unreadable outcome record does not hide a rejection`, + enters: [`rejection-read-past-unreadable-record`], + build: (generated: History): History => + spliced(generated, [{ type: `unreadable-outcome-before-rejection` }]), + }, + { + name: `a decision with no error still settles its row`, + enters: [`decision-without-error-settled`], + build: (generated: History): History => + spliced(generated, [{ type: `decision-without-error` }]), + }, + { + name: `a removed running write's retryable failure is recorded`, + enters: [`removed-retryable-failure-recorded`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-running-retryable` }]), + }, { name: `a write before initialization takes the online path`, enters: [`pre-initialization-write`], diff --git a/packages/offline-transactions/tests/harness.ts b/packages/offline-transactions/tests/harness.ts index e649f65db6..71d9a07044 100644 --- a/packages/offline-transactions/tests/harness.ts +++ b/packages/offline-transactions/tests/harness.ts @@ -219,6 +219,9 @@ export function createTestOfflineEnvironment( return { ok: true, mutations } } + // The default provider syncs only a Collection this environment made. + if (options.collection && !options.mutationFn) + throw new Error(`A reused collection needs its own mutationFn`) const mutationFn: TestMutationFn = options.mutationFn ?? defaultMutation const leader = new FakeLeaderElection() From d0dda25657d7aedd88c69e1e6b1ea79d02f32cde Mon Sep 17 00:00:00 2001 From: daveycodez Date: Thu, 26 Nov 2026 23:53:11 -0800 Subject: [PATCH 15/16] fix(offline-transactions): address thirteenth durable follower write review - A removal fences each unstarted write against admission and replay from its first step until it is decided, instead of excluding it only once its decision has landed. A removal that does not commit, or yields at a handover, releases the fence and reads the row again; a committed deletion releases it on success, so no exclusion is left behind. - A removal reads a row's phase without decoding its mutations, and a failed read is reported and keeps the row instead of treating a sent write as unsent. - When a removal took a running write's row, its outcome is published outside the send queue: a failed rejection record is retried on a timer and on connectivity whichever tab leads, and the running marker stays until the record lands. - A connectivity change during a follower's outbox check starts another check, so a failure that check records later is not left until the next change. - An unreadable decision no longer replaces a readable decision's error. - The guide states that a write whose tab closes before announcing its save waits for the next leader's replay. The durable follower oracle delivers an added message while an unsent write's removal is decided, fails a removed running write's error record before its leader stops leading, changes connectivity during an outbox check that then fails, fails a removal's phase read, and stores a readable decision beside an unreadable one. It credits a retried rejection record only when a record attempt for that write failed and a later one landed, and a lost-settlement recovery only when a writer that still waited after the loss then settled with the expected outcome. --- docs/contributing/oracle-coverage.md | 7 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 108 +++--- .../src/executor/TransactionExecutor.ts | 142 +++++-- .../src/outbox/OutboxManager.ts | 44 ++- .../durable-follower-oracle.property.test.ts | 351 +++++++++++++++++- 6 files changed, 562 insertions(+), 92 deletions(-) diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index e3edf33d5e..746622f388 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4265,7 +4265,12 @@ The post-merge review added three missing domains to existing owners: overlapping removals of a running write, a rejection recorded after its writer listed the outcome records, unreadable outcome records and decisions, and a removed running write whose call fails with a retryable - error. It does not cover real browser contexts. + error. It also covers an added message while an unsent write's removal is + being decided, a removed running write whose error record fails before its + leader stops leading, a connectivity change during an outbox check that + then fails, a failed read of a sent row's phase during its removal, and a + readable decision beside an unreadable one. It does not cover real browser + contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) and diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index 9400a7ad11..ee2c26d018 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. The follower's transaction settles with the leader's result. This requires BroadcastChannel: a follower without it uses the online path, while a tab that leads still saves its own writes to the outbox. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending, and a leader whose outbox replay failed replays again when connectivity changes. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. A write whose tab closes before it can tell the current leader about the save waits for the next leader's replay. The follower's transaction settles with the leader's result. This requires BroadcastChannel: a follower without it uses the online path, while a tab that leads still saves its own writes to the outbox. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending, and a leader whose outbox replay failed replays again when connectivity changes. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index 70706884d8..f28f916225 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -127,6 +127,7 @@ export class OfflineExecutor { private reconcileFailed = false // Only the newest outbox check sets or clears reconcileFailed. private sweeps = 0 + private sweepsRunning = 0 private outboxChannelName: string | null = null private initialized = false private term = 0 @@ -324,7 +325,11 @@ export class OfflineExecutor { } this.unsubscribeOnline = this.onlineDetector.subscribe(() => { - if (this.reconcileFailed) this.reconcileFollowerWrites() + // A check still running may yet fail; a new one reads after this change. + if (this.reconcileFailed || this.sweepsRunning > 0) + this.reconcileFollowerWrites() + // Outcomes of removed calls are recorded whichever tab leads. + this.executor?.retryPublications() if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays() // A failed replay of this term runs again; admissions wait for it. @@ -638,35 +643,40 @@ export class OfflineExecutor { if (!this.recordsOutcomes) return const sweep = ++this.sweeps let failed = false - // A predecessor this executor settles may have left saved writes; each is - // checked against the outbox its executor saved it to. - const waiters = this.relatedExecutors().flatMap((owner) => - [...owner.pendingTransactionPromises].map( - ([id, waiter]) => [owner, id, waiter] as const, - ), - ) - for (const [owner, id, waiter] of waiters) { - try { - if (!(await waiter.saved)) continue - // Absence means success only where rejections are recorded, and not - // while this runtime still runs the write's call. - if (!owner.recordsOutcomes || this.callRunning(id, owner)) continue - const outbox = owner.outbox! - // A row that cannot be decoded is still there. - if (await outbox.has(id)) continue - const outcome = await outbox.getOutcome(id) - // Its call is still running after a removal. - if (outcome?.pending) continue - const error = outcome?.error - // A record older than the retention window may have been pruned, so - // no record cannot mean success. - if (!error && Date.now() - waiter.savedAt! > OUTCOME_RETENTION_MS) - continue - owner.settleFollowerWrite(id, error && outboxMessageError(error)) - } catch (error) { - failed = true - console.warn(`Failed to reconcile follower writes:`, error) + this.sweepsRunning++ + try { + // A predecessor this executor settles may have left saved writes; each is + // checked against the outbox its executor saved it to. + const waiters = this.relatedExecutors().flatMap((owner) => + [...owner.pendingTransactionPromises].map( + ([id, waiter]) => [owner, id, waiter] as const, + ), + ) + for (const [owner, id, waiter] of waiters) { + try { + if (!(await waiter.saved)) continue + // Absence means success only where rejections are recorded, and not + // while this runtime still runs the write's call. + if (!owner.recordsOutcomes || this.callRunning(id, owner)) continue + const outbox = owner.outbox! + // A row that cannot be decoded is still there. + if (await outbox.has(id)) continue + const outcome = await outbox.getOutcome(id) + // Its call is still running after a removal. + if (outcome?.pending) continue + const error = outcome?.error + // A record older than the retention window may have been pruned, so + // no record cannot mean success. + if (!error && Date.now() - waiter.savedAt! > OUTCOME_RETENTION_MS) + continue + owner.settleFollowerWrite(id, error && outboxMessageError(error)) + } catch (error) { + failed = true + console.warn(`Failed to reconcile follower writes:`, error) + } } + } finally { + this.sweepsRunning-- } if (sweep === this.sweeps) this.reconcileFailed = failed } @@ -1101,18 +1111,19 @@ export class OfflineExecutor { /** * Removes saved transactions. A write that has not started fails with a * removal error, which a writer in another tab also reads from its record; - * a started call keeps the provider's outcome. - */ - /** - * Removes saved transactions; returns those it left to the next leader - * because it stopped leading before deciding them. + * a started call keeps the provider's outcome. Returns those it left to the + * next leader because it stopped leading before deciding them. */ private async removeSaved(ids: Array): Promise> { const outbox = this.outbox! + const executor = this.executor! const error = removedError() // Off the queue before any await, so this tab cannot start them // meanwhile; the one already running keeps the provider's outcome. const unstarted = new Set(this.scheduler.removePendingTransactions(ids)) + // Until its removal is decided, no admission or replay schedules an + // unstarted write again. + for (const id of unstarted) executor.fence(id) // A leader's removal yields if it stops leading before its decision is // recorded; the term only counts gains. const term = this.term @@ -1129,6 +1140,9 @@ export class OfflineExecutor { await Promise.all( ids.map(async (id) => { let committed = false + // A write whose removal did not commit is eligible again; the row is + // read again, so one another leader settled meanwhile is not queued. + let readmit = false try { if (!(await outbox.has(id))) { if (this.saving.has(id)) this.saving.set(id, true) @@ -1152,9 +1166,14 @@ export class OfflineExecutor { if (this.saving.has(id)) this.saving.set(id, true) return } - // A row whose call already settled keeps that outcome. - const row = await outbox.get(id).catch(() => null) - if (row?.outboxPhase) { + // A row whose call already settled keeps that outcome. A phase + // that cannot be read leaves the row and reports the failure. + const row = await outbox.getPhase(id) + if (!row) { + if (this.saving.has(id)) this.saving.set(id, true) + return + } + if (row.outboxPhase) { const outcome = row.outboxPhase === `rejection-pending` && row.lastError ? outboxMessageError(row.lastError) @@ -1178,13 +1197,12 @@ export class OfflineExecutor { if (decision !== undefined) await outbox.removeDecision(id, decision).catch(() => {}) yielded.push(id) + readmit = true return } // Only a persisted decision commits a removal; without one, a failed // deletion is reported and the write stays eligible. committed = decision !== undefined - // No admission runs it while its deletion is pending. - if (committed) this.executor!.exclude(id) if (records(id)) await outbox.recordRejection(id, error) await outbox.remove(id) if (decision !== undefined) @@ -1192,13 +1210,15 @@ export class OfflineExecutor { } catch (removalError) { if (!committed) { failures.push(removalError) - // The row is read again, so a write another leader settled - // meanwhile is not queued again. - this.executor!.admitTransaction(id).catch(() => {}) + readmit = true return } - // A committed removal stands; its deletion is retried. - this.executor!.retryDecided(id, error) + // A committed removal stands; its deletion is retried, excluded + // from admission until it lands. + executor.retryDecided(id, error) + } finally { + if (unstarted.has(id)) executor.release(id) + if (readmit) executor.admitTransaction(id).catch(() => {}) } if (this.saving.has(id)) this.saving.set(id, true) this.rejectTransaction(id, error) diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index cebfa86d84..5d0a8e8ed0 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -45,6 +45,14 @@ export class TransactionExecutor { private cleanupTimer: ReturnType | null = null private cleanupAttempts = 0 private cleaning = false + // Unstarted writes a removal is deciding, by how many removals hold each. + private readonly removing = new Map() + // Writes a removal took while their call ran, with the outcome whose + // record failed. Retried in any tab state until disposal. + private readonly unpublished = new Map() + private publishTimer: ReturnType | null = null + private publishAttempts = 0 + private paused = false constructor( scheduler: KeyScheduler, @@ -145,6 +153,7 @@ export class TransactionExecutor { !(await this.removeSettledTransaction( deletionPending, !transaction.outboxPhase, + terminalError, )) ) return @@ -278,7 +287,13 @@ export class TransactionExecutor { ) try { // A rejection waits until it is recorded and its row removed. - if (!(await this.removeSettledTransaction(rejectionPending, true))) + if ( + !(await this.removeSettledTransaction( + rejectionPending, + true, + terminalError, + )) + ) return } catch (storageError) { this.offlineExecutor.rejectTransaction(transaction.id, terminalError) @@ -326,17 +341,9 @@ export class TransactionExecutor { // Public removal can finish while the named mutation function runs. // The removed row cannot be retried, but its caller still owns the // provider failure and later queued work must be able to run. - // A writer in another tab reads the error from its record, as for a - // rejection, and the running marker goes; a failed record is retried - // without calling the provider again. if (persistError instanceof OutboxTransactionNotFoundError) { - const failed: OfflineTransaction = { - ...updatedTransaction, - outboxPhase: `rejection-pending`, - } - this.scheduler.updateTransaction(failed) - if (await this.removeSettledTransaction(failed, false)) - this.offlineExecutor.rejectTransaction(transaction.id, error) + this.scheduler.markCompleted(transaction) + await this.publishRemovedOutcome(transaction.id, error) return } throw persistError @@ -345,10 +352,15 @@ export class TransactionExecutor { } } - /** False when the row stays because its rejection could not be recorded. */ + /** + * False when this call leaves the write unsettled: its rejection could not + * be recorded, or a removal took the row and its outcome is published + * separately. + */ private async removeSettledTransaction( transaction: OfflineTransaction, persistMarker: boolean, + outcome: Error | undefined, ): Promise { // Read by this function's development-only oracle probes, as above. const probing = @@ -360,17 +372,21 @@ export class TransactionExecutor { try { await this.outbox.update(transaction.id, transaction) } catch (error) { - // A public removal can finish while the provider is still running. - if (!(error instanceof OutboxTransactionNotFoundError)) { - // Development-only oracle probe; a production build removes it. - probing && - ( - globalThis as { - __oracleProbe?: (name: string, condition: unknown) => void - } - ).__oracleProbe?.(`offline-transactions#phase-write-fault`, true) - throw error + // A public removal can finish while the provider is still running; + // only its outcome is left to publish. + if (error instanceof OutboxTransactionNotFoundError) { + this.scheduler.markCompleted(transaction) + await this.publishRemovedOutcome(transaction.id, outcome) + return false } + // Development-only oracle probe; a production build removes it. + probing && + ( + globalThis as { + __oracleProbe?: (name: string, condition: unknown) => void + } + ).__oracleProbe?.(`offline-transactions#phase-write-fault`, true) + throw error } } // A writer in another tab that misses the settlement message reads a @@ -516,8 +532,11 @@ export class TransactionExecutor { // The retry hook is user code and may synchronously revoke replay rights. if (!this.offlineExecutor.isOfflineEnabled) return - const newlyLoaded = filteredTransactions.filter((transaction) => - this.scheduler.schedule(transaction), + // A removal deciding a row admits it again if it does not commit. + const newlyLoaded = filteredTransactions.filter( + (transaction) => + (this.removing.size === 0 || !this.removing.has(transaction.id)) && + this.scheduler.schedule(transaction), ) removedIds = providerPending @@ -668,9 +687,69 @@ export class TransactionExecutor { else this.scheduleCleanupRetry() } - /** Keeps a write a committed removal is deleting out of admission. */ - exclude(id: string): void { - this.excluding.add(id) + /** Keeps an unstarted write out of admission while a removal decides it. */ + fence(id: string): void { + this.removing.set(id, (this.removing.get(id) ?? 0) + 1) + } + + /** Ends one removal's hold on a write. */ + release(id: string): void { + const holds = this.removing.get(id)! - 1 + if (holds > 0) this.removing.set(id, holds) + else this.removing.delete(id) + } + + /** + * Publishes the outcome of a write a removal took while its call ran: the + * rejection a writer in another tab reads, the running markers' + * withdrawal, then the settlement. It needs no leadership, and a failed + * record is retried without calling the provider again. + */ + private async publishRemovedOutcome( + id: string, + error: Error | undefined, + ): Promise { + try { + if (error && this.recordsFor(id)) + await this.outbox.recordRejection(id, error) + } catch (recordError) { + console.warn( + `Failed to record rejection of transaction ${id}:`, + recordError, + ) + this.unpublished.set(id, error) + this.schedulePublishRetry() + return + } + await this.offlineExecutor.finishRunningRemoval?.(id) + // A subscriber's error is not a storage fault of this executor. + try { + if (error) this.offlineExecutor.rejectTransaction(id, error) + else this.offlineExecutor.resolveTransaction(id, undefined) + } catch (settleError) { + console.warn(`Failed to settle transaction ${id}:`, settleError) + } + } + + private schedulePublishRetry(): void { + if (this.publishTimer || this.paused || this.unpublished.size === 0) return + this.publishTimer = setTimeout(() => { + this.publishTimer = null + this.publishAttempts++ + this.retryPublications() + }, this.retryPolicy.calculateDelay(this.publishAttempts)) + } + + /** Retries recording removed writes' outcomes, also on connectivity. */ + retryPublications(): void { + if (this.paused) return + if (this.publishTimer) clearTimeout(this.publishTimer) + this.publishTimer = null + if (this.unpublished.size === 0) this.publishAttempts = 0 + for (const [id, error] of [...this.unpublished]) { + this.unpublished.delete(id) + void this.publishRemovedOutcome(id, error) + } } /** Finishes a committed removal whose deletion failed, outside the queue. */ @@ -705,12 +784,14 @@ export class TransactionExecutor { throw new Error(`The outbox replay for this leadership has not completed`) const transaction = await this.outbox.getCurrent(id) // A row this leader decided to reject, or loaded with a decision, is in - // `excluding` and is settled, never sent. + // `excluding` and is settled, never sent; one a removal is deciding waits + // for that removal. if ( !transaction || !this.offlineExecutor.isOfflineEnabled || term !== this.offlineExecutor.leadershipTerm || - this.excluding.has(id) + this.excluding.has(id) || + this.removing.has(id) ) return // A duplicate message is harmless: both steps ignore a known transaction. @@ -787,6 +868,9 @@ export class TransactionExecutor { // Retain queued work and let the issued call finish its acknowledgment. this.clearRetryTimer() this.dropFailedCleanups() + this.paused = true + if (this.publishTimer) clearTimeout(this.publishTimer) + this.publishTimer = null } /** diff --git a/packages/offline-transactions/src/outbox/OutboxManager.ts b/packages/offline-transactions/src/outbox/OutboxManager.ts index c2548fec82..a1b3b9e56c 100644 --- a/packages/offline-transactions/src/outbox/OutboxManager.ts +++ b/packages/offline-transactions/src/outbox/OutboxManager.ts @@ -276,6 +276,33 @@ export class OutboxManager { return `${this.decisionPrefix}${encodeURIComponent(id)}:` } + /** + * A saved row's phase and stored error, read without decoding its + * mutations; null when no row is stored. A failed read, or a phase this + * version does not know, throws. A row that is not JSON was never sent. + */ + async getPhase( + id: string, + ): Promise | null> { + const data = await this.storage.get(this.getStorageKey(id)) + if (data === null) return null + let row: unknown + try { + row = JSON.parse(data) + } catch { + return {} + } + if (typeof row !== `object` || row === null) return {} + const { outboxPhase, lastError } = row as Record + if (outboxPhase === undefined) return {} + if ( + outboxPhase !== `deletion-pending` && + outboxPhase !== `rejection-pending` + ) + throw new Error(`Unsupported transaction outbox phase`) + return { outboxPhase, lastError: readError(lastError) } + } + /** Whether a row is saved, without decoding it. */ async has(id: string): Promise { return (await this.storage.get(this.getStorageKey(id))) !== null @@ -319,20 +346,21 @@ export class OutboxManager { this.storage.delete(key).catch(() => {}) continue } - let error = { - name: `NonRetriableError`, - message: `Transaction rejected by a recorded decision`, - } + let error: { name: string; message: string } | undefined try { const data = await this.storage.get(key) if (data === null) continue - error = - readError((JSON.parse(data) as { error?: unknown }).error) ?? - error + error = readError((JSON.parse(data) as { error?: unknown }).error) } catch { // The unread decision still rejects its row. } - decisions.set(id, error) + // Another decision's readable error wins over the fallback. + if (error) decisions.set(id, error) + else if (!decisions.has(id)) + decisions.set(id, { + name: `NonRetriableError`, + message: `Transaction rejected by a recorded decision`, + }) } } const transactionKeys = keys.filter((key) => diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index c05565877b..7fc57d6066 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -42,7 +42,12 @@ * replay and then reconnect, let a replay outlive its term, remove a running * write twice, record a rejection after its writer listed the outcome * records, store an unreadable outcome record or a decision with no error, - * and fail a removed running write's call with a retryable error. + * and fail a removed running write's call with a retryable error. The rest + * deliver an added message while an unsent write's removal is decided, fail + * the error record of a removed running write before its leader stops + * leading, change connectivity during an outbox check that then fails, fail + * a removal's read of a sent row's phase, and store a readable decision + * beside an unreadable one. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. @@ -281,6 +286,20 @@ const reachStates = [ // A removed running write whose call failed with a retryable error failed // its writer through the recorded error. `removed-retryable-failure-recorded`, + // An added message while an unsent write's removal was being decided sent + // nothing. + `unsent-removal-not-admitted`, + // A removed running write's error, whose record failed, reached its writer + // after its leader stopped leading. + `removed-outcome-survived-handover`, + // A connectivity change during an outbox check that then failed settled + // the lost write. + `check-retried-after-running-sweep`, + // A removal whose read of a sent row's phase failed reported it and kept + // the row. + `phase-read-failure-kept-row`, + // A readable decision beside an unreadable one kept its error. + `readable-decision-kept`, ] as const type ReachState = (typeof reachStates)[number] @@ -360,6 +379,11 @@ type SharedActionType = | `unreadable-outcome-before-rejection` | `decision-without-error` | `remove-running-retryable` + | `added-during-unsent-removal` + | `remove-running-record-fails-handover` + | `connectivity-during-failing-check` + | `remove-phase-read-fails` + | `readable-decision-before-unreadable` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -450,6 +474,17 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( { weight: 1, arbitrary: sharedAction(`unreadable-outcome-before-rejection`) }, { weight: 1, arbitrary: sharedAction(`decision-without-error`) }, { weight: 1, arbitrary: sharedAction(`remove-running-retryable`) }, + { weight: 1, arbitrary: sharedAction(`added-during-unsent-removal`) }, + { + weight: 1, + arbitrary: sharedAction(`remove-running-record-fails-handover`), + }, + { weight: 1, arbitrary: sharedAction(`connectivity-during-failing-check`) }, + { weight: 1, arbitrary: sharedAction(`remove-phase-read-fails`) }, + { + weight: 1, + arbitrary: sharedAction(`readable-decision-before-unreadable`), + }, { weight: 1, arbitrary: sharedAction(`replace-writer`) }, { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, { weight: 1, arbitrary: tabAction(`remove-running`) }, @@ -543,6 +578,11 @@ const spliced = ( action.type !== `unreadable-outcome-before-rejection` && action.type !== `decision-without-error` && action.type !== `remove-running-retryable` && + action.type !== `added-during-unsent-removal` && + action.type !== `remove-running-record-fails-handover` && + action.type !== `connectivity-during-failing-check` && + action.type !== `remove-phase-read-fails` && + action.type !== `readable-decision-before-unreadable` && action.type !== `remove-running`, ) .slice(0, MAX_ACTIONS - prefix.length), @@ -643,8 +683,11 @@ class ControlledOnline { class ReadFailingStorage extends FakeStorageAdapter { failReads = 0 - // The next read of this key fails. + // The next read of this key fails, after this many reads of it succeed. failReadKey: string | undefined + failReadKeyAfter = 0 + // Transactions with a rejection record that landed. + readonly recordedRejections = new Set() // The next outcome record write fails. failOutcomeWrites = 0 // Outcome keys whose write failed. @@ -782,7 +825,9 @@ class ReadFailingStorage extends FakeStorageAdapter { const fail = await new Promise((resolve) => held.push(resolve)) if (fail) throw new Error(`storage write failed`) } - return super.set(key, value) + await super.set(key, value) + if (key.startsWith(`outcome:`) && value.includes(`"error"`)) + this.recordedRejections.add(decodeURIComponent(key.split(`:`)[1]!)) } holdNextRead(): void { this.staleRead = null @@ -793,8 +838,11 @@ class ReadFailingStorage extends FakeStorageAdapter { } override async get(key: string): Promise { if (this.failReadKey === key) { - this.failReadKey = undefined - throw new Error(`storage read failed`) + if (this.failReadKeyAfter > 0) this.failReadKeyAfter -= 1 + else { + this.failReadKey = undefined + throw new Error(`storage read failed`) + } } if (this.failReads > 0) { this.failReads -= 1 @@ -3398,6 +3446,232 @@ async function runHistory( reach(`removed-retryable-failure-recorded`) break } + case `added-during-unsent-removal`: { + // The leader removes a queued follower write; while its decision + // is still being recorded, a duplicate added message arrives + // online. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if (!durable || leader < 0 || follower < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(follower, `write`) + if (!write) break + storage.holdNextDecision() + const removal = tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + await settle() + expect(storage.decisionHeld(), `the removal's decision stalls`).toBe( + true, + ) + online.set(true) + await settle() + channels.inject({ type: `added`, id: write.transactionId }) + await settle() + expect(calls, `${write.id} not admitted`).not.toContain(write.id) + storage.releaseDecision() + await removal + await settle() + write.removed = true + write.deliverable = false + expect(write.outcome, `${write.id} fails on its removal`).toBe( + `failed`, + ) + reach(`unsent-removal-not-admitted`) + break + } + case `remove-running-record-fails-handover`: { + // The leader removes a follower's running write, whose call then + // fails with a retryable error. Recording that error fails once, + // and the leader stops leading before it records it again. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + election.queue.length === 0 || + !(await quiet()) + ) + break + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + callGate = null + release() + await settle() + break + } + retryable.add(write.id) + write.rejected = true + write.failure = `retry ${write.id}` + await tabs[leader]!.env.executor.removeFromOutbox( + write.transactionId!, + ) + storage.failOutcomeWrites = 1 + release() + await settle() + expect( + storage.outcomeFailed(write.transactionId!), + `${write.id}'s record failed`, + ).toBe(true) + expect(write.outcome, `${write.id} waits for its record`).toBe( + undefined, + ) + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + online.set(true) + await settle() + expect( + storage.recordedRejections.has(write.transactionId!), + `${write.id}'s error recorded`, + ).toBe(true) + expect(write.outcome, `${write.id} takes the call's error`).toBe( + `failed`, + ) + reach(`removed-outcome-survived-handover`) + await original.requestLeadership() + await settle() + break + } + case `connectivity-during-failing-check`: { + // A follower's settlement is lost. Its outbox check fails to read + // that write, then waits for another save of the same tab, and + // connectivity changes meanwhile. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + channels.state.loseSettlement = true + const lost = await doWrite(follower, `write`) + channels.state.loseSettlement = false + if ( + !lost || + !channels.state.lostIds.includes(lost.transactionId!) || + lost.outcome !== undefined + ) + break + storage.holdWrites() + await doWrite(follower, `write`) + storage.failReadKey = `tx:${lost.transactionId}` + expectedWarnings.check += 1 + channels.inject({ type: `leader` }) + await settle() + expect(storage.failReadKey, `the check's read failed`).toBe(undefined) + online.set(true) + await settle() + storage.releaseWrites(false) + await settle() + expect(lost.outcome, `${lost.id} settled after reconnecting`).toBe( + `completed`, + ) + reach(`check-retried-after-running-sweep`) + break + } + case `remove-phase-read-fails`: { + // The leader sends a follower's write and fails to delete its row. + // Offline, the next leader loads that row; its removal finds the + // row, then fails to read its phase. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + storage.failDeletes = 1 + const write = await doWrite(follower, `write`) + if (!write || !calls.includes(write.id)) { + storage.failDeletes = 0 + break + } + online.set(false) + const successor = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + await rotateTo(tabs[successor]!.election) + storage.failReadKey = `tx:${write.transactionId}` + storage.failReadKeyAfter = 1 + await expect( + tabs[successor]!.env.executor.removeFromOutbox( + write.transactionId!, + ), + `the removal reports the failed read`, + ).rejects.toThrow(`storage read failed`) + await settle() + expect(storage.failReadKey, `the phase read failed`).toBe(undefined) + expect( + await storage.get(`tx:${write.transactionId}`), + `${write.id}'s row kept`, + ).not.toBe(null) + expect(write.outcome, `${write.id} still waits`).toBe(undefined) + online.set(true) + await settle() + expect(write.outcome, `${write.id} completes`).toBe(`completed`) + reach(`phase-read-failure-kept-row`) + await closeTab(leader) + break + } + case `readable-decision-before-unreadable`: { + // A follower's saved write has a removal decision and, after it, + // an unreadable one; another tab leads and replays. + const leader = leaderIndex() + const writer = tabs.findIndex((tab, index) => tab && index !== leader) + if (!durable || leader < 0 || writer < 0 || !(await quiet())) break + online.set(false) + const write = await doWrite(writer, `write`) + if (!write) break + const prefix = `decision:${encodeURIComponent(write.transactionId!)}` + await storage.set( + `${prefix}:a`, + JSON.stringify({ + error: { + name: `NonRetriableError`, + message: `Transaction removed from the outbox`, + }, + at: Date.now(), + }), + ) + await storage.set(`${prefix}:b`, `{not json`) + write.deliverable = false + write.removed = true + const original = tabs[leader]!.election + original.releaseLeadership() + await settle() + await original.requestLeadership() + online.set(true) + await settle() + expect(calls, `${write.id} never sent`).not.toContain(write.id) + expect(write.outcome, `${write.id} settled as decided`).toBe(`failed`) + expect( + (write.error as Error).message, + `${write.id} keeps the readable error`, + ).toBe(`Transaction removed from the outbox`) + reach(`readable-decision-kept`) + break + } case `remove-deletion-pending`: { // The leader sends a follower's write and fails to delete its row. // Offline, the next leader loads that row, and it is removed. @@ -3613,6 +3887,22 @@ async function runHistory( // write: by the writer itself if it became leader, or else after one // handover to another tab. channels.state.loseSettlement = false + // Writes whose settlement was lost and whose open tab still waits; only + // their settlement afterwards is a recovery. + const waitingAfterLoss = writes.filter( + (write) => + write.transactionId !== undefined && + channels.state.lostIds.includes(write.transactionId) && + openSessions().has(write.session) && + write.outcome === undefined, + ) + const recovered = () => + waitingAfterLoss.some( + (write) => + openSessions().has(write.session) && + write.outcome === + (write.rejected || !write.deliverable ? `failed` : `completed`), + ) online.set(true) await settle() // The writer whose check failed settles on connectivity, before any @@ -3631,7 +3921,6 @@ async function runHistory( channels.state.lostIds.includes(write.transactionId), ) if (lostWrites.length > 0) { - reach(`lost-settlement-recovered`) const holder = leaderIndex() const leaderSession = tabs[holder]?.session for (const write of lostWrites) { @@ -3659,6 +3948,7 @@ async function runHistory( reach(`lost-settlement-recovered-by-follower`) } } + if (recovered()) reach(`lost-settlement-recovered`) if ( lostWrites.some( (write) => @@ -3763,7 +4053,13 @@ async function runHistory( `Transaction removed from the outbox`, ) } - if (write.recordRetried && write.outcome === `failed`) + // The record attempt failed, and a later one for the same write landed. + if ( + write.recordRetried && + write.outcome === `failed` && + storage.outcomeFailed(write.transactionId!) && + storage.recordedRejections.has(write.transactionId!) + ) reach(`outcome-record-retried`) if (write.excluded) { const error = write.error as Error @@ -3805,7 +4101,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. A failed replay runs again on connectivity before a refused admission, a replay that outlives its term leaves admission to the newer one, every running marker of overlapping removals is withdrawn, a writer reads a rejection recorded after it listed the records, an unreadable record or decision never hides or blocks a rejection, and a removed running write whose call fails retryably fails its writer with that error. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. A failed replay runs again on connectivity before a refused admission, a replay that outlives its term leaves admission to the newer one, every running marker of overlapping removals is withdrawn, a writer reads a rejection recorded after it listed the records, an unreadable record or decision never hides or blocks a rejection, and a removed running write whose call fails retryably fails its writer with that error, also when its first record fails and its leader then stops leading. No admission sends an unsent write while its removal is being decided, a removal that cannot read a row's phase reports that and keeps the row, a failed outbox check that a connectivity change overlapped runs again, and an unreadable decision never replaces a readable decision's error. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -3843,7 +4139,12 @@ oracleProperty({ `src/outbox/OutboxManager.ts#OutboxManager.recordDecision`, `src/outbox/OutboxManager.ts#OutboxManager.removeDecision`, `src/outbox/OutboxManager.ts#OutboxManager.removeDecisions`, - `src/executor/TransactionExecutor.ts#TransactionExecutor.exclude`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.fence`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.release`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.publishRemovedOutcome`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.schedulePublishRetry`, + `src/executor/TransactionExecutor.ts#TransactionExecutor.retryPublications`, + `src/outbox/OutboxManager.ts#OutboxManager.getPhase`, `src/executor/TransactionExecutor.ts#TransactionExecutor.retryDecided`, `src/outbox/OutboxManager.ts#OutboxManager.recordPending`, `src/outbox/OutboxManager.ts#OutboxManager.recordOutcome`, @@ -4465,6 +4766,38 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `remove-running-retryable` }]), }, + { + name: `an added message during an unsent removal sends nothing`, + enters: [`unsent-removal-not-admitted`], + build: (generated: History): History => + spliced(generated, [{ type: `added-during-unsent-removal` }]), + }, + { + name: `a removed running write's error survives a handover`, + enters: [`removed-outcome-survived-handover`], + build: (generated: History): History => + spliced(generated, [ + { type: `remove-running-record-fails-handover` }, + ]), + }, + { + name: `connectivity during a failing outbox check retries it`, + enters: [`check-retried-after-running-sweep`], + build: (generated: History): History => + spliced(generated, [{ type: `connectivity-during-failing-check` }]), + }, + { + name: `a failed phase read keeps a sent row`, + enters: [`phase-read-failure-kept-row`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-phase-read-fails` }]), + }, + { + name: `an unreadable decision keeps a readable one's error`, + enters: [`readable-decision-kept`], + build: (generated: History): History => + spliced(generated, [{ type: `readable-decision-before-unreadable` }]), + }, { name: `a write before initialization takes the online path`, enters: [`pre-initialization-write`], From 6d27300ce34864f70ef1e2d7e8d8c4548dca1fbc Mon Sep 17 00:00:00 2001 From: daveycodez Date: Fri, 27 Nov 2026 02:58:05 -0800 Subject: [PATCH 16/16] fix(offline-transactions): address fourteenth durable follower write review - When a removed running write's call ends retryably before the removal's deletion lands, the removal takes its queued retry and fails its writer with the removal error, instead of leaving a retry that sends the removed write again. - When the deletion lands while the failed call is still persisting its retry, the call deletes any row its update restored and publishes its error, instead of saving and queueing the removed write again. - The guide requires every tab that shares the outbox to use the same store, and says how a write waiting to retry is removed. The durable follower oracle fails a removed running write's call with a retryable error while the removal's deletion is held, and for another write while the failure's read of the row is held. --- docs/contributing/oracle-coverage.md | 6 +- docs/guides/offline-transactions.md | 2 +- .../src/OfflineExecutor.ts | 28 +++++ .../src/executor/TransactionExecutor.ts | 7 ++ packages/offline-transactions/src/types.ts | 2 + .../durable-follower-oracle.property.test.ts | 103 +++++++++++++++++- 6 files changed, 142 insertions(+), 6 deletions(-) diff --git a/docs/contributing/oracle-coverage.md b/docs/contributing/oracle-coverage.md index 746622f388..4a102f8c97 100644 --- a/docs/contributing/oracle-coverage.md +++ b/docs/contributing/oracle-coverage.md @@ -4268,8 +4268,10 @@ The post-merge review added three missing domains to existing owners: error. It also covers an added message while an unsent write's removal is being decided, a removed running write whose error record fails before its leader stops leading, a connectivity change during an outbox check that - then fails, a failed read of a sent row's phase during its removal, and a - readable decision beside an unreadable one. It does not cover real browser + then fails, a failed read of a sent row's phase during its removal, a + readable decision beside an unreadable one, and a removed running write + whose call fails retryably before the removal's deletion lands or between + the failure's read and rewrite of the row. It does not cover real browser contexts. - Settlement-time drop of optimistic state is owned by the [optimistic history model](https://github.com/TanStack/db/blob/main/packages/db/tests/optimistic-history-oracle.ts) diff --git a/docs/guides/offline-transactions.md b/docs/guides/offline-transactions.md index ee2c26d018..cfc2f8d0fd 100644 --- a/docs/guides/offline-transactions.md +++ b/docs/guides/offline-transactions.md @@ -189,7 +189,7 @@ console.log(executor.storageDiagnostic) console.log(executor.isOfflineEnabled) ``` -Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. A write whose tab closes before it can tell the current leader about the save waits for the next leader's replay. The follower's transaction settles with the leader's result. This requires BroadcastChannel: a follower without it uses the online path, while a tab that leads still saves its own writes to the outbox. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. A leader that cannot read a follower's saved write reports it and keeps the write pending, and a leader whose outbox replay failed replays again when connectivity changes. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. +Set `followerWrites: 'durable'` to keep a follower's writes when it goes offline or closes. The follower saves each write to the shared outbox, and the current or next leader sends it. A write whose tab closes before it can tell the current leader about the save waits for the next leader's replay. The follower's transaction settles with the leader's result. This requires BroadcastChannel: a follower without it uses the online path, while a tab that leads still saves its own writes to the outbox. Every tab that shares the outbox must set the same `followerWrites` mode: a default-mode tab opens no channel, so as leader it never hears a follower's saved write, and it records no outcome for a write it rejects or removes. A follower's write made before `waitForInit()` resolves also uses the online path, while a tab that already leads, for example in `onLeadershipChange(true)` during startup, waits for initialization instead; await `waitForInit()` before writing. A reloaded follower does not show another tab's pending writes optimistically until they sync. The leader records a rejection before it removes the row, so a follower that misses the report still fails with the server's error; a write with no record completed. A rejection record stays until its tab reads it; a leader's replay prunes records older than seven days, and a write saved longer ago than that keeps waiting instead of reading a missing record as success. Every tab must register its collections under the same keys, which also name the channel the tabs share; collection ids may differ. Every tab must also use the same outbox store: the channel does not include the store, and a removal reaches only the leader's store, so a write saved to another store stays pending there even after its removal resolves. Without `storage`, each tab probes on its own and falls back to localStorage when IndexedDB is unavailable; pass the same `storage`, such as `new IndexedDBAdapter()`, in every tab to rule that out. A leader that cannot read a follower's saved write reports it and keeps the write pending, and a leader whose outbox replay failed replays again when connectivity changes. Removing a saved write with `removeFromOutbox()` or `clearOutbox()` before it is sent fails its writer's transaction. A follower asks the leader to make the removal, because only the leader knows whether the server call started; a call that already started keeps the server's outcome, while a write waiting to retry after a retryable failure fails with the removal error. An executor that replaces a disposed one over the same Collection objects also settles the writes its predecessor saved when another tab settled them meanwhile. Without BroadcastChannel, and in the default mode, a tab that saved a write as leader and lost leadership before it was sent learns no outcome from the outbox, so its transaction keeps waiting. Use `onStorageFailure` when the built-in web stores are unavailable. Use `onLeadershipChange` when the UI needs to show which tab owns the outbox. A follower can become the leader after the current leader leaves. diff --git a/packages/offline-transactions/src/OfflineExecutor.ts b/packages/offline-transactions/src/OfflineExecutor.ts index f28f916225..12e91a433c 100644 --- a/packages/offline-transactions/src/OfflineExecutor.ts +++ b/packages/offline-transactions/src/OfflineExecutor.ts @@ -138,6 +138,8 @@ export class OfflineExecutor { // Running markers this leader recorded for removed writes, by id; each // overlapping removal leaves its own. private readonly runningRemovals = new Map>() + // Writes whose row a removal took while their call ran. + private readonly removedRunning = new Set() // Removals this follower asked the leader for, by request. private readonly removals = new Map< string, @@ -1164,6 +1166,26 @@ export class OfflineExecutor { } await outbox.remove(id) if (this.saving.has(id)) this.saving.set(id, true) + if (this.scheduler.isRunning(id)) { + this.removedRunning.add(id) + return + } + // A call that ended retryably meanwhile left a queued retry, which + // the removal takes like an unsent write. + if ( + !this.scheduler + .getAllPendingTransactions() + .some((transaction) => transaction.id === id) + ) + return + this.scheduler.removePendingTransactions([id]) + try { + if (records(id)) await outbox.recordRejection(id, error) + await this.finishRunningRemoval(id) + } catch { + executor.retryDecided(id, error) + } + this.rejectTransaction(id, error) return } // A row whose call already settled keeps that outcome. A phase @@ -1228,8 +1250,14 @@ export class OfflineExecutor { return yielded } + /** Whether a removal took this write's row while its call ran. */ + removedWhileRunning(id: string): boolean { + return this.removedRunning.has(id) + } + /** Withdraws the running markers of a removed write whose call finished. */ async finishRunningRemoval(id: string): Promise { + this.removedRunning.delete(id) const tokens = this.runningRemovals.get(id) if (!tokens) return this.runningRemovals.delete(id) diff --git a/packages/offline-transactions/src/executor/TransactionExecutor.ts b/packages/offline-transactions/src/executor/TransactionExecutor.ts index 5d0a8e8ed0..6533cc2485 100644 --- a/packages/offline-transactions/src/executor/TransactionExecutor.ts +++ b/packages/offline-transactions/src/executor/TransactionExecutor.ts @@ -337,6 +337,13 @@ export class TransactionExecutor { // that landed meanwhile must not settle it at a later replay. if (this.offlineExecutor.recordsOutcomes) await this.outbox.removeDecisions(transaction.id).catch(() => {}) + // A removal took the row meanwhile; the update may have restored it. + if (this.offlineExecutor.removedWhileRunning?.(transaction.id)) { + await this.outbox.remove(transaction.id) + this.scheduler.markCompleted(transaction) + await this.publishRemovedOutcome(transaction.id, error) + return + } } catch (persistError) { // Public removal can finish while the named mutation function runs. // The removed row cannot be retried, but its caller still owns the diff --git a/packages/offline-transactions/src/types.ts b/packages/offline-transactions/src/types.ts index dfae4ac649..c704ca3f01 100644 --- a/packages/offline-transactions/src/types.ts +++ b/packages/offline-transactions/src/types.ts @@ -181,6 +181,8 @@ export interface TransactionSignaler { trackIssued?: (transactionId: string, active: boolean) => void /** A removed write's call finished: its running marker goes. */ finishRunningRemoval?: (transactionId: string) => Promise + /** A removal took this write's row while its call ran. */ + removedWhileRunning?: (transactionId: string) => boolean resolveTransaction: (transactionId: string, result: any) => void rejectTransaction: ( transactionId: string, diff --git a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts index 7fc57d6066..0e793d0111 100644 --- a/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts +++ b/packages/offline-transactions/tests/durable-follower-oracle.property.test.ts @@ -46,8 +46,10 @@ * deliver an added message while an unsent write's removal is decided, fail * the error record of a removed running write before its leader stops * leading, change connectivity during an outbox check that then fails, fail - * a removal's read of a sent row's phase, and store a readable decision - * beside an unreadable one. + * a removal's read of a sent row's phase, store a readable decision + * beside an unreadable one, and fail a removed running write's call with a + * retryable error before the removal's deletion lands or between the + * failure's read and rewrite of the row. * * Production driver: real executors over one shared storage adapter, with a * controlled leader election, online detector and BroadcastChannel. @@ -298,6 +300,9 @@ const reachStates = [ // A removal whose read of a sent row's phase failed reported it and kept // the row. `phase-read-failure-kept-row`, + // A removed running write whose call failed retryably during the removal + // was neither queued again nor saved again, and failed its writer. + `removed-retry-not-requeued`, // A readable decision beside an unreadable one kept its error. `readable-decision-kept`, ] as const @@ -384,6 +389,7 @@ type SharedActionType = | `connectivity-during-failing-check` | `remove-phase-read-fails` | `readable-decision-before-unreadable` + | `remove-running-retry-race` type Action = { type: TabActionType; tab: number } | { type: SharedActionType } type Mode = `durable` | `online` type History = { mode: Mode; actions: Array } @@ -485,6 +491,7 @@ const actionArbitrary: fc.Arbitrary = fc.oneof( weight: 1, arbitrary: sharedAction(`readable-decision-before-unreadable`), }, + { weight: 1, arbitrary: sharedAction(`remove-running-retry-race`) }, { weight: 1, arbitrary: sharedAction(`replace-writer`) }, { weight: 1, arbitrary: sharedAction(`replace-rejected-writer`) }, { weight: 1, arbitrary: tabAction(`remove-running`) }, @@ -583,6 +590,7 @@ const spliced = ( action.type !== `connectivity-during-failing-check` && action.type !== `remove-phase-read-fails` && action.type !== `readable-decision-before-unreadable` && + action.type !== `remove-running-retry-race` && action.type !== `remove-running`, ) .slice(0, MAX_ACTIONS - prefix.length), @@ -868,6 +876,9 @@ class StorageView implements StorageAdapter { holdNextRead(): void { this.readHolds += 1 } + readHeld(): boolean { + return this.heldReads.length > 0 + } releaseRead(): void { this.heldReads.shift()?.() } @@ -3446,6 +3457,86 @@ async function runHistory( reach(`removed-retryable-failure-recorded`) break } + case `remove-running-retry-race`: { + // The leader removes a follower's running write, whose call fails + // with a retryable error first while the removal's deletion is + // held, then for another write while the failure's read of the row + // is held. + const leader = leaderIndex() + const follower = tabs.findIndex( + (tab, index) => tab && index !== leader, + ) + if ( + !durable || + !online.online || + leader < 0 || + follower < 0 || + !(await quiet()) + ) + break + const { executor } = tabs[leader]!.env + const view = tabs[leader]!.view + let release!: () => void + callGate = new Promise((resolve) => { + release = resolve + }) + const queued = await doWrite(follower, `write`) + if (!queued || !calls.includes(queued.id)) { + callGate = null + release() + await settle() + break + } + retryable.add(queued.id) + storage.holdNextDelete() + const removal = executor.removeFromOutbox(queued.transactionId!) + await settle() + expect(storage.deleteHeld(), `${queued.id}'s deletion stalls`).toBe( + true, + ) + release() + await settle() + storage.releaseDelete() + await removal + await settle() + queued.rejected = true + queued.removed = true + queued.failure = `Transaction removed from the outbox` + expect(queued.outcome, `${queued.id} fails on its removal`).toBe( + `failed`, + ) + expect(await executor.peekOutbox(), `${queued.id} gone`).toEqual([]) + callGate = new Promise((resolve) => { + release = resolve + }) + const restored = await doWrite(follower, `write`) + if (!restored || !calls.includes(restored.id)) { + callGate = null + release() + await settle() + break + } + retryable.add(restored.id) + view.holdNextRead() + release() + await settle() + expect(view.readHeld(), `the failure's read stalls`).toBe(true) + await executor.removeFromOutbox(restored.transactionId!) + view.releaseRead() + await settle() + restored.rejected = true + restored.failure = `retry ${restored.id}` + expect( + restored.outcome, + `${restored.id} takes the call's error`, + ).toBe(`failed`) + expect( + await executor.peekOutbox(), + `${restored.id} is not saved again`, + ).toEqual([]) + reach(`removed-retry-not-requeued`) + break + } case `added-during-unsent-removal`: { // The leader removes a queued follower write; while its decision // is still being recorded, a duplicate added message arrives @@ -4101,7 +4192,7 @@ const loseSettlement: Action = { type: `lose-settlement` } oracleProperty({ id: property, law: { - statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. A failed replay runs again on connectivity before a refused admission, a replay that outlives its term leaves admission to the newer one, every running marker of overlapping removals is withdrawn, a writer reads a rejection recorded after it listed the records, an unreadable record or decision never hides or blocks a rejection, and a removed running write whose call fails retryably fails its writer with that error, also when its first record fails and its leader then stops leading. No admission sends an unsent write while its removal is being decided, a removal that cannot read a row's phase reports that and keeps the row, a failed outbox check that a connectivity change overlapped runs again, and an unreadable decision never replaces a readable decision's error. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, + statement: `With followerWrites 'durable', a write from an initialized tab stays pending until the leading tab sends it to the server exactly once while online, whether or not its tab stayed open, and its open tab's transaction settles with the server's outcome, also when the settlement message is lost. A leader that could not read a saved write sends it once connectivity changes, a row it cannot decode is reported, a failed row removal after a successful send is not reported as the outcome, and a follower's failed outbox check runs again on connectivity. An admission read across a change of leadership schedules nothing, and a write excluded by beforeRetry fails its writer even when the message is lost; if its rejection record fails, the leader retries the cleanup and nothing sends it meanwhile. Removing or clearing an unsent write fails its writer at once, a write removed while it is saved never runs, an outbox load from an earlier leadership term schedules nothing, and a tab that only observes a write leaves its writer's record. A follower's removal goes to the leader, which alone knows whether the call started; an exclusion cleanup stops when its leadership ends; and a replacement executor over the same collections settles its predecessor's saved writes against the outbox they were saved to. A removal or exclusion is recorded as a decision beside its row before anything else, so a later leader settles the row as decided rather than send it, a decision that lands late never recreates a row, and a writer reads a rejection only once its decision committed. A row whose call already settled keeps that outcome when removed, and a removal that yields at a handover is made by the next leader. A successor's adopted decision outlives the first recorder withdrawing its own, a committed removal keeps the write out of direct admission, a running marker is withdrawn even when the call finishes before the removal's deletion, and a call issued by an intermediate replacement keeps its write pending. A removed write whose call is running stays pending until the call settles, also when it is the leader's own; a durable replacement does not read a default-mode predecessor's missing record as success; an unreadable saved row keeps its writer waiting, each removal settles by its own deletion, and a cleanup that failed after its term ended is not retried. A failed replay runs again on connectivity before a refused admission, a replay that outlives its term leaves admission to the newer one, every running marker of overlapping removals is withdrawn, a writer reads a rejection recorded after it listed the records, an unreadable record or decision never hides or blocks a rejection, and a removed running write whose call fails retryably fails its writer with that error, also when its first record fails and its leader then stops leading. No admission sends an unsent write while its removal is being decided, a removal that cannot read a row's phase reports that and keeps the row, a failed outbox check that a connectivity change overlapped runs again, and an unreadable decision never replaces a readable decision's error. A removed running write whose call fails retryably while the removal runs is neither retried nor saved again, and fails its writer. In the default mode, a write another leader settled stays pending in its former leader, which cannot tell the outcome. Stale and duplicate messages change nothing. A write made before its tab initializes, and the default mode, keep the online path.`, authority: `Issue #2464 and the followerWrites option in docs/guides/offline-transactions.md.`, limits: `Three tabs over one storage adapter with controlled election, connectivity and BroadcastChannel; up to twelve actions; no real browser contexts; rejection records of writers that never return are kept, and none is ever expired.`, }, @@ -4798,6 +4889,12 @@ oracleProperty({ build: (generated: History): History => spliced(generated, [{ type: `readable-decision-before-unreadable` }]), }, + { + name: `a retryable failure during a running removal is not retried`, + enters: [`removed-retry-not-requeued`], + build: (generated: History): History => + spliced(generated, [{ type: `remove-running-retry-race` }]), + }, { name: `a write before initialization takes the online path`, enters: [`pre-initialization-write`],