feat(db): shared live-query observer + migrate all five adapters (RFC #1623 step 3) #1642
main fromrefs/pull/1642/head·merged by tannerlinsley RFC #1623 step 3 — the shared observer that unifies the live-query lifecycle, now adopted by all five adapters. This is where the duplicated lifecycle across adapters actually collapses.
Base: stacked on refactor/extract-adapter-helpers (#1641, step 2) → conformance suite (#1636). Re-target down the stack as each lands.
The observer#
createLiveQueryObserver(collection | null, { deferInitialNotify? }) in @tanstack/db. Given a resolved live-query collection (or null for disabled), it owns everything the five adapters used to each re-implement:
- start sync
- subscribe to changes (with
includeInitialState, so consumers get initial rows + deltas through one aligned channel) - the already-ready / loading→ready notify race (
onFirstReady, de-duplicated) - a stable per-revision snapshot for wholesale consumers (
getSnapshot()— reference-stable foruseSyncExternalStore) - delivery of the raw
ChangeMessage[]to subscribers for granular consumers
The last two are the item-6 decision made concrete: the observer carries both a snapshot and the change set, so Vue/Svelte/Solid keep fine-grained keyed-map updates while React/Angular consume the snapshot.
Input resolution stays in each adapter (query fn / config / collection / disabled) — it's framework-reactive and fixed separately (#1637/#1638). The observer owns everything after the input resolves.
All five adapters migrated#
Each keeps its native reactivity; the duplicated subscribe/onFirstReady/status/ready-race plumbing is gone:
| Adapter | Consumer kind | How it materializes |
|---|---|---|
| React | wholesale | useSyncExternalStore(observer.subscribe, observer.getSnapshot) — opts into deferInitialNotify |
| Vue | granular | applies ChangeMessage[] deltas to its reactive map |
| Svelte | granular | applies deltas to its SvelteMap (runes) |
| Solid | granular | applies deltas to its ReactiveMap; keeps createResource/Suspense + reconcile |
| Angular | wholesale | re-reads the collection into signals on each notify |
Two contract refinements the migrations forced (both interesting)#
includeInitialStateis required, not optional. Seeding a granular adapter's map fromgetSnapshot()and subscribing without initial state desyncs the collection's per-subscriber change stream — deletes arrived as empty batches. The observer must subscribe with initial state so initial rows + deltas flow through one channel.deferInitialNotifyis per-consumer. React'suseSyncExternalStoremust not get a synchronous notify duringsubscribe, so React opts into deferring the initial notify to a microtask. Effect/watcher adapters (Svelte reads synchronously afterflushSync) want it synchronous, which is the default.
Bonus#
Angular's config-object-input conformance gap closes here as a side effect — the observer starts sync on the resolved collection regardless of the config path. (PR #1638 still fixes the source path directly.)
Verification#
All green: @tanstack/db 2461, react 119, vue 54, svelte 54, solid 62, angular 50 (+1 todo) — including the cross-adapter conformance suite that guards every migration. Observer unit tests cover both wholesale and granular paths, disabled, deferred-notify, and dispose. Minor changeset for db, patch for all five adapters.
🤖 Generated with Claude Code
Summary by CodeRabbit#
New Features
- Added a shared live-query observer API (
createLiveQueryObserver) available from the main DB package. - Exposed live-query
statein adapter conformance results/handles (React, Vue, Svelte, Solid, Angular) and added a new conformance scenario. - Updated live-query hooks to use the shared observer for consistent behavior across frameworks.
- Added a shared live-query observer API (
Bug Fixes
- Improved live-query lifecycle correctness (readiness transitions, cleanup/disposal, and preventing stale updates), plus stable snapshot/state consistency across resubscribe and recompile.
Tests
- Added observer, React StrictMode, and additional live-query state/async continuation test coverage.
- 1
More templates
@tanstack/angular-db
npm i https://pkg.pr.new/@tanstack/angular-db@1642@tanstack/browser-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/browser-db-sqlite-persistence@1642@tanstack/capacitor-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/capacitor-db-sqlite-persistence@1642@tanstack/cloudflare-durable-objects-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/cloudflare-durable-objects-db-sqlite-persistence@1642@tanstack/db
npm i https://pkg.pr.new/@tanstack/db@1642@tanstack/db-ivm
npm i https://pkg.pr.new/@tanstack/db-ivm@1642@tanstack/db-sqlite-persistence-core
npm i https://pkg.pr.new/@tanstack/db-sqlite-persistence-core@1642@tanstack/electric-db-collection
npm i https://pkg.pr.new/@tanstack/electric-db-collection@1642@tanstack/electron-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/electron-db-sqlite-persistence@1642@tanstack/expo-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/expo-db-sqlite-persistence@1642@tanstack/node-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/node-db-sqlite-persistence@1642@tanstack/offline-transactions
npm i https://pkg.pr.new/@tanstack/offline-transactions@1642@tanstack/powersync-db-collection
npm i https://pkg.pr.new/@tanstack/powersync-db-collection@1642@tanstack/query-db-collection
npm i https://pkg.pr.new/@tanstack/query-db-collection@1642@tanstack/react-db
npm i https://pkg.pr.new/@tanstack/react-db@1642@tanstack/react-native-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/react-native-db-sqlite-persistence@1642@tanstack/rxdb-db-collection
npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@1642@tanstack/solid-db
npm i https://pkg.pr.new/@tanstack/solid-db@1642@tanstack/svelte-db
npm i https://pkg.pr.new/@tanstack/svelte-db@1642@tanstack/tauri-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/tauri-db-sqlite-persistence@1642@tanstack/trailbase-db-collection
npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@1642@tanstack/vue-db
npm i https://pkg.pr.new/@tanstack/vue-db@1642commit:
c91af81Size Change: +2.25 kB (+1.79%)
Total Size: 128 kB
📦 View Changed
Filename Size Change packages/db/dist/esm/collection/changes.js1.4 kB +22 B (+1.59%) packages/db/dist/esm/collection/index.js3.73 kB +112 B (+3.09%) packages/db/dist/esm/collection/lifecycle.js1.7 kB +4 B (+0.24%) packages/db/dist/esm/errors.js5.13 kB +37 B (+0.73%) packages/db/dist/esm/index.js3.21 kB +44 B (+1.39%) packages/db/dist/esm/live-query-observer.js2.03 kB +2.03 kB (new file) 🆕 compressed-size-action::db-package-sizeℹ️ View Unchanged
Filename Size packages/db/dist/esm/collection/change-events.js1.43 kB packages/db/dist/esm/collection/cleanup-queue.js810 B packages/db/dist/esm/collection/events.js434 B packages/db/dist/esm/collection/indexes.js1.99 kB packages/db/dist/esm/collection/mutations.js2.47 kB packages/db/dist/esm/collection/state.js5.48 kB packages/db/dist/esm/collection/subscription.js3.74 kB packages/db/dist/esm/collection/sync.js2.88 kB packages/db/dist/esm/collection/transaction-metadata.js144 B packages/db/dist/esm/deferred.js207 B packages/db/dist/esm/event-emitter.js748 B packages/db/dist/esm/indexes/auto-index.js829 B packages/db/dist/esm/indexes/base-index.js784 B packages/db/dist/esm/indexes/basic-index.js2.17 kB packages/db/dist/esm/indexes/btree-index.js2.29 kB packages/db/dist/esm/indexes/index-registry.js820 B packages/db/dist/esm/indexes/reverse-index.js557 B packages/db/dist/esm/live-query-adapter.js318 B packages/db/dist/esm/local-only.js916 B packages/db/dist/esm/local-storage.js2.12 kB packages/db/dist/esm/optimistic-action.js359 B packages/db/dist/esm/paced-mutations.js496 B packages/db/dist/esm/proxy.js3.75 kB packages/db/dist/esm/query/builder/functions.js1.47 kB packages/db/dist/esm/query/builder/index.js5.84 kB packages/db/dist/esm/query/builder/ref-proxy.js1.24 kB packages/db/dist/esm/query/compiler/evaluators.js1.89 kB packages/db/dist/esm/query/compiler/expressions.js430 B packages/db/dist/esm/query/compiler/group-by.js3.56 kB packages/db/dist/esm/query/compiler/index.js6.67 kB packages/db/dist/esm/query/compiler/joins.js2.5 kB packages/db/dist/esm/query/compiler/lazy-targets.js923 B packages/db/dist/esm/query/compiler/order-by.js1.74 kB packages/db/dist/esm/query/compiler/select.js1.53 kB packages/db/dist/esm/query/effect.js4.77 kB packages/db/dist/esm/query/expression-helpers.js1.43 kB packages/db/dist/esm/query/ir.js1.25 kB packages/db/dist/esm/query/live-query-collection.js360 B packages/db/dist/esm/query/live/collection-config-builder.js9.1 kB packages/db/dist/esm/query/live/collection-registry.js264 B packages/db/dist/esm/query/live/collection-subscriber.js1.93 kB packages/db/dist/esm/query/live/internal.js145 B packages/db/dist/esm/query/live/utils.js1.81 kB packages/db/dist/esm/query/optimizer.js2.92 kB packages/db/dist/esm/query/predicate-utils.js2.97 kB packages/db/dist/esm/query/query-once.js359 B packages/db/dist/esm/query/subset-dedupe.js960 B packages/db/dist/esm/scheduler.js1.3 kB packages/db/dist/esm/SortedMap.js1.3 kB packages/db/dist/esm/strategies/debounceStrategy.js247 B packages/db/dist/esm/strategies/queueStrategy.js428 B packages/db/dist/esm/strategies/throttleStrategy.js246 B packages/db/dist/esm/transactions.js3.04 kB packages/db/dist/esm/utils.js927 B packages/db/dist/esm/utils/array-utils.js273 B packages/db/dist/esm/utils/browser-polyfills.js304 B packages/db/dist/esm/utils/btree.js5.61 kB packages/db/dist/esm/utils/comparison.js1.15 kB packages/db/dist/esm/utils/cursor.js457 B packages/db/dist/esm/utils/index-optimization.js2.39 kB packages/db/dist/esm/utils/type-guards.js157 B packages/db/dist/esm/utils/uuid.js449 B packages/db/dist/esm/virtual-props.js360 B Size Change: 0 B
Total Size: 4.22 kB
compressed-size-action::react-db-package-sizeℹ️ View Unchanged
Filename Size packages/react-db/dist/esm/index.js249 B packages/react-db/dist/esm/useLiveInfiniteQuery.js1.32 kB packages/react-db/dist/esm/useLiveQuery.js1.33 kB packages/react-db/dist/esm/useLiveQueryEffect.js355 B packages/react-db/dist/esm/useLiveSuspenseQuery.js567 B packages/react-db/dist/esm/usePacedMutations.js401 B kevin-dp(GitHub profile, opens in a new tab) changed the title
- packages/angular-db/tests/conformance.test.ts line 218Outdated@@ -213,10 +213,6 @@213213 mountCollection,214214 mountConfig,215215 mountDisabled,216- // Divergence the suite surfaced: angular-db's plain `{ query }` config-object217- // path calls createLiveQueryCollection(opts) as-is, without injecting218- // startSync:true the way the query-fn path does — so a bare `{ query }` never219- // syncs and returns empty. React/Vue/Svelte/Solid all auto-start a config220- // object; Angular requires an explicit `startSync: true` (its own config test221- // passes it). Recorded until angular-db aligns.222- knownGaps: [`config-object-input`],216+ // The config-object gap is now closed here: the observer starts sync on the217+ // resolved collection regardless of the config path, so a bare `{ query }`218+ // syncs. (PR #1638 also fixes the source path directly.)
This comment is not needed. It only makes sense with the scope of this PR but no longer makes sense when we will merge it into main.
Removed in cf92efd4 — the comment was scoped to this PR and wouldn't make sense on main.
packages/angular-db/tests/conformance.test.ts line 218Outdated@@ -213,10 +213,6 @@213213 mountCollection,214214 mountConfig,215215 mountDisabled,216- // Divergence the suite surfaced: angular-db's plain `{ query }` config-object217- // path calls createLiveQueryCollection(opts) as-is, without injecting218- // startSync:true the way the query-fn path does — so a bare `{ query }` never219- // syncs and returns empty. React/Vue/Svelte/Solid all auto-start a config220- // object; Angular requires an explicit `startSync: true` (its own config test221- // passes it). Recorded until angular-db aligns.222- knownGaps: [`config-object-input`],216+ // The config-object gap is now closed here: the observer starts sync on the217+ // resolved collection regardless of the config path, so a bare `{ query }`218+ // syncs. (PR #1638 also fixes the source path directly.)let's remove this comment, it only makes sense within this PR but in main it won't make sense anymore.
Removed in cf92efd4 — the comment was scoped to this PR and wouldn't make sense on main.
kevin-dp(GitHub profile, opens in a new tab)replied on
packages/angular-db/tests/conformance.test.tsline 218Removed in cf92efd4 — the comment was scoped to this PR and wouldn't make sense on main.
kevin-dp(GitHub profile, opens in a new tab)replied on
packages/angular-db/tests/conformance.test.tsline 218Removed in cf92efd4 — the comment was scoped to this PR and wouldn't make sense on main.
Code review#
Found 1 issue:
onFirstReadyregistration is not detach-safe.LiveQueryObserverImpl.attach()registers a callback every time the observer gets its first listener while the collection is not ready, butdetach()only unsubscribes the change subscription. SinceCollectionLifecycleManager.onFirstReady()only pushes into an array and does not return an unsubscribe, a subscribe → unsubscribe before ready → subscribe again sequence leaves two callbacks queued; whenmarkReady()drains them, both callnotify(undefined)against the current listener.
I red-tested this locally with a temporary observer test on this branch: after subscribing, unsubscribing before first ready, subscribing again, and then calling
markReady, the listener saw 2 synthetic ready notifications where the expected value was 1.Suggested fix: either make
onFirstReadyreturn an unsubscribe and dispose it withcollectionUnsub, or arm only one ready callback per observer/collection and guard it with a generation token so stale callbacks no-op after detach/dispose.🤖 Generated with Claude Code
- If this code review was useful, please react with 👍. Otherwise, react with 👎.Good catch — reproduced it exactly (subscribe → unsubscribe-before-ready → subscribe →
markReadygave 2 synthetic ready notifications instead of 1). Fixed in 8ee8e8e7 with your option B: an attach-generation token, so a callback left behind by a superseded attach no-ops instead of notifying. Went with the observer-local guard rather than changingonFirstReady's signature to keep the fix contained. Added a regression test for the sequence.KyleAMathews(GitHub profile, opens in a new tab) approved these changes
Actionable comments posted: 5
🧹 Nitpick comments (3)
packages/db/src/live-query-observer.ts (1)
24-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTighten the collection generic instead of exposing
any.The observer API can use
Collection<T, TKey>here; the default utility generic keeps the API precise without leakingany.Proposed typing cleanup
- collection: Collection<T, TKey, any> | undefined + collection: Collection<T, TKey> | undefined ... - private readonly collection: Collection<T, TKey, any> | null + private readonly collection: Collection<T, TKey> | null ... - collection: Collection<T, TKey, any> | null, + collection: Collection<T, TKey> | null, ... - collection: Collection<T, TKey, any> | null | undefined, + collection: Collection<T, TKey> | null | undefined,As per coding guidelines, “Avoid using
anytypes; useunknowninstead when the type is truly unknown, and provide proper type annotations for return values.”Also applies to: 86-100, 248-253
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/src/live-query-observer.ts` at line 24, The observer typings are leaking `any` through the collection generic, so tighten the `LiveQueryObserver` API to use `Collection<T, TKey>` (or the existing default utility generic) instead of `Collection<T, TKey, any>`. Update the `collection` field and the related observer methods/types in `live-query-observer` that reference this shape, including the other affected spots noted in the diff, so the generic stays precise without exposing `any`.Source: Coding guidelines
packages/db/tests/live-query-observer.test.ts (1)
45-45: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the
as anycasts from observer tests.These casts hide whether the new public factory accepts the collection types it is expected to support.
As per coding guidelines, “Avoid using
anytypes; useunknowninstead when the type is truly unknown.”Also applies to: 60-60, 92-92, 121-123, 138-138
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/tests/live-query-observer.test.ts` at line 45, The observer tests are masking the real type compatibility of createLiveQueryObserver by casting sources to any; update the affected test cases to pass properly typed collection/source values instead of any so the public factory is exercised against its supported collection types. Use the existing test helpers and types around createLiveQueryObserver, makeSource, and the other affected observer assertions to infer the correct typings, and replace any remaining any casts in the referenced test blocks with explicit, appropriate types.Source: Coding guidelines
packages/react-db/src/useLiveQuery.ts (1)
435-439: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid erasing the hook return type with
any.The new
as anybypasses the overload contracts at the return boundary. Please cast to the hook’s concrete result type or add a typed adapter fromLiveQuerySnapshotto the existing public return shape. As per coding guidelines, “Avoid usinganytypes” and “Always provide the most precise return type annotation.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/react-db/src/useLiveQuery.ts` around lines 435 - 439, The return in useLiveQuery is erasing the hook’s type contract with as any, which bypasses the overload guarantees. Update the useSyncExternalStore result to preserve the concrete hook return type by casting to the existing public snapshot/result type or introducing a typed adapter from LiveQuerySnapshot, and keep the return aligned with the function’s declared overloads instead of using any.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/db/src/live-query-observer.ts`: - Around line 112-115: The snapshot cache in `LiveQueryObserver.getSnapshot()` can stay stale when `preload()` or a status-only transition makes the collection ready without bumping `version`. Update the cache invalidation logic so `preload()` and any readiness/status changes also force a cached snapshot refresh, not just version changes. Use the existing `cachedVersion`, `version`, and `getSnapshot()` flow, and make sure the invalidation also covers the related status transition path referenced in the observer. - Around line 199-204: The deferred initial notification flush in LiveQueryObserver can still emit stale changes after a subscribe/unsubscribe/resubscribe cycle. Update the deferInitialNotify path in live-query-observer’s attach logic to associate the queued microtask with the specific attach instance (for example via an incrementing attach token or generation) and skip flushing if a newer attach has superseded it or the observer was detached. Ensure the guard is checked before emitting deferred changes in the queueMicrotask callback. In `@packages/db/tests/live-query-observer.test.ts`: - Around line 120-155: Add regression coverage for the remaining lifecycle races in createLiveQueryObserver: extend the existing observer tests to reproduce a deferInitialNotify flow where a subscription is unsubscribed and then resubscribed before the microtask flush, and verify only the latest subscription receives the deferred notify. Also add a test around getSnapshot() and preload() that calls getSnapshot() before preload(), then asserts a ready snapshot is returned after preload() completes. Use the existing createLiveQueryObserver, subscribe, getSnapshot, and preload behavior to keep the tests aligned with the bug scenarios. In `@packages/react-db/src/useLiveQuery.ts`: - Around line 414-423: Move the observer teardown out of the render path in useLiveQuery: the needsNewCollection branch should not call observerRef.current?.dispose() during render, because that can tear down the committed subscription before React finishes updating. Update useLiveQuery to perform observer disposal/recreation in a commit-phase effect or cleanup, and add separate state/flag tracking for initialization so disabled queries do not recreate the observer on every render when collectionRef.current remains null. In `@packages/solid-db/src/useLiveQuery.ts`: - Around line 393-397: Clear the existing Solid state before wiring up the new observer in useLiveQuery so stale rows from the previous collection are removed when collection() changes. Add the reset immediately before createLiveQueryObserver/currentCollection subscription setup, and keep the logic localized around observer.subscribe so includeInitialState only repopulates the new collection instead of leaving old keys behind. --- Nitpick comments: In `@packages/db/src/live-query-observer.ts`: - Line 24: The observer typings are leaking `any` through the collection generic, so tighten the `LiveQueryObserver` API to use `Collection<T, TKey>` (or the existing default utility generic) instead of `Collection<T, TKey, any>`. Update the `collection` field and the related observer methods/types in `live-query-observer` that reference this shape, including the other affected spots noted in the diff, so the generic stays precise without exposing `any`. In `@packages/db/tests/live-query-observer.test.ts`: - Line 45: The observer tests are masking the real type compatibility of createLiveQueryObserver by casting sources to any; update the affected test cases to pass properly typed collection/source values instead of any so the public factory is exercised against its supported collection types. Use the existing test helpers and types around createLiveQueryObserver, makeSource, and the other affected observer assertions to infer the correct typings, and replace any remaining any casts in the referenced test blocks with explicit, appropriate types. In `@packages/react-db/src/useLiveQuery.ts`: - Around line 435-439: The return in useLiveQuery is erasing the hook’s type contract with as any, which bypasses the overload guarantees. Update the useSyncExternalStore result to preserve the concrete hook return type by casting to the existing public snapshot/result type or introducing a typed adapter from LiveQuerySnapshot, and keep the return aligned with the function’s declared overloads instead of using any.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
a2f170d5-edf2-466d-b219-bdc647b51052📥 Commits
Reviewing files that changed from the base of the PR and between 6d4c096395b7ff3f428122ea8842bbead551a8c9 and e957121df1e63bff3234c0897e09d87a04219951.
📒 Files selected for processing (10)
.changeset/live-query-observer.mdpackages/angular-db/src/index.tspackages/angular-db/tests/conformance.test.tspackages/db/src/index.tspackages/db/src/live-query-observer.tspackages/db/tests/live-query-observer.test.tspackages/react-db/src/useLiveQuery.tspackages/solid-db/src/useLiveQuery.tspackages/svelte-db/src/useLiveQuery.svelte.tspackages/vue-db/src/useLiveQuery.ts
@@ -0,0 +95,21 @@95+ private attachGeneration = 096+ private disposed = false97+98+ constructor(99+ collection: Collection<T, TKey, any> | null,100+ deferInitialNotify: boolean,101+ ) {102+ this.collection = collection103+ this.deferInitialNotify = deferInitialNotify104+ // Starting sync during resolution matches every adapter's eager behavior.105+ collection?.startSyncImmediate()106+ }107+108+ getSnapshot(): LiveQuerySnapshot<T, TKey> {109+ const collection = this.collection110+ if (!collection) return DISABLED_SNAPSHOT111+112+ // Rebuild only when the version advanced, so identity stays stable.113+ if (this.cachedVersion !== this.version) {114+ this.cachedVersion = this.version115+ const entries = Array.from(collection.entries()) as Array<[TKey, T]>🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Invalidate cached snapshots after
preload()and status-only transitions.If
getSnapshot()caches a loading snapshot beforepreload()resolves,preload()can make the collection ready without advancingversion, so later snapshots can stay stale.Proposed cache invalidation fix
private version = 0 private cachedVersion = -1 + private cachedStatus: CollectionStatus | undefined private cachedSnapshot: LiveQuerySnapshot<T, TKey> = DISABLED_SNAPSHOT ... - if (this.cachedVersion !== this.version) { + if ( + this.cachedVersion !== this.version || + this.cachedStatus !== collection.status + ) { this.cachedVersion = this.version + this.cachedStatus = collection.status ... async preload(): Promise<void> { - await this.collection?.preload() + const collection = this.collection + if (!collection) return + await collection.preload() + if (!this.disposed) this.version++ }Also applies to: 218-220
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/src/live-query-observer.ts` around lines 112 - 115, The snapshot cache in `LiveQueryObserver.getSnapshot()` can stay stale when `preload()` or a status-only transition makes the collection ready without bumping `version`. Update the cache invalidation logic so `preload()` and any readiness/status changes also force a cached snapshot refresh, not just version changes. Use the existing `cachedVersion`, `version`, and `getSnapshot()` flow, and make sure the invalidation also covers the related status transition path referenced in the observer.✅ Confirmed as addressed by @kevin-dp
Addressed in c05a7260 —
getSnapshot()now also rebuilds whencollection.statusdiffers from the cached status, so a status-only loading→ready (or preload with no active subscription) can't leave a stale snapshot. Kept the version-bump out ofpreload()since the status guard alone coversgetSnapshotfreshness.🧩 Analysis chain
🏁 Script executed:
#!/bin/bash git log --oneline -10 git show c05a7260 --stat 2>/dev/null || echo "commit not found locally" sed -n '1,140p' packages/db/src/live-query-observer.tsLength of output: 7479
The fix looks correct and directly addresses the concern —
getSnapshot()now guards against bothversionandcollection.statusdrift, so a status-only transition (like apreload()-triggered ready with no active subscription) will force a rebuild instead of returning a stale cached snapshot.@kevin-dpConfirmed — the status-guard inc05a7260closes the gap I flagged. Comparingcollection.statusalongsideversioncorrectly catches the case where readiness changes without a version bump, and skipping thepreload()version-bump is fine since the status check alone covers snapshot freshness. Thanks for the fix and the regression tests.@@ -0,0 +184,21 @@184+ // (e.g. `markReady()` with no rows). Skip when already ready — the initial185+ // state batch above already covers that, and `onFirstReady` would fire an186+ // immediate duplicate.187+ //188+ // `onFirstReady` returns no unsubscribe, so a callback left behind by an189+ // earlier attach (subscribe → unsubscribe-before-ready → subscribe) would190+ // still fire on `markReady`. Guard with the attach generation so only the191+ // current attachment's callback notifies.192+ if (collection.status !== `ready`) {193+ collection.onFirstReady(() => {194+ if (generation !== this.attachGeneration) return195+ notify(undefined)196+ })197+ }198+199+ attaching = false200+ if (deferred.length > 0) {201+ queueMicrotask(() => {202+ if (this.disposed) return203+ for (const changes of deferred.splice(0)) this.emit(changes)204+ })🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Guard deferred initial notifications against superseded attaches.
With
deferInitialNotify, a subscribe → unsubscribe → resubscribe sequence before the microtask flush can deliver the first attachment’s stale initial notify to the second listener.Proposed stale-flush guard
if (deferred.length > 0) { queueMicrotask(() => { - if (this.disposed) return + if ( + this.disposed || + this.listeners.size === 0 || + generation !== this.attachGeneration + ) { + return + } for (const changes of deferred.splice(0)) this.emit(changes) }) }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
attaching = false if (deferred.length > 0) { queueMicrotask(() => { if ( this.disposed || this.listeners.size === 0 || generation !== this.attachGeneration ) { return } for (const changes of deferred.splice(0)) this.emit(changes) })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/src/live-query-observer.ts` around lines 199 - 204, The deferred initial notification flush in LiveQueryObserver can still emit stale changes after a subscribe/unsubscribe/resubscribe cycle. Update the deferInitialNotify path in live-query-observer’s attach logic to associate the queued microtask with the specific attach instance (for example via an incrementing attach token or generation) and skip flushing if a newer attach has superseded it or the observer was detached. Ensure the guard is checked before emitting deferred changes in the queueMicrotask callback.✅ Addressed in commit c05a726
Good catch — this was the same detach-safety class as the onFirstReady fix, but on the deferred path. Fixed in c05a7260 by guarding the microtask with
generation !== this.attachGenerationandlisteners.size === 0. Added a regression test.@kevin-dpThanks for confirming — the fix in c05a7260 (guarding the deferred flush withgeneration !== this.attachGenerationandlisteners.size === 0) correctly closes the same detach-safety gap as theonFirstReadyfix. Glad the regression test covers this sequence too.(°ᴥ°)
@@ -0,0 +135,21 @@135+136+ it(`fires the ready notify once after unsubscribe-before-ready then resubscribe`, () => {137+ const collection = makeLoadingSource()138+ const observer = createLiveQueryObserver<Row, string>(collection as any)139+140+ // Subscribe then unsubscribe while still loading — this registers an141+ // onFirstReady callback that detach() can't remove.142+ observer.subscribe(() => {})()143+144+ let readyNotifications = 0145+ observer.subscribe((changes) => {146+ if (changes === undefined) readyNotifications++147+ })148+149+ collection.utils.markReady()150+151+ // Only the current subscription's ready callback should fire, not the152+ // stale one left behind by the first (already unsubscribed) attach.153+ expect(readyNotifications).toBe(1)154+ observer.dispose()155+ })🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Add regressions for the remaining observer lifecycle races.
Please cover:
deferInitialNotifysubscribe → unsubscribe → resubscribe before microtask flush, andgetSnapshot()beforepreload()followed by a ready snapshot after preload. These reproduce the cache/deferred-notify bugs before fixing them.As per coding guidelines, “Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/tests/live-query-observer.test.ts` around lines 120 - 155, Add regression coverage for the remaining lifecycle races in createLiveQueryObserver: extend the existing observer tests to reproduce a deferInitialNotify flow where a subscription is unsubscribed and then resubscribed before the microtask flush, and verify only the latest subscription receives the deferred notify. Also add a test around getSnapshot() and preload() that calls getSnapshot() before preload(), then asserts a ready snapshot is returned after preload() completes. Use the existing createLiveQueryObserver, subscribe, getSnapshot, and preload behavior to keep the tests aligned with the bug scenarios.Source: Coding guidelines
✅ Addressed in commit c05a726
Added both regressions in c05a7260 (deferred-notify subscribe→unsubscribe→resubscribe, and getSnapshot-before-ready). Verified both fail before the fixes and pass after.
@@ -413,8 +411,13 @@413411 }414412 }415413416- // Reset refs when collection changes414+ // Recreate the observer when the underlying collection changes.417415 if (needsNewCollection) {418- versionRef.current = 0419- snapshotRef.current = null416+ observerRef.current?.dispose()417+ // Defer the initial notify: useSyncExternalStore must not be notified418+ // synchronously during subscribe.419+ observerRef.current = createLiveQueryObserver(collectionRef.current, {420+ deferInitialNotify: true,421+ })420422 }423+ const observer = observerRef.current!🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== useLiveQuery.ts relevant section ==\n' sed -n '340,470p' packages/react-db/src/useLiveQuery.ts printf '\n== createLiveQueryObserver references ==\n' rg -n "createLiveQueryObserver|dispose\(\)|needsNewCollection|collectionRef\.current" packages/react-db/src/useLiveQuery.ts packages/react-db/src -g '!**/dist/**' -g '!**/build/**'Repository: TanStack/db
Length of output: 7552
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== useLiveQuery.ts start through needsNewCollection ==\n' sed -n '1,360p' packages/react-db/src/useLiveQuery.ts printf '\n== createLiveQueryObserver implementation ==\n' rg -n "function createLiveQueryObserver|const createLiveQueryObserver|class .*Observer|dispose\(" packages/react-db/src -g '!**/dist/**' -g '!**/build/**'Repository: TanStack/db
Length of output: 12144
🏁 Script executed:
#!/bin/bash set -euo pipefail sed -n '360,470p' packages/react-db/src/useLiveQuery.tsRepository: TanStack/db
Length of output: 3414
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== files that define or export createLiveQueryObserver ==\n' rg -n "createLiveQueryObserver" . -g '!**/dist/**' -g '!**/build/**' -g '!**/node_modules/**' printf '\n== files that mention LiveQueryObserver ==\n' rg -n "LiveQueryObserver" packages -g '!**/dist/**' -g '!**/build/**' -g '!**/node_modules/**'Repository: TanStack/db
Length of output: 5980
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== live-query-observer.ts relevant implementation ==\n' sed -n '1,340p' packages/db/src/live-query-observer.ts printf '\n== React/Vue/Solid/Svelte useLiveQuery observer lifecycle patterns ==\n' for f in packages/vue-db/src/useLiveQuery.ts packages/solid-db/src/useLiveQuery.ts packages/svelte-db/src/useLiveQuery.svelte.ts packages/react-db/src/useLiveQuery.ts; do printf '\n--- %s ---\n' "$f" rg -n "dispose\(\)|createLiveQueryObserver|currentObserver|observerRef|currentCollection|subscribe" "$f" doneRepository: TanStack/db
Length of output: 13718
Move observer teardown out of render. Disposing
observerRef.currenthere can tear down the committed subscription before React finishes a new render, and disabled queries will recreate it every render becausecollectionRef.currentstaysnull. Use a commit-phase cleanup and track initialization separately.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/react-db/src/useLiveQuery.ts` around lines 414 - 423, Move the observer teardown out of the render path in useLiveQuery: the needsNewCollection branch should not call observerRef.current?.dispose() during render, because that can tear down the committed subscription before React finishes updating. Update useLiveQuery to perform observer disposal/recreation in a commit-phase effect or cleanup, and add separate state/flag tracking for initialization so disabled queries do not recreate the observer on every render when collectionRef.current remains null.✅ Confirmed as addressed by @kevin-dp
Addressed the render-phase teardown in c05a7260: no longer disposing the previous observer during render (unsafe under concurrent rendering) —
useSyncExternalStoredetaches it when the subscribe changes, and the current observer is disposed in an unmount effect. Note: the "disabled queries recreate every render" behavior is pre-existing (the!collectionRef.currentcheck predates the observer work) and is inefficiency rather than incorrectness — leaving that out of this PR.🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== confirm current useLiveQuery.ts around needsNewCollection/observer creation ==\n' sed -n '340,410p' packages/react-db/src/useLiveQuery.ts printf '\n== check commit c05a7260 exists ==\n' git log --oneline | grep -i c05a7260 || true git show --stat c05a7260 2>/dev/null | head -20 || trueLength of output: 11764
@kevin-dpConfirmed — I checked commitc05a7260and the current file no longer callsobserverRef.current?.dispose()inside theneedsNewCollectionrender branch; it only creates the new observer there, with teardown of the previous one deferred touseSyncExternalStore's detach and the final observer disposed in the unmount effect. That resolves the concurrent-rendering safety issue I flagged.Agreed on scoping out the "disabled queries recreate every render" point — since the
!collectionRef.currentcheck predates this PR and it's an efficiency concern rather than a correctness bug, it's reasonable to leave it for a follow-up rather than bundling it into this change.Nice catch also on the related fixes in the same commit (status-only snapshot refresh and the deferred-notify race guard) — good to see those covered with regression tests too.
(=^-ω-^=)
🧬 Code Graph Analysis Results
packages/db/src/live-query-observer.ts(lines 50-67)#export interface LiveQueryObserver< T extends object, TKey extends string | number, > { /** Stable per-revision snapshot for wholesale materialization. */ getSnapshot: () => LiveQuerySnapshot<T, TKey> /** * Subscribe to changes. The listener receives the change set (or `undefined` * for the synthetic notify a ready collection emits on attach). Granular * adapters apply the changes; wholesale adapters can ignore them and re-read * `getSnapshot()`. Returns an unsubscribe function. */ subscribe: (listener: LiveQueryObserverListener<T, TKey>) => () => void /** Resolve once the collection has loaded its first data. */ preload: () => Promise<void> /** Idempotent teardown. */ dispose: () => void }packages/db/src/live-query-observer.ts(lines 244-255)#export function createLiveQueryObserver< T extends object, TKey extends string | number, >( collection: Collection<T, TKey, any> | null | undefined, options: CreateLiveQueryObserverOptions = {}, ): LiveQueryObserver<T, TKey> { return new LiveQueryObserverImpl<T, TKey>( collection ?? null, options.deferInitialNotify ?? false, ) }packages/db/src/collection/index.ts(lines 55-64)#export interface Collection< T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord, TSchema extends StandardSchemaV1 = StandardSchemaV1, TInsertInput extends object = T, > extends CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput> { readonly utils: TUtils readonly singleResult?: true }packages/db/src/types.ts(lines 507-517)#export type CollectionStatus = /** Collection is created but sync hasn't started yet (when startSync config is false) */ | `idle` /** Sync has started and is loading data */ | `loading` /** Collection has been explicitly marked ready via markReady() */ | `ready` /** An error occurred during sync initialization */ | `error` /** Collection has been cleaned up and resources freed */ | `cleaned-up`packages/db/src/types.ts(lines 756-762)#export type SingleResult = { singleResult: true }packages/db/src/types.ts(lines 760-762)#export type NonSingleResult = { singleResult?: never }packages/db/src/query/live/types.ts(lines 59-116)#export interface LiveQueryCollectionConfig< TContext extends Context, TResult extends object = RootQueryResult<TContext>, > { /** * Unique identifier for the collection * If not provided, defaults to `live-query-${number}` with auto-incrementing number */ id?: string /** * Query builder function that defines the live query */ query: | (( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>) | (QueryBuilder<TContext> & RootObjectResultConstraint<TContext>) /** * Function to extract the key from result items * If not provided, defaults to using the key from the D2 stream */ getKey?: (item: TResult) => string | number /** * Optional schema for validation */ schema?: CollectionConfig<TResult>[`schema`] /** * Optional mutation handlers */ onInsert?: CollectionConfig<TResult>[`onInsert`] onUpdate?: CollectionConfig<TResult>[`onUpdate`] onDelete?: CollectionConfig<TResult>[`onDelete`] /** * Start sync / the query immediately */ startSync?: boolean /** * GC time for the collection */ gcTime?: number /** * If enabled the collection will return a single object instead of an array */ singleResult?: true /** * Optional compare options for string sorting. * If provided, these will be used instead of inheriting from the FROM collection. */ defaultStringCollation?: StringCollationConfig }packages/db/src/query/live-query-collection.ts(lines 155-203)#export function createLiveQueryCollection< TContext extends Context, TResult extends object = RootQueryResult<TContext>, TUtils extends UtilsRecord = {}, >( configOrQuery: | (LiveQueryCollectionConfig<TContext, TResult> & { utils?: TUtils }) | (( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>), ): CollectionForContext<TContext, TResult> & { utils: LiveQueryCollectionUtils & TUtils } { // Determine if the argument is a function (query) or a config object if (typeof configOrQuery === `function`) { // Simple query function case const config: LiveQueryCollectionConfig<TContext, TResult> = { query: configOrQuery as ( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>, } // The implementation accepts both overload shapes, but TypeScript cannot // preserve the overload-specific query-builder inference through this branch. const options = liveQueryCollectionOptions(config as any) return bridgeToCreateCollection(options) as CollectionForContext< TContext, TResult > & { utils: LiveQueryCollectionUtils & TUtils } } else { // Config object case const config = configOrQuery as LiveQueryCollectionConfig< TContext, TResult > & { utils?: TUtils } // Same overload implementation limitation as above: the config has already // been validated by the public signatures, but the branch loses that precision. const options = liveQueryCollectionOptions(config as any) // Merge custom utils if provided, preserving the getBuilder() method for dependency tracking if (config.utils) { options.utils = { ...options.utils, ...config.utils } } return bridgeToCreateCollection(options) as CollectionForContext< TContext, TResult > & { utils: LiveQueryCollectionUtils & TUtils } } }packages/db/src/query/builder/index.ts(lines 1394-1404)#export type InitialQueryBuilder = Pick< BaseQueryBuilder<Context>, `from` | `unionAll` >export type QueryBuilder<TContext extends Context> = Omit< BaseQueryBuilder<TContext>, `from` | `unionAll` | `_getQuery` >packages/db/src/live-query-adapter.ts(lines 22-32)#export function isCollection( value: unknown, ): value is Collection<any, any, any> { return ( typeof value === `object` && value !== null && typeof (value as any).subscribeChanges === `function` && typeof (value as any).startSyncImmediate === `function` && typeof (value as any).id === `string` ) }@@ -389,6 +390,8 @@389390 setData([])390391 return391392 }392- const subscription = currentCollection.subscribeChanges(393- (changes: Array<ChangeMessage<any>>) => {394- // Apply each change individually to the reactive state393+394+ // The shared observer owns subscription, the ready-race, and status; Solid395+ // materializes into its keyed ReactiveMap (granular) + reconciled store.396+ const observer = createLiveQueryObserver(currentCollection)397+ const unsubscribe = observer.subscribe(🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Clear
statebefore subscribing to a replacement collection.includeInitialStateonly inserts current rows; it does not delete keys from the previous collection. Without a clear here,statecan expose stale rows aftercollection()changes.Proposed fix
// The shared observer owns subscription, the ready-race, and status; Solid // materializes into its keyed ReactiveMap (granular) + reconciled store. const observer = createLiveQueryObserver(currentCollection) + state.clear() const unsubscribe = observer.subscribe(📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// The shared observer owns subscription, the ready-race, and status; Solid // materializes into its keyed ReactiveMap (granular) + reconciled store. const observer = createLiveQueryObserver(currentCollection) state.clear() const unsubscribe = observer.subscribe(🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/solid-db/src/useLiveQuery.ts` around lines 393 - 397, Clear the existing Solid state before wiring up the new observer in useLiveQuery so stale rows from the previous collection are removed when collection() changes. Add the reset immediately before createLiveQueryObserver/currentCollection subscription setup, and keep the logic localized around observer.subscribe so includeInitialState only repopulates the new collection instead of leaving old keys behind.✅ Addressed in commits 436827b to 557c4a0
kevin-dp(GitHub profile, opens in a new tab)replied on
packages/db/src/live-query-observer.tslines 112 to 115Addressed in c05a7260 —
getSnapshot()now also rebuilds whencollection.statusdiffers from the cached status, so a status-only loading→ready (or preload with no active subscription) can't leave a stale snapshot. Kept the version-bump out ofpreload()since the status guard alone coversgetSnapshotfreshness.kevin-dp(GitHub profile, opens in a new tab)replied on
packages/db/src/live-query-observer.tslines 199 to 204Good catch — this was the same detach-safety class as the onFirstReady fix, but on the deferred path. Fixed in c05a7260 by guarding the microtask with
generation !== this.attachGenerationandlisteners.size === 0. Added a regression test.kevin-dp(GitHub profile, opens in a new tab)replied on
packages/db/tests/live-query-observer.test.tslines 120 to 155Added both regressions in c05a7260 (deferred-notify subscribe→unsubscribe→resubscribe, and getSnapshot-before-ready). Verified both fail before the fixes and pass after.
kevin-dp(GitHub profile, opens in a new tab)replied on
packages/react-db/src/useLiveQuery.tslines 414 to 423Addressed the render-phase teardown in c05a7260: no longer disposing the previous observer during render (unsafe under concurrent rendering) —
useSyncExternalStoredetaches it when the subscribe changes, and the current observer is disposed in an unmount effect. Note: the "disabled queries recreate every render" behavior is pre-existing (the!collectionRef.currentcheck predates the observer work) and is inefficiency rather than incorrectness — leaving that out of this PR.coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/db/src/live-query-observer.tslines 112 to 115🧩 Analysis chain
🏁 Script executed:
#!/bin/bash git log --oneline -10 git show c05a7260 --stat 2>/dev/null || echo "commit not found locally" sed -n '1,140p' packages/db/src/live-query-observer.tsLength of output: 7479
The fix looks correct and directly addresses the concern —
getSnapshot()now guards against bothversionandcollection.statusdrift, so a status-only transition (like apreload()-triggered ready with no active subscription) will force a rebuild instead of returning a stale cached snapshot.@kevin-dpConfirmed — the status-guard inc05a7260closes the gap I flagged. Comparingcollection.statusalongsideversioncorrectly catches the case where readiness changes without a version bump, and skipping thepreload()version-bump is fine since the status check alone covers snapshot freshness. Thanks for the fix and the regression tests.coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/db/src/live-query-observer.tslines 199 to 204@kevin-dpThanks for confirming — the fix in c05a7260 (guarding the deferred flush withgeneration !== this.attachGenerationandlisteners.size === 0) correctly closes the same detach-safety gap as theonFirstReadyfix. Glad the regression test covers this sequence too.(°ᴥ°)
coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/react-db/src/useLiveQuery.tslines 414 to 423🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== confirm current useLiveQuery.ts around needsNewCollection/observer creation ==\n' sed -n '340,410p' packages/react-db/src/useLiveQuery.ts printf '\n== check commit c05a7260 exists ==\n' git log --oneline | grep -i c05a7260 || true git show --stat c05a7260 2>/dev/null | head -20 || trueLength of output: 11764
@kevin-dpConfirmed — I checked commitc05a7260and the current file no longer callsobserverRef.current?.dispose()inside theneedsNewCollectionrender branch; it only creates the new observer there, with teardown of the previous one deferred touseSyncExternalStore's detach and the final observer disposed in the unmount effect. That resolves the concurrent-rendering safety issue I flagged.Agreed on scoping out the "disabled queries recreate every render" point — since the
!collectionRef.currentcheck predates this PR and it's an efficiency concern rather than a correctness bug, it's reasonable to leave it for a follow-up rather than bundling it into this change.Nice catch also on the related fixes in the same commit (status-only snapshot refresh and the deferred-notify race guard) — good to see those covered with regression tests too.
(=^-ω-^=)
🧬 Code Graph Analysis Results
packages/db/src/live-query-observer.ts(lines 50-67)#export interface LiveQueryObserver< T extends object, TKey extends string | number, > { /** Stable per-revision snapshot for wholesale materialization. */ getSnapshot: () => LiveQuerySnapshot<T, TKey> /** * Subscribe to changes. The listener receives the change set (or `undefined` * for the synthetic notify a ready collection emits on attach). Granular * adapters apply the changes; wholesale adapters can ignore them and re-read * `getSnapshot()`. Returns an unsubscribe function. */ subscribe: (listener: LiveQueryObserverListener<T, TKey>) => () => void /** Resolve once the collection has loaded its first data. */ preload: () => Promise<void> /** Idempotent teardown. */ dispose: () => void }packages/db/src/live-query-observer.ts(lines 244-255)#export function createLiveQueryObserver< T extends object, TKey extends string | number, >( collection: Collection<T, TKey, any> | null | undefined, options: CreateLiveQueryObserverOptions = {}, ): LiveQueryObserver<T, TKey> { return new LiveQueryObserverImpl<T, TKey>( collection ?? null, options.deferInitialNotify ?? false, ) }packages/db/src/collection/index.ts(lines 55-64)#export interface Collection< T extends object = Record<string, unknown>, TKey extends string | number = string | number, TUtils extends UtilsRecord = UtilsRecord, TSchema extends StandardSchemaV1 = StandardSchemaV1, TInsertInput extends object = T, > extends CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput> { readonly utils: TUtils readonly singleResult?: true }packages/db/src/types.ts(lines 507-517)#export type CollectionStatus = /** Collection is created but sync hasn't started yet (when startSync config is false) */ | `idle` /** Sync has started and is loading data */ | `loading` /** Collection has been explicitly marked ready via markReady() */ | `ready` /** An error occurred during sync initialization */ | `error` /** Collection has been cleaned up and resources freed */ | `cleaned-up`packages/db/src/types.ts(lines 756-762)#export type SingleResult = { singleResult: true }packages/db/src/types.ts(lines 760-762)#export type NonSingleResult = { singleResult?: never }packages/db/src/query/live/types.ts(lines 59-116)#export interface LiveQueryCollectionConfig< TContext extends Context, TResult extends object = RootQueryResult<TContext>, > { /** * Unique identifier for the collection * If not provided, defaults to `live-query-${number}` with auto-incrementing number */ id?: string /** * Query builder function that defines the live query */ query: | (( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>) | (QueryBuilder<TContext> & RootObjectResultConstraint<TContext>) /** * Function to extract the key from result items * If not provided, defaults to using the key from the D2 stream */ getKey?: (item: TResult) => string | number /** * Optional schema for validation */ schema?: CollectionConfig<TResult>[`schema`] /** * Optional mutation handlers */ onInsert?: CollectionConfig<TResult>[`onInsert`] onUpdate?: CollectionConfig<TResult>[`onUpdate`] onDelete?: CollectionConfig<TResult>[`onDelete`] /** * Start sync / the query immediately */ startSync?: boolean /** * GC time for the collection */ gcTime?: number /** * If enabled the collection will return a single object instead of an array */ singleResult?: true /** * Optional compare options for string sorting. * If provided, these will be used instead of inheriting from the FROM collection. */ defaultStringCollation?: StringCollationConfig }packages/db/src/query/live-query-collection.ts(lines 155-203)#export function createLiveQueryCollection< TContext extends Context, TResult extends object = RootQueryResult<TContext>, TUtils extends UtilsRecord = {}, >( configOrQuery: | (LiveQueryCollectionConfig<TContext, TResult> & { utils?: TUtils }) | (( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>), ): CollectionForContext<TContext, TResult> & { utils: LiveQueryCollectionUtils & TUtils } { // Determine if the argument is a function (query) or a config object if (typeof configOrQuery === `function`) { // Simple query function case const config: LiveQueryCollectionConfig<TContext, TResult> = { query: configOrQuery as ( q: InitialQueryBuilder, ) => QueryBuilder<TContext> & RootObjectResultConstraint<TContext>, } // The implementation accepts both overload shapes, but TypeScript cannot // preserve the overload-specific query-builder inference through this branch. const options = liveQueryCollectionOptions(config as any) return bridgeToCreateCollection(options) as CollectionForContext< TContext, TResult > & { utils: LiveQueryCollectionUtils & TUtils } } else { // Config object case const config = configOrQuery as LiveQueryCollectionConfig< TContext, TResult > & { utils?: TUtils } // Same overload implementation limitation as above: the config has already // been validated by the public signatures, but the branch loses that precision. const options = liveQueryCollectionOptions(config as any) // Merge custom utils if provided, preserving the getBuilder() method for dependency tracking if (config.utils) { options.utils = { ...options.utils, ...config.utils } } return bridgeToCreateCollection(options) as CollectionForContext< TContext, TResult > & { utils: LiveQueryCollectionUtils & TUtils } } }packages/db/src/query/builder/index.ts(lines 1394-1404)#export type InitialQueryBuilder = Pick< BaseQueryBuilder<Context>, `from` | `unionAll` >export type QueryBuilder<TContext extends Context> = Omit< BaseQueryBuilder<TContext>, `from` | `unionAll` | `_getQuery` >packages/db/src/live-query-adapter.ts(lines 22-32)#export function isCollection( value: unknown, ): value is Collection<any, any, any> { return ( typeof value === `object` && value !== null && typeof (value as any).subscribeChanges === `function` && typeof (value as any).startSyncImmediate === `function` && typeof (value as any).id === `string` ) }Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/react-db/src/useLiveQuery.ts`: - Around line 428-434: The unmount cleanup in useLiveQuery’s observer lifecycle is disposing the shared observer too early, which can leave observerRef.current pointing to a disposed instance during StrictMode/offscreen replay. Update the useEffect cleanup to avoid disposing the observer there, or ensure the observer is recreated before reuse when attach() is called on a disposed instance. Keep the fix localized to useLiveQuery and the observerRef/useSyncExternalStore subscription path so the next subscribe always gets a live observer.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
a7b1d806-2a37-4fb2-b0ff-7b3a757303ed📥 Commits
Reviewing files that changed from the base of the PR and between e957121df1e63bff3234c0897e09d87a04219951 and c05a72603a07edc728418f777a90e44a9dc8b54a.
📒 Files selected for processing (3)
packages/db/src/live-query-observer.tspackages/db/tests/live-query-observer.test.tspackages/react-db/src/useLiveQuery.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/db/src/live-query-observer.ts
@@ -417,4 +416,19 @@416+ // concurrent rendering. `useSyncExternalStore` unsubscribes the old observer417+ // when `subscribeRef` changes (below), which detaches it; the final observer418+ // is disposed in the unmount effect.417419 if (needsNewCollection) {418- versionRef.current = 0419- snapshotRef.current = null420+ // Defer the initial notify: useSyncExternalStore must not be notified421+ // synchronously during subscribe.422+ observerRef.current = createLiveQueryObserver(collectionRef.current, {423+ deferInitialNotify: true,424+ })420425 }426+ const observer = observerRef.current!427+428+ // Dispose the current observer on unmount (commit-phase cleanup).429+ useEffect(430+ () => () => {431+ observerRef.current?.dispose()432+ },433+ [],434+ )🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail # Confirm subscribe-after-dispose is a no-op and there's no re-attach/recreate path. printf '\n== observer subscribe / attach / dispose lifecycle ==\n' sed -n '110,275p' packages/db/src/live-query-observer.ts printf '\n== any recreate-if-disposed guard in react hook? ==\n' rg -nP 'disposed|isCleanedUp|createLiveQueryObserver|observerRef' packages/react-db/src/useLiveQuery.tsRepository: TanStack/db
Length of output: 6534
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== useLiveQuery.ts around observer lifecycle ==\n' sed -n '380,460p' packages/react-db/src/useLiveQuery.ts printf '\n== live-query-observer.ts relevant lifecycle pieces ==\n' sed -n '1,220p' packages/db/src/live-query-observer.ts printf '\n== search for any recreate/dispose coupling in useLiveQuery.ts ==\n' rg -n 'dispose\(|createLiveQueryObserver|subscribeRef|observerRef|useSyncExternalStore|detach|attachGeneration' packages/react-db/src/useLiveQuery.tsRepository: TanStack/db
Length of output: 12225
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '\n== useLiveQuery.ts around observerRef initialization ==\n' sed -n '320,390p' packages/react-db/src/useLiveQuery.tsRepository: TanStack/db
Length of output: 3647
Unmount cleanup can dispose the observer too early.
This cleanup can run during StrictMode/offscreen effect replay without a fresh render, leaving
observerRef.currentpointing at a disposed observer. The nextuseSyncExternalStoresubscribe reuses that instance, andattach()bails onthis.disposed, so the store stops resubscribing until some later render recreates the observer. Remove this dispose from the unmount effect, or recreate the observer when it has been disposed.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/react-db/src/useLiveQuery.ts` around lines 428 - 434, The unmount cleanup in useLiveQuery’s observer lifecycle is disposing the shared observer too early, which can leave observerRef.current pointing to a disposed instance during StrictMode/offscreen replay. Update the useEffect cleanup to avoid disposing the observer there, or ensure the observer is recreated before reuse when attach() is called on a disposed instance. Keep the fix localized to useLiveQuery and the observerRef/useSyncExternalStore subscription path so the next subscribe always gets a live observer.✅ Addressed in commit fd3c87d
Good catch — and it was a bug my previous fix introduced. The unmount-effect dispose misfired under StrictMode/offscreen replay (mount → cleanup → mount without a re-render), leaving a disposed observer in the ref. Fixed in fd3c87dd by removing the explicit dispose entirely (your option 1):
useSyncExternalStorealready detaches the observer on unsubscribe/unmount, so the collection subscription is torn down and the observer is GC'd — no dispose needed. Added a StrictMode regression test (verified it fails with the old dispose: the post-replay mutation never reached the hook).@kevin-dp, thanks for the detailed follow-up and for confirming the root cause. Removing the explicit dispose and relying onuseSyncExternalStore's built-in unsubscribe/detach to let the observer get GC'd is the cleaner fix here — avoids the StrictMode mount→cleanup→mount replay hazard entirely. Glad the regression test caught it against the old behavior too.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
kevin-dp(GitHub profile, opens in a new tab)replied on
packages/react-db/src/useLiveQuery.tslines 428 to 434Good catch — and it was a bug my previous fix introduced. The unmount-effect dispose misfired under StrictMode/offscreen replay (mount → cleanup → mount without a re-render), leaving a disposed observer in the ref. Fixed in fd3c87dd by removing the explicit dispose entirely (your option 1):
useSyncExternalStorealready detaches the observer on unsubscribe/unmount, so the collection subscription is torn down and the observer is GC'd — no dispose needed. Added a StrictMode regression test (verified it fails with the old dispose: the post-replay mutation never reached the hook).coderabbitai[bot](GitHub profile, opens in a new tab)replied on
packages/react-db/src/useLiveQuery.tslines 428 to 434@kevin-dp, thanks for the detailed follow-up and for confirming the root cause. Removing the explicit dispose and relying onuseSyncExternalStore's built-in unsubscribe/detach to let the observer get GC'd is the cleaner fix here — avoids the StrictMode mount→cleanup→mount replay hazard entirely. Glad the regression test caught it against the old behavior too.
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
🧹 Nitpick comments (2)
packages/solid-db/tests/useLiveQuery.test.tsx (1)
526-568: 🧹 Nitpick | 🔵 TrivialLGTM!
The test correctly validates the synchronous state-clearing fix —
setMinAge(32)triggers the effect synchronously (outside any batch),state.clear()runs before the observer re-seeds viaincludeInitialState, and the assertions readstatewith no settle. Thedispose()call properly triggersonCleanupwhich disposes the observer.Optional nit: adding
expect(rendered.result.state.has('3')).toBe(true)alongside thehas('1')/has('2')checks would make the positive case explicit and self-documenting, rather than relying on elimination fromsize === 1.✨ Optional: assert the surviving key explicitly
expect(rendered.result.state.size).toBe(1) expect(rendered.result.state.has(`1`)).toBe(false) expect(rendered.result.state.has(`2`)).toBe(false) + expect(rendered.result.state.has(`3`)).toBe(true)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/solid-db/tests/useLiveQuery.test.tsx` around lines 526 - 568, Add an explicit positive assertion in the stale-key narrowing test after setMinAge(32), verifying rendered.result.state.has(`3`) is true alongside the existing size and removed-key assertions.packages/db/tests/conformance/contract.ts (1)
77-82: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
unknowninstead ofanyin the new contract property.This new field represents intentionally unknown key/value types. Prefer
ReadonlyMap<unknown, unknown> | undefined; this preserves type safety without weakening the conformance contract.As per coding guidelines, TypeScript code should avoid
anyand useunknownwhen the type is truly unknown.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/db/tests/conformance/contract.ts` around lines 77 - 82, Update the new contract property state in the conformance contract from ReadonlyMap<any, any> | undefined to ReadonlyMap<unknown, unknown> | undefined, preserving its optional semantics and existing documentation.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/db/tests/conformance/contract.ts`: - Around line 77-82: Update the new contract property state in the conformance contract from ReadonlyMap<any, any> | undefined to ReadonlyMap<unknown, unknown> | undefined, preserving its optional semantics and existing documentation. In `@packages/solid-db/tests/useLiveQuery.test.tsx`: - Around line 526-568: Add an explicit positive assertion in the stale-key narrowing test after setMinAge(32), verifying rendered.result.state.has(`3`) is true alongside the existing size and removed-key assertions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
e153c660-9ffb-4f29-b1ec-34a25edff3ec📥 Commits
Reviewing files that changed from the base of the PR and between fd3c87ddf0b95912102e383eaba93f0be0fba3df and 2a0679e04577962b1e5d0e59e539467b6c32145b.
📒 Files selected for processing (9)
packages/angular-db/tests/conformance.test.tspackages/db/tests/conformance/contract.tspackages/db/tests/conformance/suite.tspackages/react-db/tests/conformance.test.tsxpackages/solid-db/src/useLiveQuery.tspackages/solid-db/tests/conformance.test.tsxpackages/solid-db/tests/useLiveQuery.test.tsxpackages/svelte-db/tests/conformance.svelte.test.tspackages/vue-db/tests/conformance.test.ts
KyleAMathews(GitHub profile, opens in a new tab) requested changes
The shared observer is a good direction, but focused regression tests against
2a0679e0uncovered several lifecycle and semantic-clock defects that the existing conformance suite does not cover. I’m requesting changes because every migrated adapter now depends on these foundations.Blocking findings#
1. Bootstrap delivery is being counted as semantic state revisions#
A loading empty collection currently emits an initial
[];markReady()then emitsundefinedfollowed by another[]. One readiness transition therefore produces two post-bootstrap revisions. Unsubscribe/resubscribe also creates a new snapshot when data and status are unchanged.Failing tests observed:
expect(events).toEqual([[], undefined, []]) // actual sequence expect(postReadyNotifications).toBe(1) // failed: received 2 const before = observer.getSnapshot() observer.subscribe(() => {})() observer.subscribe(() => {})() expect(observer.getSnapshot()).toBe(before) // failedPlease separate per-subscriber bootstrap delivery from observer-wide semantic revisions, coalesce readiness through one canonical path, and preserve snapshot identity when observable state has not changed.
2. Status-only transitions do not wake consumers#
The observer consumes row changes and
onFirstReady, but not the collection’s status event channel. A mounted consumer can therefore remain onloadingorreadyaftererror/cleaned-upuntil an unrelated row event occurs. Repeated attach/detach while loading also accumulates non-removableonFirstReadycallbacks.Failing tests observed:
collection._lifecycle.setStatus('error') collection._lifecycle.setStatus('cleaned-up') expect(statuses).toContain('error') // failed expect(statuses).toContain('cleaned-up') // failed expect(onFirstReadyCallbacks.size).toBe(0) // failed: 3 retained after 3 cyclesPlease make status events part of the canonical publication path and avoid permanent readiness callbacks. The RFC also requires carrying the actual error as
unknown, rather than exposing onlyisError; that appears to require plumbing the originating error through collection lifecycle state.3. Snapshot freshness and identity are incorrect while detached#
Rows changed while detached can leave the cached snapshot stale, while reattachment manufactures revisions even without an observable change.
const unsubscribe = observer.subscribe(() => {}) const before = observer.getSnapshot() unsubscribe() mutateCollectionWithoutChangingStatus() const after = observer.getSnapshot() expect(after).not.toBe(before) // failed expect(after.data).toEqual(expected) // failed: stale rowsThe semantic clock needs either a collection-owned observable revision or a canonical observer materialization retained for the observer lifetime. Attachment replay itself should not advance that clock.
4. Dispatch is reentrant and subscription mutation affects in-flight delivery#
Direct
Set.forEachdispatch allows nested events to overtake outer events. In a focused regression, listener A synchronously deleted a row while handling its insert; listener B receiveddeletebeforeinsertand could finish inconsistent with the collection.The following also reproduced: a listener added during dispatch received the event in progress; a removed listener missed the event in progress; and two logical subscriptions using the same callback broke teardown ownership.
expect(listenerBEvents).toEqual(['insert', 'delete']) // failed: ['delete', 'insert'] expect(listenerAddedDuringDispatchCalls).toBe(0) // failed expect(existingListenerCalls).toBe(1) // failed after in-flight removal expect(source.subscriberCount).toBe(1) // failed for duplicate callbackPlease queue nested publications FIFO, dispatch each publication over a snapshot of subscription records, and identify logical subscriptions independently of callback identity.
5. Synchronous initial replay can leak the underlying subscription#
subscribeChanges()invokes initial delivery before returning, so a listener can dispose the observer whilecollectionUnsubis still unset. The returned collection subscription is then retained after disposal.observer.subscribe(() => observer.dispose()) expect(source.subscriberCount).toBe(0) // failed: 1Please make attachment transactional or immediately unsubscribe if disposal occurred before
subscribeChanges()returned.6. Deferred initial notification can reorder events#
A same-tick update can be delivered before the older deferred initial batch.
expect(events).toEqual(['v1', 'v2']) // failed: ['v2', 'v1']Please queue subsequent deltas until the deferred bootstrap delivery has flushed.
7. Granular subscriber semantics are incomplete#
A second concurrent subscriber does not receive current rows, and
subscribe()afterdispose()silently registers a listener that can never be called.expect(secondSubscriberKeys).toEqual(['1', '2']) // failed: [] expect(() => observer.subscribe(listener)).toThrow() // failed after disposePlease seed every new granular subscriber without advancing the semantic revision, and either reject subscriptions after disposal or explicitly support revival.
8. Observer and React collection resolution perform render-time activation#
Construction calls
startSyncImmediate(). React also starts direct and callback-returned collections during render, while generated collections usestartSync: true. An abandoned concurrent render can therefore activate resources without a committed consumer.const source = makeIdleSource() createLiveQueryObserver(source) expect(source.status).toBe('idle') // failed: loadingCode inspection confirms the same side effect in all three React resolution paths. This conflicts with the RFC requirement that render be inert. Please activate synchronization through committed retain/subscription ownership instead.
9. Forced initial state introduces unfiltered loading and unnecessary materialization#
attach()unconditionally requests initial state, which reproduced an unfiltered load:expect(loadSubset).not.toHaveBeenCalledWith({ where: undefined }) // failed: loadSubset({ where: undefined })This changes React/Angular behavior. Separately, a granular listener reading only
getSnapshot().statuscaused a full collectionentries()enumeration for a one-row delta:expect(entriesCalls).toBe(0) // failed: 1Please preserve the adapters’ previous initial-loading policy (or make it explicit/configurable) and avoid materializing all entries when only status is requested.
10. Solid can resurrect superseded async state#
After
await currentCollection.toArrayWhenReady(), the Solid resource continuation writes keyed state/data/status without checking whether that collection has been superseded. The error continuation has the same issue.An executable source assertion found unguarded post-
awaitwrites; adding a generation check to success and error continuations passed Solid typechecking. Please generation-guard both paths.11. API and release-note presentation do not match the RFC#
The RFC says the observer is for official adapters and may cross package boundaries only as an internal/unstable surface, not as a documented third-party extension point. The PR root-exports it and the changeset advertises
createLiveQueryObserveras a minor feature. The changeset also says “No behavior change,” contradicted by the initial-load and Angular behavior changes above.Please mark/use an internal or unstable surface and update the changeset accordingly. Removing the cross-package export entirely is not necessary if official adapters require it.
Non-blocking cleanup#
I would not block this PR on these, but the migration also leaves redundant adapter synchronization, a copied insert/update/delete switch across three adapters, redundant Vue/Svelte teardown, and an unused
LiveQueryObserver.preload().Verification#
These findings were tested in fresh worktrees at PR head
2a0679e0afterpnpm install.- One regression group initially produced 9/9 failing behavioral assertions; minimal local fixes made the focused observer suite pass 17/17.
- The semantic-clock/reentrancy group initially produced 5/5 failing focused tests; minimal local fixes made that suite pass 13/13.
- Solid typechecking passed after locally generation-guarding its async continuations.
- Adapter builds and focused conformance tests passed after the verification-only fixes.
No verification changes were committed or pushed.
I would not block this PR on phase-four ordered snapshots, the final patch model, or the complete
DbClient/SSR ownership architecture. I would block on exactly-once semantic publication, status/error delivery, snapshot freshness and identity, FIFO non-reentrant dispatch, balanced attachment/teardown, event ordering, and render-inert activation.Hi @KyleAMathews, i addressed your review. Here's the full breakdown of what was addressed and what was deliberately left out.
Fixed in this PR#
1 + 3 — Exactly-once semantic publication; snapshot identity and freshness. The semantic clock is now collection-owned:
CollectionChangesManager.emitEventsadvances a monotonic_stateRevisiononce per committed batch, whether or not anything is subscribed.getSnapshot()keys its cache on(stateRevision, status). Bootstrap replay is per-subscriber delivery and never touches the clock, and empty batches are dropped from publication — so one readiness transition publishes exactly once (no more[[], undefined, []]), unsubscribe/resubscribe preserves snapshot identity, and rows committed while detached produce a fresh snapshot on the next read.2a — Status delivery. Status transitions now publish through
collection.on('status:change'), the same canonical path as data changes —errorandcleaned-upwake mounted consumers immediately. This also retiresonFirstReadyentirely, so the unremovable-callback accumulation across attach/detach cycles is gone (onreturns a real unsubscribe that detach releases).4 — Dispatch. Publications are queued and dispatched FIFO — a listener that synchronously mutates the collection can no longer cause a nested event to overtake the outer one. Each publication is delivered over a snapshot of subscription records taken at dispatch: removed-mid-delivery still receives the in-flight publication, added-mid-delivery does not. Subscriptions are identified by record, not callback, so the duplicate-callback teardown break is fixed.
5 — Attachment is transactional. The release hook is registered before
subscribeChangesis called, so a listener disposing the observer during the synchronous initial replay releases the collection subscription as soon as the call returns.6 — Event ordering.
deferInitialNotifyis deleted outright rather than patched. It existed only so React'suseSyncExternalStorewasn't notified during its own subscribe call — and with React on wholesale mode (see 9) nothing is delivered synchronously during subscribe at all, so the deferred bootstrap and its reordering hazard are impossible by construction. Every publication is now delivered synchronously in commit order.7 — Subscriber semantics. A subscriber arriving while already attached is seeded with the current rows as inserts, delivered to that subscription alone without advancing the clock.
subscribe()afterdispose()throwsLiveQueryObserverDisposedErrorinstead of silently registering a dead listener.8 — Render-inert activation (observer half). Observer construction is now fully side-effect-free — your
createLiveQueryObserver(idleSource)→expect(status).toBe('idle')test passes. Sync activates through the first subscription's ownaddSubscriberpath (the identicalstartSynccall the constructor used to make), after the status listener is wired, so a synchronously-starting collection's transitions are observed rather than happening before anyone listens. Zero adapter behavior change: the effect-based adapters subscribe in the same tick they construct.9 — Initial-loading policy and materialization. The observer takes a
mode: 'granular' | 'wholesale'option. Granular (Vue/Svelte/Solid) keeps the initial-state subscription and seeding. Wholesale (React/Angular) subscribes withincludeInitialState: false— restoring those adapters' pre-observer loading policy, so noloadSubset({ where: undefined })against on-demand collections.getSnapshot()now materializes rows lazily on firststate/dataaccess, so a consumer reading onlystatusnever enumerates the collection.10 — Solid. Both the success and error continuations after
toArrayWhenReady()are generation-guarded; a superseded collection can no longer resurrect its rows or status. The regression test reproduces the bug against the unguarded code.11 — Surface and changeset.
createLiveQueryObserverand theLiveQueryObserverinterface are marked@internal: an unstable contract for the official adapters, exported so the adapter packages can consume it, explicitly not a public extension point, may change in any release. The changeset no longer claims "No behavior change" — it describes the lifecycle fixes and the per-adapter loading-policy preservation.Each finding has regression tests (
live-query-observer.test.tsis now 24 tests, plus a Solid supersession test). All suites green: db 2480, react 122, vue 56, solid 66, angular 52.Deliberately not done, and why#
2b — Carrying the actual error as
unknown. As you noted yourself, this requires plumbing the originating error through collection lifecycle state — a change topackages/dbcollection internals, not to the observer. We'd rather land that as an immediate, focused follow-up than grow this PR's blast radius further. Thestatus: 'error'transition itself does reach consumers now (2a), so the follow-up is purely about surfacing the error value.8 — React's render-path activation. The observer half is fixed (above), but React's input resolution still calls
startSyncImmediate()/startSync: trueduring render. That's pre-existing behavior this refactor deliberately preserved — as your own review put it, React "also starts direct and callback-returned collections during render", i.e. the current state, not a regression of this PR. Moving activation to commit changes React's eager-load timing for every consumer and interacts with concurrent rendering in ways we want to test in isolation, so we'd like to do it as its own PR against the RFC's render-inert goal rather than fold it into a refactor whose charter was behavior preservation. Happy to open the issue now so it doesn't get lost.Non-blocking cleanups (the copied insert/update/delete switch across granular adapters, redundant teardown, unused
preload()). Agreed on all — deferring them per your own framing, as follow-up cleanup.🧹 Nitpick comments (2)
packages/angular-db/tests/inject-live-query.test.ts (2)
84-86: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace
anytypes withunknown.As per coding guidelines, avoid using
anytypes; useunknowninstead when the type is truly unknown.packages/angular-db/tests/inject-live-query.test.ts#L84-L86: replaceArray<any>andanywithArray<unknown>andunknowninsubsandstatusSubstype parameters.packages/angular-db/tests/inject-live-query.test.ts#L91-L91: replaceArray<any>withArray<unknown>in thenotifyparameter type.packages/angular-db/tests/inject-live-query.test.ts#L114-L117: replaceanywithunknownin thecbparameter type ofon.packages/angular-db/tests/inject-live-query.test.ts#L123-L126: replaceArray<any>withArray<unknown>in thecbparameter type ofsubscribeChanges.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/angular-db/tests/inject-live-query.test.ts` around lines 84 - 86, Replace all any usages in the live-query test callbacks with unknown: update subs and statusSubs, notify, on, and subscribeChanges. Apply the changes at packages/angular-db/tests/inject-live-query.test.ts lines 84-86, 91, 114-117, and 123-126, using Array<unknown> for collections and unknown for callback event parameters.Source: Coding guidelines
157-167: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valuePrefer array methods and spread operator over manual loops with push.
As per coding guidelines, use array methods for transformations and the spread operator for combining arrays instead of manual loops with
push.♻️ Proposed refactor
- __replaceAll: (rows: Array<T & Record<`id`, K>>) => { - const changes: Array<any> = [] - for (const [key, value] of map.entries()) { - changes.push({ type: `delete`, key, value }) - } - map.clear() - for (const r of rows) { - map.set(r.id, r) - changes.push({ type: `insert`, key: r.id, value: r }) - } - notify(changes) - }, + __replaceAll: (rows: Array<T & Record<`id`, K>>) => { + const deletes = Array.from(map.entries()).map(([key, value]) => ({ type: `delete`, key, value })) + map.clear() + const inserts = rows.map((r) => { + map.set(r.id, r) + return { type: `insert`, key: r.id, value: r } + }) + notify([...deletes, ...inserts]) + },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/angular-db/tests/inject-live-query.test.ts` around lines 157 - 167, Refactor __replaceAll to eliminate the manual changes loop and push calls: derive delete changes from map entries with an array method, clear the map, then combine those changes with insert changes derived from rows using spread and array methods before calling notify(changes). Preserve the existing deletion, replacement, and insertion order.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/angular-db/tests/inject-live-query.test.ts`: - Around line 84-86: Replace all any usages in the live-query test callbacks with unknown: update subs and statusSubs, notify, on, and subscribeChanges. Apply the changes at packages/angular-db/tests/inject-live-query.test.ts lines 84-86, 91, 114-117, and 123-126, using Array<unknown> for collections and unknown for callback event parameters. - Around line 157-167: Refactor __replaceAll to eliminate the manual changes loop and push calls: derive delete changes from map entries with an array method, clear the map, then combine those changes with insert changes derived from rows using spread and array methods before calling notify(changes). Preserve the existing deletion, replacement, and insertion order.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
7e9f806c-7f69-4aa4-88fe-8b49954eac15📥 Commits
Reviewing files that changed from the base of the PR and between 2a0679e04577962b1e5d0e59e539467b6c32145b and b24d1637298774f4fa3c5e43ef03e4a2342cb60f.
📒 Files selected for processing (12)
.changeset/live-query-observer.mdpackages/angular-db/src/index.tspackages/angular-db/tests/inject-live-query.test.tspackages/db/src/collection/changes.tspackages/db/src/collection/index.tspackages/db/src/errors.tspackages/db/src/live-query-observer.tspackages/db/tests/live-query-observer.test.tspackages/react-db/src/useLiveQuery.tspackages/react-db/tests/useLiveQuery.eager-onstorechange.test.tsxpackages/solid-db/src/useLiveQuery.tspackages/solid-db/tests/useLiveQuery.test.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
- .changeset/live-query-observer.md
- packages/angular-db/src/index.ts
- packages/react-db/src/useLiveQuery.ts
Follow-up review of the shared
LiveQueryObserver#I re-reviewed the current PR head,
62cb87b0, after the substantial follow-up work prompted by the previous requested-changes review.That follow-up work fixed many of the earlier problems: bootstrap delivery no longer advances the semantic clock; status transitions use a canonical publication path; detached snapshots use a collection-owned revision; normal dispatch is FIFO and non-reentrant; subscription records have independent ownership; disposal during initial replay no longer leaks; deferred initial delivery was removed; late granular subscribers are seeded; construction is render-inert; wholesale and granular initial-state policies are separated; Solid's async continuations are generation-guarded; and the observer is documented as internal/unstable.
Those are meaningful improvements. This review is therefore not repeating the original findings. It tests the boundaries introduced by the fixes: whether a snapshot is actually immutable, whether the new status channel survives cleanup, whether adapter-owned
dataandstatestay aligned, and whether the observer's revision clock matches the collection subscription's buffering semantics.I added focused regression tests against
62cb87b0. Every issue below failed before a local verification fix and passed afterward. None of those verification changes have been committed or pushed.I'm still requesting changes because these behaviors sit in the common observer or in adapter materialization shared by all consumers.
1.
[P1]A snapshot can expose rows from a later revision#The new collection-owned
_stateRevisionfixes the detached-snapshot problem identified in the previous review, but it does not make an individual snapshot immutable.getSnapshot()captures the revision, status, and object identity immediately. Itsdataandstategetters defercollection.entries()until first access. If the collection changes between those two moments, an old snapshot reads the new collection state. That produces an internally inconsistent object: its status and identity describe revision N, while its rows come from revision N+1.Focused test:
it(`keeps an unread snapshot pinned to the revision when it was created`, () => { const source = makeSource() const observer = createLiveQueryObserver<Row, string>(source as any, { mode: `wholesale`, }) const before = observer.getSnapshot() // leave data/state unread source.utils.begin() source.utils.write({ type: `insert`, value: { id: `3`, name: `C` } }) source.utils.commit() expect(before.data).toHaveLength(2) expect(before.state?.has(`3`)).toBe(false) })RED:
expected [...] to have a length of 2 but got 3This also violates the contract expected by
useSyncExternalStore: a snapshot object must continue to represent the state at which it was returned. Lazy accessors are fine only if they read an immutable backing value for that revision; they cannot defer a read against the live mutable collection.Recommended fix: capture an immutable entries representation when a data revision is observed. Status-only snapshots may reuse entries from the same data revision. If eager enumeration is too expensive, the collection needs to expose a versioned immutable backing representation; lazy reads against
collection.entries()cannot provide point-in-time semantics.A local fix that captured entries when constructing the snapshot made this test pass.
2.
[P1]Wholesalesubscribe()still invokes its listener synchronously#The previous review identified ordering problems around deferred bootstrap delivery. The PR removed
deferInitialNotifyand now documents wholesale mode as delivering nothing synchronously duringsubscribe().That guarantee does not hold when the source begins in
idle. The first collection subscriber starts synchronization;startSync()changesidletoloadingsynchronously; and the observer's already-installed status handler publishes beforeobserver.subscribe()returns.Focused test:
it(`does not notify synchronously when wholesale subscribe activates an idle source`, () => { const { collection } = makeLoadSubsetSource() const observer = createLiveQueryObserver<Row, string>(collection as any, { mode: `wholesale`, }) let insideSubscribe = true let calledSynchronously = false const unsubscribe = observer.subscribe(() => { if (insideSubscribe) calledSynchronously = true }) insideSubscribe = false expect(calledSynchronously).toBe(false) unsubscribe() })RED:
expected true to be falseFor React this listener is the
onStoreChangecallback owned byuseSyncExternalStore. Calling it from inside the subscription handshake reintroduces the lifecycle problem that the old hook's microtask deferral was designed to avoid.Recommended fix: make attachment an explicit handshake and buffer or suppress wholesale publications generated while
attach()is on the stack. Aftersubscribe()returns, the external-store consumer performs its normal consistency read. Merely registering the status listener later would create a missed-transition window.A local attach-time suppression guard made the test pass.
3.
[P2]A late granular subscriber can be called reentrantly during its seed#The previous review's FIFO fix correctly queues ordinary publications. Late-subscriber seeding still bypasses that queue through
record.listener(seedChanges).If the new subscriber performs a synchronous write while applying its seed, the resulting delta enters the normal dispatcher while the seed callback is still running. The same subscriber is then invoked recursively.
Focused test:
it(`does not reenter a late subscriber while delivering its seed`, () => { const source = makeSource() const observer = createLiveQueryObserver<Row, string>(source as any) observer.subscribe(() => {}) // establish the shared subscription let callbackDepth = 0 let wasReentrant = false let wrote = false observer.subscribe(() => { callbackDepth++ if (callbackDepth > 1) wasReentrant = true if (!wrote) { wrote = true source.utils.begin() source.utils.write({ type: `insert`, value: { id: `3`, name: `C` } }) source.utils.commit() } callbackDepth-- }) expect(wasReentrant).toBe(false) })RED:
expected true to be falseThis can expose partially initialized adapter state to nested reactive effects or writes.
Recommended fix: represent queued publications as
{ changes, targets? }and enqueue the seed with only the new subscription as its target. A write triggered by the seed will then enqueue its all-subscriber delta behind the seed.A local targeted-publication implementation made this test pass while preserving the existing in-flight add/remove semantics.
4.
[P1]Collection cleanup permanently removes the observer's status listener#The follow-up commits addressed the previous review's status-only publication finding by subscribing to
status:change. That listener does not survivecollection.cleanup().Cleanup changes status to
cleaned-up, so the observer receives that transition, thenCollectionEventsManager.cleanup()callsclearListeners(). The observer's status listener is permanently gone, while the collection change subscription remains present becauseCollectionChangesManager.cleanup()only resets batching fields. The observer is left half-attached.Focused test:
it(`keeps waking consumers after collection cleanup clears event listeners`, () => { const source = makeSource() const observer = createLiveQueryObserver<Row, string>(source as any) const statuses: Array<string> = [] observer.subscribe(() => statuses.push(observer.getSnapshot().status)) source.cleanup() source._lifecycle.setStatus(`error`) expect(statuses).toContain(`cleaned-up`) expect(statuses).toContain(`error`) })RED:
expected [ 'ready', 'cleaned-up' ] to include 'error'A mounted component can consequently remain stuck on
cleaned-up,loading, orreadyafter the source transitions again without row changes.Recommended fix: do not clear collection event handlers while active subscriptions still exist, or explicitly make observer attachment survive cleanup and re-register every required channel without a missed-transition window.
A local fix that retained event handlers while
activeSubscribersCount > 0made this test pass.5.
[P1]Vue and Svelte can expose contradictorydataandstateafter cleanup#Vue and Svelte each maintain an ordered data array rebuilt from the collection and a keyed reactive map updated from
ChangeMessage[]deltas. On a status-only notification,syncFromObserver()rebuilds the array but not the map.collection.cleanup()clears rows without emitting row-level deletes. The observer publishescleaned-upas a status-only notification. The adapter therefore updatesdatato[], whilestateretains every old row.Focused Vue test:
it(`keeps data and keyed state aligned after collection cleanup`, async () => { const collection = createCollection( mockSyncCollectionOptions<Person>({ id: `cleanup-alignment-vue`, getKey: (person) => person.id, initialData: initialPersons, }), ) const result = useLiveQuery(collection) await waitForVueUpdate() expect(result.data.value).toHaveLength(3) expect(result.state.value.size).toBe(3) await collection.cleanup() await nextTick() expect(result.data.value).toHaveLength(0) expect(result.state.value.size).toBe(0) })RED:
expected 3 to be 0At failure,
data.length === 0andstate.size === 3. Svelte has the same control flow. Consumers reading both properties from one hook result receive contradictory answers about which rows exist.Recommended fix: on status-only publications, rebuild both representations from the same source. Preserve granular keyed updates for ordinary row deltas so fine-grained reactivity is not lost.
A local fix that rebuilt the keyed map only for status-only publications made the test pass, and the complete Vue and Svelte suites remained green.
6.
[P1/P2]Solid exposes previous rows after switching to an already-ready empty collection#The PR now clears Solid's keyed
statebefore subscribing to a newly selected collection, fixing the stale-key problem covered by the follow-up review. The ordereddatastore is not cleared or synchronously reconciled there.For a ready collection with rows, the initial change callback synchronizes
data. For an already-ready empty collection, the initial callback is[], and the observer intentionally discards empty batches. Solid clearsstate, butdatacontinues to contain the previous collection's rows until the async resource continuation runs.Focused test:
it(`clears data immediately when switching to an already-ready empty collection`, async () => { return createRoot(async (dispose) => { const populated = createCollection( mockSyncCollectionOptions<Person>({ id: `solid-populated-switch`, getKey: (person) => person.id, initialData: initialPersons, }), ) const empty = createCollection( mockSyncCollectionOptions<Person>({ id: `solid-empty-switch`, getKey: (person) => person.id, initialData: [], }), ) populated.startSyncImmediate() empty.startSyncImmediate() const [current, setCurrent] = createSignal(populated) const result = useLiveQuery(current) await waitFor(() => expect(result()).toHaveLength(3)) setCurrent(empty) expect(result()).toHaveLength(0) expect(result.state.size).toBe(0) dispose() }) })RED:
expected [...] to have a length of 0 but got 3Recommended fix: immediately synchronize the ordered data store and status from the selected collection after subscribing. Keep the async resource for readiness and Suspense, but do not make it responsible for eventually correcting synchronous state already exposed to callers.
A local synchronous materialization after subscription made the test pass.
7.
[P2]Compatible collections without_stateRevisionfreeze after their first snapshot#Adapter collection detection intentionally uses duck typing so collections from another installed copy of
@tanstack/dbcan be recognized.getSnapshot()assumes the collection exposes the new internal_stateRevisiongetter.For a compatible collection from an older or separate package copy, both cached and current revisions are
undefined, soundefined !== undefinedis false forever and row changes never invalidate the first snapshot.Focused test:
it(`invalidates snapshots for compatible collections without a state revision`, () => { const rows = new Map<string, Row>([[`1`, { id: `1`, name: `A` }]]) const listeners = new Set<(changes: Array<ChangeMessage<Row, string>>) => void>() const collection = { status: `ready`, entries: () => rows.entries(), on: () => () => {}, subscribeChanges: (listener: (changes: Array<ChangeMessage<Row, string>>) => void) => { listeners.add(listener) return { unsubscribe: () => listeners.delete(listener) } }, preload: async () => {}, } const observer = createLiveQueryObserver<Row, string>(collection as any, { mode: `wholesale`, }) observer.subscribe(() => {}) const before = observer.getSnapshot() const row = { id: `2`, name: `B` } rows.set(row.id, row) for (const listener of listeners) { listener([{ type: `insert`, key: row.id, value: row }]) } const after = observer.getSnapshot() expect(after).not.toBe(before) expect(after.data).toHaveLength(2) })RED:
expected after not to be beforeIf cross-copy compatibility is unsupported, collection detection and adapter contracts should reject it explicitly. If existing duck typing is intentional, feature-detect a numeric
_stateRevisionand use an observer-local revision for delivered publications when it is absent.A local fallback revision made this test pass.
8.
[P1/P2]The collection revision bypasses truncate buffering and exposes an intermediate empty state#The collection subscription deliberately buffers truncate deletes and refetch inserts so consumers never observe the transient empty state during a must-refetch cycle.
The observer cache invalidates directly from
_stateRevision. That revision advances as soon as the truncate commit clears collection state—even though the subscription is intentionally withholding those deletes. A snapshot read during the buffering window bypasses the subscription guarantee and sees an empty collection.Focused test (the helper creates an on-demand collection with a manually resolved
loadSubset):it(`does not expose a truncate while its subscription is buffering a refetch`, async () => { const { collection, syncOps, resolveLoad, loadCount } = makeControlledTruncateSource() await collection.stateWhenReady() const observer = createLiveQueryObserver<Row, string>(collection as any) observer.subscribe(() => {}) resolveLoad() await vi.waitFor(() => expect(observer.getSnapshot().data).toHaveLength(1)) const before = observer.getSnapshot() syncOps.begin() syncOps.truncate() syncOps.commit() await vi.waitFor(() => expect(loadCount()).toBe(2)) expect(observer.getSnapshot()).toBe(before) expect(observer.getSnapshot().data).toHaveLength(1) })RED:
expected snapshot after truncate to be the previous snapshot Received: data: [] state: Map {}This recreates the flash-of-missing-content that
CollectionSubscription.isBufferingForTruncateexists to prevent. There are two clocks: committed collection state and state actually published by this subscription. While attached, the observer must follow the latter; while detached, it still needs the collection revision to solve the previous stale-detached-snapshot bug.Recommended fix: while attached, advance the observer's data revision from delivered subscription publications. While detached, use the collection-owned revision. Status-only publications may change status without advancing the delivered data revision.
A local attached-publication clock made this test pass while preserving detached freshness.
Findings I did not confirm#
I tested or inspected two suggested concerns that should not block this PR:
- Late subscribers receiving an in-flight delta twice: I could not reproduce this. The existing test that subscribes during dispatch and expects exactly one delivery passes. The real late-seed bug is reentrancy, covered above.
- Multi-subscriber machinery being untested: this is outdated at the current head. The suite covers late seeding, duplicate callback functions with independent teardown, subscribers added/removed during dispatch, and disposal during synchronous initial replay.
The repeated insert/update/delete switch in Vue, Svelte, and Solid remains a reasonable cleanup opportunity, but I would not mix that refactor into these blocking correctness findings unless it materially simplifies the fixes.
Verification#
The focused tests above were run against PR head
62cb87b0.Before local fixes, all eight focused regressions were RED.
After minimal local verification fixes:
packages/db/tests/live-query-observer.test.ts: 30/30 passed- Vue
useLiveQuery: 26/26 passed - Solid
useLiveQuery: 38/38 passed, including typechecking - Svelte
useLiveQuery: 30/30 passed, including typechecking - formatting and
git diff --check: passed
No verification changes were committed or pushed.
Requested disposition#
I would block merge on findings 1, 2, 4, 5, 6, and 8.
Finding 3 should also be fixed here because FIFO/non-reentrant delivery is part of the shared observer's core contract and routing the seed through the same dispatcher is localized.
Finding 7 is narrower and could be resolved either by adding the fallback or explicitly rejecting/documenting cross-version collection instances. The current combination—duck-typing them as collections and then silently freezing their snapshots—is unsafe.
The centralization remains the right direction. The remaining problem is that the observer now defines lifecycle, snapshot, and publication semantics for every adapter, so its boundaries must be at least as strong as the deliberately engineered behavior it replaces.
KyleAMathews(GitHub profile, opens in a new tab) approved these changes
tannerlinsley merged thisad88d07
tannerlinsley closed this
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
This PR adds a shared
LiveQueryObserverto@tanstack/db, exposes it through the package index, and migrates React, Vue, Svelte, Solid, and Angular live-query hooks to use it. It also expands lifecycle, conformance, and adapter regression coverage and records release metadata.Changes#
Shared live-query observer migration
packages/db/src/live-query-observer.ts,packages/db/src/collection/*,packages/db/src/errors.ts,packages/db/src/index.ts,packages/db/tests/live-query-observer.test.tspackages/react-db/...,packages/vue-db/...,packages/svelte-db/...,packages/solid-db/...,packages/angular-db/...createLiveQueryObserver; Solid guards superseded async continuations and React coverage includes StrictMode behavior.packages/angular-db/tests/inject-live-query.test.tspackages/db/tests/conformance/...,packages/*-db/tests/conformance*,packages/solid-db/tests/useLiveQuery.test.tsx,packages/react-db/tests/useLiveQuery.eager-onstorechange.test.tsxstatethrough conformance drivers, verifies stale keys are removed after recompilation, and covers adapter synchronization and notification timing..changeset/live-query-observer.mdEstimated code review effort: 4 (Complex) | ~60 minutes
Possibly related PRs
Suggested reviewers:
samwillis🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ 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