Repository navigation
Description
- I've validated the bug against the latest version of DB packages
Describe the bug
When a tab loses leadership, the executor only pauses its retry timer (pause()), so its KeyScheduler keeps what it had queued. When the tab leads again, loadPendingTransactions() schedules what the outbox holds, but KeyScheduler.schedule() ignores an id it already has, and nothing drops ids the outbox no longer has. The tab then runs its own old copy of each transaction, whatever another tab did with it meanwhile:
- Another tab sent it and removed it: this tab sends it again, over any newer write to the same rows.
- Another tab stored an
outboxPhasefor it (rejection-pendingordeletion-pending) and the row stayed, for example because removing it failed: the old copy has no phase, soexecuteTransaction()calls the mutation function again for a transaction the provider already refused or accepted.
Versions: @tanstack/offline-transactions 1.2.1, and main at 371e40d.
A tab can lose and regain leadership with a custom leaderElection (ours hands the lead to the visible tab), and with BroadcastChannelLeader, which gives up the lead to a tab with a lower id and can be elected again later. WebLocksLeader only lets go on dispose, on main and with #2470, so it doesn't run into this.
To Reproduce
Save this as packages/offline-transactions/tests/leader-regain.test.ts on 371e40d. After pnpm install and building @tanstack/db, run pnpm --filter @tanstack/offline-transactions exec vitest --run --coverage.enabled=false tests/leader-regain.test.ts. Both tests fail, with expected 'first' to be 'second' and expected 1 to be +0:
import { expect, it } from 'vitest'
import { NonRetriableError } from '../src/types'
import {
FakeStorageAdapter,
createTestOfflineEnvironment,
turn,
} from './harness'
const waitUntil = async (predicate: () => boolean | Promise<boolean>) => {
const deadline = Date.now() + 5000
while (Date.now() < deadline) {
if (await predicate()) return
await new Promise((resolve) => setTimeout(resolve, 20))
}
throw new Error(`Timed out waiting for condition`)
}
it(`a tab that leads again does not resend a transaction another tab already sent`, async () => {
const storage = new FakeStorageAdapter()
// The server both tabs write to: item id -> value.
const server = new Map<string, string>()
const send = (mutations: ReadonlyArray<{ modified: unknown }>) => {
for (const m of mutations) {
const item = m.modified as { id: string; value: string }
server.set(item.id, item.value)
}
}
let online = false
const envA = createTestOfflineEnvironment({
storage,
mutationFn: (params) => {
if (!online) throw new Error(`offline`)
send(params.transaction.mutations)
return { ok: true }
},
})
const envB = createTestOfflineEnvironment({
storage,
mutationFn: (params) => {
send(params.transaction.mutations)
return { ok: true }
},
})
// B starts as a follower.
envB.leader.setLeader(false)
try {
await envA.waitForLeader()
await envB.executor.waitForInit()
expect(envB.executor.isOfflineEnabled).toBe(false)
// A queues an insert while offline; its first attempt fails.
const txA = envA.executor.createOfflineTransaction({
mutationFnName: envA.mutationFnName,
autoCommit: false,
})
txA.mutate(() => {
envA.collection.insert({
id: `item`,
value: `first`,
completed: false,
updatedAt: new Date(),
})
})
txA.commit().catch(() => {})
await waitUntil(
async () =>
envA.mutationCalls.length === 1 &&
(await envA.executor.peekOutbox()).length === 1,
)
// The lead moves to B, which sends A's insert and empties the outbox.
envA.leader.setLeader(false)
envB.leader.setLeader(true)
await waitUntil(async () => (await envB.executor.peekOutbox()).length === 0)
expect(server.get(`item`)).toBe(`first`)
// A newer value for the same row reaches the server.
server.set(`item`, `second`)
// The lead comes back to A, now online.
const callsBefore = envA.mutationCalls.length
online = true
envB.leader.setLeader(false)
envA.leader.setLeader(true)
await waitUntil(() => envA.executor.getPendingCount() === 0)
await turn()
// B already sent A's insert: A sends nothing, and the newer value stays.
expect(server.get(`item`)).toBe(`second`)
expect(envA.mutationCalls.length - callsBefore).toBe(0)
} finally {
envA.executor.dispose()
envB.executor.dispose()
}
})
it(`a tab that leads again does not resend a transaction another tab stored as rejected`, async () => {
// Removing the rejected row fails once, so its `rejection-pending` record stays.
let failDelete = false
class Storage extends FakeStorageAdapter {
override async delete(key: string): Promise<void> {
if (failDelete) {
failDelete = false
throw new Error(`storage unavailable`)
}
return super.delete(key)
}
}
const storage = new Storage()
let online = false
const envA = createTestOfflineEnvironment({
storage,
mutationFn: () => {
if (!online) throw new Error(`offline`)
return { ok: true }
},
})
const envB = createTestOfflineEnvironment({
storage,
mutationFn: () => {
failDelete = true
throw new NonRetriableError(`refused`)
},
})
envB.leader.setLeader(false)
try {
await envA.waitForLeader()
await envB.executor.waitForInit()
const txA = envA.executor.createOfflineTransaction({
mutationFnName: envA.mutationFnName,
autoCommit: false,
})
txA.mutate(() => {
envA.collection.insert({
id: `item`,
value: `first`,
completed: false,
updatedAt: new Date(),
})
})
txA.commit().catch(() => {})
await waitUntil(
async () =>
envA.mutationCalls.length === 1 &&
(await envA.executor.peekOutbox()).length === 1,
)
// B leads, the server refuses the insert for good, and B stores that.
envA.leader.setLeader(false)
envB.leader.setLeader(true)
await waitUntil(async () => {
const [stored] = await envB.executor.peekOutbox()
return stored?.outboxPhase === `rejection-pending`
})
const callsBefore = envA.mutationCalls.length
online = true
envB.leader.setLeader(false)
envA.leader.setLeader(true)
await waitUntil(() => envA.executor.getPendingCount() === 0)
await turn()
// The stored record says the provider already refused it: A only cleans up.
expect(envA.mutationCalls.length - callsBefore).toBe(0)
} finally {
envA.executor.dispose()
envB.executor.dispose()
}
})In the first test, tab A queues an insert while offline. The lead moves to B, which sends it and empties the outbox, and the server then takes a newer value. When the lead comes back to A, A sends its old insert again. In the second test, B's call is refused for good and the rejection-pending row stays; A, leading again, calls the mutation function again.
Expected behavior
A tab that leads again runs only what the outbox holds now, as stored: nothing for a transaction another tab removed, and only the cleanup for one stored with a phase.
Additional context
I think a fix needs two parts:
- Queue only what the outbox holds, and send nothing until it has been read.
pause()keeps the queue on purpose ("Retain queued work and let the issued call finish its acknowledgment"), but once the tab leads again that queue is out of date. Either drop it when the lead goes, keeping the call in flight (removePendingTransactionsalready keepsactiveTransactionId), or drop it insidewithAllfrom a snapshot taken before the read. Then hold sends until the read is done, asinitPromisedoes at startup: otherwise an online event or a write made during the read runs the old queue, or sends the new write ahead of older stored ones. A read that began before the lead went and came back should be dropped too. Either variant makes both tests pass, but tab A'stxA.commit()never settles: in the first test it's still pending after the lead comes back, because its waiter inpendingTransactionPromisesonly settles from this tab's own execution. - Decide how a waiter settles once another tab has removed its row. Treating a missing row as success would hide another tab's permanent rejection, so the outcome has to be stored. feat(offline-transactions): add durable follower writes #2471 adds stored rejections (
recordRejection/getOutcome) and settles a follower's saved write once it has left the outbox (settleRemovedWrites). A tab that leads again has the same question about its own earlier writes, so both probably want one answer. The transaction this tab still has in flight should be left to that call, since the lead can go and come back while it runs.
I'm happy to open a PR for the first part with these tests, and to fit the second to whatever #2471 settles on.
Activity