Open History to see the last commit
1# Query Collection initial and placeholder data semantics
2
3## Status and scope
4
5This document defines the semantics for TanStack Query `initialData` and
6`placeholderData` at the `@tanstack/query-db-collection` boundary. It is the
7design follow-up for [RFC #1643](https://github.com/TanStack/db/issues/1643)
8and [issue #346](https://github.com/TanStack/db/issues/346). The accompanying
9implementation adds the approved eager `initialData` behavior without changing
10the persistence format.
11
12The adapter connects two different models:
13
14- TanStack Query owns a document cache and remote-query lifecycle.
15- TanStack DB owns normalized rows, local queries, and optimistic writes.
16- Query Collection projects a Query response into rows and records which Query
17 key owns each materialized row.
18
19`initialData` and `placeholderData` must not be treated as equivalent ways to
20provide an array. In Query Core 5.90.20, `initialData` initializes Query cache
21state with `status: "success"` and a `dataUpdatedAt` timestamp. By contrast,
22`placeholderData` is computed per observer only while Query state is pending;
23it produces an observer result with `isPlaceholderData: true` but is not stored
24in Query state.
25
26## Decision
27
28Support Query-owned `initialData` as an additive, eager-mode option. Materialize
29it immediately through the existing row extraction and ownership pipeline.
30Do not expose or materialize `placeholderData` in the first implementation.
31
32Query Collection can already materialize data that was seeded or hydrated into
33the QueryClient before the observer is created, and QueryClient defaults can
34already provide `initialData` indirectly. That is useful existing behavior, but
35it does not close the configuration gap. Applications commonly share one
36QueryClient across many Query Collections: a client-wide default is too broad,
37while imperative `setQueryData` requires coordinating collection construction,
38exact Query keys, and initialization elsewhere. The additive field supplies a
39collection-local declaration while leaving Query as the cache authority.
40
41The minimal additive API is:
42
43```ts
44initialData?: TQueryData | (() => TQueryData)
45initialDataUpdatedAt?: number | (() => number | undefined)
46```
47
48These remain flat top-level fields. Their types describe the original Query
49response, not the extracted row array. Consequently, wrapped responses use the
50same adapter `select` as network responses:
51
52```ts
53queryCollectionOptions({
54 queryKey: ["todos"],
55 queryFn: fetchTodos,
56 initialData: { items: serverTodos, nextCursor: null },
57 select: (response) => response.items,
58 // ...
59})
60```
61
62Query keys still define cache identity. If two Query Collections on the same
63QueryClient use the same exact key, they observe one shared Query document;
64`initialData` initializes that document only when it does not already exist.
65Collection-local configuration does not create collection-local cache data, and
66later observers must not replace an existing document with their initializer.
67Collections that require independent initial documents must use distinct keys.
68
69This initial API is limited to `syncMode: "eager"`. A single configuration-level
70value cannot lawfully initialize an open-ended family of on-demand subset keys,
71and Query's `initialData` function receives no query key or subset context.
72Applications that already know data for an exact on-demand key should seed or
73hydrate that Query cache entry instead. A future subset-aware initializer would
74need an explicit key/subset argument and a separate design.
75
76`placeholderData` remains Query UI vocabulary. A DB collection has no
77observer-local result surface: materializing a placeholder would make it visible
78to every DB query and mutation, assign it row ownership, and potentially persist
79it. Callers should render placeholders in the consuming UI. A future opt-in
80temporary-row feature, if needed, should be a DB feature with explicit provenance
81and lifecycle rather than Query's `placeholderData` option.
82
83## Authority model
84
85"Authoritative" has two dimensions here. Query owns the authoritative document
86for a Query key, while DB owns the current normalized row state. A server result
87is the newest remote snapshot, but local optimistic transactions can temporarily
88overlay its rows.
89
90| Phase | Query document authority | Materialized row authority | Consequence |
91| --- | --- | --- | --- |
92| No cached data | None | Existing DB/persisted rows, if any | The collection waits for Query; absence is not an empty result. |
93| Initial data | Query cache `initialData` | Its projected rows, subject to normal local overlays | It is a real cached snapshot, not temporary presentation data. |
94| Fetch/refetch in flight | Existing Query document | Existing rows | Loading does not clear rows or ownership. |
95| Server success | Returned response replaces the Query document | Projected server rows reconcile the owning Query key | Missing rows lose this Query owner's lease; shared rows remain. |
96| Fetch/refetch error | Last successful Query document | Existing rows | An error does not retract initial or previously fetched rows. |
97| Placeholder presentation | No Query document | No rows | Placeholder data is never passed to DB. |
98
99`initialDataUpdatedAt` and `staleTime` remain Query-owned. They decide whether a
100fetch starts; the adapter does not reproduce their freshness calculation. An
101initial value is therefore a seed snapshot with ordinary Query authority, not a
102weaker class of row waiting to be promoted. The first successful server result
103reconciles it through the same path as any later refetch.
104
105## Behavior matrix
106
107| Concern | `initialData` | `placeholderData` |
108| --- | --- | --- |
109| Query cache | Stored as successful Query data | Not stored; observer-only |
110| Existing cache entry | Existing cached/hydrated data wins; `initialData` is not reapplied | Not applicable |
111| DB materialization | Immediate in eager mode | Never |
112| Wrapped response | Adapter `select(initialData)` extracts rows; original envelope stays cached | Unsupported |
113| Function value | Evaluated by Query once when the Query is created | Not forwarded or evaluated by the adapter |
114| Ownership | The Query key owns projected rows exactly like a server success | No ownership |
115| Overlapping subsets | Not applicable to the initial eager-only API | Not applicable |
116| Ready state | Initial successful result can make the collection ready synchronously | Cannot make the collection ready |
117| Refetch success | Reconciles additions, updates, and removals normally | N/A |
118| Refetch error | Initial rows and ownership remain; error state is reported | N/A |
119| Cancellation/cleanup | Existing ownership cleanup rules apply; a cancelled fetch does not retract the cached seed | No rows to clean up |
120| Query cache GC/unload | Existing Query-to-row ownership and persisted-retention rules apply | No effect |
121| Query dehydration | Query owns persistence of the initial response | Never persisted |
122| DB persistence/hydration | Rows and owner metadata use the existing format; no provenance tag is added | Never persisted or hydrated |
123| Direct writes before server success | Allowed under the existing write rules below | No target rows exist |
124| QueryClient defaults | Supported for eager `initialData`; see compatibility guard below | Must be suppressed at this adapter boundary |
125
126## Select and writes
127
128Adapter `select` remains a one-way row extractor. It is applied identically to
129initial and network responses, and TanStack Query retains the original response
130shape. Query observer-level `select` remains unsupported.
131
132Direct writes before the first server result follow the current authority rule:
133they update DB immediately and may patch Query cache only when the reverse update
134is lawful. A raw array can be replaced. For a wrapped response, the existing
135best-effort patch is lawful only when `select` returns an array property of the
136cached object by reference, allowing the wrapper to be preserved. A derived
137projection such as `response.edges.map(...)` has no general reverse projection;
138the adapter must leave that Query document unchanged and rely on invalidate or
139refetch. It must never fabricate an envelope around rows.
140
141The next successful remote response remains authoritative for that Query key and
142may overwrite a direct cache patch or normalized row value. Mutation handlers and
143optimistic transaction barriers retain their existing semantics.
144
145## Ownership, persistence, and transitions
146
147Initial rows use the existing `queryToRows` and `rowToQueries` relationship. No
148`seed`, `temporary`, or `placeholder` bit is added to a row. This keeps these
149invariants intact:
150
1511. A successful result, whether initial or fetched, is a complete snapshot for
152 its Query key.
1532. A row is deleted when a snapshot omits it only if no other Query key owns it.
1543. Unload, cache GC, and collection cleanup remove only the relevant ownership.
1554. A failed or cancelled fetch cannot turn the last successful snapshot into an
156 empty snapshot.
1575. Persistence records only Query data and the existing row ownership metadata;
158 observer-only presentation state is never persisted.
159
160The expected transitions are:
161
162- **Initial, fresh:** materialize and become ready; do not fetch until Query's
163 normal freshness triggers say to do so.
164- **Initial, stale:** materialize and become ready while Query fetches; success
165 reconciles the same ownership, and error retains the seed.
166- **Loading without data:** keep the collection's prior independently owned or
167 hydrated rows; do not infer an empty result.
168- **Placeholder to loading/success/error:** the placeholder is UI-only. DB sees
169 no transition until success; error leaves DB unchanged.
170- **Cleanup before network completion:** existing cancellation and readiness
171 listener cleanup apply. A late result must not mutate a cleaned-up collection.
172
173## Defaults and compatibility guard
174
175Query Collection currently constructs a `QueryObserver`, so QueryClient defaults
176can contain semantic fields even when Query Collection does not expose them.
177Implementation must explicitly enforce this design after Query defaults are
178resolved:
179
180- reject an explicitly configured `initialData` in on-demand mode;
181- prevent default `initialData` from initializing on-demand subset observers;
182- prevent explicit or default `placeholderData` from reaching all Query
183 Collection observers;
184- continue to let omitted eager `initialData` and `initialDataUpdatedAt` inherit
185 QueryClient defaults;
186- never copy a function-valued initializer into adapter metadata or persisted
187 ownership metadata. Query Core may own it as an option and stores only its
188 evaluated data in Query state.
189
190Silently materializing default placeholder data would violate the public
191compatibility table even before a top-level field is added. The guard is therefore
192a correctness fix, not support for placeholder semantics.
193
194Other Query-owned options keep their current classification. Query key creation,
195adapter `select`, subscriptions, `notifyOnChangeProps`, and structural sharing
196remain adapter-owned or reinterpreted. No nested `queryOptions`, runtime binding
197API, subset deduplication, or lease manager is introduced by this design.
198
199## Rejected designs
200
201- **Forward both options mechanically.** `result.isSuccess` is true for a
202 placeholder observer result, so the current success handler would normalize
203 presentation-only data and give it durable-looking ownership.
204- **Tag placeholder rows and later promote or delete them.** Tags would have to
205 survive collisions with real rows, overlapping observers, local writes,
206 unload, GC, persistence, and hydration. Query's observer-local placeholder has
207 no collection-wide lifetime that can drive those transitions safely.
208- **Treat initial rows as unowned temporary rows.** Query considers initial data
209 real cached data. Bypassing normal ownership would leak rows or allow cleanup
210 of one Query to remove rows still represented by another.
211- **Seed every on-demand key from one value.** A collection-level initializer
212 cannot prove membership in arbitrary predicate/order/limit subsets.
213- **Create a wrapped response from selected rows.** A read projection is not an
214 inverse. Fabricating metadata, cursors, or edges corrupts Query cache meaning.
215- **Persist initializer functions.** Functions are not structured-clone safe and
216 are runtime configuration, not data.
217
218## Implementation and test sequence
219
220Each behavior PR should begin with the named failing or characterization tests.
221
2221. **Guard the existing boundary.** Add focused tests proving that explicit and
223 QueryClient-default `placeholderData` never materialize, never mark the
224 collection ready, and never survive dehydration as data. Characterize current
225 default `initialData` behavior in eager and on-demand modes. Then suppress
226 placeholder and on-demand initialization when constructing observers.
2272. **Add eager initial data.** Add the two flat typed fields and forward only
228 defined values so QueryClient defaults remain intact. Test static and function
229 values, fresh versus stale timestamps, synchronous readiness, fetch error,
230 cancellation, cleanup, an explicit on-demand configuration error, multiple
231 collections on one QueryClient, and same-key first-initializer-wins behavior.
2323. **Lock projection and writes.** Test raw arrays, direct-property wrapped
233 responses, and derived projections. Verify the full initial envelope remains
234 in Query cache, lawful direct writes preserve it, unlawful reverse projection
235 does not fabricate one, and server success reconciles rows.
2364. **Lock ownership.** Test initial-to-server row removal, overlapping ownership
237 with externally hydrated/persisted rows, GC/unload, remount within `gcTime`,
238 and late notification after cleanup. Reuse the existing ownership machinery;
239 do not add a second seed ownership map.
2405. **Lock persistence.** Dehydrate and `structuredClone` initial raw and wrapped
241 data; hydrate Query and DB state; verify ownership reconciliation and that no
242 function appears in Query metadata or adapter persistence metadata.
2436. **Document the shipped API.** Move the settled behavior into the Query Options,
244 row extraction, direct writes, on-demand, and persistence sections of the user
245 guide. Update RFC #1643 and close or narrow #346 only after these contracts ship.
246
247Placeholder materialization, subset-aware initialization, and a lawful general
248reverse projection are separate future proposals. None is a prerequisite for the
249minimal eager `initialData` API.