feat(db): shared live-query window controller (RFC #1623 phase 5) #1675
main fromrefs/pull/1675/head·merged by KyleAMathews(GitHub profile, opens in a new tab) This implements Phase 5 of the live-query platform RFC (#1623): an internal, framework-neutral window controller now owns infinite-query pagination. React's useLiveInfiniteQuery is a thin binding over that controller, with no public API change.
Users keep the same forward-pagination behavior, while concurrent consumers, failed subset loads, cleanup/restart cycles, runtime page-size changes, and order-only updates now produce coherent results.
Root cause#
The React hook previously owned page state and mutated a live-query collection's physical window directly. That coupled pagination to React and left no shared owner when several consumers used the same collection.
The first extraction exposed several distinctions that the old hook did not need to model explicitly:
- a requested window is not committed until its async subset load succeeds;
- several controllers may hold leases on one physical query window;
- preload, subscribe, reset, and page expansion may overlap;
- layout-only changes still need to reach both observer and public collection subscribers;
- a released runtime window must not survive collection cleanup and recompilation.
Without those distinctions, overlapping operations could shrink a pending page request, failures could leave an inflated shared lease, observer updates could disappear while a load was pending, and a stale window could return after restart.
Approach#
- Add
createLiveQueryWindowControllerto@tanstack/db. It owns page slicing, peek-aheadhasNextPage, loading/error state, reset, preload, subscription, and disposal. - Coordinate physical windows per collection with leases. The largest active lease wins, failed requests roll back transactionally, and stale async completions cannot commit superseded state.
- Have
setWindowreturn the real subset-load promise so page commits and errors follow the underlying load outcome. - Preserve source and status notifications during pending pagination, including public empty change batches for order-only moves.
- Expose the query's compiled initial window and clear runtime window state on sync cleanup, so later consumers restart from the query definition.
- Rebuild
useLiveInfiniteQueryarounduseSyncExternalStore, preserving loaded pages across page-shape changes and structurally equal dependency values.
Key invariants#
- The physical window covers the largest active controller lease.
- A page count changes only after its requested window succeeds.
- A failed or released request cannot inflate, shrink, or resurrect another consumer's window.
statusand its boolean flags always agree.- Data and status updates remain observable while pagination is pending.
- The last released lease does not override the query's compiled window after cleanup.
- The React hook retains its existing public return type and forward-only semantics.
Non-goals#
- No bidirectional or backward pagination.
- No new
getNextPageParambehavior; it remains accepted but unused. - No stabilization of the controller as a public extension API. It remains internal and unstable while the RFC is in progress.
- No redesign of the publication queue; its target snapshots preserve reentrant subscribe/unsubscribe semantics.
Trade-offs#
The coordinator adds generation and lease bookkeeping, but keeps arbitration in one collection-scoped place instead of spreading race handling across framework hooks. React still lets useSyncExternalStore unsubscribe replaced controllers rather than disposing them during render, which avoids breaking abandoned or concurrent renders.
Verification#
cd packages/db
pnpm vitest run tests/live-query-window-controller.test.ts tests/live-query-order-only-move.test.ts --pool-options.threads.maxThreads=2 --coverage.enabled=false
cd ../react-db
pnpm vitest run tests/useLiveInfiniteQuery.test.tsx --pool-options.threads.maxThreads=2 --coverage.enabled=false
cd ../..
pnpm --filter @tanstack/db build
pnpm --filter @tanstack/react-db build
Focused results:
@tanstack/db: 47 tests passed@tanstack/react-db: 42 tests passed- ESLint passed for all changed TypeScript files
- Both production builds passed
- The implementation commit passed Test, E2E, Preview, example build, security, and autofix checks
Files changed#
packages/db/src/live-query-window-controller.ts: shared controller, lease coordinator, transactional commits, and snapshot state.packages/db/src/query/live/collection-config-builder.ts: physical-window inspection, real subset-load completion, and restart cleanup.packages/db/src/collection/*andpackages/db/src/query/live/collection-subscriber.ts: layout publication and rejection-safe load tracking.packages/db/tests/live-query-window-controller.test.tsandlive-query-order-only-move.test.ts: controller races, failures, lifecycle, and public layout regressions.packages/react-db/src/useLiveInfiniteQuery.ts: thin React binding with stable pagination across compatible rerenders.packages/react-db/tests/useLiveInfiniteQuery.test.tsx: hook lifecycle, dependency, error, warning, and pagination coverage..changeset/live-query-window-controller.md: patch release note for@tanstack/dband@tanstack/react-db.
Related work#
- 1
More templates
@tanstack/angular-db
npm i https://pkg.pr.new/@tanstack/angular-db@1675@tanstack/browser-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/browser-db-sqlite-persistence@1675@tanstack/capacitor-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/capacitor-db-sqlite-persistence@1675@tanstack/cloudflare-durable-objects-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/cloudflare-durable-objects-db-sqlite-persistence@1675@tanstack/db
npm i https://pkg.pr.new/@tanstack/db@1675@tanstack/db-ivm
npm i https://pkg.pr.new/@tanstack/db-ivm@1675@tanstack/db-sqlite-persistence-core
npm i https://pkg.pr.new/@tanstack/db-sqlite-persistence-core@1675@tanstack/electric-db-collection
npm i https://pkg.pr.new/@tanstack/electric-db-collection@1675@tanstack/electron-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/electron-db-sqlite-persistence@1675@tanstack/expo-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/expo-db-sqlite-persistence@1675@tanstack/node-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/node-db-sqlite-persistence@1675@tanstack/offline-transactions
npm i https://pkg.pr.new/@tanstack/offline-transactions@1675@tanstack/powersync-db-collection
npm i https://pkg.pr.new/@tanstack/powersync-db-collection@1675@tanstack/query-db-collection
npm i https://pkg.pr.new/@tanstack/query-db-collection@1675@tanstack/react-db
npm i https://pkg.pr.new/@tanstack/react-db@1675@tanstack/react-native-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/react-native-db-sqlite-persistence@1675@tanstack/rxdb-db-collection
npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@1675@tanstack/solid-db
npm i https://pkg.pr.new/@tanstack/solid-db@1675@tanstack/svelte-db
npm i https://pkg.pr.new/@tanstack/svelte-db@1675@tanstack/tauri-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/tauri-db-sqlite-persistence@1675@tanstack/trailbase-db-collection
npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@1675@tanstack/vue-db
npm i https://pkg.pr.new/@tanstack/vue-db@1675commit:
b7172eaSize Change: 0 B
Total Size: 132 kB
compressed-size-action::db-package-sizeℹ️ View Unchanged
Filename Size packages/db/dist/esm/collection/change-events.js1.44 kB packages/db/dist/esm/collection/changes.js1.51 kB packages/db/dist/esm/collection/cleanup-queue.js810 B packages/db/dist/esm/collection/events.js434 B packages/db/dist/esm/collection/index.js3.86 kB packages/db/dist/esm/collection/indexes.js1.99 kB packages/db/dist/esm/collection/lifecycle.js1.7 kB packages/db/dist/esm/collection/mutations.js2.47 kB packages/db/dist/esm/collection/state.js5.51 kB packages/db/dist/esm/collection/subscription.js3.77 kB packages/db/dist/esm/collection/sync.js3.05 kB packages/db/dist/esm/collection/transaction-metadata.js144 B packages/db/dist/esm/deferred.js207 B packages/db/dist/esm/errors.js5.16 kB packages/db/dist/esm/event-emitter.js748 B packages/db/dist/esm/index.js3.26 kB 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/live-query-observer.js2.35 kB packages/db/dist/esm/live-query-window-controller.js3.04 kB 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.32 kB packages/db/dist/esm/query/live/collection-registry.js264 B packages/db/dist/esm/query/live/collection-subscriber.js1.95 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: 3.79 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.29 kB packages/react-db/dist/esm/useLiveQuery.js920 B packages/react-db/dist/esm/useLiveQueryEffect.js355 B packages/react-db/dist/esm/useLiveSuspenseQuery.js567 B packages/react-db/dist/esm/usePacedMutations.js401 B I reproduced the reported failures against head
1ca1a07with focused tests. The extraction is the right direction, but I think the following correctness issues should be fixed before merge.1. Render-time activation and callback generation#
useLiveInfiniteQuerycallscollection.startSyncImmediate()for a supplied collection and creates query-function collections withstartSync: trueduring render. A render that never commits therefore activates resources with no committed subscription cleanup.This reproduction fails with
source.subscriberCount === 2instead of0:const never = new Promise<void>(() => {}) function AbandonedQuery(): ReactNode { useLiveInfiniteQuery( (q) => q.from({ row: source }).orderBy(({ row }) => row.n, `asc`), { pageSize: 3 }, ) throw never } render( <Suspense fallback={null}> <AbandonedQuery /> </Suspense>, ) await new Promise((resolve) => setTimeout(resolve, 0)) expect(source.subscriberCount).toBe(0)The stable pagination callback has a related generation problem:
const fetchNextPage = useCallback(() => { controllerRef.current?.fetchNextPage() }, [])A callback returned for controller A follows the mutable ref after a later render replaces it with controller B. Retaining A's callback, replacing the collection, and then invoking A's callback advances B to two pages.
Please make collection construction inert and let the first committed
subscribe()activate synchronization. Bind the callback to the controller from its render:const fetchNextPage = useCallback(() => { void controller.fetchNextPage() }, [controller])One clarification: a normal Strict Mode mount/unmount sequence did return subscriber counts to baseline. The verified lifecycle failure is an abandoned render that never commits.
2. Dependency identity collisions#
JSON.stringify(deps)is now the sole query-generation key. Distinct dependencies can serialize identically. For example, allMapinstances serialize as{}.This test remains on group
aafter replacing the dependency with a map for groupb:const { result, rerender } = renderHook( ({ filter }: { filter: Map<string, string> }) => useLiveInfiniteQuery( (q) => q .from({ row: source }) .where(({ row }) => eq(row.group, filter.get(`group`))) .orderBy(({ row }) => row.n, `asc`), { pageSize: 3 }, [filter], ), { initialProps: { filter: new Map([[`group`, `a`]]) } }, ) await waitFor(() => expect(result.current.data.every((row) => row.group === `a`)).toBe(true), ) rerender({ filter: new Map([[`group`, `b`]]) }) await waitFor(() => expect(result.current.data.every((row) => row.group === `b`)).toBe(true), )Functions,
Set,RegExp, and objects with omittedundefinedfields have similar collisions. Circular values also throw even though React dependency arrays need not be serializable.Please match
useLiveQuerywith elementwise identity comparison and retain a shallow copy of the accepted dependency array.3. Changing page shape discards loaded pages#
Recreating the controller when
pageSizeorinitialPageParamchanges resetsloadedPageCountto one. Before this extraction, page count lived independently and a page-size change re-windowed the same number of loaded pages.I loaded three 3-row pages, changed
pageSizeto 5, and expected three 5-row pages. On this head, the result resets to one page and five rows:await waitFor(() => expect(result.current.isReady).toBe(true)) act(() => result.current.fetchNextPage()) await waitFor(() => expect(result.current.pages).toHaveLength(2)) act(() => result.current.fetchNextPage()) await waitFor(() => expect(result.current.pages).toHaveLength(3)) rerender({ pageSize: 5 }) await waitFor(() => expect(result.current.pages).toHaveLength(3)) expect(result.current.data).toHaveLength(15)If this is meant to preserve public behavior, carry the committed page count into the replacement controller or add a reconfiguration operation. If reset semantics are intentional, please document the behavior change and test it after multiple pages have loaded. The current runtime page-size test changes the size while only one page exists, so it cannot distinguish these semantics.
4. Failed window updates commit pagination and poison retries#
fetchNextPage()incrementsloadedPageCountbeforesetWindow()succeeds.applyWindow()assignsappliedLimitbefore invokingsetWindow()and swallows promise rejection.A synchronous failure poisons the next attempt:
const setWindow = vi .spyOn(collection.utils, `setWindow`) .mockImplementationOnce(() => { throw new Error(`window failed`) }) .mockReturnValue(true) expect(() => controller.subscribe(() => {})).toThrow(`window failed`) controller.subscribe(() => {}) expect(setWindow).toHaveBeenCalledTimes(2)Actual result:
setWindowis called once because the failed first call leavesappliedLimitset.An asynchronous failure also commits the next page:
expect(controller.getSnapshot().hasNextPage).toBe(true) vi.spyOn(collection.utils, `setWindow`).mockRejectedValueOnce( new Error(`load failed`), ) await expect(controller.fetchNextPage()).rejects.toThrow(`load failed`) expect(controller.getSnapshot().pages).toHaveLength(1) expect(controller.getSnapshot().hasNextPage).toBe(true)On this head, the controller exposes two pages after rejection. It can also lose
hasNextPage, removing the normal retry path.Please separate committed page count, requested page count, pending generation/limit, accepted limit, and pagination error. Keep slicing at the committed count until the current-generation window request succeeds. On failure, retain the old pages and
hasNextPage, expose the error asunknown, and leave the limit retryable.fetchNextPage()should return the load promise, as required by RFC #1623.5. Async expansion publishes duplicate and incoherent snapshots#
For an asynchronous window expansion,
setFetching(true)notifies andfetchNextPage()immediately callsnotify()again. Both callbacks expose the same state, and both expose the new page count before the load succeeds.This sequence test receives two identical immediate
{ pages: 2, fetching: true }snapshots:const snapshots: Array<{ pages: number; fetching: boolean }> = [] controller.subscribe(() => { const snapshot = controller.getSnapshot() snapshots.push({ pages: snapshot.pages.length, fetching: snapshot.isFetchingNextPage, }) }) let resolveWindow!: () => void vi.spyOn(collection.utils, `setWindow`).mockReturnValueOnce( new Promise<void>((resolve) => { resolveWindow = resolve }), ) const fetch = controller.fetchNextPage() expect(snapshots).toEqual([{ pages: 1, fetching: true }]) resolveWindow() await fetch expect(snapshots).toEqual([ { pages: 1, fetching: true }, { pages: 2, fetching: false }, ])Please place observer delivery behind a publication barrier while requested window, fetching state, and committed page count change. Emit one coherent loading snapshot and one success or failure snapshot. Synchronous observer notifications raised by
setWindow()should join the same transition rather than expose intermediate state.6. Preload and pipeline restart lose the desired window#
The controller's
appliedLimitoutlives the compiled operator it was applied to. Collection cleanup clears the graph and pipeline caches. A later synchronization compiles a fresh top-K operator from the original AST limit, while the controller still believes its larger limit is installed.Reproduction:
const unsubscribe = controller.subscribe(() => {}) await collection.preload() controller.fetchNextPage() await flush() expect(controller.getSnapshot().data).toHaveLength(4) unsubscribe() await collection.cleanup() controller.subscribe(() => {}) await collection.preload() await flush() expect(controller.getSnapshot().data).toHaveLength(4) expect(controller.getSnapshot().hasNextPage).toBe(true)With an original AST limit of 3 and a controller-expanded limit of 5, the restarted result contains only 3 rows. The controller skips reapplication because
appliedLimitstill equals 5.controller.preload()has the same gap. Starting with an AST limit of 2 andpageSize: 2, this fails because preload never installs the required limit of 3:await controller.preload() expect(controller.getSnapshot().hasNextPage).toBe(true) expect(collection.utils.getWindow()).toEqual({ offset: 0, limit: 3 })Please store the desired window as durable builder state and replay it whenever
compileBasePipeline()installs a newwindowFn. The controller should establish that desired window before preload and on each zero-to-one attachment. A cache of the last applied limit cannot outlive the pipeline generation it mutated.7. Multiple controllers overwrite one shared collection window#
Each controller stores a private page count, but
setWindow()mutates one collection-global operator. Two consumers of the same pre-created collection therefore overwrite each other.const larger = createLiveQueryWindowController(collection, { pageSize: 2, mode: `wholesale`, }) const smaller = createLiveQueryWindowController(collection, { pageSize: 1, mode: `wholesale`, }) larger.subscribe(() => {}) smaller.subscribe(() => {}) await collection.preload() await flush() expect(larger.getSnapshot().data).toHaveLength(2) expect(larger.getSnapshot().hasNextPage).toBe(true)The second assertion fails. The smaller controller applies limit 2 after the larger controller applies limit 3. The larger controller then loses its peek row and reports
hasNextPage === false.For the current forward-only, offset-zero model, a collection-owned lease coordinator can apply the maximum active requested limit while each controller slices its own snapshot. Updating or releasing a lease recomputes the physical window. This also gives pipeline recompilation one authoritative desired window to reinstall. If shared ownership is out of scope, please enforce exclusive ownership and throw when a second controller attaches; silent last-writer-wins behavior corrupts pagination state.
8. The default observer mode does not match the controller contract#
The controller inherits the observer's default granular mode, but its listener is only
() => void; it discards the granularChangeMessage[]payload.With default options, this test fails because the listener fires synchronously inside
subscribe():await collection.preload() const controller = createLiveQueryWindowController(collection, { pageSize: 2, }) let subscribing = true let notifiedDuringSubscribe = false controller.subscribe(() => { if (subscribing) notifiedDuringSubscribe = true }) subscribing = false expect(notifiedDuringSubscribe).toBe(false)The existing no-synchronous-notify test passes
mode: 'wholesale', so it does not cover the factory default.Please make the window controller wholesale and non-reentrant by construction and remove
modefrom its options. If a granular controller is added later, it should expose a delta-bearing listener contract.API boundary#
RFC #1623 describes this as a shared internal controller and explicitly requires promise/error semantics, non-reentrant subscriptions, inert rendering, one atomic revision per observable change, and single ownership of the active window. This PR root-exports the controller and advertises it in a changeset without an
@internal/unstable marker.Please either complete that contract before presenting the controller as a new framework-neutral feature, or mark the factory, controller, options, and snapshot as internal/unstable for this phase and update the changeset accordingly.
Verification#
I implemented proof fixes locally and reran the focused regressions plus both full package suites:
@tanstack/db: 2,554 passed, 5 skipped, no type errors@tanstack/react-db: 129 passed, no type errors- both package builds and focused lint passed
I recommend keeping the extraction. The main design change is to treat requested pagination state, committed pagination state, and the collection-owned physical window as separate concepts.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/react-db/src/useLiveInfiniteQuery.ts (1)
158-167: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winReplace
JSON.stringify(deps)with elementwise identity comparison.JSON.stringifyis not injective over the values React users put in a deps array, so distinct deps produce an equaldepsKeyand the hook does not recreate the collection. The query keeps its stale captured values.Concrete collisions:
- Any two
MaporSetvalues serialize to{}. - Any two functions serialize to
null, and[fn]equals[undefined]. - Objects that differ only in
undefined-valued or non-enumerable fields serialize identically.
Elementwise
Object.iscomparison matches React's own deps semantics, is O(n) instead of a full serialization, and removes the circular-reference failure mode along with itsthrow.Note that removing the
throwchanges behavior for the circular-deps case. The test at Line 1964 ofpackages/react-db/tests/useLiveInfiniteQuery.test.tsxasserts that error and needs updating.🐛 Proposed fix using elementwise comparison
Replace the
depsKeyblock:- // Track deps for query functions (stringify for comparison) - let depsKey: string - try { - depsKey = JSON.stringify(deps) - } catch { - throw new Error( - `useLiveInfiniteQuery: dependency array contains values that cannot be serialized (e.g. circular references). ` + - `Ensure all dependency values are JSON-serializable.`, - ) - }Add a module-level helper:
/** React-style deps comparison: same length, elementwise `Object.is`. */ function depsChanged( previous: ReadonlyArray<unknown> | null, next: ReadonlyArray<unknown>, ): boolean { if (previous === null || previous.length !== next.length) return true return next.some((value, i) => !Object.is(value, previous[i])) }Then change the ref and the
needsNewterm:- const depsRef = useRef<string | null>(null) + const depsRef = useRef<ReadonlyArray<unknown> | null>(null)- (!isCollection && depsRef.current !== depsKey) + (!isCollection && depsChanged(depsRef.current, deps))- depsRef.current = depsKey + depsRef.current = [...deps]🤖 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/useLiveInfiniteQuery.ts` around lines 158 - 167, Replace the JSON.stringify-based depsKey logic in useLiveInfiniteQuery with module-level elementwise Object.is comparison that checks dependency length and identity, removing serialization and its circular-reference throw. Update the ref and needsNew logic to use this comparison so query collections recreate when any dependency identity changes, and update the circular-dependency test expectation accordingly.🧹 Nitpick comments (8)
packages/react-db/src/useLiveInfiniteQuery.ts (2)
263-279: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe blanket cast can hide missing fields.
UseLiveInfiniteQueryReturn<TContext>is derived fromOmit<ReturnType<typeof useLiveQuery<TContext>>, 'data'>. Theascast at Line 279 suppresses any structural mismatch. IfuseLiveQuerygains a return field, this object omits it and the compiler stays silent, so consumers getundefinedat runtime for a field the type promises.Remove the assertion and let the object literal be checked against the declared return type. The per-field casts on
data,pages, andpageParamscan stay.🤖 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/useLiveInfiniteQuery.ts` around lines 263 - 279, Remove the blanket `as UseLiveInfiniteQueryReturn<TContext>` assertion from the object returned by the live infinite query hook, allowing structural type checking to catch omitted fields. Keep the existing per-field casts for `data`, `pages`, and `pageParams` unchanged.Source: Coding guidelines
22-25: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMake
hasSetWindowan actual type guard or correct the doc comment.The JSDoc calls this a type guard, but the return type is
boolean, so it narrows nothing. Callers still accesscollection.utils.getWindow?.()andcollection.utils.setWindowwithout type support.As per coding guidelines: "Always provide the most precise return type annotation".
♻️ Proposed predicate signature
+type WindowedCollection = Collection<any, any, any> & { + utils: { + setWindow: (w: { offset: number; limit: number }) => true | Promise<void> + getWindow?: () => { offset: number; limit: number } | undefined + } +} + /** Type guard: does this collection expose `setWindow` (i.e. has an orderBy)? */ -function hasSetWindow(collection: Collection<any, any, any>): boolean { +function hasSetWindow( + collection: Collection<any, any, any>, +): collection is WindowedCollection { return typeof collection.utils?.setWindow === `function` }🤖 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/useLiveInfiniteQuery.ts` around lines 22 - 25, Update hasSetWindow to use a type-predicate return annotation that narrows the collection to one whose utils exposes setWindow, matching the existing JSDoc and enabling type-safe access for callers. Preserve the current runtime function check and use the narrowed type in the predicate target.Source: Coding guidelines
packages/react-db/tests/useLiveInfiniteQuery.test.tsx (2)
702-739: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtend the test to cover a
pageSizechange after pages are loaded.The test changes
pageSizewhile only page 1 is loaded, so it cannot observe what happens to already loaded pages.The hook recreates the controller on a
pageSizechange, and a fresh controller starts atloadedPageCount = 1. If a user has paged to 3 pages andpageSizethen changes, the loaded pages are discarded. The PR objectives record this as an open concern about changing established behavior. No test pins the intended outcome.Add a case that calls
fetchNextPage()before the rerender, then asserts the intended row count. That documents the decision and catches an unintended change later.🤖 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/tests/useLiveInfiniteQuery.test.tsx` around lines 702 - 739, Extend the “re-windows and re-slices when pageSize changes at runtime” test to call result.current.fetchNextPage() and wait until a second page is loaded before rerendering with the new pageSize. After the rerender, assert the intended data and pages row counts, explicitly documenting whether previously loaded pages are preserved or discarded.
1801-1813: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAwait
setWindowand assert the window is actually adjusted.Two problems in this test.
Line 1804 discards the
setWindowreturn value.setWindowreturnstrue | Promise<void>, as declared at Lines 291-294 ofpackages/db/src/live-query-window-controller.ts. If it returns a promise, the window is not established whenrenderHookruns at Line 1808. The test still passes today because the query was built with.limit(5), sogetWindow()reports limit 5 either way. The precondition is therefore not deterministic.The test asserts only that the warning fires. The warning text promises "Adjusting window now.", and the test never checks that the window becomes
{offset: 0, limit: 11}. The observable outcome is the part that matters to users.
As per coding guidelines: "Test corner cases including: empty arrays/sets, single-element collections, undefined vs null values, resolved promises, async race conditions, and limit/offset edge cases".
💚 Proposed test hardening
- liveQueryCollection.utils.setWindow({ offset: 0, limit: 5 }) + const applied = liveQueryCollection.utils.setWindow({ + offset: 0, + limit: 5, + }) + if (applied !== true) await applied const warn = vi.spyOn(console, `warn`).mockImplementation(() => {}) try { renderHook(() => useLiveInfiniteQuery(liveQueryCollection, { pageSize: 10 }), ) expect(warn).toHaveBeenCalledWith( expect.stringContaining(`Pre-created collection has window`), ) + // The warning promises the window is adjusted; verify it. + await waitFor(() => + expect(liveQueryCollection.utils.getWindow?.()).toEqual({ + offset: 0, + limit: 11, + }), + ) } finally {🤖 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/tests/useLiveInfiniteQuery.test.tsx` around lines 1801 - 1813, Make the test await the return value of liveQueryCollection.utils.setWindow before rendering the hook, handling both synchronous and promise results. After renderHook, retain the warning assertion and also assert that the collection window is adjusted to offset 0 and limit 11, using the collection’s existing window-inspection API.Source: Coding guidelines
packages/db/tests/live-query-window-controller.test.ts (3)
101-116: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd tests for an empty source and for a falsy
pageSize.The suite covers a partial last page and a source smaller than one page. Two documented edges are untested.
- An empty source collection.
getSnapshot()reportsenabled === true, so the loop at Lines 167-170 still produces one page, andpagesbecomes[[]]withhasNextPage === false. Lines 162-163 state this is intended. A test locks it in. pageSize: 0. The constructor at Line 130 uses||, so the value falls back toDEFAULT_PAGE_SIZE. Without a test, a later change to??would silently maketotalRequestedzero and keephasNextPagepermanently true.
As per coding guidelines: "Test corner cases including: empty arrays/sets, single-element collections, undefined vs null values, resolved promises, async race conditions, and limit/offset edge cases".
🤖 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-window-controller.test.ts` around lines 101 - 116, Add tests alongside the existing live-query window controller pagination tests for an empty source and for a controller created with pageSize 0. Assert the empty source yields an enabled snapshot with pages containing one empty page and hasNextPage false; assert pageSize 0 uses the default page size and does not leave hasNextPage permanently true. Use the existing helpers and cleanup pattern.Source: Coding guidelines
150-153: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTighten the notification assertions.
Both tests assert
toBeGreaterThan(0). That passes for any notification count, so it cannot detect duplicate or redundant publications.The PR objectives record a known concern that async window expansion can emit duplicate snapshots and should be batched into one loading and one settled notification. With the current assertion, a regression in publication count stays invisible, and a future batching change produces no test signal either.
Assert a bounded count, for example
expect(notifications).toBeLessThanOrEqual(2)alongside the existing lower bound, so the publication shape is pinned.Also applies to: 189-194
🤖 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-window-controller.test.ts` around lines 150 - 153, In both notification assertions around controller.fetchNextPage(), retain the existing positive lower-bound check and add an upper-bound assertion limiting notifications to two. Apply this to both referenced tests so async window expansion is constrained to at most one loading and one settled publication.
252-274: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a regression test for unsubscribe during a publication.
This test covers
dispose()from inside a listener. It does not cover the adjacent case: one listener unsubscribes a different listener during the same publication.The dispatch loop in
live-query-window-controller.tsat Lines 336-342 iterates a captured target list and never readsrecord.active, so the unsubscribed listener still receives the call. A test that mirrors this one, but calls the second subscriber's unsubscribe function instead ofdispose(), reproduces it.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-window-controller.test.ts` around lines 252 - 274, Add a regression test alongside the existing in-flight publication test that stores the second subscription’s unsubscribe function, has the first listener invoke it during publication, and asserts the second listener is not notified. Preserve the same setup and publication trigger used by the existing test, targeting the controller’s listener dispatch behavior rather than calling controller.dispose().Source: Coding guidelines
packages/db/src/index.ts (1)
15-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMark the controller surface internal or unstable before release.
Line 15 re-exports every symbol from
live-query-window-controller, socreateLiveQueryWindowController,LiveQueryWindowController,LiveQueryWindowSnapshot, andCreateLiveQueryWindowControllerOptionsbecome public API of@tanstack/db. The stack includes a changeset, so this ships as a supported surface.The PR still lists open design questions for window semantics, forward-only versus bidirectional pagination,
getNextPageParam, and window ownership for pre-created collections. Publishing the API now creates a compatibility obligation before those decisions are settled.Add an
@internal/unstable note to the module doc comment, matching howlive-query-observerwas documented. Based on the PR objectives, which state the reviewer asked either to complete the RFC contract or mark the API as internal/unstable.🤖 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/index.ts` at line 15, Mark the live query window controller module as internal or unstable in its module documentation, following the existing documentation pattern used by live-query-observer. Update the doc comment associated with the symbols re-exported by the index rather than changing the re-export itself, and clearly indicate the API is not yet a supported public contract.🤖 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 @.changeset/live-query-window-controller.md: - Around line 2-3: The changeset must not publish createLiveQueryWindowController and LiveQueryWindowController as an unresolved stable patch API. Either finalize and document their RFC contract, update `@tanstack/db` to a minor release, or explicitly mark the exports unstable/internal and state that status in the changeset. In `@packages/db/src/live-query-window-controller.ts`: - Around line 336-342: Update the publication dispatch loop in packages/db/src/live-query-window-controller.ts lines 336-342 to skip records whose SubscriptionRecord.active is false before invoking record.listener(). Add a test in packages/db/tests/live-query-window-controller.test.ts lines 252-274 mirroring the dispose-during-publication case, but unsubscribe the second subscriber and assert it receives no notification. - Around line 280-318: Update applyWindow in packages/db/src/live-query-window-controller.ts:280-318 to validate setWindow before changing appliedLimit, commit the limit only after the call succeeds, and restore the prior invalidated state when it throws synchronously or its promise rejects. In the last-subscriber detach path at packages/db/src/live-query-window-controller.ts:227-235, clear appliedLimit so the next subscribe re-applies the window. In `@packages/react-db/src/useLiveInfiniteQuery.ts`: - Around line 188-243: Dispose the existing controller before replacing it in the needsNew block, and add an unmount cleanup effect that disposes and clears controllerRef.current. Update the React imports to include useEffect, ensuring every controller created by createLiveQueryWindowController is released on parameter changes and unmount. --- Outside diff comments: In `@packages/react-db/src/useLiveInfiniteQuery.ts`: - Around line 158-167: Replace the JSON.stringify-based depsKey logic in useLiveInfiniteQuery with module-level elementwise Object.is comparison that checks dependency length and identity, removing serialization and its circular-reference throw. Update the ref and needsNew logic to use this comparison so query collections recreate when any dependency identity changes, and update the circular-dependency test expectation accordingly. --- Nitpick comments: In `@packages/db/src/index.ts`: - Line 15: Mark the live query window controller module as internal or unstable in its module documentation, following the existing documentation pattern used by live-query-observer. Update the doc comment associated with the symbols re-exported by the index rather than changing the re-export itself, and clearly indicate the API is not yet a supported public contract. In `@packages/db/tests/live-query-window-controller.test.ts`: - Around line 101-116: Add tests alongside the existing live-query window controller pagination tests for an empty source and for a controller created with pageSize 0. Assert the empty source yields an enabled snapshot with pages containing one empty page and hasNextPage false; assert pageSize 0 uses the default page size and does not leave hasNextPage permanently true. Use the existing helpers and cleanup pattern. - Around line 150-153: In both notification assertions around controller.fetchNextPage(), retain the existing positive lower-bound check and add an upper-bound assertion limiting notifications to two. Apply this to both referenced tests so async window expansion is constrained to at most one loading and one settled publication. - Around line 252-274: Add a regression test alongside the existing in-flight publication test that stores the second subscription’s unsubscribe function, has the first listener invoke it during publication, and asserts the second listener is not notified. Preserve the same setup and publication trigger used by the existing test, targeting the controller’s listener dispatch behavior rather than calling controller.dispose(). In `@packages/react-db/src/useLiveInfiniteQuery.ts`: - Around line 263-279: Remove the blanket `as UseLiveInfiniteQueryReturn<TContext>` assertion from the object returned by the live infinite query hook, allowing structural type checking to catch omitted fields. Keep the existing per-field casts for `data`, `pages`, and `pageParams` unchanged. - Around line 22-25: Update hasSetWindow to use a type-predicate return annotation that narrows the collection to one whose utils exposes setWindow, matching the existing JSDoc and enabling type-safe access for callers. Preserve the current runtime function check and use the narrowed type in the predicate target. In `@packages/react-db/tests/useLiveInfiniteQuery.test.tsx`: - Around line 702-739: Extend the “re-windows and re-slices when pageSize changes at runtime” test to call result.current.fetchNextPage() and wait until a second page is loaded before rerendering with the new pageSize. After the rerender, assert the intended data and pages row counts, explicitly documenting whether previously loaded pages are preserved or discarded. - Around line 1801-1813: Make the test await the return value of liveQueryCollection.utils.setWindow before rendering the hook, handling both synchronous and promise results. After renderHook, retain the warning assertion and also assert that the collection window is adjusted to offset 0 and limit 11, using the collection’s existing window-inspection API.🪄 Autofix
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 Plus
Run ID:
7f080acc-7635-4a4b-828d-b2a6bf46a00e📥 Commits
Reviewing files that changed from the base of the PR and between 2985e0b67ab9e0bd91fe9af0cb3ee6e77713486d and f994c55b27b114e087661656480f0d6061d9e834.
📒 Files selected for processing (7)
.changeset/live-query-window-controller.mdpackages/db/src/errors.tspackages/db/src/index.tspackages/db/src/live-query-window-controller.tspackages/db/tests/live-query-window-controller.test.tspackages/react-db/src/useLiveInfiniteQuery.tspackages/react-db/tests/useLiveInfiniteQuery.test.tsx
@@ -0,0 +1,3 @@1+---2+'@tanstack/db': patch3+'@tanstack/react-db': patch🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Resolve the public API status before publishing this changeset.
createLiveQueryWindowControllerandLiveQueryWindowControllerare root-exported frompackages/db/src/live-query-window-controller.ts, so@tanstack/dbreceives a new public API. A new stable export normally requires aminorrelease, notpatch. The PR also lists unresolved window semantics and ownership questions.Either complete and document the RFC contract before release, or mark the API as unstable/internal and state that status in this changeset.
🤖 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 @.changeset/live-query-window-controller.md around lines 2 - 3, The changeset must not publish createLiveQueryWindowController and LiveQueryWindowController as an unresolved stable patch API. Either finalize and document their RFC contract, update `@tanstack/db` to a minor release, or explicitly mark the exports unstable/internal and state that status in the changeset.✅ Addressed in commit 1bf883f
@@ -0,0 +298,21 @@298+299+ const generation = ++this.windowGeneration300+ const result = utils.setWindow({ offset: 0, limit })301+ if (result === true) {302+ this.setFetching(false)303+ return304+ }305+306+ this.setFetching(true)307+ result308+ .catch(() => {309+ // Swallow — the load error surfaces through the collection's status.310+ })311+ .finally(() => {312+ // Only clear for the window this call requested; a newer apply owns the313+ // flag otherwise.314+ if (!this.disposed && generation === this.windowGeneration) {315+ this.setFetching(false)316+ }317+ })318+ }🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
appliedLimithas no requested-versus-applied distinction and only one invalidation point. The field records an intent, not a confirmed state, andreset()is the only place that clears it. Both sites below letappliedLimitblock a needed re-apply at Line 286.packages/db/src/live-query-window-controller.ts#L280-L318: commitappliedLimitonly aftersetWindowsucceeds, and roll it back when the call throws synchronously or the returned promise rejects. Move thetypeof utils?.setWindow !== 'function'check ahead of the commit.packages/db/src/live-query-window-controller.ts#L227-L235: setappliedLimit = undefinedwhen the last subscriber detaches, so the nextsubscribe()re-establishes the window instead of trusting a limit applied during a previous subscription.
📍 Affects 1 file
packages/db/src/live-query-window-controller.ts#L280-L318(this comment)packages/db/src/live-query-window-controller.ts#L227-L235
🤖 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-window-controller.ts` around lines 280 - 318, Update applyWindow in packages/db/src/live-query-window-controller.ts:280-318 to validate setWindow before changing appliedLimit, commit the limit only after the call succeeds, and restore the prior invalidated state when it throws synchronously or its promise rejects. In the last-subscriber detach path at packages/db/src/live-query-window-controller.ts:227-235, clear appliedLimit so the next subscribe re-applies the window.✅ Addressed in commit 1bf883f
@@ -0,0 +322,21 @@322+ this.isFetchingNextPage = value323+ this.notify()324+ }325+326+ private notify(): void {327+ if (this.disposed || this.blockDelivery || this.subscriptions.size === 0) {328+ return329+ }330+331+ this.publicationQueue.push({ targets: [...this.subscriptions] })332+ if (this.dispatching) return333+334+ this.dispatching = true335+ try {336+ while (this.publicationQueue.length > 0) {337+ const publication = this.publicationQueue.shift()!338+ for (const record of publication.targets) {339+ if (this.hasBeenDisposed()) return340+ record.listener()341+ }342+ }🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
SubscriptionRecord.activeis written but never read during dispatch. The unsubscribe closure at Line 229 anddispose()at Line 268 both setactive = false, yet the publication loop invokes every captured target unconditionally. A listener unsubscribed mid-publication still receives the notification.packages/db/src/live-query-window-controller.ts#L336-L342: addif (!record.active) continuebeforerecord.listener()in the dispatch loop.packages/db/tests/live-query-window-controller.test.ts#L252-L274: add a test that mirrors the existing dispose-during-publication case but calls the second subscriber's unsubscribe function, and assert that subscriber receives no notification.
📍 Affects 2 files
packages/db/src/live-query-window-controller.ts#L336-L342(this comment)packages/db/tests/live-query-window-controller.test.ts#L252-L274
🤖 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-window-controller.ts` around lines 336 - 342, Update the publication dispatch loop in packages/db/src/live-query-window-controller.ts lines 336-342 to skip records whose SubscriptionRecord.active is false before invoking record.listener(). Add a test in packages/db/tests/live-query-window-controller.test.ts lines 252-274 mirroring the dispose-during-publication case, but unsubscribe the second subscriber and assert it receives no notification.✅ Addressed in commit 1bf883f
packages/react-db/src/useLiveInfiniteQuery.ts lines 188 to 243Outdated@@ -298 +223,21 @@223+ .limit(pageSize + 1)224+ .offset(0),225+ startSync: true,226+ gcTime: DEFAULT_GC_TIME_MS,227+ })228+ depsRef.current = depsKey298229 }230+ controllerRef.current = createLiveQueryWindowController(231+ collectionRef.current,232+ {233+ pageSize,234+ initialPageParam,235+ // Wholesale mode provides useSyncExternalStore's no-sync-notify contract.236+ mode: 'wholesale',237+ // A query-function collection already carries page 1's window in its238+ // query, so defer the (redundant) first apply until it is ready; a239+ // pre-created collection needs its window established up front.240+ waitForReady: !isCollection,241+ },242+ )243+ }🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
Dispose the previous controller and the collection it owns.
Line 230 overwrites
controllerRef.currentwithout callingdispose()on the controller it replaces. The hook never disposes a controller at all — there is no effect in this file that runs teardown on unmount.Two consequences:
- Every
pageSizeorinitialPageParamchange leaks a controller and its observer. The new test at Line 702 ofpackages/react-db/tests/useLiveInfiniteQuery.test.tsxdrives this path directly. - In the query-function branch, Line 220 creates a live-query collection with
startSync: true. The replaced collection is abandoned while syncing.gcTime: 1may reclaim the collection, but the controller that wraps it is never told to release the observer.
A related risk sits in the same block. Line 214 calls
startSyncImmediate(), and Line 220 starts sync, both during render. React discards renders in Strict Mode, under Suspense, and on concurrent interruption. Each discarded render activates synchronization that nothing tears down.Add disposal for the replaced controller, and add an unmount effect that disposes the final one. Moving activation into an effect is the fuller fix and is worth planning before this ships.
🐛 Minimal fix: dispose the replaced controller and dispose on unmount
if (needsNew) { + // Release the controller (and its observer subscription) being replaced. + controllerRef.current?.dispose() pageSizeRef.current = pageSize initialPageParamRef.current = initialPageParamAdd an unmount-only effect after the controller is resolved:
// Dispose whichever controller is current when the hook unmounts. useEffect(() => { return () => { controllerRef.current?.dispose() controllerRef.current = null } }, [])useEffectmust be added to thereactimport at Line 1.📝 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.
if (needsNew) { // Release the controller (and its observer subscription) being replaced. controllerRef.current?.dispose() pageSizeRef.current = pageSize initialPageParamRef.current = initialPageParam if (isCollection) { const collection = queryFnOrCollection as Collection<any, any, any> if (!hasSetWindow(collection)) { throw new Error( `useLiveInfiniteQuery: Pre-created live query collection must have an orderBy clause for infinite pagination to work. ` + `Please add .orderBy() to your createLiveQueryCollection query.`, ) } // Warn once per collection instance if its current window doesn't match // the first page the hook is about to enforce. if (validatedCollectionRef.current !== collection) { validatedCollectionRef.current = collection const currentWindow = collection.utils.getWindow?.() if ( currentWindow && (currentWindow.offset !== 0 || currentWindow.limit !== pageSize + 1) ) { console.warn( `useLiveInfiniteQuery: Pre-created collection has window {offset: ${currentWindow.offset}, limit: ${currentWindow.limit}} ` + `but the hook expects {offset: 0, limit: ${pageSize + 1}}. Adjusting window now.`, ) } } collection.startSyncImmediate() collectionRef.current = collection configRef.current = queryFnOrCollection } else { // Wrap the query with the first page's peek-ahead window; the controller // grows the limit from here via setWindow. collectionRef.current = createLiveQueryCollection({ query: (q: InitialQueryBuilder) => queryFnOrCollection(q) .limit(pageSize + 1) .offset(0), startSync: true, gcTime: DEFAULT_GC_TIME_MS, }) depsRef.current = depsKey } controllerRef.current = createLiveQueryWindowController( collectionRef.current, { pageSize, initialPageParam, // Wholesale mode provides useSyncExternalStore's no-sync-notify contract. mode: 'wholesale', // A query-function collection already carries page 1's window in its // query, so defer the (redundant) first apply until it is ready; a // pre-created collection needs its window established up front. waitForReady: !isCollection, }, ) } // Dispose whichever controller is current when the hook unmounts. useEffect(() => { return () => { controllerRef.current?.dispose() controllerRef.current = null } }, [])🤖 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/useLiveInfiniteQuery.ts` around lines 188 - 243, Dispose the existing controller before replacing it in the needsNew block, and add an unmount cleanup effect that disposes and clears controllerRef.current. Update the React imports to include useEffect, ensuring every controller created by createLiveQueryWindowController is released on parameter changes and unmount.- Any two
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/db/src/live-query-window-controller.ts (1)
343-364: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winA rejected window promise stays unhandled when observer activation throws.
activateLeaseat Line 348 can return a promise. Ifthis.observer.subscribeat Line 350 throws, control moves to the catch block, and no handler is ever attached to that promise. A later rejection fromsetWindowthen becomes an unhandled rejection.Attach a no-op rejection handler before rethrowing.
🛡️ Proposed fix
} catch (error) { + if (windowResult !== undefined && windowResult !== true) { + // The lease is being released; the caller has no channel for this error. + void windowResult.catch(() => {}) + } observerUnsub?.() this.observerUnsub = null this.deactivateLease()Declare
let windowResult: WindowResult | undefinedoutside thetryblock and assign it inside.🤖 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-window-controller.ts` around lines 343 - 364, Update the activation error path in the surrounding lease-subscription flow so any promise returned by activateLease is given a no-op rejection handler before the caught error is rethrown. Declare windowResult outside the try block, assign it from activateLease inside, and in catch attach the handler when the result is promise-like while preserving existing cleanup.🧹 Nitpick comments (4)
packages/react-db/tests/useLiveInfiniteQuery.test.tsx (1)
139-139: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueExtract the render-flush sleep into a shared helper.
Both abandoned-render tests use the same inline
await new Promise((resolve) => setTimeout(resolve, 0)). Extract one helper, for exampleflushMicrotasks(), and call it from both tests.As per coding guidelines: "Extract common logic into utility functions when identical or near-identical code blocks appear in multiple places".
🤖 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/tests/useLiveInfiniteQuery.test.tsx` at line 139, Extract the duplicated zero-delay render-flush promise into a shared helper such as flushMicrotasks in the test module, then replace the inline sleeps in both abandoned-render tests with calls to that helper.Source: Coding guidelines
packages/db/tests/live-query-window-controller.test.ts (2)
329-349: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider a larger
gcTimefor this test.gcTime: 1allows garbage collection of the live-query collection one millisecond after the last subscriber releases it.controller.preload()releases the temporary lease in itsfinallyblock before the assertions run. Under a slow CI event loop, the collection can be cleaned up beforelq.utils.getWindow()is read, which makes the test flaky. Use a value that clearly exceeds test scheduling jitter.♻️ Proposed change
- gcTime: 1, + gcTime: 5000,🤖 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-window-controller.test.ts` around lines 329 - 349, Increase the gcTime configured in the createLiveQueryCollection call within the “establishes the desired window before preload” test to a value that comfortably exceeds normal test scheduling jitter, while preserving the existing preload and window assertions.
120-122: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffReplace the repeated
lq as anycasts with a typed helper.Every controller construction in this file casts the live-query collection with
as any. The coding guidelines require avoidingany. GivemakeOrderedLiveQueryan explicitCollection<Row, string, ...>return type, or introduce one small helper that performs the construction once, so the casts disappear from each test.As per coding guidelines: "Avoid using
anytypes; useunknowninstead when the type is truly unknown, and provide proper type annotations for return values".🤖 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-window-controller.test.ts` around lines 120 - 122, Remove the repeated lq as any casts from controller construction in live-query-window-controller.test.ts by giving makeOrderedLiveQuery an explicit Collection<Row, string, ...> return type or adding a typed construction helper. Update every createLiveQueryWindowController call to use the typed result without any while preserving the existing test behavior.Source: Coding guidelines
packages/db/src/live-query-window-controller.ts (1)
549-556: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the peek-row computation shared with
getSnapshot.getComputedHasNextPagerepeats the logic at Lines 289-295: readisEnabled, verify the data is an array, then compare the row count againstcommittedPageCount * pageSize. Two copies of the peek-row rule can drift when the window arithmetic changes.Add one private helper that takes the observer snapshot and returns the computed value, and call it from both sites.
As per coding guidelines: "Extract common logic into utility functions when identical or near-identical code blocks appear in multiple places".
🤖 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-window-controller.ts` around lines 549 - 556, Extract the shared peek-row calculation into one private helper that accepts a LiveQuerySnapshot and returns whether the enabled array data exceeds committedPageCount * pageSize. Update both getSnapshot and getComputedHasNextPage to call this helper, removing their duplicated isEnabled, array, and row-count logic.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-window-controller.ts`: - Around line 398-417: Update preload() to clear hasPaginationError and paginationError at the start of each attempt, before activating the lease or calling observer.preload(). After a successful preload that cleared a prior error, call notify() so getSnapshot() reflects the recovered state; preserve the existing catch, rethrow, and lease-cleanup behavior. - Around line 503-512: The temporary lease is tracked per call, allowing overlapping reset/fetch requests to release the shared lease prematurely. In the request flow around releaseTemporaryLease, replace the boolean with an in-flight temporary-lease holder count, increment when a request acquires the lease, decrement in finally, and deactivate only when the count reaches zero and there are no subscriptions. Add a regression test covering overlapping reset() and fetchNextPage() calls. In `@packages/db/src/query/live/collection-config-builder.ts`: - Around line 278-288: The setWindow rollback in the currentWindow update flow must restore the actual initial operator window, including when previousWindow is undefined, then rerun maybeRunGraphFn after restoration to remove partial results. Make recovery exception-safe by preserving and rethrowing the original error even if windowFn or graph rerun fails during rollback. In `@packages/react-db/tests/useLiveInfiniteQuery.test.tsx`: - Around line 890-892: Strengthen the stale-callback test around fetchFromA by awaiting the asynchronous work to settle before asserting the page count remains unchanged. Then call result.current.fetchNextPage() explicitly, await its completion, and assert the current controller’s page count increases as expected, proving both stale-callback isolation and the new callback binding. --- Outside diff comments: In `@packages/db/src/live-query-window-controller.ts`: - Around line 343-364: Update the activation error path in the surrounding lease-subscription flow so any promise returned by activateLease is given a no-op rejection handler before the caught error is rethrown. Declare windowResult outside the try block, assign it from activateLease inside, and in catch attach the handler when the result is promise-like while preserving existing cleanup. --- Nitpick comments: In `@packages/db/src/live-query-window-controller.ts`: - Around line 549-556: Extract the shared peek-row calculation into one private helper that accepts a LiveQuerySnapshot and returns whether the enabled array data exceeds committedPageCount * pageSize. Update both getSnapshot and getComputedHasNextPage to call this helper, removing their duplicated isEnabled, array, and row-count logic. In `@packages/db/tests/live-query-window-controller.test.ts`: - Around line 329-349: Increase the gcTime configured in the createLiveQueryCollection call within the “establishes the desired window before preload” test to a value that comfortably exceeds normal test scheduling jitter, while preserving the existing preload and window assertions. - Around line 120-122: Remove the repeated lq as any casts from controller construction in live-query-window-controller.test.ts by giving makeOrderedLiveQuery an explicit Collection<Row, string, ...> return type or adding a typed construction helper. Update every createLiveQueryWindowController call to use the typed result without any while preserving the existing test behavior. In `@packages/react-db/tests/useLiveInfiniteQuery.test.tsx`: - Line 139: Extract the duplicated zero-delay render-flush promise into a shared helper such as flushMicrotasks in the test module, then replace the inline sleeps in both abandoned-render tests with calls to that helper.🪄 Autofix
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 Plus
Run ID:
ccfb4d0e-c05b-423a-9766-0983813c3122📥 Commits
Reviewing files that changed from the base of the PR and between f994c55b27b114e087661656480f0d6061d9e834 and 1bf883f48fc0311c983fefbf1146570aeb9d1782.
📒 Files selected for processing (7)
.changeset/live-query-window-controller.mdpackages/db/src/index.tspackages/db/src/live-query-window-controller.tspackages/db/src/query/live/collection-config-builder.tspackages/db/tests/live-query-window-controller.test.tspackages/react-db/src/useLiveInfiniteQuery.tspackages/react-db/tests/useLiveInfiniteQuery.test.tsx
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/db/src/index.ts
- .changeset/live-query-window-controller.md
- packages/react-db/src/useLiveInfiniteQuery.ts
@@ -0,0 +397,21 @@397+398+ async preload(): Promise<void> {399+ if (this.disposed) throw new LiveQueryWindowControllerDisposedError()400+401+ const temporaryLease = !this.leaseActive402+ try {403+ const result = this.activateLease(this.committedPageCount)404+ if (result !== true) await result405+ await this.observer.preload()406+ } catch (error) {407+ this.hasPaginationError = true408+ this.paginationError = error409+ this.failedHasNextPage = this.getComputedHasNextPage()410+ this.notify()411+ throw error412+ } finally {413+ if (temporaryLease && this.subscriptions.size === 0) {414+ this.deactivateLease()415+ }416+ }417+ }🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
preload()never clears a previous pagination error.requestPageCountclearshasPaginationErrorandpaginationErrorbefore it starts (Lines 444-445).preload()does not. If a firstpreload()fails and a retry succeeds,hasPaginationErrorstaystrue.getSnapshot()then keeps reportingstatus: 'error',isError: true, and the staleerrorvalue for a controller that loaded successfully.Clear the pagination error when the preload attempt begins, and notify after a successful attempt that cleared a previous error.
🐛 Proposed fix
async preload(): Promise<void> { if (this.disposed) throw new LiveQueryWindowControllerDisposedError() const temporaryLease = !this.leaseActive + const hadPaginationError = this.hasPaginationError + this.hasPaginationError = false + this.paginationError = undefined try { const result = this.activateLease(this.committedPageCount) if (result !== true) await result await this.observer.preload() + if (hadPaginationError) this.notify() } catch (error) { this.hasPaginationError = true📝 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.
async preload(): Promise<void> { if (this.disposed) throw new LiveQueryWindowControllerDisposedError() const temporaryLease = !this.leaseActive const hadPaginationError = this.hasPaginationError this.hasPaginationError = false this.paginationError = undefined try { const result = this.activateLease(this.committedPageCount) if (result !== true) await result await this.observer.preload() if (hadPaginationError) this.notify() } catch (error) { this.hasPaginationError = true this.paginationError = error this.failedHasNextPage = this.getComputedHasNextPage() this.notify() throw error } finally { if (temporaryLease && this.subscriptions.size === 0) { this.deactivateLease() } } }🤖 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-window-controller.ts` around lines 398 - 417, Update preload() to clear hasPaginationError and paginationError at the start of each attempt, before activating the lease or calling observer.preload(). After a successful preload that cleared a prior error, call notify() so getSnapshot() reflects the recovered state; preserve the existing catch, rethrow, and lease-cleanup behavior.✅ Addressed in commit d704b95
@@ -0,0 +492,21 @@492+ this.pendingWindowGeneration = undefined493+ this.isFetchingNextPage = false494+ this.hasPaginationError = true495+ this.paginationError = error496+ this.failedHasNextPage = previousHasNextPage497+ this.notify()498+ this.endTransition()499+ }500+ throw error501+ },502+ )503+ .finally(() => {504+ this.releaseTemporaryLease(temporaryLease)505+ })506+ }507+508+ private releaseTemporaryLease(temporaryLease: boolean): void {509+ if (temporaryLease && this.subscriptions.size === 0) {510+ this.deactivateLease()511+ }512+ }🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Description: Look for existing coverage of overlapping window requests on an unsubscribed controller. set -euo pipefail fd -t f 'live-query-window-controller.test.ts' | while IFS= read -r f; do rg -n -C 6 'reset\(\)|fetchNextPage\(\)|preload\(\)|subscribe\(' "$f" doneRepository: TanStack/db
Length of output: 16843
🏁 Script executed:
#!/bin/bash set -euo pipefail file=$(fd -t f 'live-query-window-controller.ts' | head -n 1) printf '%s\n' "FILE=$file" ast-grep outline "$file" --match 'function createLiveQueryWindowController' --view expanded || true printf '%s\n' '--- relevant implementation ---' sed -n '1,180p' "$file" sed -n '380,530p' "$file" printf '%s\n' '--- related symbols and call sites ---' rg -n -C 4 'temporaryLease|releaseTemporaryLease|activateLease|deactivateLease|committedPageCount|reset|fetchNextPage' "$file"Repository: TanStack/db
Length of output: 19180
🏁 Script executed:
#!/bin/bash set -euo pipefail controller=$(fd -t f 'live-query-window-controller.ts' | head -n 1) tests=$(fd -t f 'live-query-window-controller.test.ts' | head -n 1) printf '%s\n' '--- controller lifecycle and pagination ---' sed -n '210,380p' "$controller" printf '%s\n' '--- existing overlap tests ---' sed -n '236,305p' "$tests" printf '%s\n' '--- test helpers and no-subscription calls ---' sed -n '1,48p' "$tests" rg -n -C 5 'controller\.(fetchNextPage|reset|preload)\(' "$tests"Repository: TanStack/db
Length of output: 15807
🏁 Script executed:
#!/bin/bash set -euo pipefail node - <<'JS' class WindowCoordinator { constructor(setWindow) { this.setWindow = setWindow this.leases = new Map() this.appliedLimit = undefined this.pending = undefined this.generation = 0 } request(lease, limit) { this.leases.set(lease, limit) return this.applyDesiredWindow() } release(lease) { if (!this.leases.delete(lease)) return this.generation++ this.pending = undefined if (this.leases.size === 0) { this.appliedLimit = undefined return } try { const result = this.applyDesiredWindow() if (result !== true) void result.catch(() => { this.appliedLimit = undefined }) } catch { this.appliedLimit = undefined } } desired() { return this.leases.size ? Math.max(...this.leases.values()) : undefined } applyDesiredWindow() { const limit = this.desired() if (limit === undefined) return true if (this.pending?.limit === limit) return this.pending.promise if (this.pending) { this.generation++ this.pending = undefined this.appliedLimit = undefined } if (limit === this.appliedLimit) return true const generation = ++this.generation const result = this.setWindow(limit) if (result === true) { if (generation === this.generation && this.desired() === limit) { this.appliedLimit = limit } return true } const promise = result.then( () => { if (generation === this.generation && this.desired() === limit) { this.appliedLimit = limit } if (this.pending?.generation === generation) this.pending = undefined }, (error) => { if (this.pending?.generation === generation) this.pending = undefined throw error }, ) this.pending = { generation, limit, promise } return promise } } class ControllerModel { constructor(coordinator) { this.coordinator = coordinator this.lease = Symbol("controller") this.leaseActive = false this.subscriptions = 0 this.committedPageCount = 1 this.windowGeneration = 0 } activateLease(pageCount) { this.leaseActive = true return this.coordinator.request(this.lease, pageCount === 2 ? 5 : 3) } deactivateLease() { if (!this.leaseActive) return this.leaseActive = false this.coordinator.release(this.lease) } requestPageCount(requestedPageCount) { const generation = ++this.windowGeneration const temporaryLease = !this.leaseActive && this.subscriptions === 0 const result = this.activateLease(requestedPageCount) if (result === true) { if (generation === this.windowGeneration) { this.committedPageCount = requestedPageCount } if (temporaryLease) this.deactivateLease() return Promise.resolve() } return result.then( () => { if (generation !== this.windowGeneration) return this.committedPageCount = requestedPageCount }, (error) => { throw error }, ).finally(() => { if (temporaryLease && this.subscriptions === 0) { this.deactivateLease() } }) } } const deferred = [] const calls = [] const setWindow = (limit) => { calls.push(limit) let resolve const promise = new Promise((r) => { resolve = r }) deferred.push(resolve) return promise } const coordinator = new WindowCoordinator(setWindow) const controller = new ControllerModel(coordinator) // A: fetchNextPage, with no subscribers, requests the larger window. const expansion = controller.requestPageCount(2) // B: reset overlaps A and reuses the active lease, but does not become a temporary holder. const reset = controller.requestPageCount(1) console.log(JSON.stringify({ afterStart: { setWindowCalls: calls, leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) // Settle A first. Its finally() releases the shared lease while B is pending. deferred[0]() await expansion console.log(JSON.stringify({ afterExpansion: { leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) // Settle B. B commits page count even though its lease was released by A. deferred[1]() await reset console.log(JSON.stringify({ final: { setWindowCalls: calls, leaseCount: coordinator.leases.size, appliedLimit: coordinator.appliedLimit, committedPageCount: controller.committedPageCount, }, })) JSRepository: TanStack/db
Length of output: 376
🏁 Script executed:
#!/bin/bash set -euo pipefail node - <<'JS' class WindowCoordinator { constructor(setWindow) { this.setWindow = setWindow this.leases = new Map() this.appliedLimit = undefined this.pending = undefined this.generation = 0 } request(lease, limit) { this.leases.set(lease, limit) return this.applyDesiredWindow() } release(lease) { if (!this.leases.delete(lease)) return this.generation++ this.pending = undefined if (this.leases.size === 0) { this.appliedLimit = undefined return } try { const result = this.applyDesiredWindow() if (result !== true) void result.catch(() => { this.appliedLimit = undefined }) } catch { this.appliedLimit = undefined } } desired() { return this.leases.size ? Math.max(...this.leases.values()) : undefined } applyDesiredWindow() { const limit = this.desired() if (limit === undefined) return true if (this.pending?.limit === limit) return this.pending.promise if (this.pending) { this.generation++ this.pending = undefined this.appliedLimit = undefined } if (limit === this.appliedLimit) return true const generation = ++this.generation const result = this.setWindow(limit) if (result === true) { if (generation === this.generation && this.desired() === limit) { this.appliedLimit = limit } return true } const promise = result.then( () => { if (generation === this.generation && this.desired() === limit) { this.appliedLimit = limit } if (this.pending?.generation === generation) this.pending = undefined }, (error) => { if (this.pending?.generation === generation) this.pending = undefined throw error }, ) this.pending = { generation, limit, promise } return promise } } class ControllerModel { constructor(coordinator) { this.coordinator = coordinator this.lease = Symbol("controller") this.leaseActive = false this.subscriptions = 0 this.committedPageCount = 1 this.windowGeneration = 0 } activateLease(pageCount) { this.leaseActive = true return this.coordinator.request(this.lease, pageCount === 2 ? 5 : 3) } deactivateLease() { if (!this.leaseActive) return this.leaseActive = false this.coordinator.release(this.lease) } requestPageCount(requestedPageCount) { const generation = ++this.windowGeneration const temporaryLease = !this.leaseActive && this.subscriptions === 0 const result = this.activateLease(requestedPageCount) if (result === true) { if (generation === this.windowGeneration) { this.committedPageCount = requestedPageCount } if (temporaryLease) this.deactivateLease() return Promise.resolve() } return result.then( () => { if (generation !== this.windowGeneration) return this.committedPageCount = requestedPageCount }, (error) => { throw error }, ).finally(() => { if (temporaryLease && this.subscriptions === 0) { this.deactivateLease() } }) } } const deferred = [] const calls = [] const setWindow = (limit) => { calls.push(limit) let resolve const promise = new Promise((r) => { resolve = r }) deferred.push(resolve) return promise } const coordinator = new WindowCoordinator(setWindow) const controller = new ControllerModel(coordinator) const expansion = controller.requestPageCount(2) const reset = controller.requestPageCount(1) console.log(JSON.stringify({ afterStart: { setWindowCalls: calls, leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) deferred[0]() await expansion console.log(JSON.stringify({ afterExpansion: { leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) deferred[1]() await reset console.log(JSON.stringify({ final: { setWindowCalls: calls, leaseCount: coordinator.leases.size, appliedLimit: coordinator.appliedLimit, committedPageCount: controller.committedPageCount, }, })) JSRepository: TanStack/db
Length of output: 376
🏁 Script executed:
#!/bin/bash set -euo pipefail node - <<'JS' class Coordinator { constructor(setWindow) { this.setWindow = setWindow this.leases = new Map() this.pending = undefined this.appliedLimit = undefined this.generation = 0 } request(lease, limit) { this.leases.set(lease, limit) return this.apply() } release(lease) { if (!this.leases.delete(lease)) return this.generation++ this.pending = undefined if (this.leases.size === 0) { this.appliedLimit = undefined return } this.apply() } apply() { const limit = this.leases.size ? Math.max(...this.leases.values()) : undefined if (limit === undefined) return true if (this.pending?.limit === limit) return this.pending.promise if (this.pending) { this.generation++ this.pending = undefined this.appliedLimit = undefined } if (limit === this.appliedLimit) return true const generation = ++this.generation const result = this.setWindow(limit) const promise = result.then(() => { if ( generation === this.generation && this.leases.size > 0 && Math.max(...this.leases.values()) === limit ) { this.appliedLimit = limit } if (this.pending?.generation === generation) this.pending = undefined }) this.pending = { generation, limit, promise } return promise } } class Controller { constructor(coordinator) { this.coordinator = coordinator this.lease = Symbol() this.leaseActive = false this.subscriptions = 0 this.windowGeneration = 0 this.committedPageCount = 2 } request(pageCount) { const generation = ++this.windowGeneration const temporaryLease = !this.leaseActive && this.subscriptions === 0 this.leaseActive = true const result = this.coordinator.request( this.lease, pageCount * 2 + 1, ) return result.then(() => { if (generation === this.windowGeneration) { this.committedPageCount = pageCount } }).finally(() => { if (temporaryLease && this.subscriptions === 0) { this.leaseActive = false this.coordinator.release(this.lease) } }) } } const resolves = [] const requestedLimits = [] const setWindow = (limit) => { requestedLimits.push(limit) return new Promise((resolve) => resolves.push(resolve)) } const coordinator = new Coordinator(setWindow) const controller = new Controller(coordinator) // A: reset from two committed pages. It takes a temporary lease. const reset = controller.request(1) // B: fetchNextPage starts before A settles. It sees leaseActive=true, // so it does not take a temporary lease of its own. const expansion = controller.request(3) resolves[0]() await reset console.log(JSON.stringify({ afterA: { requestedLimits, leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) resolves[1]() await expansion console.log(JSON.stringify({ afterB: { requestedLimits, leaseCount: coordinator.leases.size, appliedLimit: coordinator.appliedLimit, committedPageCount: controller.committedPageCount, }, })) JSRepository: TanStack/db
Length of output: 299
🏁 Script executed:
#!/bin/bash set -euo pipefail node - <<'JS' class Coordinator { constructor(setWindow) { this.setWindow = setWindow this.leases = new Map() this.pending = undefined this.appliedLimit = undefined this.generation = 0 } request(lease, limit) { this.leases.set(lease, limit) return this.apply() } release(lease) { if (!this.leases.delete(lease)) return this.generation++ this.pending = undefined if (this.leases.size === 0) { this.appliedLimit = undefined return } this.apply() } apply() { const limit = this.leases.size ? Math.max(...this.leases.values()) : undefined if (limit === undefined) return true if (this.pending?.limit === limit) return this.pending.promise if (this.pending) { this.generation++ this.pending = undefined this.appliedLimit = undefined } if (limit === this.appliedLimit) return true const generation = ++this.generation const result = this.setWindow(limit) const promise = result.then(() => { if ( generation === this.generation && this.leases.size > 0 && Math.max(...this.leases.values()) === limit ) { this.appliedLimit = limit } if (this.pending?.generation === generation) this.pending = undefined }) this.pending = { generation, limit, promise } return promise } } class Controller { constructor(coordinator) { this.coordinator = coordinator this.lease = Symbol() this.leaseActive = false this.subscriptions = 0 this.windowGeneration = 0 this.committedPageCount = 2 } request(pageCount) { const generation = ++this.windowGeneration const temporaryLease = !this.leaseActive && this.subscriptions === 0 this.leaseActive = true const result = this.coordinator.request( this.lease, pageCount * 2 + 1, ) return result.then(() => { if (generation === this.windowGeneration) { this.committedPageCount = pageCount } }).finally(() => { if (temporaryLease && this.subscriptions === 0) { this.leaseActive = false this.coordinator.release(this.lease) } }) } } const resolves = [] const requestedLimits = [] const setWindow = (limit) => { requestedLimits.push(limit) return new Promise((resolve) => resolves.push(resolve)) } const coordinator = new Coordinator(setWindow) const controller = new Controller(coordinator) const reset = controller.request(1) const expansion = controller.request(3) resolves[0]() await reset console.log(JSON.stringify({ afterA: { requestedLimits, leaseCount: coordinator.leases.size, pendingLimit: coordinator.pending?.limit, committedPageCount: controller.committedPageCount, }, })) resolves[1]() await expansion console.log(JSON.stringify({ afterB: { requestedLimits, leaseCount: coordinator.leases.size, appliedLimit: coordinator.appliedLimit, committedPageCount: controller.committedPageCount, }, })) JSRepository: TanStack/db
Length of output: 299
Track overlapping temporary leases independently.
When overlapping unsubscribed requests run, the first request can release the shared lease while the second request is still pending. The second request can then commit
committedPageCountwithout a coordinator lease. Replace the per-calltemporaryLeaseboolean with an in-flight holder count, and release the lease only when the count reaches zero. Add a regression test for overlappingreset()andfetchNextPage()calls.🤖 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-window-controller.ts` around lines 503 - 512, The temporary lease is tracked per call, allowing overlapping reset/fetch requests to release the shared lease prematurely. In the request flow around releaseTemporaryLease, replace the boolean with an in-flight temporary-lease holder count, increment when a request acquires the lease, decrement in finally, and deactivate only when the count reaches zero and there are no subscriptions. Add a regression test covering overlapping reset() and fetchNextPage() calls.✅ Addressed in commit d704b95
@@ -275,6 +275,14 @@275275 throw new SetWindowRequiresOrderByError()276276 }277277278- this.currentWindow = options279- this.windowFn(options)280- this.maybeRunGraphFn?.()278+ const previousWindow = this.currentWindow279+ try {280+ this.windowFn(options)281+ this.maybeRunGraphFn?.()282+ this.currentWindow = options283+ } catch (error) {284+ if (previousWindow) {285+ this.windowFn(previousWindow)286+ }287+ throw error288+ }🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Description: Find the window operator contract to determine the correct "no window" reset value. set -euo pipefail rg -n -C 6 'WindowOptions' --type=ts packages/db/src | head -80 ast-grep run --pattern 'setWindowFn($$$)' --lang typescript packages/db/src || true rg -n -C 8 'windowFn' --type=ts packages/db/srcRepository: TanStack/db
Length of output: 32124
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- WindowOptions and related types ---' rg -n -C 12 'export (type|interface) WindowOptions|type WindowOptions|interface WindowOptions' packages/db/src packages -g '*.ts' -g '*.tsx' | head -160 printf '%s\n' '--- order-by operator construction and window callbacks ---' sed -n '300,390p' packages/db/src/query/compiler/order-by.ts printf '%s\n' '--- currentWindow and setWindow call sites ---' rg -n -C 10 'currentWindow|setWindow\(' packages/db/src packages/db-ivm -g '*.ts' -g '*.tsx' 2>/dev/null | head -240 printf '%s\n' '--- repository files containing top-K/window implementations ---' git ls-files | rg -i 'top.?k|window|order.?by|ivm' | head -200Repository: TanStack/db
Length of output: 21753
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- top-K window mutation implementations ---' for f in packages/db-ivm/src/operators/topKWithFractionalIndex.ts \ packages/db-ivm/src/operators/topKWithFractionalIndexBTree.ts \ packages/db-ivm/src/operators/groupedTopKWithFractionalIndex.ts \ packages/db-ivm/src/operators/topK.ts \ packages/db-ivm/src/operators/topKState.ts; do if [ -f "$f" ]; then echo "### $f" ast-grep outline "$f" rg -n -C 12 'setWindow|window|limit|offset' "$f" fi done printf '%s\n' '--- graph execution and error propagation ---' rg -n -C 15 'maybeRunGraphFn|graph\.run\(|run\(\)' packages/db/src/query/live/collection-config-builder.ts packages/db-ivm/src/graph.tsRepository: TanStack/db
Length of output: 40100
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- setWindow scheduling semantics ---' sed -n '330,460p' packages/db/src/query/live/collection-config-builder.ts sed -n '620,665p' packages/db/src/query/live/collection-config-builder.ts printf '%s\n' '--- TopKArray window mutation semantics ---' ast-grep outline packages/db-ivm/src/operators/topKArray.ts rg -n -C 18 'move\(|constructor|`#offset`|`#limit`' packages/db-ivm/src/operators/topKArray.ts printf '%s\n' '--- grouped window mutation semantics ---' sed -n '90,135p' packages/db-ivm/src/operators/groupedTopKWithFractionalIndex.ts printf '%s\n' '--- tests for setWindow failure and window state ---' rg -n -C 12 'setWindow|getWindow|window.*throw|throw.*window|rollback|moveTopK' packages/db/tests packages/db-ivm/tests -g '*.ts' | head -300Repository: TanStack/db
Length of output: 38224
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- complete scheduleGraphRun implementation ---' sed -n '430,570p' packages/db/src/query/live/collection-config-builder.ts printf '%s\n' '--- complete TopKArray.move implementation ---' sed -n '95,190p' packages/db-ivm/src/operators/topKArray.ts printf '%s\n' '--- direct window callback behavior in tests ---' sed -n '488,562p' packages/db-ivm/tests/operators/orderByWithFractionalIndex.test.ts sed -n '562,650p' packages/db-ivm/tests/operators/orderByWithFractionalIndex.test.tsRepository: TanStack/db
Length of output: 14319
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- scheduler execution for immediate schedules ---' rg -n -C 18 'class .*Scheduler|schedule\(|transactionScopedScheduler|executeGraphRun' packages/db/src -g '*.ts' | head -320 printf '%s\n' '--- range validation and window error paths ---' rg -n -C 18 'function diffHalfOpen|diffHalfOpen|throw new Error' packages/db-ivm/src/operators/topKArray.ts packages/db-ivm/src -g '*.ts' | head -260 printf '%s\n' '--- live-query window tests around error/session behavior ---' rg -n -C 18 'setWindow|scheduleGraphRun|active sync|sync session|unsubscribe' packages/db/tests/live-query-window-controller.test.ts packages/db/tests/query/order-by.test.ts -g '*.ts' | head -360Repository: TanStack/db
Length of output: 50367
🏁 Script executed:
#!/bin/bash set -euo pipefail printf '%s\n' '--- executeGraphRun and immediate graph failure handling ---' sed -n '545,625p' packages/db/src/query/live/collection-config-builder.ts printf '%s\n' '--- scheduler flush failure propagation ---' sed -n '100,205p' packages/db/src/scheduler.ts printf '%s\n' '--- output operator and pending-message behavior ---' sed -n '1,180p' packages/db-ivm/src/operators/output.ts sed -n '1,125p' packages/db-ivm/src/graph.tsRepository: TanStack/db
Length of output: 10395
Make
setWindowrollback complete and exception-safe. WhenmaybeRunGraphFnruns without a transaction context, it executes the graph synchronously. If that graph run throws afterwindowFn(options)mutates the operator, the catch block restores the operator but does not rerun the graph. The collection can retain partial results from the failed window. On the first call, no rollback occurs becausepreviousWindowis undefined. Restore the actual initial operator window, rerun the graph after rollback, and preserve the original error if recovery fails.🤖 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/query/live/collection-config-builder.ts` around lines 278 - 288, The setWindow rollback in the currentWindow update flow must restore the actual initial operator window, including when previousWindow is undefined, then rerun maybeRunGraphFn after restoration to remove partial results. Make recovery exception-safe by preserving and rethrowing the original error even if windowFn or graph rerun fails during rollback.✅ Addressed in commit d704b95
@@ -697,0 +872,21 @@872+ query: (q) =>873+ q.from({ post: sourceB }).orderBy(({ post }) => post.createdAt, `desc`),874+ })875+ const { result, rerender } = renderHook(876+ ({ query }) => useLiveInfiniteQuery(query, { pageSize: 2 }),877+ { initialProps: { query: queryA } },878+ )879+880+ await waitFor(() => expect(result.current.isReady).toBe(true))881+ const fetchFromA = result.current.fetchNextPage882+883+ rerender({ query: queryB })884+ await waitFor(() => {885+ expect(result.current.collection).toBe(queryB)886+ expect(result.current.isReady).toBe(true)887+ expect(result.current.pages).toHaveLength(1)888+ })889+890+ act(() => fetchFromA())891+892+ expect(result.current.pages).toHaveLength(1)🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Strengthen the stale-callback assertion.
fetchNextPageruns asynchronously; the hook wrapper callsvoid controller.fetchNextPage(). The assertion on Line 892 runs in the same tick as theactcall, sopagesstill has length 1 even iffetchFromAreached the new controller forqueryB. The test therefore passes with a broken binding and does not reproduce the regression it targets.Wait for the pending work to settle, then assert that the page count is unchanged. Also assert the page count for the current controller after an explicit
result.current.fetchNextPage()call, to prove the new callback still works.As per coding guidelines: "Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression".
💚 Proposed change
act(() => fetchFromA()) - - expect(result.current.pages).toHaveLength(1) + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + expect(result.current.pages).toHaveLength(1) + + // The current callback must still paginate the active controller. + act(() => result.current.fetchNextPage()) + await waitFor(() => expect(result.current.pages).toHaveLength(2)) })📝 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.
act(() => fetchFromA()) await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)) }) expect(result.current.pages).toHaveLength(1) // The current callback must still paginate the active controller. act(() => result.current.fetchNextPage()) await waitFor(() => expect(result.current.pages).toHaveLength(2))🤖 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/tests/useLiveInfiniteQuery.test.tsx` around lines 890 - 892, Strengthen the stale-callback test around fetchFromA by awaiting the asynchronous work to settle before asserting the page count remains unchanged. Then call result.current.fetchNextPage() explicitly, await its completion, and assert the current controller’s page count increases as expected, proving both stale-callback isolation and the new callback binding.Source: Coding guidelines
✅ Addressed in commit d704b95
@KyleAMathews All eight reproduced blockers are fixed, the follow-up review pass is clean, and every check is green. Please re-review and merge when ready: https://github.com/TanStack/db/pull/1675
I rechecked the follow-up changes on current head
d704b954. The earlier window-controller blockers are fixed, but two additional correctness issues still reproduce.1.
useLiveInfiniteQueryreuses the wrong controller after an input-kind round trip#needsNewCollectionchecksconfigRefonly on the collection path anddepsRefonly on the query-function path:const needsNewCollection = !collectionRef.current || (isCollection && configRef.current !== queryFnOrCollection) || dependenciesChangedThose refs retain values from the last visit to their respective path. This makes the first kind switch work, but switching back to the same prior input makes
needsNewCollectionfalse and leaves the hook bound to the intervening collection.Collection -> query function -> same collection#
const { result, rerender } = renderHook( ({ useCollection }) => useLiveInfiniteQuery( useCollection ? collectionInput : queryInput, { pageSize: 3 }, ...(useCollection ? [] : [[]]), ), { initialProps: { useCollection: true } }, ) await waitFor(() => expect(result.current.data[0].id).toBe(`1`)) rerender({ useCollection: false }) await waitFor(() => expect(result.current.data[0].id).toBe(`query-1`)) rerender({ useCollection: true }) await waitFor(() => expect(result.current.data[0].id).toBe(`1`))The final assertion fails: the hook still returns
query-1.The inverse round trip also fails:
// query function -> collection -> same query function expect(result.current.data[0].id).toBe(`1`) rerender({ useCollection: true }) await waitFor(() => expect(result.current.data[0].id).toBe(`collection-1`)) rerender({ useCollection: false }) await waitFor(() => expect(result.current.data[0].id).toBe(`1`))The final value remains
collection-1.Please track the active input kind as part of collection identity. For example, include
inputKindRef.current !== isCollectioninneedsNewCollection, update that ref whenever a new collection is accepted, and clear or overwrite the inactive branch's identity state. Add regressions for both round-trip directions; a one-way switch does not expose this bug.2. Order-only moves escape through the public change API as an empty batch#
CollectionChangesManager.emitEvents()now allowsrawEvents.length === 0whenlayoutChangedis true, then calls every publicsubscribeChangescallback with[]. That reuses the existing empty-batch/ready sentinel as a new layout signal. A public consumer that treats a post-ready callback as containing at least oneChangeMessagecan now misfire or crash.This focused reproduction fails on the current head:
const source = makeSource([ { id: `1`, name: `Alice`, age: 30 }, { id: `2`, name: `Bob`, age: 20 }, { id: `3`, name: `Carol`, age: 40 }, ]) const lq = createLiveQueryCollection((q) => q .from({ p: source }) .orderBy(({ p }) => p.age, `asc`) .select(({ p }) => ({ id: p.id, name: p.name })), ) await lq.preload() const publications: Array<Array<unknown>> = [] const subscription = lq.subscribeChanges( (changes) => publications.push(changes), { includeInitialState: false }, ) source.utils.begin() source.utils.write({ type: `update`, value: { id: `2`, name: `Bob`, age: 99 }, }) source.utils.commit() expect([...lq.values()].map((row) => row.id)).toEqual([`1`, `3`, `2`]) expect(publications).toEqual([])Actual
publicationsis[[]]. The same behavior is encoded in the currentpublishes a mixed batch to a subscriber that filters out the row updatetest, which expects[[]].The observer does need an explicit layout-only notification so wholesale consumers can re-read the ordered snapshot. Please carry that through a separate internal layout event/channel rather than overloading
ChangeMessage[]. PublicsubscribeChangesshould remain a stream of actual changes (apart from its documented bootstrap/ready behavior), whileLiveQueryObservercan subscribe to both value changes and layout changes.Verification on
d704b954:- both input-kind round-trip tests fail, with no type errors;
- the layout-only public-subscription test fails with
expected [ [] ] to deeply equal [].
🧹 Nitpick comments (2)
packages/db/src/live-query-observer.ts (1)
412-422: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove
anyfrom the layout subscription cast.Line 413 introduces
Collection<T, TKey, any>. Use the default utility type instead.Proposed fix
- collection as Collection<T, TKey, any> & { + collection as Collection<T, TKey> & {As per coding guidelines,
**/*.{ts,tsx}: “Avoid usinganytypes; useunknowninstead when 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/src/live-query-observer.ts` around lines 412 - 422, Update the layout subscription cast in subscribeLayoutChanges to use the Collection default utility type instead of any, preserving the optional _subscribeLayoutChanges signature and existing subscription behavior.Source: Coding guidelines
packages/db/tests/live-query-order-only-move.test.ts (1)
405-408: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the repeated observer setup.
Lines 405-408 and 484-487 duplicate the observer creation, notification counter, subscription, and initial-notification reset. Extract a small test helper that accepts the collection and returns the observer with notification access. This keeps both tests consistent.
As per coding guidelines,
**/*.{ts,tsx,js}says: “Extract common logic into utility functions when identical or near-identical code blocks appear in multiple places.”Also applies to: 484-487
🤖 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-order-only-move.test.ts` around lines 405 - 408, Extract the duplicated observer setup from the tests around createLiveQueryObserver into a small helper that accepts a collection, subscribes to the observer, resets the initial notification count, and returns the observer plus notification access. Replace both setup blocks at the referenced test locations with this helper while preserving each test’s existing behavior.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/src/live-query-observer.ts`: - Around line 412-422: Update the layout subscription cast in subscribeLayoutChanges to use the Collection default utility type instead of any, preserving the optional _subscribeLayoutChanges signature and existing subscription behavior. In `@packages/db/tests/live-query-order-only-move.test.ts`: - Around line 405-408: Extract the duplicated observer setup from the tests around createLiveQueryObserver into a small helper that accepts a collection, subscribes to the observer, resets the initial notification count, and returns the observer plus notification access. Replace both setup blocks at the referenced test locations with this helper while preserving each test’s existing behavior.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
59cf5c99-59f6-4872-8472-24339ece7ed7📥 Commits
Reviewing files that changed from the base of the PR and between d704b954d79ad3daa6bccd15b741cdd40d6be94d and ed51adbf6516b47de7f2c70d2b5c214306218bd0.
📒 Files selected for processing (7)
packages/db/src/collection/changes.tspackages/db/src/collection/index.tspackages/db/src/collection/subscription.tspackages/db/src/live-query-observer.tspackages/db/tests/live-query-order-only-move.test.tspackages/react-db/src/useLiveInfiniteQuery.tspackages/react-db/tests/useLiveInfiniteQuery.test.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/react-db/tests/useLiveInfiniteQuery.test.tsx
- packages/react-db/src/useLiveInfiniteQuery.ts
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/tests/useLiveInfiniteQuery.test.tsx`: - Around line 931-933: Strengthen the failed-window-update test around fetchNextPage by capturing the loaded page’s row IDs before invoking fetchNextPage, then asserting the post-failure page IDs match the captured IDs in the same order. Keep the existing pages-length and hasNextPage assertions, but replace the length-only preservation check with content comparison.🪄 Autofix
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 Plus
Run ID:
ecfb244f-17c1-443a-b543-877c04c5479e📥 Commits
Reviewing files that changed from the base of the PR and between ed51adbf6516b47de7f2c70d2b5c214306218bd0 and e7309803a7c9e0ef0760d4034741ce720c57467d.
📒 Files selected for processing (2)
packages/react-db/src/useLiveInfiniteQuery.tspackages/react-db/tests/useLiveInfiniteQuery.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/react-db/src/useLiveInfiniteQuery.ts
packages/react-db/tests/useLiveInfiniteQuery.test.tsx lines 991 to 993@@ -697,0 +913,21 @@913+ useLiveInfiniteQuery(query, { pageSize: 2 }),914+ )915+916+ await waitFor(() => {917+ expect(result.current.isReady).toBe(true)918+ expect(result.current.hasNextPage).toBe(true)919+ })920+921+ const failure = new Error(`window load failed`)922+ vi.spyOn(query.utils, `setWindow`).mockRejectedValueOnce(failure)923+924+ act(() => result.current.fetchNextPage())925+926+ await waitFor(() => {927+ expect(result.current.isError).toBe(true)928+ expect(result.current.error).toBe(failure)929+ expect(result.current.isFetchingNextPage).toBe(false)930+ })931+ expect(result.current.pages).toHaveLength(1)932+ expect(result.current.hasNextPage).toBe(true)933+ })🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Assert the loaded page contents, not only its length.
The test claims that a failed window update preserves the loaded page.
toHaveLength(1)also passes if the page becomes empty or contains different rows. Capture the page IDs beforefetchNextPage()and compare them after the failure, including their order.💚 Proposed test strengthening
await waitFor(() => { expect(result.current.isReady).toBe(true) expect(result.current.hasNextPage).toBe(true) }) + const pageIdsBefore = result.current.pages.map((page) => + page.map((post) => post.id), + ) const failure = new Error(`window load failed`) ... expect(result.current.pages).toHaveLength(1) + expect( + result.current.pages.map((page) => page.map((post) => post.id)), + ).toEqual(pageIdsBefore) expect(result.current.hasNextPage).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/react-db/tests/useLiveInfiniteQuery.test.tsx` around lines 931 - 933, Strengthen the failed-window-update test around fetchNextPage by capturing the loaded page’s row IDs before invoking fetchNextPage, then asserting the post-failure page IDs match the captured IDs in the same order. Keep the existing pages-length and hasNextPage assertions, but replace the length-only preservation check with content comparison.KyleAMathews(GitHub profile, opens in a new tab) 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#
The change adds a shared live-query window controller for pagination, leases, snapshots, retries, and lifecycle handling.
useLiveInfiniteQuerynow consumes controller snapshots throughuseSyncExternalStore. Collection windows become transactional, and layout-only publications use a separate notification path.Changes#
Live query pagination
packages/db/src/live-query-window-controller.ts,packages/db/src/errors.ts,packages/db/src/index.tspackages/db/src/live-query-window-controller.ts,packages/db/src/query/live/collection-config-builder.tspackages/react-db/src/useLiveInfiniteQuery.tsuseSyncExternalStore, and handles collection, dependency, and pagination changes.packages/db/src/collection/changes.ts,packages/db/src/collection/index.ts,packages/db/src/collection/subscription.ts,packages/db/src/live-query-observer.tspackages/db/tests/live-query-window-controller.test.ts,packages/react-db/tests/useLiveInfiniteQuery.test.tsx,packages/db/tests/live-query-order-only-move.test.ts.changeset/live-query-window-controller.mdEstimated code review effort: 4 (Complex) | ~60 minutes
Possibly related issues
Possibly related PRs
Suggested reviewers:
kyleamathewsSequence Diagram(s)#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
🧪 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