Skip to content

Commit 0e1a1c1

Browse files
KyleAMathewsTest
andauthored
fix(offline-transactions): preserve callers across executor replacement (#2401)
* fix(offline-transactions): preserve callers across executor replacement Law: disposal preserves admitted caller and optimistic obligations on retained Collections; a sequential same-outbox successor settles them. Authority: maintainer decision offline-disposal-handoff-2026-11-10 and README settlement. Reach: both campaigns meet all 19 handoff states, including registry growth; real QueryDB refetch receiving campaigns reach all four states 16 times each. RED: original implementation fails completed/caller settlement with campaign seed 20261110 and shrink path 0:1:1:1:1:1. GREEN: 462 package tests, typecheck, build, ESLint, Prettier and lint:changed. Mutant: full-source run 1c2a9145625b rejects 275/295 by named laws, including 44/44 changed-line operators. No crashes/timeouts. Remaining 20 are accounted by typed-domain invariants or absence of the proposed stronger product law. Limits: bounded controlled storage/provider, sequential same-runtime executors, Node/V8 resource sentinel, no cross-tab promises or native durability claim. Evidence: docs/contributing/oracle-reviews/issue-2254-executor-handoff.md * chore: add offline executor handoff changeset * test: register offline executor oracle replay owners * fix(offline-transactions): settle issued outcomes before successor leadership Law: Retained-Collection replacement owes every pending caller its durable outcome, including a successor awaiting leadership. Authority: README Tracking Submission Status and decision offline-disposal-handoff-2026-11-10. Reach: 24 generated plus 11 constructed issued-handoff histories per campaign; both issued boundaries reached 35 times in each normal campaign. RED: Before production changed, seed 20261110/path 3:0:0:0:0:0 failed caller settlement at completed. The previous barrier recorder also accepted an injected settled barrier at provider held. GREEN: Both issued campaigns, real QueryDB receiving comparisons, 466 package tests, seven observer tests, final guarded replay and type/build checks pass. Mutant: One-direction containment fails caller settlement; the settled-barrier injection now fails refresh barrier at provider held. Full-source run fd3da244acf0 kills 278/298 operators, all 47 changed-line; 20 residual labels are individually adjudicated, not a zero-gap claim. Limits: Controlled storage/providers, one issued executor, retained Collections, one runtime. Copied-outbox isolation remains outside this PR by maintainer decision offline-copied-outbox-limit-2026-11-10. Also guarantee production-hook reach in the lint-scope oracle. CI seed 1392514884 fails without the construction and passes with it; the normal campaign reaches all 25 states. Preserve run budgets and the reach minimum. * docs: pin final executor handoff evidence * Audit executor handoff review boundaries and registry work Keep completion routing while deduplicating recipient selection and registering only when obligations first appear. Move the real QueryDB receiving campaign to its package and share the independent barrier judgment. Extend handoff histories for falsy storage failures, throwing nonfinal subscribers, and live offline predecessors. Repair the lint-scope construction premise. Law: same-outbox durable outcomes settle retained-Collection callers; disposal preserves unfinished obligations. Authority: README and maintainer decision 2026-11-10; first-error publication follows Transaction.touchCollection. Reach: review campaigns run 24 generated +14 constructed histories, reaching all 14 required states; QueryDB reaches all four states 16 times per campaign. RED: raw-storage, disposed-only, one-direction and instance-only mutants fail named caller/durable laws. Seed-zero lint construction misses its premise. GREEN: unchanged-production boundary comparison; 465 offline tests; five real QueryDB receiving tests; both lint-scope campaigns; types, build and lint. Mutant: retaining a settled barrier fails the relocated QueryDB receipt law. Limits: controlled storage/provider, one issued executor, one runtime; copied outboxes and concurrent issued outcome precedence remain outside this promise. * test: fix receiving oracle discovery and pin final gap evidence --------- Co-authored-by: Test <test@test.com>
1 parent caa936d commit 0e1a1c1

22 files changed

Lines changed: 6147 additions & 31 deletions
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/offline-transactions': patch
3+
---
4+
5+
Preserve pending callers and optimistic mutations when an offline executor is replaced. A successor over the same outbox settles the original callers when it retains the configured Collection objects in the same runtime.

‎docs/contributing/oracle-coverage.md‎

Lines changed: 7 additions & 2 deletions
Large diffs are not rendered by default.

‎docs/contributing/oracle-reviews/issue-2254-executor-handoff.md‎

Lines changed: 1364 additions & 0 deletions
Large diffs are not rendered by default.

‎docs/guides/offline-transactions.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,19 @@ removal does not cancel a running named mutation function. If that call later
236236
fails, its waiting promises reject with the named mutation function error and
237237
the removed row is not retried. Call `dispose()` when the executor's owner ends.
238238

239+
You can replace an executor to change its configuration while keeping the same
240+
Collections and durable outbox. Disposal stops new processing and releases
241+
resources. It preserves pending optimistic state and caller promises. A
242+
successor in the same runtime that replays the outbox and retains every configured
243+
Collection object under its existing registry key settles the original transaction
244+
receipts and per-ID waiters. An unchanged ancillary Collection does not transfer
245+
callers when an affected Collection object changes. Core's conflicting-transaction
246+
rollback rules still apply to pending restored snapshots. You can
247+
construct a new storage adapter over that outbox. Without resumed work, the
248+
callers remain pending. This does not transfer promises across tabs or a page
249+
reload. On logout, separately clean up the account's Collections and decide
250+
whether to keep or discard its stored outbox.
251+
239252
## Use SQLite persistence with the outbox
240253

241254
This React Native recipe stores applied Collection rows in OP-SQLite and pending mutations in AsyncStorage. The Query Collection supplies server sync. Install the packages for both stores and for Query Collection sync:

‎packages/db/tests/oracle-config.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,17 @@ const staticOracleProperties = [
221221
`ivm.index-refinement`,
222222
`offline.key-scheduler-fifo-ledger`,
223223
`offline.interruption-settlement`,
224+
`offline.disposal-handoff`,
225+
`offline.disposal-issued-handoff`,
226+
`offline.disposal-review-boundaries`,
227+
`offline.disposal-handoff-resources`,
228+
`offline.settled-id-window`,
229+
`offline.executor-api`,
230+
`offline.executor-controls`,
231+
`offline.executor-coordination-lifecycle`,
232+
`offline.executor-connectivity-barrier`,
233+
`offline.executor-connectivity-query-db`,
234+
`offline.executor-environment`,
224235
`offline.fifo-retry`,
225236
`offline.leadership.serial-work`,
226237
`offline.leadership.report`,

‎packages/db/tests/oracle-replay-manifest.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,41 @@ const ownerGroups: ReadonlyArray<
712712
`offline`,
713713
`interruption-settlement`,
714714
],
715+
[
716+
`offline-transactions/tests/interruption-settlement-oracle.property.test.ts`,
717+
`offline`,
718+
`disposal-handoff disposal-issued-handoff disposal-review-boundaries disposal-handoff-resources`,
719+
`offline-transactions/tests/interruption-handoff-oracle.ts`,
720+
],
721+
[
722+
`offline-transactions/tests/interruption-settlement-oracle.property.test.ts`,
723+
`offline`,
724+
`settled-id-window`,
725+
`offline-transactions/tests/settled-id-window-oracle.ts`,
726+
],
727+
[
728+
`offline-transactions/tests/interruption-settlement-oracle.property.test.ts`,
729+
`offline`,
730+
`executor-api executor-controls`,
731+
`offline-transactions/tests/executor-api-oracle.ts`,
732+
],
733+
[
734+
`offline-transactions/tests/interruption-settlement-oracle.property.test.ts`,
735+
`offline`,
736+
`executor-coordination-lifecycle executor-connectivity-barrier`,
737+
`offline-transactions/tests/executor-lifecycle-oracle.ts`,
738+
],
739+
[
740+
`query-db-collection/tests/offline-executor-refresh-oracle.test.ts`,
741+
`offline`,
742+
`executor-connectivity-query-db`,
743+
],
744+
[
745+
`offline-transactions/tests/executor-environment-oracle.property.test.ts`,
746+
`offline`,
747+
`executor-environment`,
748+
`offline-transactions/tests/executor-environment-oracle.ts`,
749+
],
715750
[
716751
`offline-transactions/tests/fifo-retry-oracle.property.test.ts`,
717752
`offline`,

‎packages/offline-transactions/README.md‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ mutation function after restart; an unmarked row may replay.
226226
- `removeFromOutbox(id)` - Manually remove transaction from outbox
227227
- `clearOutbox()` - Manually remove all outbox transactions
228228
- `peekOutbox()` - View all pending transactions
229-
- `dispose()` - Clean up resources
229+
- `dispose()` - Stop new processing and release executor resources. Pending durable transactions and optimistic state on surviving Collections remain live.
230230

231231
An acknowledged `removeFromOutbox(id)` or `clearOutbox()` while a named
232232
mutation function is running does not cancel that call. If the call later
@@ -300,6 +300,26 @@ It means the server confirmed or exposed the write only when that
300300
`mutationFn` explicitly waits for the provider's acknowledgement, read-back, or
301301
sync observation before returning.
302302

303+
Disposing an executor does not cancel its admitted transactions or reject their
304+
callers. Their optimistic state stays on surviving Collections. If you replace
305+
the executor over the same outbox and retain every configured Collection object
306+
under its existing registry key in this runtime, its replay settles the original
307+
`commit()`, `when('settled')`, and per-ID waiters with each transaction's outcome.
308+
Storage adapter objects may
309+
change. An already-issued provider call can also finish after disposal.
310+
Disposal alone supplies no outcome if nothing resumes the work. This promise
311+
does not transport JavaScript promises across tabs or a page reload, and a
312+
different Collection object does not inherit those callers through an unchanged
313+
ancillary Collection. Core's conflicting-transaction rollback rules still apply
314+
to pending restored snapshots. Dispose and clean up account-scoped Collections
315+
separately when ending an account's UI lifetime;
316+
decide separately what to do with that account's durable outbox.
317+
318+
Copying or migrating pending rows between independent outboxes is outside this
319+
handoff guarantee. The executor has no durable outbox identity. Replaying a copied
320+
row with the same transaction ID and Collection objects can settle the original
321+
callers while the original outbox still retains its copy.
322+
303323
After `mutationFn` returns, the executor records a `deletion-pending` outbox
304324
phase before removing the row. If recording that phase or removing the row
305325
fails, `commit()`, `when('settled')`, and the per-ID completion waiter reject

‎packages/offline-transactions/src/OfflineExecutor.ts‎

Lines changed: 87 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,24 @@ import type { Transaction } from '@tanstack/db'
4343
/** How many settled ids an executor remembers to reject late waiters. */
4444
const SETTLED_TRANSACTIONS_REMEMBERED = 1000
4545

46+
// Pending callers and restored optimism belong to surviving Collections, even
47+
// when their executor is replaced. Adapter objects can change over one store.
48+
// Weak keys keep this coordination local to the Collections' runtime lifetime.
49+
const completionOwners = new WeakMap<
50+
OfflineConfig[`collections`][string],
51+
Set<OfflineExecutor>
52+
>()
53+
54+
/** A replacement may add Collections while retaining every prior registry entry. */
55+
function retainsCollections(
56+
configured: OfflineConfig[`collections`],
57+
prior: OfflineConfig[`collections`],
58+
): boolean {
59+
return Object.entries(prior).every(
60+
([name, collection]) => configured[name] === collection,
61+
)
62+
}
63+
4664
export class OfflineExecutor {
4765
private config: OfflineConfig
4866

@@ -493,41 +511,94 @@ export class OfflineExecutor {
493511
deferred.reject = reject
494512
})
495513

514+
this.trackCompletion()
496515
this.pendingTransactionPromises.set(transactionId, deferred)
497516
return deferred.promise
498517
}
499518

500519
// Method for TransactionExecutor to signal completion
501520
resolveTransaction(transactionId: string, result: any): void {
502-
this.rememberSettled(transactionId)
503-
const deferred = this.pendingTransactionPromises.get(transactionId)
504-
if (deferred) {
505-
deferred.resolve(result)
506-
this.pendingTransactionPromises.delete(transactionId)
507-
}
508-
509-
// Clean up the restoration transaction - the sync will provide authoritative data
510-
this.cleanupRestorationTransaction(transactionId)
521+
this.settleTransaction(transactionId, result)
511522
}
512523

513524
// Method for TransactionExecutor to signal failure
514525
rejectTransaction(transactionId: string, error: Error): void {
515-
this.rememberSettled(transactionId)
516-
const deferred = this.pendingTransactionPromises.get(transactionId)
517-
if (deferred) {
518-
deferred.reject(error)
519-
this.pendingTransactionPromises.delete(transactionId)
526+
this.settleTransaction(transactionId, undefined, error)
527+
}
528+
529+
private trackCompletion(): void {
530+
if (
531+
this.pendingTransactionPromises.size > 0 ||
532+
this.restorationTransactions.size > 0
533+
)
534+
return
535+
for (const collection of Object.values(this.config.collections)) {
536+
let owners = completionOwners.get(collection)
537+
if (!owners) completionOwners.set(collection, (owners = new Set()))
538+
owners.add(this)
520539
}
540+
}
521541

522-
// Clean up the restoration transaction and rollback optimistic state
523-
this.cleanupRestorationTransaction(transactionId, true)
542+
private settleTransaction(
543+
transactionId: string,
544+
result: unknown,
545+
error?: Error,
546+
): void {
547+
const candidates = new Set<OfflineExecutor>([this])
548+
for (const collection of Object.values(this.config.collections)) {
549+
for (const owner of completionOwners.get(collection) ?? [])
550+
candidates.add(owner)
551+
}
552+
// Select every recipient before publication can reenter this executor.
553+
const owners = [...candidates].filter(
554+
(owner) =>
555+
owner === this ||
556+
((owner.pendingTransactionPromises.has(transactionId) ||
557+
owner.restorationTransactions.has(transactionId)) &&
558+
// Either executor may deliver the outcome: a retired issued call or
559+
// its successor's replay. An ancillary overlap alone is insufficient.
560+
(retainsCollections(
561+
this.config.collections,
562+
owner.config.collections,
563+
) ||
564+
retainsCollections(
565+
owner.config.collections,
566+
this.config.collections,
567+
))),
568+
)
569+
570+
const cleanupErrors: Array<unknown> = []
571+
for (const owner of owners) {
572+
owner.rememberSettled(transactionId)
573+
const deferred = owner.pendingTransactionPromises.get(transactionId)
574+
owner.pendingTransactionPromises.delete(transactionId)
575+
if (error) deferred?.reject(error)
576+
else deferred?.resolve(result)
577+
// Publication can throw from user subscribers. Every owner still receives
578+
// its durable outcome before that exception leaves this operation.
579+
try {
580+
owner.cleanupRestorationTransaction(transactionId, !!error)
581+
} catch (cleanupError) {
582+
cleanupErrors.push(cleanupError)
583+
}
584+
585+
if (
586+
owner.pendingTransactionPromises.size === 0 &&
587+
owner.restorationTransactions.size === 0
588+
) {
589+
for (const collection of Object.values(owner.config.collections))
590+
completionOwners.get(collection)?.delete(owner)
591+
}
592+
}
593+
if (cleanupErrors.length > 0) throw cleanupErrors[0]
524594
}
525595

526596
// Method for TransactionExecutor to register restoration transactions
527597
registerRestorationTransaction(
528598
offlineTransactionId: string,
529599
restorationTransaction: Transaction,
530600
): void {
601+
this.trackCompletion()
531602
this.restorationTransactions.set(
532603
offlineTransactionId,
533604
restorationTransaction,

0 commit comments

Comments
 (0)