@tanstack/db-ivm#
1.0.0-rc.1#
Major Changes#
Release the first 1.0 candidate. Remove deprecated pre-1.0 APIs and give (#2171) published row metadata precedence over colliding selected fields. Structured source spreads and direct source-row returns keep source attribution; new functional objects and other projections receive output Collection metadata. Keep the two packages accidentally released as stable 1.x on their stable release lines. Both stable minor releases require
@tanstack/db@^1.0.0-rc.0for the RC health and restoration settlement APIs; upgrade DB with them.Remove Query Collection’s automatic refetch after mutation handlers. Handlers return
Promise<void>and must awaitcollection.utils.refetch()or write confirmed data with thewrite*utilities;{ refetch: false }is removed.
Patch Changes#
Breaking: Collection keys now always match the declared key type, a string or a number. (#2266)
- A grouped live query that groups by one field now gives a
null,undefined, boolean, or bigint group value a string key. Before, the key was the raw value, so$keywasnullfor thenullgroup. Read a group's key from its$key. String and number group values keep their keys. sync.writethrowsUndefinedKeyErrororInvalidKeyErrorwhengetKeyreturns a key that is not a string or a number. Optimistic mutations already threw these errors. For a bigint key, the development message now shows the key instead of failing with aTypeError.@tanstack/dbno longer exportsSortedMap, andSortedMapno longer hasforEach.SortedMapis the internal ordered map of Collection state.- When one publication applies 512 or more sync operations, the Collection now merges the changed keys into the existing order. Before, it sorted all rows again. With 50,000 rows, a
compareoption, and 600 operations in each sync transaction, the load takes 181 ms instead of 1,589 ms. - Keyed
MultiSet.consolidategroups entries in nested maps. It no longer encodes each value as a string.
- A grouped live query that groups by one field now gives a
0.2.0#
Minor Changes#
Remove operators and helpers that
@tanstack/dbdoes not use. This is a breaking change for code that imports them from@tanstack/db-ivmdirectly: (#2133)topK,topKWithIndex,orderBy,orderByWithIndexandorderByWithFractionalIndexBase. UseorderByWithFractionalIndexorgroupedOrderByWithFractionalIndex.innerJoin,leftJoin,rightJoin,fullJoinandantiJoin. Usejoin(other, type). Its result values are typed as nullable for every join type, so code that used the preciseinnerJoinresult type needs a cast or a null check.- The
count,negate,debug,filterBy,keyBy,unkeyandrekeyoperators. Thecountaggregate ingroupByOperatorsis unchanged. - The never-implemented piped aggregates in
groupBy. An aggregate must supplypreMapandreduce; an object with onlypipenow fails when the graph runs, where it was ignored before.
The package also no longer depends on
sorted-btree, which only an internal B+ tree top-K used.
Patch Changes#
Structural hashing now gives equal objects the same hash when two of their keys are distinct strings that locale collation ranks as equal, such as a precomposed
ÅandAfollowed by a combining ring. Before, the hash sorted keys withlocaleCompare, so the hash of such an object depended on the order its keys were inserted, and two equal rows could fail to consolidate in a live query. Keys now sort by UTF-16 code unit, which is a total order. This changes the digest of objects whose keys sort differently by code unit than by locale, for example{ a: 1, B: 2 }. Digests are per process, so no stored value depends on them. Hashing also writes whole 32-bit words to the hash stream, which makes hashing rows faster. The stream still hashes the same bytes. (#2108)An ordered, limited live query or Effect filtered through a LEFT join no longer shows a later row in place of an earlier one. The query loads a bounded prefix of root rows, and a row inserted after that prefix could enter the query's input. When a row left the window without a root delete, for example because its joined row was deleted or inserted, or its join key changed, the later row filled the window while an earlier eligible row was never loaded. A window row after the loaded prefix no longer counts toward a full window, so the query loads the next page first. (#2122)
An ordered, limited query with a full, outer or cross join now reads its full source, as inner and right joins already did. A full join loaded a bounded prefix of root rows, so a joined row whose root match had not loaded yet looked unmatched and could take a place in the window.
reduce,groupBy, and the joins they feed do less work per changed key: a reduce whose key has at most one output before and after compares the two directly instead of building two maps, its state no longer keeps a per-key presence count that only joins read, and index reads build their result directly. Live queries with includes hydrate slightly faster. (#2114)Aggregate queries hydrate and update faster.
groupBymerges equal contributions to a group, and it used to find them by hashing every contribution. Each contribution now leads with an identity string built from its group key and its pre-aggregate values, and the reduce index merges contributions with equal identities without hashing them. D2 value identity (equalHashValues) defines the identity: two values get the same identity string exactly when D2 treats them as equal. Primitives, arrays, plain and class-instance objects, Dates, RegExps, Maps, Sets and Uint8Arrays get an identity. A contribution that holds anything else, a value nested more than four levels deep, or an object with an enumerable symbol key still goes through the structural hash. A grouped count or min over 10,000 rows hydrates about 2× faster. (#2112)
0.1.26#
Patch Changes#
- Fix CommonJS declaration imports so Node16 and NodeNext TypeScript consumers can resolve the public APIs. Preserve ESM module references and string-literal types. (#1179)
0.1.25#
Patch Changes#
Fix joins over rows keyed by
NaN. The index compared row-key prefixes with===, which treatsNaNas unequal to itself, while theMapholding the prefixes treats it as one key. A retractedNaN-keyed row then never cancelled, so the join published a duplicate row or threwMismatching prefixes. (#1956)Keep keyed records distinct when keys or values share text across types, contain delimiters, or hold different symbols and functions. Prevent a retraction of one record from canceling a different record. (#1967)
0.1.24#
Patch Changes#
Share one type dispatch between structural hashing and
equalHashValues. Value identity, cycle rejection, and the structural work cap do not change. The standalone@tanstack/db-ivmentry is about 1 KB smaller when minified (about 225 B with gzip). (#1961)Share one loop for keyed and unkeyed
MultiSetconsolidation. Identity rules do not change, and a-0record in single-number data still consolidates to0. The standalone@tanstack/db-ivmentry is about 970 B smaller when minified (about 325 B with gzip). Consolidation is faster or equal in the measured workloads. (#1951)Run only D2 operators with queued input so unrelated branches do no operator work during an update. (#1959)
0.1.23#
Patch Changes#
Add regression coverage for structural hash type markers and empty top-K window moves. (#1918)
Preserve only captured accepted local inserts across a truncate. Preserve sparse-array length and RegExp state through ordered-query hashing, including hosts without a global File constructor. Prevent delayed replay reads from rerunning any transaction removed while the read was in flight, without rescanning the outbox. (#1822)
Keep distinct Temporal values in separate
groupBygroups and prevent plain objects with Temporal tags from sharing those groups. (#1919)Compare min and max aggregates against
undefinedinstead of truthiness so0,0n, and""can be the extreme of a group. (#1809)
0.1.22#
Patch Changes#
Preserve fractional top-k replacements regardless of delta order, including left-join updates, and honor B-tree lookup fallbacks after node splits. Preserve own JSON data properties such as
__proto__during mutation detachment and offline transaction serialization. (#1816)Compare same-key top-k values directly instead of hashing every replacement. This preserves cyclic payloads and avoids unnecessary full-payload traversal for ordinary updates.
Cancel structurally equal mapped top-k deltas before applying replacements. Escape Date-marker-shaped user objects in new offline records while retaining read support for the original record format.
Offline storage compatibility: new records use
valueEncoding: 2. Older clients cannot decode escaped marker-shaped objects correctly, so do not mix old and new clients against the same pending outbox or downgrade while new records remain. New clients still read the original unversioned format. Unknown encodings and corrupt records are reported through warnings and left in storage, not silently discarded; recovery policy is tracked in RFC #1659.Reject malformed escaped-object markers rather than inventing empty mutation data. Avoid redundant transfer work for zero-width fractional top-k windows and avoid descriptor writes for ordinary keys during draft copying.
Keep B-tree top-k results empty when the limit is zero, and advance the result window correctly when its first row is deleted. (#1816)
0.1.21#
Patch Changes#
- Correct the
distinctoperator's return type to reflect its numeric keys and preserved input values. (#1819)
0.1.20#
Patch Changes#
Fix on-demand load settlement, ordered pagination, and replay to preserve coherent results across cancellation, failure, cleanup, and restart. Preserve subset results and ownership across Electric, PowerSync, Query, and SQLite persistence adapters. Correct live-query grouping, include projections, value identity, and indexed comparisons. D2 hashing now rejects structural cycles and excessive traversal depth or work with an explicit error; Collection handles retain object-reference identity without traversing their mutable contents. (#1797)
Remove the unused public subset-algebra helpers:
isWhereSubset,unionWherePredicates,minusWherePredicates,isOrderBySubset,isLimitSubset,isOffsetLimitSubset,isPredicateSubset, andisLoadSubsetRequestSubsumedBy. Apps that import these helpers must remove those imports; normal queries and adapters are unaffected.DeduplicatedLoadSubsetremains available and shares only exact demand identities.Reject compiled Collection-valued includes as
fn.select()inputs, including nested descendants, before invoking the callback. UsetoArray()ormaterialize()in the upstream.select()for child-value calculations. To keep live child Collections, use expression.select()or perform parent-only functional work before adding the includes. Ordinary Collection-valued includes remain supported.Remove proxy
DEBUGlogging and automatic index timing statistics to avoid diagnostic work on reads and writes. RemovegetStats()andIndexStats; useindex.keyCountfor the current entry count, and instrument index methods externally when profiling. Custom index subclasses must remove calls to the retiredtrackLookup()andupdateTimestamp()helpers.Fix mutation drafts so Map/Set
forEachcalls each callback once and read-only iteration reports no changes. Track nested Mapfor...ofedits throughcollection.update(). Keep Set entries in place during nested edits, preserving live iteration and usablehas,delete, andaddhandles without duplicate entries or repeated visits. Reverting one entry no longer discards another entry's pending changes.Preserve shared values within a row's draft. Newly supplied objects use normal shared references during the update callback, including Map values and Set members; editing through either handle changes the same new object. Copy completed changes at callback return so later caller edits cannot mutate stored data. Existing collection values remain isolated. Copy a new caller-owned value before insertion if it must remain untouched during the callback.
Keep rejected local-storage mutations out of later successful saves. Stage insert, update, delete, and manual transaction writes before persisting, then promote the shared cache only after storage succeeds.
Deliver live-query observer publications to peer listeners even when one listener throws. Preserve queued publication order and stop delivery on disposal; report the first listener failure after delivery.
Wait for PowerSync demands admitted during tracking finalization before reporting them loaded. Preserve untouched object and array key identity when they contain
NaN. Retire every failed ordered acquisition on explicit retry, while retaining a full-source demand repaired by replay.After authoritative ordered recovery succeeds, retire settled page and tie demands so later truncate replay fetches only the full-source replacement. Keep unfinished requests observed until settlement and preserve independent query ownership.
Remove the live-query
utils.getRunCount()diagnostic and its runtime counter. Apps that call this diagnostic must remove those calls. Query scheduling and results are unchanged.Remove test-only index inspection getters (
indexedKeysSet,valueMapData,orderedEntriesArray, andorderedEntriesArrayReversed) and unused scheduler diagnostics.ReverseIndexnow exposes only theIndexReaderlookup, range, and forward traversal surface returned byfindIndexForField; mutate the original index instead. ExportIndexReaderfor callers that name this return type. Remove the unused subscriptionreleaseLoadSubset()method; request owners use the release callback supplied byonLoadSubsetResult. Ordinary query and adapter APIs remain unchanged by these removals.Remove unused internal helpers and the unused public error classes
WhereClauseConversionError,SubscriptionNotFoundError, andAggregateNotSupportedError. These classes have no remaining runtime throw sites; remove any imports of them. Keep the existing query and index behavior and exercise identity/evaluation tests through the production entry points.Ensure failed mutations roll back even when their rejection value cannot be converted to a string. Preserve ordinary Error instances; report unprintable rejection values as
Unknown error.Make reentrant effect disposal share the active cleanup result, including calls from abort listeners or source release callbacks. A release failure reaches every waiting disposer while each source still receives one release attempt.
Reject starting or preloading a collection from inside its active cleanup callbacks with a clear
CollectionStateError. Nested cleanup cannot admit replacement work that the old teardown would discard. Restart after cleanup completes, or from its finalcleaned-upstatus event, remains supported.Prevent older page or tie-boundary completions from clearing a newer full-source failure or starting redundant loading. Failed window moves retain their settled public snapshot; an explicit retry releases the failed acquisition once and publishes the completed replacement.
Restrict direct subscription
requestLimitedSnapshot()cursor inputs to one order term and oneminValuesentry. Composite and partial-composite cursor inputs now throw before local delivery or adapter work. Use normal live-query ordering and window APIs for multi-column pagination; those remain supported through prefix-and-tie loading. Existing adapters need no changes.Treat
LoadSubsetOptionsand their nested request data as immutable from submission onward. Core no longer copies expression trees or mutable constant payloads at the sync and deduplication boundaries. Create a new Date, byte array, membership array, or options object when changing a demand instead of mutating submitted data. Adapters must also leave request data unchanged. Use stable data properties rather than stateful getters.AbortSignalcancellation and subscription release remain live.Replace replay acquisitions sequentially: release the prior physical lease before starting its replacement. The logical demand and last complete public result remain retained. A failed release prevents replacement startup; failed startup leaves demand available for a later authoritative replay. Custom adapters must support a release/load gap and preserve resources still held by other owners; a sole underlying resource may stop and restart.
0.1.19#
Patch Changes#
- Rebuild correlated include materialization as one D2 graph, fixing stale or missing nested results across route changes, batching, lazy loading, optimistic updates, and layered queries. Add canonical structural relation keys, abortable subset demand, and coherent publication for Collection-valued includes. Dispose delayed PowerSync subset hooks after cleanup, and prevent released Query Collection cache results from reaching the collection. (#1740)
0.1.18#
Patch Changes#
- Fix Temporal objects breaking live query updates when used with joins. Temporal objects (e.g.
Temporal.PlainDate) have no enumerable properties, so the structural hash function produced identical hashes for all Temporal values, causing join index updates to be silently swallowed. Also add Temporal support to value normalization for join key matching and to the comparator for correct sort ordering. (#1370)
0.1.17#
Patch Changes#
- Add string support to
min()andmax()aggregate functions. These functions now work with strings using lexicographic comparison, matching standard SQL behavior. (#1120)
0.1.16#
Patch Changes#
- Add
groupedOrderByWithFractionalIndexoperator. This operator groups elements by a providedgroupKeyFnand applies ordering and limits independently to each group. Each group maintains its own sorted collection with independent limit/offset, which is useful for hierarchical data projections where child collections need to enforce limits within each parent's slice of the stream rather than across the entire dataset. (#997)
0.1.15#
Patch Changes#
- Adds a GroupedTopKWithFractionalIndexOperator that maintains separate topK windows for each group. (#993)
0.1.14#
Patch Changes#
Use row keys for stable tie-breaking in ORDER BY operations instead of hash-based object IDs. (#957)
Previously, when multiple rows had equal ORDER BY values, tie-breaking used
globalObjectIdGenerator.getId(key)which could produce hash collisions and wasn't stable across page reloads for object references. Now, the row key (which is alwaysstring | numberand unique per row) is used directly for tie-breaking, ensuring deterministic and stable ordering.This also simplifies the internal
TaggedValuetype from a 3-tuple[K, V, Tag]to a 2-tuple[K, V], removing unnecessary complexity.
0.1.13#
Patch Changes#
Fix Uint8Array/Buffer comparison to work by content instead of reference. This enables proper equality checks for binary IDs like ULIDs in WHERE clauses using the
eqfunction. (#779)Fix bug with setWindow on ordered queries that have no limit. (#763)
0.1.12#
Patch Changes#
- Fix bug with setWindow on ordered queries that have no limit. (#701)
0.1.11#
Patch Changes#
Add
utils.setWindow()method to live query collections to dynamically change limit and offset on ordered queries. (#663)You can now change the pagination window of an ordered live query without recreating the collection:
const users = createLiveQueryCollection((q) => q .from({ user: usersCollection }) .orderBy(({ user }) => user.name, 'asc') .limit(10) .offset(0), ) users.utils.setWindow({ offset: 10, limit: 10 })
0.1.10#
Patch Changes#
- Redesign of the join operators with direct algorithms for major performance improvements by replacing composition-based joins (inner+anti) with implementation using mass tracking. Delivers significant performance gains while maintaining full correctness for all join types (inner, left, right, full, anti). (#571)
0.1.9#
Patch Changes#
- Add support for Date objects to min/max aggregates and range queries when using an index. (#428)
0.1.8#
Patch Changes#
Fix a bug with distinct operator (#564)
Change the ivm indexes to use a three level
key->prefix->hash->valuestructure, only falling back to structural hashing when there are multiple values for a single prefix. This removes all hashing during the initial run of a query delivering a 2-3x speedup. (#549)
0.1.7#
Patch Changes#
- Fix memory leak that results in linear memory growth with incremental changes over time. Thanks to @sorenbs for finding and fixing this. (#550)
0.1.6#
Patch Changes#
- optimise key loading into query graph (#526)
0.1.5#
Patch Changes#
- Fix bug where different numbers would hash to the same value. This caused distinct not to work properly. (#525)
0.1.4#
Patch Changes#
- Check typeof Buffer before instanceof to avoid ReferenceError in browsers (#519)
0.1.3#
Patch Changes#
fix count aggregate function (evaluate only not null field values like SQL count) (#453)
Hybrid index implementation to track values and their multiplicities (#489)
Replace JSON.stringify based hash function by structural hashing function. (#491)
0.1.2#
Patch Changes#
Optimize order by to lazily load ordered data if a range index is available on the field that is being ordered on. (#410)
Optimize joins to use index on the join key when available. (#335)
0.1.1#
Patch Changes#
- Fix bug with orderBy that resulted in query results having less rows than the configured limit. (#405)
0.1.0#
Minor Changes#
- 0.1 release - first beta 🎉 (#332)
Patch Changes#
- We have moved development of the differential dataflow implementation from @electric-sql/d2mini to a new @tanstack/db-ivm package inside the tanstack db monorepo to make development simpler. (#330)