Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

skill_spec.md

206 lines19.6 KB

TanStack DB — Skill Specification (Reviewed)

TanStack DB is a reactive client-side data store that provides normalized collections, sub-millisecond live queries via differential dataflow (d2ts), and instant optimistic mutations with automatic rollback. It supports multiple data sources (REST APIs via TanStack Query, sync engines like ElectricSQL/PowerSync/RxDB/TrailBase, and local storage) through a unified collection API with framework adapters for React, Vue, Svelte, Solid, and Angular.

Domains

DomainDescriptionSkills
Collection Setup & SchemaCreating and configuring typed collections from any data source, with schema validation and adapter-specific sync patternscollection-setup
Live Query ConstructionBuilding SQL-like reactive queries with expressions, joins, aggregations, and incremental view maintenancelive-queries
Framework IntegrationBinding live queries to UI framework components using hooks, dependency tracking, Suspense, and paginationframework-integration
Mutations & Optimistic StateWriting data with instant optimistic feedback, transaction lifecycles, and automatic rollbackmutations-optimistic
Meta-Framework IntegrationClient-side preloading of collections in route loaders for TanStack Start, Next.js, Remix, etc.meta-framework
Custom Adapter AuthoringBuilding custom collection adapters that implement the SyncConfig contractcustom-adapter
Offline TransactionsOffline-first transaction queueing with persistence, retry, and multi-tab coordinationoffline

Skill Inventory

SkillTypeDomainWhat it coversFailure modes
collection-setupcoreCollection Setup & SchemacreateCollection, 7 adapter option creators, CollectionConfig, StandardSchema, lifecycle, sync modes, adapter-specific patterns10
live-queriescoreLive Query ConstructionQuery builder API, all operators, joins, aggregates, derived collections, IVM, $selected, predicate push-down8
framework-integrationframeworkFramework IntegrationReact/Vue/Svelte/Solid/Angular hooks, deps arrays, Suspense, infinite queries4
mutations-optimisticcoreMutations & Optimistic Stateinsert/update/delete, draft proxy, transactions, paced mutations, Pacer integration8
meta-frameworkcompositionMeta-Framework Integrationpreload() in loaders, ssr: false, pre-created live query collections, route lifecycle3
custom-adaptercoreCustom Adapter AuthoringSyncConfig, begin/write/commit/markReady, loadSubset, expression parsing3
offlinecompositionOffline TransactionsOfflineExecutor, storage adapters, retry, leader election, online detection3

Failure Mode Inventory

Collection Setup & Schema (10 failure modes)

#MistakePrioritySourceCross-skill?
1queryFn returning empty array deletes all dataCRITICALdocs—
2Not knowing which adapter to useCRITICALmaintainer—
3Using async schema validationHIGHsource—
4getKey returning undefinedHIGHsource—
5TInput not superset of TOutput with schema transformsHIGHdocs—
6Providing both explicit type param and schemaMEDIUMdocs—
7React Native missing crypto.randomUUIDHIGHdocs—
8Electric txid queried outside mutation transactionCRITICALdocs—
9queryFn returning partial data without mergingCRITICALdocs—
10Direct writes overridden by next query syncMEDIUMdocs—

Live Query Construction (8 failure modes)

#MistakePrioritySourceCross-skill?
1Using === instead of eq() in where clausesCRITICALsource—
2Filtering/transforming data in JS instead of query operatorsCRITICALmaintainer—
3Not using the full set of available query operatorsHIGHmaintainer—
4.distinct() without .select()HIGHsource—
5.having() without .groupBy()HIGHsource—
6.limit()/.offset() without .orderBy()HIGHsource—
7Join condition using operator other than eq()HIGHsource—
8Passing source directly instead of {alias: collection}MEDIUMsource—

Framework Integration (4 failure modes)

#MistakePrioritySourceCross-skill?
1Missing external values in deps arrayCRITICALdocs—
2Reading Solid signals outside query functionHIGHdocs—
3useLiveSuspenseQuery without Error BoundaryHIGHdocs—
4Svelte props not wrapped in getter functionsMEDIUMdocs—

Mutations & Optimistic State (8 failure modes)

#MistakePrioritySourceCross-skill?
1Passing object to update() instead of mutating draftCRITICALmaintainer—
2Hallucinating mutation API signaturesCRITICALmaintainer—
3onMutate callback returning a PromiseCRITICALsource—
4insert/update/delete without handler or ambient transactionCRITICALsource—
5.mutate() after transaction no longer pendingHIGHsource—
6Attempting to change primary key via updateHIGHsource—
7Inserting item with duplicate keyHIGHsource—
8Not awaiting refetch after mutation in query collection handlerHIGHdocs—

Meta-Framework Integration (3 failure modes)

#MistakePrioritySourceCross-skill?
1Not preloading collections in route loadersHIGHexamples—
2Not setting ssr: false on routes using collectionsCRITICALexamples—
3Creating new collection instances inside loaders on every navigationHIGHdocs—

Custom Adapter Authoring (3 failure modes)

#MistakePrioritySourceCross-skill?
1Not calling markReady() in sync implementationCRITICALdocs—
2Race condition: subscribing after initial fetchHIGHdocs—
3write() called without begin()HIGHsource—

Offline Transactions (3 failure modes)

#MistakePrioritySourceCross-skill?
1Using offline transactions when not neededHIGHmaintainer—
2Not handling NonRetriableError for permanent failuresHIGHsource—
3Multiple tabs executing same queued transactionCRITICALsource—

Total: 39 failure modes (14 CRITICAL, 19 HIGH, 6 MEDIUM)

