fix(store): isolate subscription observer dependency reads #369
main fromrefs/pull/369/head·merged 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.
- Fewer dependency-tracking operations during actual navigation.
| Work per navigation | Before | After |
|---|---|---|
| Location dependency-tracking calls | 2,000 | 1,000 |
| Tracking calls originating inside observer callbacks | 1,000 | 0 |
| Observer notifications | 1,000 | 1,000 |
| Link selector evaluations | 1,000 | 1,000 |
The observer’s snapshot read was unnecessarily re-entering dependency tracking. The fix removes that work.
- 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=3passes across the affected projects, including adapter tests, versioned type checks, lint, package checks, and builds.- Prettier checks for changed files and
git diff --checkpass.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
- 1
View your CI Pipeline Execution ↗ for commit 9102d603bc6350f7d5c3e932947ae71be7864e80
Command Status Duration Result nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded 2m 41s View ↗ nx run-many --target=build --exclude=examples/**✅ Succeeded 13s View ↗
☁️ Nx Cloud last updated this comment at
2026-09-27 19:25:43UTC@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@369commit:
9102d60davidkpiano(GitHub profile, opens in a new tab) approved these changes
davidkpiano(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
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.mdpackages/store/src/atom.tspackages/store/tests/observer-isolation.test.tsIncluded 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
activeSubbefore 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
packages/store/src/atom.ts,packages/store/tests/observer-isolation.test.ts,.changeset/quiet-observer-reads.mdactiveSubbefore 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
9102dThe observer-isolation change has no identified issue requiring resolution before merge.
Security Architecture Review#
Security architecture risk: 🔵 Low · up to
9102dThe 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
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
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.)
✨ Finishing Touches
🧪 Generate unit tests (beta)
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