Skip to content
Source
Sign inSign up
TanStack/db

fix(db): own a direct mutation before its handler runs #1986

MergedKyleAMathews(GitHub profile, opens in a new tab)merged 3 commits intomain fromrefs/pull/1986/headmerged by KyleAMathews(GitHub profile, opens in a new tab)

A direct mutation whose handler confirmed it through sync before returning stayed pending forever. This PR makes the Collection own the request before its handler runs, so that confirmation waits for the transaction and then settles the row.

const todos = createCollection({
  // ...
  sync: { sync: (actions) => (sync = actions) },
  onInsert: ({ transaction }) => {
    // Confirm the insert before the handler returns.
    sync.begin()
    sync.write({ type: `insert`, value: transaction.mutations[0].modified })
    sync.commit()
    return Promise.resolve()
  },
})

await todos.insert({ id: `1`, text: `a` }).isPersisted.promise
todos.get(`1`).$hasPendingWrites
// main: true, after the transaction completed. This PR: false.

The docs define $hasPendingWrites as true only "while a pending local optimistic mutation affects the row". On main, the row also kept its optimistic value, and the next remote change to it reported $origin: 'local'.

Cause

insert, update, and delete called commit() on the direct transaction before they added it to the Collection. commit() runs the handler synchronously up to its first await. A handler that wrote through sync at that point found no persisting request, so the batch applied at once and acknowledged nothing. Registration then put the optimistic overlay over the confirmed row, and nothing retired it.

Each direct path now registers the transaction, schedules its cleanup, and recomputes optimistic state before it commits. The production change is net −2 lines in collection/mutations.ts.

A handler that awaits before it writes was never affected. Transactions from createTransaction and createOptimisticAction register in mutate() before the caller commits, so they never had this gap either. Local-only collections reach the changed path, but their rows never report pending writes.

The oracle came first

The optimistic-history oracle wrote every source batch after the edit call returned, so no generated history reached the handler body. The first commit changes that:

  • edit and delete steps can carry a source batch that the handler writes before it returns.
  • The model treats that batch as a source batch written while the request is active.
  • Six pinned replays cover insert, update, and delete, immediate and not.
  • A witness requires the fixed campaign to generate these batches.

On main, the extended oracle fails 7 of 95 tests: 5 pinned cases and both generated campaigns. With the fix, all 95 pass. Six broken versions of the fix also fail it. In three, one path commits before it registers. In the other three, one path recomputes after it commits.

The bug turned up while I tested whether the existing tests would catch mistakes in the planned state.ts code-weight refactor. The review record has the details and limits.

Verification

On 3ab428439, with the built dist:

  • packages/db Vitest: 200 files, 7,857 tests. tsc --noEmit reports no errors.
  • pnpm --filter @tanstack/db test:dist (290 tests) and pnpm test:minified-db pass.
  • Unit tests pass for query-db-collection (558), electric-db-collection (629), and offline-transactions (73).

This pull request and its description were written by Isaac.