Key Maintainer Insights (not in docs)

  1. Always prefer query operators over JS — Live queries are incrementally maintained via D2 differential dataflow. A .where(eq(...)) only recomputes the delta on data changes, while .filter() in JS re-runs from scratch. This applies even for trivial transformations.

  2. The update API is Immer-style — collection.update(id, (draft) => { draft.title = "new" }) not collection.update(id, { ...item, title: "new" }). This is the single most common mutation API mistake AI agents make.

  3. Agents hallucinate mutation APIs — The mutation surface has nuance (handler signatures, ambient transaction context, createOptimisticAction vs createTransaction). Agents generate plausible-looking but wrong code.

  4. Collection type selection matters — Don't default to bare createCollection or localOnlyCollectionOptions. Each backend has a dedicated adapter that handles sync, handlers, and utilities correctly.

  5. localOnly is a valid prototyping strategy — localOnlyCollectionOptions → real backend adapter is a clean upgrade path.

  6. Offline is hard — only when needed — Don't steer users toward offline unless they need it. PowerSync/RxDB handle their own local persistence, which is different from offline transaction queuing.

  7. SSR is not supported yet — Collections are client-side only. Routes using collections must set ssr: false. Preloading happens in client-side route loaders, not on the server.

  8. Transactions stack — Concurrent transactions build optimistic state on top of each other. Use TanStack Pacer for sequential execution when ordering matters.

Tensions

TensionSkillsAgent implication
Simplicity vs. correctness in synccollection-setup ↔ custom-adapterAgents use localOnly or eager mode for everything; production needs adapter-specific patterns
Optimistic speed vs. data consistencymutations-optimistic ↔ collection-setupAgents apply optimistic updates without considering rollback UX or awaiting refetch
Query expressiveness vs. IVM constraintslive-queries ↔ framework-integrationAgents write SQL-style queries that violate IVM constraints (equality joins only, orderBy for limit, etc.)
Offline complexity vs. app simplicityoffline ↔ mutations-optimisticAgents add offline-transactions to apps that only need basic optimistic mutations

Cross-References

FromToReason
framework-integrationmeta-frameworkHooks render data; loaders preload it. Both needed for production routing.
meta-frameworkframework-integrationPreloaded collections consumed by hooks; hook API informs what to preload.
collection-setupmutations-optimisticMutation handlers configured at setup time, execute during mutations.
mutations-optimisticcollection-setupHandler signatures depend on adapter (Electric txid, Query refetch).
live-queriescollection-setupQueries reference collections; sync modes affect query behavior.
custom-adaptercollection-setupCustom adapters produce same CollectionConfig shape as built-in adapters.
offlinemutations-optimisticOffline wraps the same transaction/mutation model.

Subsystems & Reference Candidates

SkillSubsystemsReference candidates
collection-setupTanStack Query, ElectricSQL, PowerSync, RxDB, TrailBase, local-only, localStorageAdapter configs with examples
live-queries—Query operators (>20 distinct operators with signatures)
framework-integrationReact, Vue, Svelte, Solid, AngularPer-framework hook patterns
mutations-optimistic—Transaction API, draft proxy, paced mutations
meta-framework——
custom-adapter—SyncConfig contract, expression parsing helpers
offline—Storage adapters, retry policies, leader election

Remaining Gaps

SkillQuestionStatus
meta-frameworkPatterns for non-TanStack-Start frameworks (Next.js App Router, Remix, Nuxt, SvelteKit)?open
collection-setupCollection GC/disposal patterns in route-based SPAs?open
live-queriesPerformance cliffs — at what complexity/data size do queries degrade?open
mutations-optimisticRecommended pattern for temporary ID → server ID mapping?open
meta-frameworkSpecific TanStack Router integration patterns for prefetching?open
offlineBehavior of in-flight transactions when browser goes offline mid-persist?open
  • Core skills: collection-setup, live-queries, mutations-optimistic, custom-adapter
  • Framework skills: framework-integration (per-framework references)
  • Composition skills: meta-framework, offline
  • Reference files needed:
    • collection-setup: per-adapter config references (7 adapters)
    • live-queries: operator reference (>20 operators)
    • framework-integration: per-framework hook references (5 frameworks)
    • custom-adapter: SyncConfig contract reference

Monorepo skill placement

PackageSkills
packages/dbcollection-setup, live-queries, mutations-optimistic, custom-adapter
packages/react-dbframework-integration (React)
packages/vue-dbframework-integration (Vue)
packages/svelte-dbframework-integration (Svelte)
packages/solid-dbframework-integration (Solid)
packages/angular-dbframework-integration (Angular)
packages/offline-transactionsoffline
Meta-frameworkmeta-framework (in packages/db or repo-level)

Composition Opportunities

LibraryIntegration pointsComposition skill needed?
TanStack QueryqueryCollectionOptions wraps QueryObserverBuilt into collection-setup adapter refs
TanStack RouterRoute loaders for collection preloadingmeta-framework skill
TanStack StartFull-stack framework with ssr: false patternmeta-framework skill
ElectricSQLReal-time sync via ShapeStream; txid trackingBuilt into collection-setup adapter refs
PowerSyncSQLite offline persistence; diff-trigger changesBuilt into collection-setup adapter refs
RxDBObservable-driven sync; RxJS subscriptionsBuilt into collection-setup adapter refs
TrailBaseEvent stream sync; cursor-based paginationBuilt into collection-setup adapter refs
Zod / Valibot / ArkType / EffectSchema validation via StandardSchema specBuilt into collection-setup
TanStack TableVirtual table rendering of live query resultsNeeds investigation
TanStack PacerSequential transaction execution, debounced mutationsBuilt into mutations-optimistic