perf: systematic live query engine optimizations (31 profile-guided iterations) #1645
main fromperf-rindle-improvements·opened Summary#
Systematic performance work on the live query engine, driven by samwillis/rindle-db-bench: 48 profile-guided optimizations across @tanstack/db and @tanstack/db-ivm. Versus the released baseline on that benchmark's own harness: 1.7× geomean faster hydration (individual queries up to 3×), incremental update pairs 2–30× faster (nested includes went from 9.6ms to ~0.1ms per change), and mutation bursts changed from quadratic to flat (3.8ms → 0.1ms per insert+delete pair at burst end). No public API changes; every commit passed the full db/db-ivm suites plus the react-db, offline-transactions, and query-db-collection suites.
Reviewer guidance#
The work clusters into nine themes. Each one names the files to look at.
1. Lightweight child stores for includes (collection-config-builder.ts)#
Root cause: every parent row in a toArray(subquery)/materialize() include created a full Collection instance for its children — 60k collections for a 10k-issue nested query — paying constructor, state-manager, commit and event machinery per parent.
Approach: inline materializations (array/singleton/concat) never expose the child collection to users — only their materialized value is visible — so createChildCollectionEntry now builds a LightweightChildCollection (a Map plus the exact surface the flush machinery touches: toArray with cached sort, get/has/getKeyFromItem, a no-op _changes facade). Only the collection materialization, which hands the instance to users, still creates a real Collection.
Key invariant: both entry-creation sites branch on the same state.materialization value that materializeIncludedValue uses to decide whether to return entry.collection itself — so a lightweight store can never escape to user code. Child rows are exclusively-owned pipeline outputs, so add-if-missing virtual props are applied in place rather than via copies.
2. Dirty-key tracking for nested includes flushes (collection-config-builder.ts)#
Root cause: flushIncludesState's deep pass iterated the entire child registry (and hasPendingIncludesChanges recursed through every entry's subtree on every graph flush), so a single comment insert on a nested query paid O(all children).
Approach: correlation keys with pending per-entry changes are recorded where they're written (deepDirtyKeys), propagated up an owner backpointer chain, and derived from raw buffered rows via the routing index (collectBufferImplicatedKeys). Flush cost is now proportional to pending work. This alone took the nested incremental from 3.2ms to 0.22ms.
Key invariant: every write site of per-entry pendingChildChanges (drain, snapshot seeding) records the owning key; unroutable buffered rows contribute nothing because they cannot be flushed anywhere until a route exists — and routes are only created during a flush of the exact entry involved.
3. Synchronous transaction completion (transactions.ts, local-only.ts, mutations.ts, state.ts)#
Root cause: Transaction.commit() was async and awaited the mutationFn unconditionally, so even fully synchronous handlers (local-only collections) deferred completed to a microtask. During a synchronous burst of mutations nothing ever terminalized: state.transactions and pendingSyncedTransactions grew by two per operation and every mutation iterated them — quadratic in burst length.
Approach: commit() calls the mutationFn and completes synchronously when the result is not a thenable (async handlers behave exactly as before); the local-only wrappers and direct-op mutationFns are no longer needlessly async. recomputeOptimisticState migrates each terminal transaction exactly once (WeakSet guard) and commitPendingTransactions prunes consumed completed transactions eagerly. A nothing-to-do early exit skips the optimistic rebuild entirely in the post-mutation steady state.
Trade-off: one ordering hazard was found and avoided — registering the direct-op transaction before commit() changed includes event ordering (18 test failures) and was reverted; the original registration order plus synchronous completion passes everything.
4. Validated key-field fast path (state.ts, index-optimization.ts, collection/index.ts, lazy-load taps)#
Root cause: eq(row.id, x) / inArray(row.id, keys) on the field backing getKey required an explicit index or fell back to a full scan with per-row deep-equality — including every lazy join load keyed on a primary key (the detail view scanned all 10k issues per hydrate).
Approach: getKey is probed once with a recording proxy; if it's a single-property pass-through, the invariant row[keyField] === key is verified O(1) on every visible-row write, and the first violation permanently disables the path. eq/in on that field become direct key lookups, marked inexact so the (≤ list length) candidates are re-checked against the predicate. Lazy join loads additionally skip keys already delivered to the subscription (hasSentKey) when the join field is the key field.
Key invariant: correctness never depends on the probe alone. A lookup miss is authoritative only because the per-write invariant guarantees any row with row[keyField] === v is stored under key v; the inexact flag forces re-checking for coercion edge cases.
5. Steady-state commit fast lanes (state.ts, changes.ts, sync.ts)#
Root cause: every graph tick commits into the live result collection through the fully general commitPendingTransactions — visible-state snapshots, virtual-props snapshot allocations per key, redundancy detection against completed optimistic ops, and an optimistic overlay rebuild — all no-ops for a collection that never has user transactions.
Approach: with no transactions, no optimistic state and no truncate, a fast lane applies operations and derives one event per key from first-previous vs final value; a further ultra path handles the dominant single-operation commit without any batch tracking structures (including its row-metadata bookkeeping — the original guard excluded it by accident and never fired). Rows already carrying all four virtual props are returned as-is instead of being defensively copied; change-event enrichment is skipped entirely when a collection has no subscribers.
6. groupBy/reduce without structural hashing (db-ivm: groupBy.ts, reduce.ts, indexes.ts, utils.ts; db: compiler/group-by.ts)#
Root cause: the reduce operator's input Index consolidated equal rows by murmur-hashing every row's values object, and group keys were JSON-serialized through a replacer per row.
Approach: groupBy emits [discriminant, values] tuples where the discriminant is an injective string encoding of the primitive pre-aggregate values; the new prefixIdentity Index option lets equal prefixes merge without hash comparison (within one reduce key the group-key content is constant, so the discriminant fully determines equality — arguably stronger than the 32-bit digest it replaces). Non-primitive aggregates (avg/median/mode) fall back to the hash path unchanged. Also: trackConsolidated: false skips join-presence bookkeeping reduce never reads, a 0/1-output fast path avoids two diff Maps per group, serializeValue gets a flat-primitive fast path with byte-identical output, single-clause primitive group keys use tagged concatenation, the two virtual-metadata aggregates merged into one bitmask, and result rows are built minimally instead of spreading the aggregated row.
Verification: property-based tests (groupBy.test.ts) drive random insert/retract sequences across ticks — retractions as fresh structurally-equal objects — and assert equivalence with a from-scratch recompute; a lossy-discriminant mutation fails the property on the first generated case.
7. Dataflow engine mechanics (db-ivm: join.ts, indexes.ts, multiset.ts, graph.ts, d2.ts)#
- Join re-key fusion:
JoinKeyExtractors+Index.fromMultiSetsBylet the operator derive join keys itself, removing a map operator per side that wrapped every row in[joinKey, [key, row]]; the lazy-load tap uses the same extractor. - Exclusive in-place transforms: an edge with exactly one reader marks delivered multisets exclusive, so
map/filterreuse the inner array and tuples in place. Producers never retain delivered instances or their tuples, and row values are never mutated; multi-reader edges stay copy-on-transform. - Join accumulator: the three delta terms append directly into the shared results multiset instead of building arrays that are immediately copied.
- Scheduler:
graph.runonly runs operators with pending input (idle operators paid empty-drain allocations per pass), and reader drain pops oldest-first instead of copy+reverse. - Linear operator fusion: at
finalize()— once the topology can no longer change — chains of map/filter/tap/negate whose intermediate edge has exactly one consumer collapse into a singleFusedLinearOperatorthat runs each message through all stage functions in order (side-effect order preserved; stage-created multisets marked exclusively-owned so in-place transforms keep working). The creator view's graph went from 21 to 14 operators; every eliminated hop was a queue push/drain plus a MultiSet delivery per message. Index.getbuilds result arrays directly instead of spreading a generator;Index.appendadopts whole buckets for previously-absent keys (deltas are ephemeral).- Keyed consolidation uses nested identity Maps instead of composite ID strings.
8. V8 hash-table churn resistance (SortedMap.ts, TombstoneMap.ts, basic-index.ts, btree-index.ts, state.ts)#
Root cause: V8's ordered hash tables degrade catastrophically under repeated delete + re-add of the same key on a large table: a microbenchmark shows ~18–22µs per delete+add cycle on a 50k-entry Map/Set versus ~0.06µs for distinct keys (each cycle appends to the internal data table and forces rehashes). Incremental row updates — the exact workload the benchmark's insert/delete pairs measure, and a common real-world churn pattern — hit this in four places: the per-index indexedKeys Sets, syncedData's backing Map, and the rowOrigins/syncedMetadata maps written by every fast-lane commit.
Approach, in three strikes:
- Index key Sets → counters. Production code only reads
keyCount, so both index classes track a numeric count (size-delta on add, delete-boolean on remove) and build the test-facingindexedKeysSetlazily fromvalueMap.BasicIndex.adddropped from 20.5µs/pair to noise. SortedMapdeferred-delete tombstones.delete()overwrites the value with aTOMBSTONEsentinel — an in-place value write that never mutates the hash table — and physical deletion is batched into a bounded compaction (>1024). The row object is still released for GC; only the key is retained.sortedKeysholds live keys only, so ordered reads are unchanged, and the monotonic-append/pop-if-tail fast paths survive a full insert→delete→insert probe cycle without ever dirtying the sort.TombstoneMapforrowOrigins/syncedMetadata. Same pattern as a minimal Map facade (get/set/delete/clear plus tombstone-filtered read surface). Fast-lane commit self-time fell from 24.7µs to 1.4µs per pair.
Relatedly, emptied per-value key sets in both index classes are kept as bounded tombstones so a remove-then-re-add of the same indexed value avoids BTree node churn / the sorted-array splice; all snapshot getters (orderedEntriesArray, valueMapData, …) filter empties so inspection APIs stay consistent with the read paths.
Combined effect: the detail-view sustained incremental probe went from ~124µs to ~45µs per insert+delete pair.
9. Ancillary hot-path fixes#
inon constant primitive arrays probes a precomputedSet;eqgets same-type primitive fast paths;normalizeValueshort-circuits primitives (comparison.ts,evaluators.ts)- Compiled expression evaluators cached by exact structural key (bounded, collision-free); indexes compile their expression once instead of per add/remove; index timestamps stored as epoch ms (
evaluators.ts,base-index.ts) SortedMap: lazy ordering (O(1) writes, rebuild-on-read) for comparator-backed maps, monotonic-append and pop-if-tail fast paths for key-ordered maps (SortedMap.ts)- Optimizer skips its iterative rewrite + full-tree
deepEqualsloop for single-source no-join queries, combining WHERE clauses directly (optimizer.ts) - Mutation IDs and transaction IDs use a session-UUID prefix + counter (allocation sampling showed UUID generation was ~19% of per-mutation allocation); schemaless inserts reuse the input as
changes; sync write operations built as literals instead of spreads (mutations.ts,sync.ts,transactions.ts) Transaction.isPersistedis created lazily on first access (most transactions are never awaited; late accessors get a deferred settled from the terminal state);applyMutationsshort-circuits the single-mutation case; update/delete mutation batches share one timestamp per call (transactions.ts,mutations.ts)commitPendingTransactionsskips the persisting-transaction scan when no transactions exist — the empty case is the steady state for sync-driven collections and still paid an ordered rebuild plus generator per call, twice per mutation per collection (state.ts)- TopK gets a bulk-load path for the initial hydrate snapshot: sort once and generate append-style fractional keys left-to-right instead of per-element binary search, between-neighbour key splits and O(n) splices; falls back for the B+-tree variant, retractions or duplicate keys — and the grouped variant (per-group ordered includes like "3 most recent comments per issue") buckets the snapshot per group and bulk-loads each, taking that view's creation from 1.8ms to 1.1ms (
db-ivm:topKArray.ts,topKState.ts,topKWithFractionalIndex.ts,groupedTopKWithFractionalIndex.ts) - Duplicate-insert filtering is fused with D2 input conversion into a single pass (
sendFilteredChangesToInput); ordered snapshots deliver through the raw callback (keys are pre-added tosentKeys, making the tracking wrapper pass redundant) and reuse values fetched during filtering instead of a secondcollection.getper row;flushIncludesStateallocates its per-flush Set/Map lazily (query/live/utils.ts,collection-subscriber.ts,subscription.ts,collection-config-builder.ts) - Ordered snapshots are delivered as D2 batches:
requestLimitedSnapshotoptionally hands raw[key, value]pairs to the ordered subscriber, which folds biggest-sent-value tracking, duplicate-key bookkeeping and multiset tuple construction into one pass feeding the D2 input directly — replacing a ChangeMessage allocation per row plus three downstream batch walks; unordered snapshots and live change delivery keep the existing path (subscription.ts,collection-subscriber.ts) - The dataflow
Indexcompares candidate values with an early-exit structuralfastEqualsinstead ofhash(a) === hash(b)(which walked both values fully even when the first field differed — the common case for updates through joins); exotic types still fall back to hash parity, anddeepEqualsallocates its cycle-detection map lazily so flat rows pay nothing (db-ivm:hashing/fastEquals.ts,indexes.ts;db:utils.ts) - Row-metadata bookkeeping is skipped for collections that never store any (all live query result collections): metadata-less inserts and deletes recorded a clear-metadata write per row — an object allocation, a Map entry and a
syncedMetadatatombstone per written row — guarding on ahasRowMetadataflag (set by the first real metadata write, withsyncedMetadata.sizecovering direct-set edge cases) removes it while keeping exact semantics for metadata-using collections like query-db-collection (sync.ts,state.ts)
Non-goals#
- No public API changes;
collection-materialized includes intentionally keep full Collection instances. - No change to optimistic/async transaction semantics — only synchronously-resolving mutationFns complete synchronously.
- Two deeper tracks were scoped out after measurement: compiler topology templates (a cross-shape warm-up experiment showed V8 shares optimized code across closure instances of the same source function, so per-creation closure reuse can't help — the hydrate ramp is shared-SFI JIT warm-up), and join
prefixIdentity(unsound: an update's retract+insert under the same row key would net to zero in the delta index and vanish; prefix merging requires content-injective prefixes, which only the groupBy discriminant provides).
Behavioral notes for reviewers#
- Join loads on a collection's key field now use key lookups instead of an index or full scan —
tests/query/indexes.test.tsandtests/collection-auto-index.test.tsexpectations were updated accordingly (mechanism assertions, not behavior). - The key-field probe adds one
getKeycall at collection construction (one spy-count test updated). - Deleted entries in
SortedMap/TombstoneMap/index value maps persist internally as bounded tombstones; all public read surfaces filter them, and deleted row objects are still released for GC (only keys are retained until compaction). tx.isPersistedis now a lazy getter. Accessing it after the transaction settled yields an immediately-settled deferred; failures no longer create a rejected promise nobody observes.tests/collection-events.test.tsis timing-sensitive under machine load and can flake in full-suite runs; it passes consistently in isolation.
Verification#
pnpm --filter @tanstack/db-ivm --filter @tanstack/db build
pnpm --filter @tanstack/db-ivm --filter @tanstack/db test
pnpm --filter @tanstack/react-db --filter @tanstack/offline-transactions --filter @tanstack/query-db-collection test
Benchmarks: clone rindle-db-bench, npm i @rindle/wasm into bench-tanstack, symlink packages/{db,db-ivm}/dist into its node_modules/@tanstack/*, then SCALE=large NODE_OPTIONS=--expose-gc tsx src/bench.ts. One methodology note: the harness takes min-of-4 hydrate rounds with a forced full GC between rounds; sub-millisecond rows are strongly sensitive to the (documented) ROUNDS env knob because JS pays a per-creation warm-up that wasm doesn't — e.g. the newest-50 view hydrates at ~1.2ms under defaults but floors at ~0.2ms given enough rounds, while Rindle's numbers are identical across regimes.
🤖 Generated with Claude Code
Summary by CodeRabbit#
- New Features
groupBynow supports optionalkeySerializer.join/reducegained optional key/prefix options, includingJoinKeyExtractors.- Added
validatedKeyFieldPathon collections andhasSentKey(key)on subscriptions.
- Bug Fixes
- Improved sync/live change derivation to suppress redundant events and handle update/delete merges more consistently.
- Performance
- Faster live query hydration/incremental updates, optimized
eq/inkey-field paths, cached expression evaluators, and lazySortedMapordering; index tombstone compaction.
- Faster live query hydration/incremental updates, optimized
- Tests
- Added property-based
groupBycoverage and synced-event “fast lane” assertions.
- Added property-based
- 1
More templates
@tanstack/angular-db
npm i https://pkg.pr.new/@tanstack/angular-db@1645@tanstack/browser-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/browser-db-sqlite-persistence@1645@tanstack/capacitor-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/capacitor-db-sqlite-persistence@1645@tanstack/cloudflare-durable-objects-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/cloudflare-durable-objects-db-sqlite-persistence@1645@tanstack/db
npm i https://pkg.pr.new/@tanstack/db@1645@tanstack/db-ivm
npm i https://pkg.pr.new/@tanstack/db-ivm@1645@tanstack/db-sqlite-persistence-core
npm i https://pkg.pr.new/@tanstack/db-sqlite-persistence-core@1645@tanstack/electric-db-collection
npm i https://pkg.pr.new/@tanstack/electric-db-collection@1645@tanstack/electron-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/electron-db-sqlite-persistence@1645@tanstack/expo-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/expo-db-sqlite-persistence@1645@tanstack/node-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/node-db-sqlite-persistence@1645@tanstack/offline-transactions
npm i https://pkg.pr.new/@tanstack/offline-transactions@1645@tanstack/powersync-db-collection
npm i https://pkg.pr.new/@tanstack/powersync-db-collection@1645@tanstack/query-db-collection
npm i https://pkg.pr.new/@tanstack/query-db-collection@1645@tanstack/react-db
npm i https://pkg.pr.new/@tanstack/react-db@1645@tanstack/react-native-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/react-native-db-sqlite-persistence@1645@tanstack/rxdb-db-collection
npm i https://pkg.pr.new/@tanstack/rxdb-db-collection@1645@tanstack/solid-db
npm i https://pkg.pr.new/@tanstack/solid-db@1645@tanstack/svelte-db
npm i https://pkg.pr.new/@tanstack/svelte-db@1645@tanstack/tauri-db-sqlite-persistence
npm i https://pkg.pr.new/@tanstack/tauri-db-sqlite-persistence@1645@tanstack/trailbase-db-collection
npm i https://pkg.pr.new/@tanstack/trailbase-db-collection@1645@tanstack/vue-db
npm i https://pkg.pr.new/@tanstack/vue-db@1645commit:
f6ded43Size Change: +5.87 kB (+4.71%) 🔍
Total Size: 131 kB
📦 View Changed
Filename Size Change packages/db/dist/esm/collection/changes.js1.39 kB +9 B (+0.65%) packages/db/dist/esm/collection/index.js3.8 kB +174 B (+4.8%) 🔍 packages/db/dist/esm/collection/mutations.js2.6 kB +125 B (+5.05%) 🔍 packages/db/dist/esm/collection/state.js6.93 kB +1.53 kB (+28.29%) 🚨 packages/db/dist/esm/collection/subscription.js3.98 kB +232 B (+6.2%) 🔍 packages/db/dist/esm/collection/sync.js2.93 kB +41 B (+1.42%) packages/db/dist/esm/indexes/base-index.js781 B +14 B (+1.83%) packages/db/dist/esm/indexes/basic-index.js2.24 kB +178 B (+8.63%) 🔍 packages/db/dist/esm/indexes/btree-index.js2.39 kB +192 B (+8.75%) 🔍 packages/db/dist/esm/local-only.js932 B +16 B (+1.75%) packages/db/dist/esm/query/compiler/evaluators.js2.56 kB +668 B (+35.36%) 🚨 packages/db/dist/esm/query/compiler/group-by.js3.69 kB +131 B (+3.68%) packages/db/dist/esm/query/compiler/index.js6.81 kB +136 B (+2.04%) packages/db/dist/esm/query/compiler/joins.js2.63 kB +125 B (+5%) 🔍 packages/db/dist/esm/query/effect.js4.75 kB -20 B (-0.42%) packages/db/dist/esm/query/live/collection-config-builder.js9.8 kB +698 B (+7.67%) 🔍 packages/db/dist/esm/query/live/collection-subscriber.js2.16 kB +226 B (+11.7%) ⚠️ packages/db/dist/esm/query/live/utils.js1.87 kB +61 B (+3.37%) packages/db/dist/esm/query/optimizer.js2.97 kB +50 B (+1.71%) packages/db/dist/esm/SortedMap.js1.57 kB +265 B (+20.37%) 🚨 packages/db/dist/esm/TombstoneMap.js469 B +469 B (new file) 🆕 packages/db/dist/esm/transactions.js3.38 kB +343 B (+11.3%) ⚠️ packages/db/dist/esm/utils.js1.06 kB +137 B (+14.78%) ⚠️ packages/db/dist/esm/utils/array-utils.js208 B -65 B (-23.81%) 🎉 packages/db/dist/esm/utils/comparison.js1.13 kB +15 B (+1.35%) packages/db/dist/esm/utils/index-optimization.js2.51 kB +120 B (+5.02%) 🔍 compressed-size-action::db-package-sizeℹ️ View Unchanged
Filename Size packages/db/dist/esm/collection/change-events.js1.43 kB packages/db/dist/esm/collection/cleanup-queue.js810 B packages/db/dist/esm/collection/events.js434 B packages/db/dist/esm/collection/indexes.js1.99 kB packages/db/dist/esm/collection/lifecycle.js1.69 kB packages/db/dist/esm/collection/transaction-metadata.js144 B packages/db/dist/esm/deferred.js207 B packages/db/dist/esm/errors.js5.1 kB packages/db/dist/esm/event-emitter.js748 B packages/db/dist/esm/index.js3.1 kB packages/db/dist/esm/indexes/auto-index.js829 B packages/db/dist/esm/indexes/index-registry.js820 B packages/db/dist/esm/indexes/reverse-index.js557 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/expressions.js430 B 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/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-registry.js264 B packages/db/dist/esm/query/live/internal.js145 B 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/strategies/debounceStrategy.js247 B packages/db/dist/esm/strategies/queueStrategy.js428 B packages/db/dist/esm/strategies/throttleStrategy.js246 B packages/db/dist/esm/utils/browser-polyfills.js304 B packages/db/dist/esm/utils/btree.js5.61 kB packages/db/dist/esm/utils/cursor.js457 B packages/db/dist/esm/utils/type-guards.js157 B packages/db/dist/esm/utils/uuid.js449 B packages/db/dist/esm/virtual-props.js360 B Size Change: 0 B
Total Size: 4.26 kB
compressed-size-action::react-db-package-sizeℹ️ View Unchanged
Filename Size packages/react-db/dist/esm/index.js249 B packages/react-db/dist/esm/useLiveInfiniteQuery.js1.32 kB packages/react-db/dist/esm/useLiveQuery.js1.37 kB packages/react-db/dist/esm/useLiveQueryEffect.js355 B packages/react-db/dist/esm/useLiveSuspenseQuery.js567 B packages/react-db/dist/esm/usePacedMutations.js401 B Actionable comments posted: 2
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/query/live/collection-config-builder.ts (1)
1254-1291: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winShared arrays can alias sibling rows.
materializeIncludedValuereturns the cachedentry.collection.toArraydirectly, so multiple parents sharing a correlation key can end up with the same array object. Mutating one row would mutate its siblings; keep the defensive copy when the correlation key fans out.🤖 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 1254 - 1291, The shared array returned by materializeIncludedValue can alias across sibling rows when multiple parents reuse the same correlation key. Update materializeIncludedValue so the array path in the IncludesOutputState materialization logic returns a fresh copy instead of the cached entry.collection.toArray reference, while preserving the existing behavior for collection, singleton, and concat cases.🧹 Nitpick comments (4)
packages/db/src/SortedMap.ts (1)
65-74: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winComparator-mode
pushis discarded on the next read.In the comparator branch you unconditionally set
dirty = true, andensureSorted()rebuildssortedKeysfrom scratch via[...this.map.keys()]. That makes thethis.sortedKeys.push(key)on Line 71 dead work: it grows a soon-discarded array on every insert. Since this is the write hot path this PR is optimizing (live query collections with fractional-index comparators callset()per synced row), dropping it avoids per-write array growth with no behavioral change.♻️ Proposed simplification
if (this.comparator) { // Lazy ordering: append new keys, defer sorting to the next read. - // Size comparison instead of has() avoids a second map lookup. - const sizeBefore = this.map.size - this.map.set(key, value) - if (this.map.size !== sizeBefore) { - this.sortedKeys.push(key) - } - this.dirty = true + // Every write marks dirty; the next read rebuilds sortedKeys from the + // map, so there is no need to touch sortedKeys here. + this.map.set(key, value) + this.dirty = true return this }🤖 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/SortedMap.ts` around lines 65 - 74, The comparator-mode insert path in SortedMap.set is doing dead work because dirty forces ensureSorted to rebuild sortedKeys from this.map.keys() on the next read. Remove the unnecessary this.sortedKeys.push(key) logic in the comparator branch and keep the dirty flag behavior in set/ensureSorted so writes stay cheap without changing ordering behavior.packages/db/src/query/compiler/joins.ts (1)
303-330: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate the validated-key-field skip logic into a shared helper.
This block (validated-key-field detection +
hasSentKeyfiltering ofjoinKeys) is near-identical topackages/db/src/query/compiler/index.tsLines 572-601, and the key-field-path detection duplicatesisKeyFieldPathinpackages/db/src/utils/index-optimization.ts. Since this logic encodes a subtle correctness invariant (single-segment validated key field), keeping three copies risks divergence. Extract a shared utility, e.g.filterUnsentKeysForKeyField(collection, targetPath, keys, subscription).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/query/compiler/joins.ts` around lines 303 - 330, The validated-key-field skip logic in joins.ts is duplicated in query/compiler/index.ts and the key-path check already exists in isKeyFieldPath, so consolidate it into a shared helper. Extract the single-segment validated key field detection plus hasSentKey-based filtering of joinKeys into a reusable utility such as filterUnsentKeysForKeyField, then call that helper from the join loading path instead of inlining the logic in Compiler/joins.ts. Make sure the helper preserves the existing correctness rule for validated key fields and returns the filtered keys plus the “skip loading” case when nothing remains.Source: Coding guidelines
packages/db/src/query/live/collection-config-builder.ts (2)
1932-1996: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffLightweightChildCollectioncast to the fullCollectiontype hides partial API surface.store as unknown as Collection<any, any, any>tells the type checker this object supports the entireCollectioninterface, butLightweightChildCollectiononly implementsget/has/getKeyFromItem/toArray/size/cleanup/_changes/id. A future call to e.g.entries(),keys(), orsubscribeChanges()onentry.collectionfor an inline-materialized entry would type-check but throw at runtime.Extracting a narrow interface (containing only the methods the flush machinery actually uses) for
entry.collection's type, implemented by bothLightweightChildCollectionand the realCollection, would let the compiler catch such mistakes instead of silently trusting the cast.🤖 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 1932 - 1996, The inline-materialized branch in createChildCollectionEntry is unsafely casting LightweightChildCollection to the full Collection type, which hides that it only supports a small subset of the API. Replace the broad cast with a narrow shared interface for entry.collection that includes only the methods the flush/mutation code actually uses, and make both LightweightChildCollection and the real createCollection result conform to it. This will keep the type on syncMethods/collection aligned and prevent accidental use of unsupported Collection methods such as entries(), keys(), or subscribeChanges() on lightweight entries.
2237-2248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReaching into
_changesviaanybypasses encapsulation.(parentCollection as any)._changesaccesses a private-looking internal field directly instead of through a public method. As per coding guidelines,**/*.{ts,tsx}should "Avoid usinganytypes; useunknowninstead" and "Avoid exposing internal properties directly; instead add public methods that delegate to internal implementations."Consider adding a small public accessor (e.g.
collection._hasChangeSubscribers()or exposing it via the existing_changestype) so this call site doesn't need to lie about the type viaany.🤖 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 2237 - 2248, This code reaches into parentCollection._changes via any, bypassing the public API and type safety. Update the collection-config-builder.ts call site to stop casting to any and instead use a public accessor or a properly typed _changes interface on parentCollection, such as a small helper that returns whether there are change subscribers. Keep the existing hasSubscribers check in place, but source it through the new typed method/property rather than directly accessing the internal field.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-ivm/src/d2.ts`: - Around line 59-74: The new run() loop in D2Executor bypasses the finalized-graph contract, so restore the same finalized-state guard used by step() before iterating operators. In run(), check the executor/graph finalization state and reject or no-op unless finalize() has been called, while keeping the existing pending-work loop on `#operators` unchanged. In `@packages/db/src/collection/state.ts`: - Around line 907-1137: Add focused regression tests for commitSyncedTransactionsFastLane to cover its own event derivation logic, not just the general commit path. Exercise a partial no-op update where deepEquals should prevent an event, verify origin-flip updates preserve previousValue via enrichRowWithVirtualProps, and include a repeated-key batch to confirm only the first pre-state is used when deriving final events. Use the commitSyncedTransactionsFastLane behavior around rowUpdateMode, touchedPreviousValues/touchedPreviousOrigins, and changes.emitEvents as the target for the assertions. --- Outside diff comments: In `@packages/db/src/query/live/collection-config-builder.ts`: - Around line 1254-1291: The shared array returned by materializeIncludedValue can alias across sibling rows when multiple parents reuse the same correlation key. Update materializeIncludedValue so the array path in the IncludesOutputState materialization logic returns a fresh copy instead of the cached entry.collection.toArray reference, while preserving the existing behavior for collection, singleton, and concat cases. --- Nitpick comments: In `@packages/db/src/query/compiler/joins.ts`: - Around line 303-330: The validated-key-field skip logic in joins.ts is duplicated in query/compiler/index.ts and the key-path check already exists in isKeyFieldPath, so consolidate it into a shared helper. Extract the single-segment validated key field detection plus hasSentKey-based filtering of joinKeys into a reusable utility such as filterUnsentKeysForKeyField, then call that helper from the join loading path instead of inlining the logic in Compiler/joins.ts. Make sure the helper preserves the existing correctness rule for validated key fields and returns the filtered keys plus the “skip loading” case when nothing remains. In `@packages/db/src/query/live/collection-config-builder.ts`: - Around line 1932-1996: The inline-materialized branch in createChildCollectionEntry is unsafely casting LightweightChildCollection to the full Collection type, which hides that it only supports a small subset of the API. Replace the broad cast with a narrow shared interface for entry.collection that includes only the methods the flush/mutation code actually uses, and make both LightweightChildCollection and the real createCollection result conform to it. This will keep the type on syncMethods/collection aligned and prevent accidental use of unsupported Collection methods such as entries(), keys(), or subscribeChanges() on lightweight entries. - Around line 2237-2248: This code reaches into parentCollection._changes via any, bypassing the public API and type safety. Update the collection-config-builder.ts call site to stop casting to any and instead use a public accessor or a properly typed _changes interface on parentCollection, such as a small helper that returns whether there are change subscribers. Keep the existing hasSubscribers check in place, but source it through the new typed method/property rather than directly accessing the internal field. In `@packages/db/src/SortedMap.ts`: - Around line 65-74: The comparator-mode insert path in SortedMap.set is doing dead work because dirty forces ensureSorted to rebuild sortedKeys from this.map.keys() on the next read. Remove the unnecessary this.sortedKeys.push(key) logic in the comparator branch and keep the dirty flag behavior in set/ensureSorted so writes stay cheap without changing ordering behavior.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
50eca9b0-fe19-4f0e-bbca-2abbe213cb56📥 Commits
Reviewing files that changed from the base of the PR and between 95e25bd1ec90187ac18bbea19522780936d48025 and e3573166152962b96170a835e1e134be33c92a90.
📒 Files selected for processing (34)
.changeset/perf-live-query-hot-paths.mdpackages/db-ivm/src/d2.tspackages/db-ivm/src/graph.tspackages/db-ivm/src/indexes.tspackages/db-ivm/src/multiset.tspackages/db-ivm/src/operators/groupBy.tspackages/db-ivm/src/operators/join.tspackages/db-ivm/src/operators/reduce.tspackages/db-ivm/src/utils.tspackages/db-ivm/tests/operators/groupBy.test.tspackages/db/src/SortedMap.tspackages/db/src/collection/changes.tspackages/db/src/collection/index.tspackages/db/src/collection/mutations.tspackages/db/src/collection/state.tspackages/db/src/collection/subscription.tspackages/db/src/collection/sync.tspackages/db/src/indexes/base-index.tspackages/db/src/indexes/basic-index.tspackages/db/src/local-only.tspackages/db/src/query/compiler/evaluators.tspackages/db/src/query/compiler/group-by.tspackages/db/src/query/compiler/index.tspackages/db/src/query/compiler/joins.tspackages/db/src/query/live/collection-config-builder.tspackages/db/src/query/live/collection-subscriber.tspackages/db/src/query/live/utils.tspackages/db/src/query/optimizer.tspackages/db/src/transactions.tspackages/db/src/utils/comparison.tspackages/db/src/utils/index-optimization.tspackages/db/tests/collection-auto-index.test.tspackages/db/tests/query/indexes.test.tspackages/query-db-collection/tests/query.test.ts
packages/db-ivm/src/d2.ts lines 119 to 137Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -57,7 +57,18 @@5757 }58585959 run(): void {60- while (this.pendingWork()) {61- this.step()60+ // Only run operators that actually have pending input; running idle61+ // operators drains empty queues and allocates for nothing. Operators are62+ // registered upstream-first, so one pass usually settles the graph and63+ // the final pass is a cheap no-work scan.64+ let anyRan = true65+ while (anyRan) {66+ anyRan = false67+ for (const op of this.#operators) {68+ if (op.hasPendingWork()) {69+ op.run()70+ anyRan = true71+ }72+ }6273 }6374 }🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Find run()/finalize() call ordering and any tests asserting the finalized guard on run rg -nP '\b(run|finalize|step)\s*\(' packages/db-ivm/src packages/db-ivm/tests -g '!**/node_modules/**' -C2Repository: TanStack/db
Length of output: 50368
🏁 Script executed:
#!/bin/bash set -euo pipefail # Inspect the relevant source around finalize/run/step in packages/db-ivm/src/d2.ts ast-grep outline packages/db-ivm/src/d2.ts --view expanded || true wc -l packages/db-ivm/src/d2.ts sed -n '1,220p' packages/db-ivm/src/d2.ts # Find the finalize guard and any run callers in the db-ivm package rg -n "Graph not finalized|`#finalized`|finalize\(|\.run\(" packages/db-ivm/src packages/db-ivm/tests -g '!**/node_modules/**' -C2Repository: TanStack/db
Length of output: 50368
🏁 Script executed:
#!/bin/bash set -euo pipefail # Narrowly inspect test coverage for unfinalized run() and for explicit finalize-before-run usage. rg -n "graph\.run\(\)|\.run\(\)" packages/db-ivm/tests -g '!**/node_modules/**' | head -n 80 rg -n "finalize\(\).*run\(\)|run\(\).*finalize\(\)" packages/db-ivm/tests -g '!**/node_modules/**' -U | head -n 80 # Search for any test or source mention of calling run before finalize rg -n "before finalize|unfinalized|Graph not finalized" packages/db-ivm -g '!**/node_modules/**' -C2Repository: TanStack/db
Length of output: 6308
🏁 Script executed:
#!/bin/bash set -euo pipefail # Inspect the public interface and any non-test run() callers. ast-grep outline packages/db-ivm/src/types.ts --view expanded || true sed -n '1,220p' packages/db-ivm/src/types.ts echo "--- non-test callers of .run() in packages/db-ivm/src ---" rg -n "\.run\(\)" packages/db-ivm/src -g '!**/node_modules/**' -C2 echo "--- mentions of finalize/run semantics ---" rg -n "finalize|Graph not finalized|Graph already finalized|run\(\)" packages/db-ivm/src packages/db-ivm/README* packages/db-ivm -g '!**/node_modules/**' -C1Repository: TanStack/db
Length of output: 50368
Preserve the finalized guard in
run()(packages/db-ivm/src/d2.ts:59-74)step()still rejects unfinalized graphs, but this new loop bypasses that check and can execute beforefinalize(). If that contract still matters, add the guard back here.🤖 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-ivm/src/d2.ts` around lines 59 - 74, The new run() loop in D2Executor bypasses the finalized-graph contract, so restore the same finalized-state guard used by step() before iterating operators. In run(), check the executor/graph finalization state and reject or no-op unless finalize() has been called, while keeping the existing pending-work loop on `#operators` unchanged.✅ Confirmed as addressed by @KyleAMathews
Addressed in 943a2951 — restored the finalized guard in
run()and added focused fast-lane regression tests (deep-equal update suppression, repeated-key batches, partial-update merge, single-op deletes). Origin-flippreviousValueenrichment isn't externally reachable under the fast lane's preconditions (it requires pendingLocalOrigins state that only user transactions create, which route to the general path), so it's covered by the general-path suites.@KyleAMathewsThanks for confirming — glad the finalized guard is back inrun()along with the fast-lane regression tests. Appreciate the clarification on the origin-flippreviousValuecase being covered by the general-path suites.(=^・ω・^=) ノ
✏️ Learnings added
Learnt from: KyleAMathews Repo: TanStack/db PR: 1645 File: packages/db-ivm/src/d2.ts:59-77 Timestamp: 2026-07-03T05:36:48.398Z Learning: In `packages/db/src/collection/state.ts`, the `commitSyncedTransactionsFastLane` fast lane path is only taken under strict preconditions that exclude `pendingLocalOrigins` state, which is only created by user transactions (those route to the general commit path instead). Therefore, origin-flip `previousValue` enrichment logic doesn't need fast-lane-specific test coverage since it's unreachable there; it's covered by the general-path test suites.Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
packages/db/src/collection/state.ts lines 914 to 1144Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -816,0 +1117,21 @@1117+ value: newValue,1118+ previousValue: enrichedPrevious,1119+ })1120+ }1121+ }1122+ }1123+1124+ // No optimistic state by precondition, so size is just the synced size1125+ this.size = this.syncedData.size1126+1127+ if (events.length > 0) {1128+ this.indexes.updateIndexes(events)1129+ }1130+ this.changes.emitEvents(events, true)1131+1132+ this.pendingSyncedTransactions = uncommittedSyncedTransactions1133+1134+ if (!this.hasReceivedFirstCommit) {1135+ this.hasReceivedFirstCommit = true1136+ }1137+ }🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash rg -nP 'commitSyncedTransactionsFastLane|FastLane|fast.?lane' packages/db/tests -C2 rg -nP '\bcommitPendingTransactions\b' packages/db/tests -C2Repository: TanStack/db
Length of output: 595
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== search tests for commit/event parity scenarios ==" rg -n --hidden --glob 'packages/db/tests/**/*.{ts,tsx,js}' \ -e 'commitPendingTransactions|commitSyncedTransactionsFastLane|fast.?lane|origin flip|rowUpdateMode|partial|deepEquals|previousValue|enrichRowWithVirtualProps|syncedTransactions' \ packages/db/tests -C 2 || true echo echo "== inspect the existing test file around commitPendingTransactions ==" sed -n '680,820p' packages/db/tests/collection-subscribe-changes.test.ts echo echo "== inspect the routing gate in source ==" rg -n 'hasPersistingTransaction|hasTruncateSync|commitSyncedTransactionsFastLane|commitPendingTransactions' packages/db/src/collection/state.ts -n -C 3Repository: TanStack/db
Length of output: 50367
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== source: routing gate and fast-lane preconditions ==" sed -n '1140,1215p' packages/db/src/collection/state.ts echo echo "== source: fast-lane header/comments ==" sed -n '907,960p' packages/db/src/collection/state.ts echo echo "== tests: multi-step updates / previousValue semantics ==" sed -n '1600,1665p' packages/db/tests/effect.test.ts echo echo "== tests: virtual-props previousValue preservation ==" sed -n '2288,2355p' packages/db/tests/collection-subscribe-changes.test.tsRepository: TanStack/db
Length of output: 9708
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "== general-path commit body around event derivation ==" sed -n '1215,1415p' packages/db/src/collection/state.ts echo echo "== search for direct fast-lane coverage in tests ==" rg -n 'fast lane|fast-lane|commitSyncedTransactionsFastLane|no optimistic state|recentlySyncedKeys|hasPersistingTransaction' packages/db/tests -C 2 || true echo echo "== search for tests with multi-step sync writes / origin preservation ==" rg -n 'multi-step|previousValue should preserve|$origin|virtual props|rowUpdateMode|partial' packages/db/tests -C 2 || trueRepository: TanStack/db
Length of output: 16237
Add explicit fast-lane regression coverage The suite covers these semantics through the general commit path, but
commitSyncedTransactionsFastLanehas its own event derivation; add a focused test for partial no-op updates, origin-flippreviousValueenrichment, and repeated-key batches.🤖 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/collection/state.ts` around lines 907 - 1137, Add focused regression tests for commitSyncedTransactionsFastLane to cover its own event derivation logic, not just the general commit path. Exercise a partial no-op update where deepEquals should prevent an event, verify origin-flip updates preserve previousValue via enrichRowWithVirtualProps, and include a repeated-key batch to confirm only the first pre-state is used when deriving final events. Use the commitSyncedTransactionsFastLane behavior around rowUpdateMode, touchedPreviousValues/touchedPreviousOrigins, and changes.emitEvents as the target for the assertions.✅ Confirmed as addressed by @KyleAMathews
Addressed in 943a2951 — restored the finalized guard in
run()and added focused fast-lane regression tests (deep-equal update suppression, repeated-key batches, partial-update merge, single-op deletes). Origin-flippreviousValueenrichment isn't externally reachable under the fast lane's preconditions (it requires pendingLocalOrigins state that only user transactions create, which route to the general path), so it's covered by the general-path suites.@KyleAMathewsThanks for the detailed follow-up — the reasoning checks out. SincecommitSyncedTransactionsFastLaneis only reached fromcommitPendingTransactionswhenthis.transactions.size === 0, andpendingLocalChanges/pendingLocalOriginsare only populated by active user transactions (which would keeptransactions.size > 0and route to the general path), the origin-flip scenario genuinely can't occur in the fast lane. Good catch, and the added regression tests for deep-equal suppression, repeated-key batches, partial-update merges, and single-op deletes cover the cases that matter here.🧹 Nitpick comments (1)
packages/db/tests/collection-subscribe-changes.test.ts (1)
2886-2886: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReplace
anywith proper types.syncApi: anyand the threeevents: Array<any>declarations can be typed precisely —syncApifrom thesync.synchandler'sapiparameter type, andeventsasArray<ChangeMessage<Row, number>>(matchingsubscribeChanges's callback payload). As per coding guidelines, "Avoid usinganytypes; useunknowninstead when the type is truly unknown, and provide proper type annotations for return values."♻️ Suggested typing
- function createSyncCollection() { - let syncApi: any + function createSyncCollection() { + let syncApi: Parameters<SyncConfig<Row, number>[`sync`]>[0]Apply similarly to the
eventsdeclarations, e.g.const events: Array<ChangeMessage<Row, number>> = [].Also applies to: 2908-2908, 2939-2939, 2974-2974
🤖 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/collection-subscribe-changes.test.ts` at line 2886, The test file still uses overly broad `any` types in `syncApi` and the `events` arrays, so replace them with precise annotations. Infer `syncApi` from the `api` parameter type used by the `sync.sync` handler, and type each `events` collection as `Array<ChangeMessage<Row, number>>` to match the `subscribeChanges` callback payload. Update all affected declarations consistently so the tests remain type-safe without relying on `any`.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/db/tests/collection-subscribe-changes.test.ts`: - Line 2886: The test file still uses overly broad `any` types in `syncApi` and the `events` arrays, so replace them with precise annotations. Infer `syncApi` from the `api` parameter type used by the `sync.sync` handler, and type each `events` collection as `Array<ChangeMessage<Row, number>>` to match the `subscribeChanges` callback payload. Update all affected declarations consistently so the tests remain type-safe without relying on `any`.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
580d86ca-64fc-4c33-84ec-25f46ddedadf📥 Commits
Reviewing files that changed from the base of the PR and between e3573166152962b96170a835e1e134be33c92a90 and 943a2951c7dcf022a779add78876bfff22a21a50.
📒 Files selected for processing (3)
packages/db-ivm/src/d2.tspackages/db/src/collection/mutations.tspackages/db/tests/collection-subscribe-changes.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/db-ivm/src/d2.ts
- packages/db/src/collection/mutations.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/db/src/indexes/btree-index.ts`: - Around line 437-457: The `orderedEntriesArray` getter still exposes tombstoned values as empty sets, unlike `take*` and `valueMapData`, so update the `BTreeIndex` snapshot path to filter out entries whose `Set` is empty before returning. Make the change in the `orderedEntriesArray` logic and ensure `ReverseIndex`’s delegated snapshot behavior stays consistent with the filtered `BTreeIndex` output.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
fc62377f-78a6-4540-aa00-585843e31830📥 Commits
Reviewing files that changed from the base of the PR and between 943a2951c7dcf022a779add78876bfff22a21a50 and 22490d16125b00c86c2f4f40917d0462aace586e.
📒 Files selected for processing (1)
packages/db/src/indexes/btree-index.ts
packages/db/src/indexes/btree-index.ts lines 458 to 478Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -430,8 +439,19 @@439+ if (keySet.size === 0) {440+ this.valueMap.delete(value)441+ this.orderedEntries.delete(value)442+ }443+ }444+ this.emptyValueTombstones = 0445+ }446+430447 get valueMapData(): Map<any, Set<TKey>> {431- // Return a new Map with denormalized keys448+ // Return a new Map with denormalized keys (tombstoned empty entries449+ // are an internal detail and excluded)432450 const result = new Map<any, Set<TKey>>()433451 for (const [key, value] of this.valueMap) {434- result.set(denormalizeUndefined(key), value)452+ if (value.size > 0) {453+ result.set(denormalizeUndefined(key), value)454+ }435455 }436456 return result437457 }🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash rg -nP '\borderedEntriesArray\b' --type=ts -C3Repository: TanStack/db
Length of output: 149
🏁 Script executed:
#!/bin/bash set -euo pipefail # Inspect the relevant file around the getters mentioned in the review comment FILE="packages/db/src/indexes/btree-index.ts" wc -l "$FILE" sed -n '390,470p' "$FILE" # Find any references to the sibling getters and related internal arrays/maps rg -n --hidden --glob '!**/dist/**' --glob '!**/build/**' \ 'orderedEntriesArray|orderedEntriesArrayReversed|valueMapData|orderedEntries' \ packages/db/src -C 3 # Look for tests or production code that consume the getter names rg -n --hidden --glob '!**/dist/**' --glob '!**/build/**' \ 'orderedEntriesArray|orderedEntriesArrayReversed|valueMapData' \ . -C 2Repository: TanStack/db
Length of output: 37694
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/db/src/indexes/btree-index.ts" # Read the add/remove/takeInternal logic and tombstone bookkeeping sed -n '90,170p' "$FILE" echo '---' sed -n '300,410p' "$FILE" # Inspect the tombstone-related tests, if any rg -n --hidden --glob '!**/dist/**' --glob '!**/build/**' \ 'tombstone|emptyValueTombstones|compactValueTombstones|orderedEntriesArrayReversed|orderedEntriesArray' \ packages/db/tests -C 3Repository: TanStack/db
Length of output: 12120
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/db/src/indexes/btree-index.ts" # Read the add/remove/takeInternal logic and tombstone bookkeeping sed -n '90,170p' "$FILE" echo '---' sed -n '300,410p' "$FILE" # Inspect tombstone-related tests or expectations rg -n --hidden --glob '!**/dist/**' --glob '!**/build/**' \ 'tombstone|emptyValueTombstones|compactValueTombstones|orderedEntriesArrayReversed|orderedEntriesArray' \ packages/db/tests -C 3Repository: TanStack/db
Length of output: 12120
Filter tombstoned entries from
orderedEntriesArraytoo.take*andvalueMapDataalready skip empty tombstones, but this getter still returns them as emptySets. That leaves the snapshot APIs inconsistent, andReverseIndexinherits the mismatch through its swapped delegation.🤖 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/indexes/btree-index.ts` around lines 437 - 457, The `orderedEntriesArray` getter still exposes tombstoned values as empty sets, unlike `take*` and `valueMapData`, so update the `BTreeIndex` snapshot path to filter out entries whose `Set` is empty before returning. Make the change in the `orderedEntriesArray` logic and ensure `ReverseIndex`’s delegated snapshot behavior stays consistent with the filtered `BTreeIndex` output.✅ Confirmed as addressed by @KyleAMathews
Addressed in 9a04e7d0 —
orderedEntriesArraynow filters tombstoned (emptied) entries, and the same contract is applied across the other snapshot getters (orderedEntriesArrayReversed,valueMapData) on bothBTreeIndexandBasicIndex, so inspection APIs stay consistent with thetake*/lookup read paths that already skip empty key sets.🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail FILE="packages/db/src/indexes/basic-index.ts" cat -n "$FILE" | sed -n '1,250p'Length of output: 14468
Confirmed — the fix in 9a04e7d0 is correct and consistently applied.
BasicIndexmirrors the same tombstone lifecycle asBTreeIndex:addreuses/decrements tombstone counts,removemarks empty sets as tombstones and triggerscompactValueTombstones()past the threshold, andclear()resetsemptyValueTombstones. Combined with the earlier confirmation onorderedEntriesArray/orderedEntriesArrayReversed/valueMapDatainBTreeIndex, all snapshot/inspection getters now uniformly skip tombstoned empty key sets. Thanks for the fix!
🧬 Code Graph Analysis Results
packages/db/src/indexes/btree-index.ts#Tombstone creation on
remove(...)(empty key sets are kept until compaction; read paths are expected to skip them)#Lines ~122-155:
/** * Removes a value from the index */ remove(key: TKey, item: any): void { let indexedValue: any try { indexedValue = this.evaluateIndexExpression(item) } catch (error) { console.warn( `Failed to evaluate index expression for key ${key} during removal:`, error, ) return } // Normalize the value for Map key usage const normalizedValue = normalizeForBTree(indexedValue) const keySet = this.valueMap.get(normalizedValue) if (keySet !== undefined) { keySet.delete(key) // Keep the emptied entry as a tombstone (read paths skip empty sets) // so a re-add of the same value avoids tree churn; compact when the // tombstone count grows. if (keySet.size === 0) { this.emptyValueTombstones++ if (this.emptyValueTombstones > BTreeIndex.MAX_VALUE_TOMBSTONES) { this.compactValueTombstones() } } } this.indexedKeys.delete(key) this.updateTimestamp() }take*path skipping tombstoned entries viakeys.size > 0#Lines ~168-236:
/** * Internal method for taking items from the index. * `@param` n - The number of items to return * `@param` nextPair - Function to get the next pair from the BTree * `@param` from - Already normalized! undefined means "start from beginning/end", sentinel means "start from the key undefined" * `@param` filterFn - Optional filter function * `@param` reversed - Whether to reverse the order of keys within each value */ private takeInternal( n: number, nextPair: (k?: any) => [any, any] | undefined, from: any, filterFn?: (key: TKey) => boolean, reversed: boolean = false, ): Array<TKey> { const keysInResult: Set<TKey> = new Set() const result: Array<TKey> = [] let pair: [any, any] | undefined let key = from // Use as-is - it's already normalized by the caller while ((pair = nextPair(key)) !== undefined && result.length < n) { key = pair[0] const keys = this.valueMap.get(key) as | Set<Exclude<TKey, undefined>> | undefined if (keys && keys.size > 0) { // Sort keys for deterministic order, reverse if needed const sorted = Array.from(keys).sort(compareKeys) if (reversed) sorted.reverse() for (const ks of sorted) { if (result.length >= n) break if (!keysInResult.has(ks) && (filterFn?.(ks) ?? true)) { result.push(ks) keysInResult.add(ks) } } } } return result }Snapshot getter contract:
orderedEntriesArrayfilters tombstoned (empty) key sets#Lines ~252-279:
get orderedEntriesArray(): Array<[any, Set<TKey>]> { // Tombstoned (emptied) values are an internal detail — filter them so // snapshot APIs stay consistent with take*/valueMapData const result: Array<[any, Set<TKey>]> = [] for (const key of this.orderedEntries.keysArray()) { const keySet = this.valueMap.get(key) if (keySet !== undefined && keySet.size > 0) { result.push([denormalizeUndefined(key), keySet]) } } return result }Snapshot getter:
orderedEntriesArrayReversedderives fromtakeReversedFromEnd(...)#Lines ~281-291:
get orderedEntriesArrayReversed(): Array<[any, Set<TKey>]> { return this.takeReversedFromEnd(this.orderedEntries.size).map((key) => [ denormalizeUndefined(key), this.valueMap.get(key) ?? new Set(), ]) }Snapshot getter contract:
valueMapDataexcludes tombstoned (empty) value sets#Lines ~311-324:
get valueMapData(): Map<any, Set<TKey>> { // Return a new Map with denormalized keys (tombstoned empty entries // are an internal detail and excluded) const result = new Map<any, Set<TKey>>() for (const [key, value] of this.valueMap) { if (value.size > 0) { result.set(denormalizeUndefined(key), value) } } return result }(Supports the tombstone lifecycle by removing tombstoned entries from both structures)#
Lines ~293-304:
private compactValueTombstones(): void { for (const [value, keySet] of this.valueMap) { if (keySet.size === 0) { this.valueMap.delete(value) this.orderedEntries.delete(value) } } this.emptyValueTombstones = 0 }
packages/db/src/utils/comparison.ts#Denormalization used by snapshot getters (
orderedEntriesArray*,valueMapData)#Lines ~239-244:
export function denormalizeUndefined(value: any): any { if (value === UNDEFINED_SENTINEL) { return undefined } return value }Normalization used for stored BTree keys (including the undefined sentinel)#
Lines ~228-233:
export function normalizeForBTree(value: any): any { if (value === undefined) { return UNDEFINED_SENTINEL } return normalizeValue(value) }
packages/db/src/utils/btree.ts#keysArray()iteration used byorderedEntriesArray#Lines ~139-159 (within the provided snippet):
/** Gets an array of all keys, sorted */ keysArray() { const results: Array<K> = [] this._root.forRange( this.minKey()!, this.maxKey()!, true, false, this, 0, (k, _v) => { results.push(k) }, ) return results }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/db/src/indexes/basic-index.ts`: - Around line 137-149: The tombstone accounting in BasicIndex is incrementing even when remove is a no-op, which can drift the counter upward. Update the removal path in the BasicIndex logic around keySet.delete(key) so emptyValueTombstones is only incremented when the set actually transitions from non-empty to empty; use the current size before deletion or the delete() return value to guard the increment. Keep the compactValueTombstones trigger tied to that real emptying transition.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
3efe3cff-75bb-49f4-8bf0-2a79da48ee00📥 Commits
Reviewing files that changed from the base of the PR and between 22490d16125b00c86c2f4f40917d0462aace586e and 9a04e7d09f4854379ee84b2f0017ccc9377bcb94.
📒 Files selected for processing (2)
packages/db/src/indexes/basic-index.tspackages/db/src/indexes/btree-index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/db/src/indexes/btree-index.ts
packages/db/src/indexes/basic-index.ts lines 143 to 155Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -128,12 +134,16 @@128134129135 const normalizedValue = normalizeValue(indexedValue)130136131- if (this.valueMap.has(normalizedValue)) {132- const keySet = this.valueMap.get(normalizedValue)!137+ const keySet = this.valueMap.get(normalizedValue)138+ if (keySet !== undefined) {133139 keySet.delete(key)134140141+ // Keep the emptied entry as a tombstone (read paths skip empty sets)142+ // so a re-add of the same value avoids the sorted-array splice;143+ // compact when the tombstone count grows.135144 if (keySet.size === 0) {136- // No more keys for this value, remove from map and sorted array137- this.valueMap.delete(normalizedValue)138- deleteInSortedArray(this.sortedValues, normalizedValue, this.compareFn)145+ this.emptyValueTombstones++146+ if (this.emptyValueTombstones > BasicIndex.MAX_VALUE_TOMBSTONES) {147+ this.compactValueTombstones()148+ }139149 }🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Guard the tombstone increment to the actual emptying transition.
keySet.delete(key)may be a no-op (stale/duplicateremove, or key already absent). If the set is already empty in that case,keySet.size === 0is still true andemptyValueTombstonesis incremented again for a value that is already tombstoned. Sinceadd's decrement is gated onsize === 0, the counter can drift upward, triggering prematurecompactValueTombstones()and unnecessaryvalueMapDatafiltering copies. Count only the real last-key removal:🛡️ Proposed guard
const keySet = this.valueMap.get(normalizedValue) if (keySet !== undefined) { - keySet.delete(key) - // Keep the emptied entry as a tombstone (read paths skip empty sets) // so a re-add of the same value avoids the sorted-array splice; // compact when the tombstone count grows. - if (keySet.size === 0) { + if (keySet.delete(key) && keySet.size === 0) { this.emptyValueTombstones++ if (this.emptyValueTombstones > BasicIndex.MAX_VALUE_TOMBSTONES) { this.compactValueTombstones() } } }📝 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.
Suggested change143+ const keySet = this.valueMap.get(normalizedValue)144+ if (keySet !== undefined) {145+ // Keep the emptied entry as a tombstone (read paths skip empty sets)146+ // so a re-add of the same value avoids the sorted-array splice;147+ // compact when the tombstone count grows.148+ if (keySet.delete(key) && keySet.size === 0) {149+ this.emptyValueTombstones++150+ if (this.emptyValueTombstones > BasicIndex.MAX_VALUE_TOMBSTONES) {151+ this.compactValueTombstones()152+ }153+ }🤖 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/indexes/basic-index.ts` around lines 137 - 149, The tombstone accounting in BasicIndex is incrementing even when remove is a no-op, which can drift the counter upward. Update the removal path in the BasicIndex logic around keySet.delete(key) so emptyValueTombstones is only incremented when the set actually transitions from non-empty to empty; use the current size before deletion or the delete() return value to guard the increment. Keep the compactValueTombstones trigger tied to that real emptying transition.✅ Addressed in commit 6b11719
Addressed in 6b117199 —
remove()in bothBasicIndexandBTreeIndexnow gates the whole block onkeySet.delete(key)returningtrue, so a stale/duplicate remove (key absent, set possibly already tombstoned) can no longer incrementemptyValueTombstones; the increment only fires on a real 1→0 transition. That commit also switcheskeyCountto counter-based tracking using the same delete-boolean discipline.@KyleAMathewsConfirmed — I checked the currentremove()implementation and it matches exactly what you described: the whole block (including theindexedKeyCount--) is now gated onkeySet.delete(key)returningtrue, so a stale/duplicate remove can no longer causeemptyValueTombstones(orindexedKeyCount) to drift. That's exactly the fix I was looking for. Thanks for the quick turnaround!(´。• ᵕ •。`) ♡
Sign in to join this conversation.
Note
Reviews paused#
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
📝 Walkthrough
Walkthrough#
This PR adds db-ivm execution and operator hot paths, query compiler and live-include fast paths, and collection/index/runtime changes for key-field-aware lookups, lower-allocation updates, and tombstoned index maintenance.
Changes#
db-ivm execution and operators
packages/db-ivm/src/d2.ts,packages/db-ivm/src/graph.ts,.changeset/perf-live-query-hot-paths.mdD2.run()now repeats passes over pending operators;drain()pops queued messages;sendData()marks a deliveredMultiSetexclusive when there is one reader; the changeset records the patch releases.packages/db-ivm/src/indexes.ts,packages/db-ivm/src/multiset.tsIndexaddsprefixIdentity/trackConsolidated,fromMultiSetsBy, and rewrittenget/append/join;PrefixMap.addValuesupports prefix-identity merging;MultiSetadds an exclusive in-place mode and a nested-map keyed consolidation path.packages/db-ivm/src/operators/groupBy.ts,packages/db-ivm/src/operators/join.ts,packages/db-ivm/src/operators/reduce.ts,packages/db-ivm/src/utils.ts,packages/db-ivm/tests/operators/groupBy.test.tsgroupByaddskeySerializerand wrapped aggregate handling;joinadds per-side key extractors and writes directly into shared results;reduceadds prefix-identity options and a small-output fast path;serializeValueadds a plain-object fast path; property tests cover incrementalgroupBybehavior.Query compilation and live includes
packages/db/src/query/compiler/evaluators.ts,packages/db/src/query/compiler/group-by.tscompileExpressionandcompileSingleRowExpressionuse cached evaluators;eqandingain fast paths;processGroupByswitches to bitmask metadata, direct key evaluation, and minimal output rows.packages/db/src/query/compiler/joins.ts,packages/db/src/query/compiler/index.tsprocessJoinuses per-item key extractors and validated-key filtering for lazy snapshots; includes snapshot loading skips already-sent keys; alias wrapping and result cleanup are tightened.packages/db/src/query/live/collection-config-builder.ts,packages/db/src/query/live/collection-subscriber.ts,packages/db/src/query/live/utils.tsIncludesOutputStategains deep-dirty tracking and ownership links; inline materialization usesLightweightChildCollection; re-emit logic becomes subscriber-aware; deep flush candidates are derived from tracked dirty keys.packages/db/src/query/optimizer.tsoptimizeQueryreturns early for a single direct collection source with no joins after combining top-levelwhereclauses withAND.Collection runtime and index maintenance
packages/db/src/collection/state.ts,packages/db/src/collection/sync.ts,packages/db/src/collection/subscription.ts,packages/db/tests/collection-subscribe-changes.test.tsCollectionStateManagerprobes and verifies key-field invariants, adds a synced-transaction fast lane, prunes processed terminal transactions, and emits plain insert events when possible; sync writes use explicit optimistic messages and subscriptions expose sent-key checks.packages/db/src/collection/mutations.ts,packages/db/src/transactions.ts,packages/db/src/local-only.tsTransaction.commitbecomes Promise-manual, and local-only wrappers confirm immediately when no handler exists.packages/db/src/indexes/base-index.ts,packages/db/src/indexes/basic-index.ts,packages/db/src/indexes/btree-index.tsBaseIndexstores update time as milliseconds and caches compiled expressions;BasicIndexandBTreeIndexadd tombstoned empty values, compaction, and filtered snapshot output.packages/db/src/utils/comparison.ts,packages/db/src/utils/index-optimization.ts,packages/db/tests/collection-auto-index.test.ts,packages/db/tests/query/indexes.test.ts,packages/query-db-collection/tests/query.test.tsnormalizeValuereturns immediately for primitives; query index optimization adds validated-keyeq/infast paths and matching capability checks; tests update join and scan expectations.Estimated code review effort: 5 (Critical) | ~120 minutes
Sequence Diagram(s)#
Possibly related issues
processJoinand validated key lookups.collection-config-builder.ts.Possibly related PRs
packages/db/src/utils/index-optimization.ts, especiallyeq/inoptimization changes.packages/db/src/query/live/collection-config-builder.tsinclude reconciliation changes.Suggested reviewers:
samwillis,kevin-dp🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 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