Summary by CodeRabbit

  • Bug Fixes
    • Direct insert, update, and delete requests confirmed by a sync inside their handlers now settle correctly after the transaction is registered, preventing stale optimistic changes and incorrect local-origin reporting.
  • Documentation
    • Added guidance and review findings on handling source batches written within mutation handlers.
  • Tests
    • Expanded coverage for handler-triggered syncs across inserts, updates, and deletes, including immediate and queued application.
    1. Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Advanced

      Run ID: 04769ac0-b381-44d5-a73c-50b6546b68d7

      📥 Commits

      Reviewing files that changed from the base of the PR and between f2f92c5b2c1500cc7b19c4294039700bb77dd4b3 and 3342978f78d6165ac985194c04cf07355e6ccd25.

      📒 Files selected for processing (6)
      • .changeset/own-request-before-handler.md
      • docs/contributing/oracle-coverage.md
      • docs/contributing/oracle-reviews/2026-10-01-handler-source-batch.md
      • packages/db/src/collection/mutations.ts
      • packages/db/tests/collection-state-retention-oracle.property.test.ts
      • packages/db/tests/optimistic-history-oracle.ts

      Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.


      📝 Walkthrough

      Walkthrough

      Direct insert, update, and delete operations now register their transactions before committing. The optimistic-history oracle models source batches written inside mutation handlers and tests how those batches interact with request settlement.

      Changes

      Direct mutation settlement

      Layer / File(s)Summary
      Register direct mutation requests before commit
      packages/db/src/collection/mutations.ts, .changeset/own-request-before-handler.md, docs/contributing/oracle-reviews/2026-10-01-handler-source-batch.md
      Insert, update, and delete register the transaction, schedule cleanup, and recompute optimistic state before commit. The review record describes the prior ordering and the documented scope of the change.
      Model handler-written source batches
      packages/db/tests/optimistic-history-oracle.ts
      The oracle adds a shared source-batch shape and writer. It can apply a configured batch inside a mutation handler and checks that the handler consumes it.
      Generate and exercise handler-batch histories
      packages/db/tests/collection-state-retention-oracle.property.test.ts, docs/contributing/oracle-coverage.md
      Generated histories can include handler batches. Tests cover insert, update, and delete with immediate and queued sync, then settle the request and apply a later source batch.

      Priority: ⬇️ Low

      Estimated code review effort: 3 (Moderate) | ~20 minutes

      Change: Bug fix · Severity of issue fixed: Low

      Merge Risk: ⚪ Minimal · up to 33429

      No actionable merge-blocking issue is established; the change is mergeable after normal checks.

      Security Architecture Review

      Security architecture risk: 🟡 Moderate · up to 33429

      The fix addresses stuck optimistic writes, but a handler that waits for its own sync confirmation can now stall both the mutation and unrelated updates in the same collection. Explicit recovery paths exist. No privilege expansion was identified in the inspected paths, although deployed usage remains unverified.

      Retained concerns

      • Medium · reliability · inferred: A direct insert, update, or delete handler that synchronously opens and writes a normal source batch, then awaits or returns sync.commit(), can deadlock its own transaction. The receipt waits for source publication, while publication waits for the persisting transaction whose handler is awaiting that receipt. Without intervention, this also blocks unrelated normal source batches in the same collection. This condition was not present during synchronous handler execution in the documented pre-repair ordering when no other persisting transaction existed.
      Security review details

      Security Blast Radius

      • inferred — The identified wait cycle can contain more than the initiating row: one stalled persisting transaction prevents ordinary source publication across its collection. Cross-collection, tenant, service, or data-store propagation was not established.

      Security Findings and Attack Paths

      • inferred — The liveness concern requires an application-configured handler that waits for its normal source batch's visibility before returning. The inspected ordering change demonstrates this failure path, but does not establish attacker control of handler implementation, an affected deployed caller, or privilege gain; it is not a verified security vulnerability.

      Trust Boundaries and Controls

      • inferred — The inspected change moves collection ownership earlier around existing configured callbacks and source publication. It does not itself supply a new callback authority or authorization mechanism. Schema and key validation remain local integrity controls, not evidence of server-side access control.

      Resilience and Maintainability Implications

      • observed — Source cancellation is effective only before application starts. Explicit transaction rollback exits persisting state, rejects persistence, and touches the collection. Immediate or truncate publication is another escape from the queue gate, so the circular wait is conditional rather than unavoidable for every handler confirmation.
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (3 skipped: 3 …Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Title check✅ PassedThe title clearly and concisely describes the main change: direct mutations now own the request before the handler runs.
      Description check✅ PassedThe description is detailed, relevant, and explains the motivation, implementation, tests, and release impact. It does not use the required template headings or include the checklist items, but the co…
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Full details: Docstring Coverage

      Explanation

      Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 3 files. (3 skipped: 3 unsupported.)

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches 💡 1
      📝 Generate docstrings 💡
      • Commit to this branch
      • Create a new PR
      🧪 Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Autopilot is currently an internal CodeRabbit preview.


      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. More templates

      @tanstack/angular-db

      npm i https://pkg.pr.new/@tanstack/angular-db@1986

      @tanstack/browser-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/browser-db-sqlite-persistence@1986

      @tanstack/capacitor-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/capacitor-db-sqlite-persistence@1986

      @tanstack/cloudflare-durable-objects-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/cloudflare-durable-objects-db-sqlite-persistence@1986

      @tanstack/db

      npm i https://pkg.pr.new/@tanstack/db@1986

      @tanstack/db-ivm

      npm i https://pkg.pr.new/@tanstack/db-ivm@1986

      @tanstack/db-sqlite-persistence-core

      npm i https://pkg.pr.new/@tanstack/db-sqlite-persistence-core@1986

      @tanstack/electric-db-collection

      npm i https://pkg.pr.new/@tanstack/electric-db-collection@1986

      @tanstack/electron-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/electron-db-sqlite-persistence@1986

      @tanstack/expo-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/expo-db-sqlite-persistence@1986

      @tanstack/node-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/node-db-sqlite-persistence@1986

      @tanstack/offline-transactions

      npm i https://pkg.pr.new/@tanstack/offline-transactions@1986

      @tanstack/powersync-db-collection

      npm i https://pkg.pr.new/@tanstack/powersync-db-collection@1986

      @tanstack/query-db-collection

      npm i https://pkg.pr.new/@tanstack/query-db-collection@1986

      @tanstack/react-db

      npm i https://pkg.pr.new/@tanstack/react-db@1986

      @tanstack/react-native-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/react-native-db-sqlite-persistence@1986

      @tanstack/react-router-with-db

      npm i https://pkg.pr.new/@tanstack/react-router-with-db@1986

      @tanstack/rxdb-db-collection

      npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@1986

      @tanstack/solid-db

      npm i https://pkg.pr.new/@tanstack/solid-db@1986

      @tanstack/svelte-db

      npm i https://pkg.pr.new/@tanstack/svelte-db@1986

      @tanstack/tauri-db-sqlite-persistence

      npm i https://pkg.pr.new/@tanstack/tauri-db-sqlite-persistence@1986

      @tanstack/trailbase-db-collection

      npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@1986

      @tanstack/vue-db

      npm i https://pkg.pr.new/@tanstack/vue-db@1986

      commit: 3342978

    3. Size Change: -1 B (0%)

      Total Size: 174 kB

      📦 View Changed
      FilenameSizeChange
      packages/db/dist/esm/collection/mutations.js2.59 kB-1 B (-0.04%)
      ℹ️ View Unchanged
      FilenameSize
      packages/db/dist/esm/client.js3.61 kB
      packages/db/dist/esm/collection-options.js236 B
      packages/db/dist/esm/collection/change-events.js2.07 kB
      packages/db/dist/esm/collection/changes.js2.72 kB
      packages/db/dist/esm/collection/cleanup-queue.js808 B
      packages/db/dist/esm/collection/events.js481 B
      packages/db/dist/esm/collection/index.js4.57 kB
      packages/db/dist/esm/collection/indexes.js2.06 kB
      packages/db/dist/esm/collection/lifecycle.js2.63 kB
      packages/db/dist/esm/collection/state.js8.32 kB
      packages/db/dist/esm/collection/subscription.js8.63 kB
      packages/db/dist/esm/collection/sync.js4.96 kB
      packages/db/dist/esm/collection/transaction-metadata.js144 B
      packages/db/dist/esm/deferred.js207 B
      packages/db/dist/esm/errors.js5.49 kB
      packages/db/dist/esm/event-emitter.js961 B
      packages/db/dist/esm/index.js3.94 kB
      packages/db/dist/esm/indexes/auto-index.js841 B
      packages/db/dist/esm/indexes/base-index.js1.25 kB
      packages/db/dist/esm/indexes/basic-index.js2.01 kB
      packages/db/dist/esm/indexes/btree-index.js2.3 kB
      packages/db/dist/esm/indexes/index-registry.js820 B
      packages/db/dist/esm/indexes/reverse-index.js370 B
      packages/db/dist/esm/live-query-adapter.js318 B
      packages/db/dist/esm/live-query-observer.js4.53 kB
      packages/db/dist/esm/live-query-options.js731 B
      packages/db/dist/esm/live-query-window-controller.js4.12 kB
      packages/db/dist/esm/local-only.js989 B
      packages/db/dist/esm/local-storage.js2.17 kB
      packages/db/dist/esm/optimistic-action.js359 B
      packages/db/dist/esm/paced-mutations.js702 B
      packages/db/dist/esm/persisted-readiness.js195 B
      packages/db/dist/esm/proxy.js2.77 kB
      packages/db/dist/esm/query/builder/clone-query.js766 B
      packages/db/dist/esm/query/builder/functions.js1.45 kB
      packages/db/dist/esm/query/builder/index.js6.79 kB
      packages/db/dist/esm/query/builder/query-ir.js116 B
      packages/db/dist/esm/query/builder/ref-proxy-identity.js198 B
      packages/db/dist/esm/query/builder/ref-proxy.js1.35 kB
      packages/db/dist/esm/query/builder/wrapper-identity.js221 B
      packages/db/dist/esm/query/compiler/evaluators.js2.1 kB
      packages/db/dist/esm/query/compiler/expressions.js603 B
      packages/db/dist/esm/query/compiler/group-by.js4.2 kB
      packages/db/dist/esm/query/compiler/index.js9.39 kB
      packages/db/dist/esm/query/compiler/joins.js3.06 kB
      packages/db/dist/esm/query/compiler/lazy-targets.js1.14 kB
      packages/db/dist/esm/query/compiler/order-by.js2 kB
      packages/db/dist/esm/query/compiler/parent-routes.js319 B
      packages/db/dist/esm/query/compiler/query-equivalence.js455 B
      packages/db/dist/esm/query/compiler/route-metadata.js1.24 kB
      packages/db/dist/esm/query/compiler/select.js1.59 kB
      packages/db/dist/esm/query/effect.js4.86 kB
      packages/db/dist/esm/query/equality-value-identity.js591 B
      packages/db/dist/esm/query/expression-helpers.js1.45 kB
      packages/db/dist/esm/query/ir-stable-identity.js4.22 kB
      packages/db/dist/esm/query/ir.js1.69 kB
      packages/db/dist/esm/query/live-query-collection.js391 B
      packages/db/dist/esm/query/live/bucket-facade-adapter.js2.67 kB
      packages/db/dist/esm/query/live/collection-config-builder.js6.47 kB
      packages/db/dist/esm/query/live/collection-registry.js264 B
      packages/db/dist/esm/query/live/collection-subscriber.js2.05 kB
      packages/db/dist/esm/query/live/graph-scheduler.js303 B
      packages/db/dist/esm/query/live/internal.js145 B
      packages/db/dist/esm/query/live/materialized-pipeline.js2.32 kB
      packages/db/dist/esm/query/live/ordered-source-loader.js4.14 kB
      packages/db/dist/esm/query/live/subset-demand-controller.js1.65 kB
      packages/db/dist/esm/query/live/utils.js1.2 kB
      packages/db/dist/esm/query/optimizer.js2.92 kB
      packages/db/dist/esm/query/query-once.js359 B
      packages/db/dist/esm/query/runtime-reference-identity.js630 B
      packages/db/dist/esm/query/subset-dedupe.js493 B
      packages/db/dist/esm/scheduler.js1.13 kB
      packages/db/dist/esm/SortedMap.js1.58 kB
      packages/db/dist/esm/strategies/debounceStrategy.js331 B
      packages/db/dist/esm/strategies/queueStrategy.js488 B
      packages/db/dist/esm/strategies/throttleStrategy.js386 B
      packages/db/dist/esm/sync-persistence.js530 B
      packages/db/dist/esm/transactions.js3.89 kB
      packages/db/dist/esm/utils.js1.43 kB
      packages/db/dist/esm/utils/array-utils.js270 B
      packages/db/dist/esm/utils/browser-polyfills.js304 B
      packages/db/dist/esm/utils/btree.js3.02 kB
      packages/db/dist/esm/utils/callbacks.js174 B
      packages/db/dist/esm/utils/comparison.js1.59 kB
      packages/db/dist/esm/utils/cursor.js677 B
      packages/db/dist/esm/utils/error.js167 B
      packages/db/dist/esm/utils/get-or-create.js155 B
      packages/db/dist/esm/utils/index-optimization.js2.42 kB
      packages/db/dist/esm/utils/source-record.js140 B
      packages/db/dist/esm/utils/type-guards.js230 B
      packages/db/dist/esm/utils/uuid.js449 B
      packages/db/dist/esm/virtual-props.js413 B
      compressed-size-action::db-package-size
    4. Size Change: 0 B

      Total Size: 8.51 kB

      ℹ️ View Unchanged
      FilenameSize
      packages/react-db/dist/esm/DbProvider.js317 B
      packages/react-db/dist/esm/HydrationBoundary.js263 B
      packages/react-db/dist/esm/index.js330 B
      packages/react-db/dist/esm/live-query-internals.js282 B
      packages/react-db/dist/esm/useLiveInfiniteQuery.js1.93 kB
      packages/react-db/dist/esm/useLiveQuery.js3.3 kB
      packages/react-db/dist/esm/useLiveQueryEffect.js355 B
      packages/react-db/dist/esm/useLiveSuspenseQuery.js1.33 kB
      packages/react-db/dist/esm/usePacedMutations.js401 B
      compressed-size-action::react-db-package-size

Sign in to join this conversation.