Skip to content
Source
Sign inSign up
TanStack/store

fix(store): isolate subscription observer dependency reads #369

MergedSheraff(GitHub profile, opens in a new tab)merged 1 commit intomain fromrefs/pull/369/headmerged by davidkpiano(GitHub profile, opens in a new tab)

Context

while trying to track down a performance issue in Router, i may have stumbled into something interesting. Not sure yet. Basically, if you read an atom inside a subscription, it becomes added to the dependencies of that subscription

A.subscribe(() => {
  console.log(B.get())
})
A.set(1) // Callback runs — expected.
B.set(1) // Callback also runs — despite A not changing.

is that intentional or accidental? a fix would be something like this, not sure what kind of impact this may have on the performance of the library

const value = A.get() // Track A: necessary.
untracked(() => {
  observer(value)     // Reads here don't add dependencies.
})

this may also apply to all useSelector calls in React, because useSyncExternalStore doesn't use the value passed to the subscription callback, so it will always re-read the atom. Conceptually it's equivalent to this:

A.subscribe(() => {
  const value = A.get()
})

which may mean that Store has to do some dependency tracking for A inside a subscription to A, figure out it's the same and deduplicate it

👇 below this point is written by AI

Benchmarking

We measured both fewer operations and lower execution time, with an important distinction between the two implementations.

  1. Fewer dependency-tracking operations during actual navigation.
Work per navigationBeforeAfter
Location dependency-tracking calls2,0001,000
Tracking calls originating inside observer callbacks1,0000
Observer notifications1,0001,000
Link selector evaluations1,0001,000

The observer’s snapshot read was unnecessarily re-entering dependency tracking. The fix removes that work.

  1. The exact minimal fix was faster in a separate microbenchmark.

With 1,000 subscribers, 1,000 warmup updates and 5,000 measured updates per fresh process:

  • Baseline median: 40.338 ns per observer
  • Minimal fix: 37.529 ns per observer

Approximately 7% lower time, faster in all six paired rounds

Public regression tests also demonstrated elimination of unintended notifications caused by reading unrelated atoms inside observers. That is additional avoided work in affected applications, although the e18e fixture didn’t require that bug to occur.

🎯 Changes

Subscription observers currently collect dependencies from atoms they read. After a source changes, an observer that reads an unrelated atom is notified again when only that unrelated atom changes.

Clear activeSub immediately before invoking the observer, after tracking the subscribed atom. The enclosing effect's existing finally block restores the previous collector and cleans up dependencies, including when the observer throws. This keeps computed source dependencies intact while preventing incidental observer reads from adding subscription edges.

Adds five regression cases covering function and object observers, computed sources, unsubscribe behavior, and restoration of enclosing computed dependency tracking after nested notifications and observer errors. Includes a patch changeset for @tanstack/store.

This promotes the Store patch tested in TanStack/router#8527. Router's Test and benchmark jobs passed. Initial inspection of the CodSpeed simulation client-navigation results suggested small improvements, consistent with avoiding extra dependency tracking. Treat those as preliminary: the CodSpeed summary does not flag a significant client-navigation improvement. The regression tests establish the correctness fix independently of the performance results.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm test:pr.

Validation:

  • Before the fix: three isolation cases fail with duplicate notifications; two restoration cases pass.
  • After the fix: all five regression cases pass; the Store suite has 38 passing tests and one existing skipped test.
  • pnpm test:pr --parallel=3 passes across the affected projects, including adapter tests, versioned type checks, lint, package checks, and builds.
  • Prettier checks for changed files and git diff --check pass.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      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: 0d88b349-6181-48c5-a172-eac7cbe4c386

      📥 Commits

      Reviewing files that changed from the base of the PR and between 4fa67bb1a0f9bfef906e6fb2849cc47b2a5baa4d and 9102d603bc6350f7d5c3e932947ae71be7864e80.

      📒 Files selected for processing (3)
      • .changeset/quiet-observer-reads.md
      • packages/store/src/atom.ts
      • packages/store/tests/observer-isolation.test.ts

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


      📝 Walkthrough

      Walkthrough

      The subscription callback now clears activeSub before invoking an observer. Added tests cover observer reads of unrelated atoms and dependency tracking during computed, nested, and error-catching execution.

      Changes

      Subscription observer dependency isolation

      Layer / File(s)Summary
      Isolate observer reads from subscription dependencies
      packages/store/src/atom.ts, packages/store/tests/observer-isolation.test.ts, .changeset/quiet-observer-reads.md
      The callback clears activeSub before calling the observer. Tests cover function and object observers, computed dependencies, nested execution, and caught observer errors. The changeset records the patch.

      Priority: ⬇️ Low

      Estimated code review effort: 2 (Simple) | ~10 minutes

      Change: Bug fix

      Merge Risk: ⚪ Minimal · up to 9102d

      The observer-isolation change has no identified issue requiring resolution before merge.

      Security Architecture Review

      Security architecture risk: 🔵 Low · up to 9102d

      The change narrows unintended observer notifications while preserving source updates and cleanup in the reviewed paths. No security concern was identified, but coverage does not establish that every consumer and failure sequence has been assessed.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — The directly evidenced change is within the store library's subscription graph. Exposure through consumers outside the inspected paths is not established by the available dependency evidence.

      Trust Boundaries and Controls

      • inferred — The inspected path invokes an existing application-supplied observer after tracking the source; clearing the collector changes dependency ownership, not the observer's privileges or access to an external boundary.

      Resilience and Maintainability Implications

      • observed — Effect cleanup runs in finally when an observer throws, and stopping a subscription purges its dependencies; the added tests exercise caught-error restoration and unsubscribe.
      🚥 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 1 functions across 2 files. (1 skipped: 1 …Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      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.
      Title check✅ PassedThe title clearly and concisely describes the main change: isolating subscription observer dependency reads in the store.
      Description check✅ PassedThe description includes the required Changes, Checklist, and Release Impact sections. It explains the motivation, implementation, tests, validation results, and changeset status. Required checklist i…
      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 1 functions across 2 files. (1 skipped: 1 unsupported.)

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      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. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 9102d603bc6350f7d5c3e932947ae71be7864e80

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded2m 41sView ↗
      nx run-many --target=build --exclude=examples/**✅ Succeeded13sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-09-27 19:25:43 UTC

    3. @tanstack/angular-store

      npm i https://pkg.pr.new/@tanstack/angular-store@369

      @tanstack/lit-store

      npm i https://pkg.pr.new/@tanstack/lit-store@369

      @tanstack/octane-store

      npm i https://pkg.pr.new/@tanstack/octane-store@369

      @tanstack/preact-store

      npm i https://pkg.pr.new/@tanstack/preact-store@369

      @tanstack/react-store

      npm i https://pkg.pr.new/@tanstack/react-store@369

      @tanstack/solid-store

      npm i https://pkg.pr.new/@tanstack/solid-store@369

      @tanstack/store

      npm i https://pkg.pr.new/@tanstack/store@369

      @tanstack/svelte-store

      npm i https://pkg.pr.new/@tanstack/svelte-store@369

      @tanstack/vue-store

      npm i https://pkg.pr.new/@tanstack/vue-store@369

      commit: 9102d60

    4. davidkpiano(GitHub profile, opens in a new tab) approved these changes

Sign in to join this conversation.