tsdf 18.3.1 → 18.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/offline.md CHANGED
@@ -109,6 +109,121 @@ A mutation is also queued while online when older mutations for the same entitie
109
109
 
110
110
  Queued mutations and pending resolutions are persisted through the store's own `persistentStorage.adapter`, and the cached entries they reference are protected from cache expiry until the queue is replayed or discarded. They are not migrated when a store's adapter changes: let the queue drain first. See [Changing a store's adapter](./persistent-storage.md#changing-a-stores-adapter).
111
111
 
112
+ The mutation promise resolves only after the queue write has settled, so a mutation is never reported as queued while its write is still in flight. If the storage adapter cannot write the queue at all (for example the browser lost its IndexedDB connection and a new one cannot be opened), the failure is reported through `onPersistentStorageError`, but the result is still `{ kind: 'queued' }`: the mutation stays queued in memory, its optimistic state stays visible, and it is replayed if the session recovers in the same page load. It is not on disk, so it is lost if the page is reloaded first. Treat an `onPersistentStorageError` call while offline as "pending changes may not survive a reload".
113
+
114
+ Without an active offline session — `getSessionKey()` returns `false`, or the [session gate](#session-gate) is closed — the same call runs as a plain online mutation: `mutation` is called, a success resolves with `{ kind: 'online', data }`, and a failure goes through the normal error handling (optimistic update rolled back, `onMutationError` called). Nothing is queued.
115
+
116
+ ## Health Check
117
+
118
+ The session is in offline mode for one of two causes: `network` (this device cannot reach the backend) or `outage` (the backend is reached but down). Browser `online` / `offline` events only cover part of the first one. For everything else the app usually has one health endpoint that answers both "this request failed: is it the network, an outage, or just this request?" and "are we back?". Wire it once with `offlineSession.healthCheck`:
119
+
120
+ ```ts
121
+ const storeManager = createStoreManager({
122
+ getSessionKey: () => currentTenantId ?? false,
123
+ errorNormalizer: normalizeError,
124
+ offlineSession: {
125
+ network: { enabled: true },
126
+ outage: { enabled: true },
127
+ healthCheck: {
128
+ check: async ({ signal }) => {
129
+ try {
130
+ const response = await fetch('/api/health', { signal });
131
+ return response.ok ? 'up' : 'outage';
132
+ } catch {
133
+ return 'unreachable';
134
+ }
135
+ },
136
+ },
137
+ },
138
+ });
139
+ ```
140
+
141
+ `check(ctx)` receives `{ sessionKey, signal }` and returns (or resolves to) one of:
142
+
143
+ | Answer | Meaning | As a failure classification | As a recovery check |
144
+ | --------------- | ---------------------------------------------- | --------------------------- | ------------------------------- |
145
+ | `'up'` | The backend answered and is healthy | The session stays online | Offline mode ends |
146
+ | `'outage'` | The backend was reached but is down | Outage mode becomes active | Outage mode (stays or replaces) |
147
+ | `'unreachable'` | The backend cannot be reached from this device | Network mode becomes active | Network mode (stays or returns) |
148
+
149
+ The session uses the same function in both places:
150
+
151
+ - **Failure classification.** When a fetch, a mutation or the replay of a queued mutation fails, the session runs the check and applies the answer.
152
+ - **Recovery checks.** While a mode is active because of a failure, its recovery probe runs the check on that mode's `recoveryProbe` cadence (network: 5s growing to 60s, outage: 30s growing to 5min by default). `'up'` ends the offline mode — both causes at once when both are active. `'outage'` during network mode means the device reaches the backend again but the backend is down: outage mode takes over, or, when outage mode is disabled, network mode just ends and requests (including the replay of queued mutations) fail with their own errors. `'unreachable'` during outage mode activates network mode and keeps the outage, since nothing can be said about it until the backend is reachable. With a health check, `outage.recoveryCheck` is optional.
153
+
154
+ In both places an answer only activates a mode that is enabled (`network.enabled` / `outage.enabled`, including runtime overrides). An answer for a disabled mode is ignored: a failed request is left to its own error.
155
+
156
+ ### `'up'` means the failure belongs to the request
157
+
158
+ When the check answers `'up'` for a failed request, the session stays online and that request's own failure handling applies, even if the endpoint it called is down. For example, an upload endpoint answering 503 while the API health check passes:
159
+
160
+ - a fetch or a direct mutation fails with its own error;
161
+ - a queued mutation being replayed goes through `classifyRetryableFailure` and the `replayRetry` budget, and ends in a `retry-exhausted` resolution (see [Conflict Resolution](#conflict-resolution)).
162
+
163
+ If the session should pause for that service instead, make `check` cover it (answer `'outage'` when it is down) or return `'outage'` for its failures from `classifyFailure`.
164
+
165
+ ### One request for many failures
166
+
167
+ While a check is in flight, every failure and recovery tick that needs an answer waits for that same call: a burst of requests failing right when the backend goes down costs one health request. Failures that arrive while the session is already in offline mode do not run the check at all — the active mode explains them, and asking "are we back?" is the job of the recovery checks.
168
+
169
+ A finished answer is never reused. A cached `'up'` could hide an outage that started right after it, so the next failure after a check has settled starts a new one. The check is never called on the success path.
170
+
171
+ ### With `classifyFailure` and `recoveryCheck`
172
+
173
+ The health check is the fallback; the more specific hooks win:
174
+
175
+ - `classifyFailure(error, ctx)` runs first. `'outage'`, `'network'` and `'ignore'` are final answers and the health check is not called for that failure. Return `'unknown'` when the error alone does not tell, to ask the health check. This keeps obvious request errors (validation, 404) from costing a health request:
176
+
177
+ ```ts
178
+ classifyFailure: (error) => (isClientError(error) ? 'ignore' : 'unknown'),
179
+ ```
180
+
181
+ Without `classifyFailure`, every failure asks the health check.
182
+
183
+ - A mode with its own `recoveryCheck` (`network.recoveryCheck` / `outage.recoveryCheck`) keeps using it for its recovery; the health check is the recovery check of the modes that do not have one.
184
+
185
+ ### When the check gives no answer
186
+
187
+ A check that throws, rejects, or takes longer than `healthCheck.timeoutMs` (default 10s) gives no answer and changes nothing: a failure being classified is left to its request, and a recovery check counts as "not recovered yet" and is retried on the normal cadence. `ctx.signal` is aborted on timeout so the health request can be cancelled. No answer is never read as `'unreachable'`: a broken or slow health endpoint is not evidence about connectivity, and the browser going offline is already detected by network mode. Return `'unreachable'` from `check` when the request itself fails, as in the example above.
188
+
189
+ The check is not called while the [session gate](#session-gate) is closed, or while both modes are disabled and neither is still active.
190
+
191
+ ## Reading While Offline
192
+
193
+ While the session is in offline mode, fetches are not sent to the server. What a document, item or query reports depends on whether it has data to return:
194
+
195
+ - **Cached data** (loaded earlier, or restored from persistent storage): the cached data stays visible with `status: 'success'` and `error: null`. A refetch attempted offline leaves it that way, so there is no offline error to hide in the UI.
196
+ - **Nothing cached**: the read fails with `status: 'error'` and the offline error `{ code: 0, id: 'offline', message: 'Offline' }`. This is the only offline state the app has to explain to the user.
197
+
198
+ Use `isOfflineStoreError(error)` to recognise that error instead of comparing `error.id` by hand. It matches the whole error shape, so an app error whose `errorNormalizer` also uses the `'offline'` id is not mistaken for it, and it narrows the error to the exported `OfflineStoreError` type:
199
+
200
+ ```tsx
201
+ import { isOfflineStoreError } from 'tsdf';
202
+
203
+ function UserName({ id }: { id: number }) {
204
+ const { data, error, isLoading } = userStore.useItem({ id });
205
+
206
+ if (isLoading) return <Spinner />;
207
+ if (isOfflineStoreError(error)) return <NotAvailableOffline />;
208
+ if (error) return <ErrorMessage error={error} />;
209
+
210
+ return <span>{data?.name}</span>;
211
+ }
212
+ ```
213
+
214
+ It also accepts the `StoreFetchError` returned by the `awaitFetch` methods, which resolve with the cached data while offline and with the offline error only when nothing is cached.
215
+
216
+ With [partial resources](./partial-resources.md), "cached" is decided per hook, by the `fields` it requests:
217
+
218
+ - A hook whose requested fields are all cached is a cached read: `status: 'success'`, `error: null`. Fields that were loaded and later invalidated count as cached — they stay visible and are refreshed after recovering.
219
+ - A hook requesting fields that were never loaded has nothing usable to return for them, so it reports `status: 'error'` with the offline error, without attempting a fetch. Its data stays hidden as it would be while loading (`data: null`, `items: []`), or stays visible with `loadingFields` when `showPartialAsRefetching` is enabled.
220
+
221
+ Both can be mounted for the same item or query at the same time: the hook waiting for missing fields does not disturb the one reading cached fields.
222
+
223
+ A cached list query that lost a row before one of the rows that are left (or every row) is not a cached read: it is not reported as a complete `success`. A list that only lost its last rows (e.g. to `maxItemBytes`) is still a cached read, with fewer rows. Hooks return the rows that are left with `status: 'error'` and the offline error (`isOfflineStoreError(error)`), so the screen can show them together with a notice that the list is incomplete. See [Cached list queries that lost rows](./persistent-storage.md#cached-list-queries-that-lost-rows).
224
+
225
+ Both kinds of reads are refetched once the session recovers (see below): reads that failed offline load, and cached reads get refreshed.
226
+
112
227
  ## Revalidation After Recovering
113
228
 
114
229
  While the session is in offline mode, automatic revalidations that could only fail are held: `onTransportReconnect()` signals and window-focus revalidations only re-check connectivity (`network.getIsOffline`) instead of refetching, and cached data stays visible. When the re-check finds the connection back, the session leaves offline mode and the stores revalidate as described below.
@@ -126,13 +241,14 @@ Mounted data refetches right away, unmounted data on its next mount. Stores with
126
241
  All offline operations define:
127
242
 
128
243
  - `inputSchema` - Validates mutation input before it enters the queue and again when restored.
129
- - `kind` - `create`, `update`, or `delete`; TSDF derives each affected entity's lifecycle from this.
244
+ - `kind` - `create`, `update`, or `delete`; TSDF derives each affected entity's lifecycle from this. Every item a `create` returns from `getEntityRefs` is treated as created by it (discarding a `create` without temp entity removes all of them), so return only the created items: change existing items in a separate `update` operation, and reference the items the creation needs with `dependsOn`.
130
245
  - `execute(ctx)` - Sends queued work to the server during replay.
131
246
 
132
247
  Collection and list-query operations also define:
133
248
 
134
249
  - `getEntityRefs({ input })` - Returns affected item/entity refs.
135
- - `dependsOn({ input })` - Optional dependencies on other offline entities.
250
+ - `dependsOn({ input })` - Optional dependencies on other offline entities of the same store.
251
+ - `cancelledWith({ input })` - Optional entities of other stores whose cancelled creation also drops this work. See [Deleting entities created offline](#deleting-entities-created-offline).
136
252
 
137
253
  Optional replay behavior:
138
254
 
@@ -143,8 +259,99 @@ Optional replay behavior:
143
259
  - `accumulation` - Merges newer queued inputs into an existing queued mutation.
144
260
  - `supersedes` - Prunes older queued work for the same entity.
145
261
 
262
+ Queued mutations and resolutions whose operation the running deploy doesn't define (for example ones queued by a newer deploy in another tab) stay in storage, together with their uploads, but that deploy neither lists nor replays them. A deploy that defines the operation picks them up and sends or resolves them. Apps are expected to reload tabs running an old deploy: TSDF doesn't coordinate the order of offline work between deploys, so an old tab can send its own edits around the work it keeps. Records of an operation removed from the app for good also stay in storage until the session's storage is cleared (`clearSessionStorage`), so keep an operation defined until its queued work is likely gone.
263
+
146
264
  Create flows for collection and list-query stores can use `tempEntity` or `tempEntities` to insert optimistic entities with temporary payloads and reconcile them to final server payloads after replay. Document stores do not support temp entities.
147
265
 
266
+ ### Temp Entities in List Queries
267
+
268
+ In a list-query store the pending entity is inserted as an item only, so it is not part of any list unless `optimisticListUpdates` rules match it. Declare `addToQueries` to add it to the lists that should show it while the mutation is queued:
269
+
270
+ ```ts
271
+ createUser: {
272
+ inputSchema: createUserInputSchema,
273
+ kind: 'create',
274
+ getEntityRefs: ({ input }) => [`temp:${input.clientId}`],
275
+ tempEntity: {
276
+ buildPendingEntity: (input) => ({ id: input.clientId, name: input.name }),
277
+ // Same shape as the `addItemToQueries` option of `addItemToState`,
278
+ // or a function of the mutation input that returns it
279
+ addToQueries: (input) => ({
280
+ queries: { teamId: input.teamId },
281
+ appendTo: 'start',
282
+ }),
283
+ reconcileServerEntity: (result) => ({
284
+ finalPayload: result.id,
285
+ finalData: result,
286
+ }),
287
+ },
288
+ execute: ({ input }) => api.createUser(input),
289
+ },
290
+ ```
291
+
292
+ - The entity is added to the queries when the mutation is queued, so `optimisticUpdate` does not need to call `addItemToState` for it. A mutation that runs online right away is never queued and creates no pending entity.
293
+ - `queries` follows `addItemToState`, except that queries saved in persistent storage but not loaded yet (after a restart, before a screen reads them) are loaded first, so the row also reaches them. A filter function only matches the queries the app session already knows, so prefer query payloads.
294
+ - The membership is stored with the queries, so the row is still in its lists after the app restarts with the mutation queued.
295
+ - When replay succeeds, the final server entity takes the place of the temp one in every query that still contains it. The declared queries that are only in persistent storage are loaded first: the function form of `addToQueries` runs again for this, so it should only depend on its arguments. Discarding the queued mutation removes the row from its lists.
296
+ - While the mutation is pending, a list refetch that does not return the row keeps it rendered at its last known position. This memory does not survive an app restart.
297
+
298
+ With `tempEntities`, each entry returned by `buildPendingEntities` declares its own `addToQueries`. The builder does not run again at replay, so a declared query that is only in persistent storage when the mutation is replayed gets the final entities on its next fetch.
299
+
300
+ With [partial resources](./partial-resources.md), the pending entity has no loaded-fields metadata, so only `inferFields` can vouch for it. Declare `loadedFields` (for example `'*'`) when the pending entity should count as loaded for hooks that read those fields: it cannot be fetched from the server before the mutation is replayed. The entity keeps the same loaded fields when it is reconciled to its final payload, so a `finalData` returned by the reconcile hook must hold at least those fields; omit `finalData` to keep the pending entity's data instead.
301
+
302
+ ```ts
303
+ tempEntity: {
304
+ buildPendingEntity: (input) => ({ id: input.clientId, name: input.name }),
305
+ addToQueries: { queries: { teamId: 'team-1' }, appendTo: 'start' },
306
+ loadedFields: '*',
307
+ // ...
308
+ },
309
+ ```
310
+
311
+ ### Deleting entities created offline
312
+
313
+ When the user deletes something that was created offline, the server may have never seen it. Declare this on the delete operation with `supersedes.dropSelfIfTempLifecycleCancelled`:
314
+
315
+ ```ts
316
+ deleteTask: {
317
+ kind: 'delete',
318
+ inputSchema: deleteTaskSchema,
319
+ getEntityRefs: ({ input }) => [input.itemId],
320
+ supersedes: { scope: 'same-entity', dropSelfIfTempLifecycleCancelled: true },
321
+ execute: async ({ input }) => {
322
+ try {
323
+ await api.deleteTask(input.itemId);
324
+ } catch (error) {
325
+ // The task is already gone: the delete is done
326
+ if (!isNotFoundError(error)) throw error;
327
+ }
328
+ },
329
+ },
330
+ ```
331
+
332
+ What happens depends on whether the creation was already sent:
333
+
334
+ - **Never sent** (still waiting in the queue, or held behind the creation of another entity that waits for a resolution): nothing is sent. TSDF drops the creation, the queued edits of the entity, the delete itself and the queued work that depends on the entity (`dependsOn`), then removes the temporary entity from the store and its lists. The same applies to a `create` of an item whose id the app generates on the client: the item is removed instead of a temporary entity.
335
+ - **Created together with other entities** (a `tempEntities` operation that creates several entities at once): the creation is never cancelled, since the other entities still need it. The delete is queued behind it and sent with the server id, as for a creation that was sent.
336
+ - **Sent** (`syncing`, `needs-confirmation`, queued again after a `retry`, or, for an id the app generates, queued after its direct online request failed or sent again with `requeue` after a conflict): the server may have the entity, so the creation is kept and the delete stays queued behind it. Once the server id is known the delete is sent with it. `execute` should treat a not-found answer as success, as above: the server answers not-found when the creation never reached it, or when an earlier delete attempt did.
337
+ - **Waiting for a manual resolution**: the creation is kept too, and the delete is held behind that resolution. See [Entities whose creation waits for a resolution](#entities-whose-creation-waits-for-a-resolution).
338
+
339
+ `getItemOfflineState(payload)` tells the first case apart before deleting: `isUnsentCreation && !creationAttempted` means the delete only discards local work, unless the item was created together with other entities. A temp entity whose creation was queued after its direct online request failed, or sent again with `requeue` after a conflict, is in that case too: an earlier request may have created a server item, but the temporary payload can't target it, so the delete leaves that item as is. This only covers temp entities: an item whose id the app generates reports `isUnsentCreation: false`, so it can't be told apart from a server item.
340
+
341
+ Work queued in **other stores** for the cancelled entity is not known to its store. Declare the relation with `cancelledWith` in the other store's operation:
342
+
343
+ ```ts
344
+ // comments store
345
+ addComment: {
346
+ kind: 'create',
347
+ // ...inputSchema, tempEntity, getEntityRefs, execute
348
+ // `tasks` is the `id` of the store that owns the task
349
+ cancelledWith: ({ input }) => [{ storeName: 'tasks', entityRef: input.taskId }],
350
+ },
351
+ ```
352
+
353
+ When the creation of that task is cancelled as above, or its manual resolution is discarded, the queued comments are dropped with it and their temporary entities are removed. A comment added with a client-generated id instead of a temporary entity is removed the same way when it was never sent, with the work queued on it and the work of other stores declared as `cancelledWith` it. `cancelledWith` only drives this cleanup: it does not delay replay or rewrite the input when the task gets its server id, and it only reaches stores that are instantiated in the tab where the cancellation happens.
354
+
148
355
  ## Conflict Resolution
149
356
 
150
357
  Stores expose resolution APIs:
@@ -160,7 +367,7 @@ await userStore.resolveOfflineResolution(resolutions[0].id, 'renameUser', {
160
367
 
161
368
  Supported resolution actions include:
162
369
 
163
- - `discard` - Drop the resolution record. The optimistic changes of the discarded mutation cannot be rolled back locally, so TSDF refetches what the operation referenced (`getEntityRefs`): the document, the collection item, or the list query item together with the store's lists (the change may have moved or removed the row). An entity that other changes still wait for a decision on is not refetched, since the refetch would replace those changes: it is revalidated once the last one is handled. Likewise, while other changes of a list query store still wait for a manual resolution, only the item is refetched: its lists are revalidated once the last one is handled. Discarding a temp create removes the temp entity and everything queued on top of it; existing entities changed on top of it are refetched.
370
+ - `discard` - Drop the resolution record. The optimistic changes of the discarded mutation cannot be rolled back locally, so TSDF refetches what the operation referenced (`getEntityRefs`): the document, the collection item, or the list query item together with the store's lists (the change may have moved or removed the row). An entity that other changes still wait for a decision on is not refetched, since the refetch would replace those changes: it is revalidated once the last one is handled. Likewise, while other changes of a list query store still wait for a manual resolution, only the item is refetched: its lists are revalidated once the last one is handled. Discarding a temp create removes the temp entity and everything queued on top of it; existing entities changed on top of it are refetched. Discarding a `create` without temp entity (the app generated the id on the client) removes the items it created (its `getEntityRefs`) from the store, its lists and the persisted cache, like a temp entity, instead of refetching them: a discarded creation is treated as never sent. If the server did create one (the response of an earlier replay attempt was lost, or a conflict reported that it already exists), it stays removed locally until something fetches it again: the recovery revalidation of a list query store's lists brings it back (right away when no other change waits for a decision, otherwise once the last one is handled), but a collection item, or a list query item outside every loaded list, shows `deleted` until it is fetched again, e.g. after a reload. Discarding a temp create has the same tradeoff. Unlike changes made on top of a temp entity, changes queued on such an item are not held behind its failed creation: they are sent on their own and need their own decision if the server rejects them. Until they are sent, their optimistic view keeps the item visible in its views, even though the discard removed it from the store.
164
371
  - `requeue` - Queue replacement input for an operation conflict.
165
372
  - `commit` - Accept an externally completed resolution result.
166
373
  - `retry` - Retry a retry-exhausted record.
@@ -169,6 +376,16 @@ A mutation that exhausted its replay retries leaves the queue when it becomes a
169
376
 
170
377
  Use `parseOfflineResolutionConflict(resolution)` to narrow a persisted resolution back to the operation-specific conflict/input type before rendering a manual resolution UI.
171
378
 
379
+ ### Entities whose creation waits for a resolution
380
+
381
+ While the creation of an entity made offline waits for a resolution, the server does not know the entity, so nothing else can be sent for it. The mutations that target or depend on it become blocked resolutions behind the creation (`blockedResolutionCount > 0`, error `Blocked by unresolved dependency`), whether they were queued before the creation failed or made afterwards, online or offline. `performMutation(...)` returns `{ kind: 'queued' }` for them and the optimistic update stays visible.
382
+
383
+ They follow the decision about the creation: `retry` (default scope) sends the creation again and then the blocked mutations with the server id, `discard` drops them with the creation. For a creation that hit a conflict, `requeue` sends them after the new creation, and `commit` sends them with the ref of the entity the result keeps. This includes a delete with `dropSelfIfTempLifecycleCancelled`: the creation may have reached the server, so it is not cancelled locally; the delete is sent after the creation is retried, or dropped when it is discarded.
384
+
385
+ A blocked mutation was never sent, so a later mutation of the same entity treats it like an unsent queued one: an `accumulation` operation merges into it, and a `supersedes` operation prunes it. This keeps the order the user made the changes in, e.g. moving a task under the waiting entity and then back under a server task sends only the second move, and retrying the creation does not move the task again. When the merged input no longer depends on the waiting entity, it is queued and sent right away. To make this possible, an online mutation of such an operation for an entity with blocked work is queued instead of sent directly. A mutation of an operation with neither `accumulation` nor `supersedes` does not touch the blocked one: it is sent first, and the blocked one is sent after it once the creation is retried.
386
+
387
+ When the merged input still depends on the waiting entity, the changes merged into it go with the decision about the creation too: discarding the creation also drops them, e.g. a rename of a server task merged into its held move under the waiting entity.
388
+
172
389
  ### Resolving From A Session-Wide UI
173
390
 
174
391
  An app-wide "sync problems" panel that lists `storeManager.useOfflineResolutions()` does not need to import every store to offer Retry / Discard. The manager applies the generic actions to any resolution of the session by finding the store that owns it:
@@ -243,6 +460,19 @@ Each store also exposes scoped APIs:
243
460
 
244
461
  List-query stores additionally expose `usePendingOfflineItems(...)`, which returns pending creates/updates and pending deletes without mounting or fetching a query.
245
462
 
463
+ ### Per-item state
464
+
465
+ Collection and list-query stores expose `useItemOfflineState(itemPayload)` / `getItemOfflineState(itemPayload)` for per-row UI such as sync badges. They return `null` when the item has nothing queued, otherwise `{ syncState, pendingMutations, requiresResolution, isUnsentCreation, creationAttempted }`:
466
+
467
+ ```tsx
468
+ const offlineState = userStore.useItemOfflineState({ id: 1 });
469
+ // null | { syncState: 'pending', pendingMutations: 1, requiresResolution: false, isUnsentCreation: false, creationAttempted: false }
470
+ ```
471
+
472
+ Prefer it over building a map from `useOfflineEntities()`: a component using the hook re-renders only when the state of its own item changes. `isUnsentCreation` is `true` for an item created offline until the server confirms it; after that the temporary payload returns `null` and the final payload reports the mutations still queued for the item. `creationAttempted` turns `true` once that creation starts being sent: before that, deleting the item only discards local work (see [Deleting entities created offline](#deleting-entities-created-offline)). See [Hooks - useItemOfflineState](./hooks.md#useitemofflinestate).
473
+
474
+ Document stores hold a single entity, so they do not need a per-item reader: use `useDocument().pendingSync` or `useOfflineEntities()[0]`.
475
+
246
476
  ## Multiple Tabs
247
477
 
248
478
  Tabs of the same session share one offline queue. Every tab can queue mutations and every tab shows the same pending state, but only one tab sends the queued work:
@@ -273,6 +503,35 @@ storeManager.resetOfflineRuntimeConfig();
273
503
 
274
504
  `getOfflineRuntimeConfig()` returns the current effective controls. Runtime updates are useful for explicit "work offline" toggles, diagnostics, or temporarily disabling queueing modes.
275
505
 
506
+ Disabling a mode only stops new work from entering it: an offline state that is already active is preserved so the work depending on it can still recover and replay. To turn the whole offline layer off, use the session gate instead.
507
+
508
+ ### Session gate
509
+
510
+ `offlineSession.enabled` turns the whole offline layer on and off at runtime — for a feature flag or a per-workspace setting — without recreating the store manager or its stores:
511
+
512
+ ```ts
513
+ const storeManager = createStoreManager({
514
+ getSessionKey: () => currentTenantId ?? false,
515
+ errorNormalizer: normalizeError,
516
+ offlineSession: {
517
+ enabled: () => featureFlags.offlineMode,
518
+ network: { enabled: true },
519
+ },
520
+ });
521
+ ```
522
+
523
+ While it returns `false` the session behaves as if no offline session existed:
524
+
525
+ - it never enters offline mode: network detection is ignored and neither `classifyFailure` nor `healthCheck` is called. The offline status reports `isOfflineMode: false`, and `getOfflineRuntimeConfig()` reports both modes as not enabled
526
+ - fetches always go to the network and fail with their normal errors
527
+ - mutations with an `offline` descriptor run as plain online mutations (see [Queuing Mutations](#queuing-mutations))
528
+
529
+ Mutations already queued when the gate closes are neither deleted nor replayed. They stay in persistent storage untouched, still listed by the offline entities / resolutions APIs, and are replayed once the gate reopens and the session is online. A queued mutation whose replay request fails because the gate closed mid-flight goes back to the queue as pending. Mutations made while the gate is closed go straight to the server, so they are not ordered after older mutations still waiting in the queue for the same entities: when that matters, close the gate only once the offline entities list is empty.
530
+
531
+ The callback is read before every fetch and every mutation with an `offline` descriptor, on browser `online` / `offline` events, before each recovery check and before each queued mutation is replayed, so it must be synchronous and cheap (read a variable or a store, no I/O). The app does not have to call anything for a flip to apply to the next fetch or mutation. To apply it right away — clear the offline status in the UI as soon as the gate closes, or start replaying the queue as soon as it reopens on an idle screen — call `storeManager.setOfflineRuntimeConfig({})` after changing the value: every runtime config update re-reads the gate. Runtime overrides and the upload helpers are not affected by the gate.
532
+
533
+ The tabs of a session key share its offline status and its replay, so `enabled()` must return the same value in every tab of that session key. A tab with the gate closed would clear an offline mode another tab still relies on, and a leading tab with the gate closed holds back the replay of every tab. To gate per workspace, include the workspace in the session key.
534
+
276
535
  ## Uploads
277
536
 
278
537
  Configure uploads on `offlineSession.uploads` when queued mutations depend on local files. The manager exposes upload helpers:
@@ -284,8 +543,73 @@ Configure uploads on `offlineSession.uploads` when queued mutations depend on lo
284
543
  - `resolveOfflineUpload(id)`
285
544
  - `resolveOfflineUploads(ids)`
286
545
  - `useOfflineUploads()`
546
+ - `useOfflineUploadFile(id)` — see [Rendering staged files](#rendering-staged-files)
547
+
548
+ Operations can declare `dependsOnUploads({ input })` and then read resolved upload refs from `execute({ uploads })`. When queued mutations are merged (`accumulation.mergeInput`), the dependencies are computed again from the merged input, so files referenced by any of the merged edits are uploaded before `execute` runs. `opfsOfflineUploadAdapter` is exported as a built-in OPFS-backed upload adapter.
549
+
550
+ ### Upload refs
287
551
 
288
- Operations can declare `dependsOnUploads({ input })` and then read resolved upload refs from `execute({ uploads })`. `opfsOfflineUploadAdapter` is exported as a built-in OPFS-backed upload adapter.
552
+ The value the `upload` transport resolves to is the upload ref: whatever the server needs to reference the uploaded file (a string, or an object such as `{ fileId, url }`). `createStoreManager` infers its type from the transport, so it does not have to be narrowed by hand:
553
+
554
+ ```ts
555
+ const uploadRefSchema = rc_object({ fileId: rc_string, url: rc_string });
556
+
557
+ const storeManager = createStoreManager({
558
+ getSessionKey: () => currentTenantId ?? false,
559
+ errorNormalizer: normalizeError,
560
+ offlineSession: {
561
+ uploads: {
562
+ adapter: opfsOfflineUploadAdapter,
563
+ // Resolves to `{ fileId: string; url: string }`.
564
+ upload: ({ file, onProgress }) => api.uploadFile(file, onProgress),
565
+ // Optional: validates refs restored from storage or other tabs.
566
+ resolvedRefSchema: uploadRefSchema,
567
+ },
568
+ },
569
+ });
570
+
571
+ // `{ fileId: string; url: string }`
572
+ type UploadRef = StoreManagerUploadRef<typeof storeManager>;
573
+
574
+ const result = await storeManager.resolveOfflineUpload(attachmentId);
575
+ if (result.ok) console.log(result.value.url);
576
+ ```
577
+
578
+ - `resolveOfflineUpload(id)`, `resolveOfflineUploads(ids)` and the `resolvedRef` of the `OfflineUpload` entries returned by `getOfflineUploads()` / `useOfflineUploads()` are typed with the inferred ref.
579
+ - Let the manager type be inferred. Annotating it as plain `StoreManager` (or its config as plain `OfflineSessionConfig`) replaces the inferred ref with the default `ValidPayload`. A manager with a typed ref is still accepted wherever a plain `StoreManager` is expected, including `storeManager` on every store.
580
+ - Stores are created with explicit type arguments, so TypeScript cannot carry the ref type from the `storeManager` option into `execute`. Pass it as the last type argument of `DefineDocumentOfflineOperations`, `DefineCollectionOfflineOperations` or `DefineListQueryOfflineOperations` (the single-operation `*OfflineOperationDefinition` aliases take it last too). Without it, operations keep the default `ValidPayload`:
581
+
582
+ ```ts
583
+ type UserOfflineOperations = DefineListQueryOfflineOperations<
584
+ User,
585
+ UsersQuery,
586
+ UserPayload,
587
+ { setAvatar: DefineOfflineOperation<{ id: number; uploadId: string }> },
588
+ UploadRef
589
+ >;
590
+
591
+ // In the operation definition:
592
+ dependsOnUploads: ({ input }) => [input.uploadId],
593
+ execute: ({ input, uploads }) => {
594
+ // `UploadRef | undefined`
595
+ const avatar = uploads.resolvedRefsById[input.uploadId];
596
+ if (!avatar) throw new Error('Missing avatar upload');
597
+
598
+ return api.setUserAvatar(input.id, avatar.fileId);
599
+ },
600
+ ```
601
+
602
+ #### Validating restored refs
603
+
604
+ A ref returned by the `upload` transport is trusted. A ref can also reach the session without going through the transport: it is persisted with the upload record, so it is read back from the upload adapter after a reload, and other browser tabs publish the refs they resolved. Either source can come from a different app version with a different ref shape.
605
+
606
+ Set `resolvedRefSchema` to validate those refs. It accepts the same schemas as an operation `inputSchema` (a `runcheck` type or a synchronous Standard Schema such as zod), and its output has to agree with what the transport returns: the inferred ref type is what both produce.
607
+
608
+ - Refs restored from the upload adapter are parsed once when their record is loaded, and refs received from another tab once per record version.
609
+ - A ref that fails the schema is dropped and its upload goes back to `pending`. The staged file is kept with the record, so the next `resolveOfflineUpload(s)` call or the replay of an operation that depends on the upload sends the file through the transport again and stores the new ref. The dependent operation is not failed, and `execute` never receives the invalid ref. The file uploaded under the old ref is not cleaned up by TSDF.
610
+ - The exception is a ref another tab sends when it deletes an upload that was already sent: its staged file is gone, so a ref that fails the schema can't be uploaded again, and its id stops resolving (`resolveOfflineUpload(s)` returns an unknown upload error).
611
+ - Queued operations only persist upload ids. Their refs are resolved when the operation replays, so they are covered by the same validation.
612
+ - Without `resolvedRefSchema`, restored refs are exposed as they were stored.
289
613
 
290
614
  ### Upload metadata
291
615
 
@@ -331,3 +655,132 @@ await storeManager.saveOfflineUpload({
331
655
  - Because it is read back from storage, it is typed as an unvalidated `ValidPayload`: parse it with a schema before using it, as above. Uploads staged without metadata reach the transport with `metadata: undefined`, so handle that case explicitly. This includes the ones persisted by older versions and files attached directly to a mutation with its `upload` option, which can't carry metadata.
332
656
  - `saveOfflineUpload` stores exactly the metadata it receives. `replaceOfflineUpload` keeps the metadata already saved for that id unless new `metadata` is passed. Both fail while that upload is queued or being sent.
333
657
  - Custom `OfflineUploadAdapter` implementations must persist and restore the record's `metadata` and `storeName` fields together with the rest of the record. `storeName` marks which store queued a file attached to a mutation. That file is removed once nothing in that store's queue uses it, and only while that store is created in the tab, so a store created later (for example on a code-split screen) still finds its files.
658
+
659
+ ### Upload lifecycle
660
+
661
+ A staged upload follows the queued work that depends on it:
662
+
663
+ - While a queue entry or resolution record declares the upload through `dependsOnUploads`, the upload is kept. This includes a failed mutation waiting for a manual resolution, so `retry` still finds the file. `deleteOfflineUpload(id)` returns an error for an upload in this state.
664
+ - When the last queue entry or resolution record that declares it leaves the queue, TSDF deletes the upload (its record and the stored file). It does not matter how the work ended:
665
+ - it replayed successfully, or `shouldSkipSync` dropped it;
666
+ - its resolution was discarded, together with the queued work discarded with it (the edits of an entity whose create was discarded);
667
+ - a later operation pruned it with `supersedes`, or cancelled it with its temp entity (`dropSelfIfTempLifecycleCancelled`);
668
+ - its conflict was resolved with `commit`, or with a `requeue` whose replacement input no longer declares the upload. Uploads the replacement input still declares are kept.
669
+ - References are session-wide. An upload declared by queued mutations of several stores is deleted only after the last of them is gone. Only stores created in the tab count: an upload staged with `saveOfflineUpload` and shared with a store that is not created in the tab yet (a code-split screen, or the app restarted on another screen) can be deleted when the stores already created release it, and that store's queued mutation then fails to replay. If an upload id is shared across lazily created stores, create those stores before their queued work replays, or stage a separate upload for each store. Files attached directly to a mutation don't have this limit: they record the store that queued them (see `storeName` above).
670
+ - An upload that no queued work declared yet is never deleted for being unreferenced: the app stages the file first and queues the mutation afterwards. It stays until a mutation that declares it is queued and leaves the queue, until the app calls `deleteOfflineUpload(id)`, or until it expires. Unreferenced uploads expire after the session has been online for one week without interruption (going offline restarts the window). This also applies to uploads the app resolves itself with `resolveOfflineUpload(s)` for an online mutation, because they never enter the queue.
671
+
672
+ After an upload that was already sent is deleted, its id keeps resolving to the same server ref for the rest of the app session, in every tab open when it was deleted: a mutation queued later that still declares it (for example from optimistic or draft data that was not updated with the server ref yet) replays with that ref without uploading again, and `resolveOfflineUpload(id)` returns it. This ref is kept in memory only: after a reload, in a tab opened later, or after `deleteOfflineUpload(id)`, the id is unknown again, so stage the file again with `saveOfflineUpload` before reusing it. Uploads deleted before they were sent (discarded, superseded or cancelled work) are not kept.
673
+
674
+ Files attached directly to a mutation (`upload: { ... }` in `performMutation`) belong to that single queued mutation and are deleted with it in the same situations.
675
+
676
+ ### Rendering staged files
677
+
678
+ An entity updated optimistically with a local file usually stores the staged upload id as its file ref. `storeManager.useOfflineUploadFile(id)` reads that staged file for rendering — also after a reload, when the object URLs the app created earlier are dead:
679
+
680
+ ```tsx
681
+ type FileRef =
682
+ | { kind: 'local'; uploadId: string }
683
+ | { kind: 'server'; url: string };
684
+
685
+ function Thumbnail({ file }: { file: FileRef }) {
686
+ // A falsy id disables the hook, so it is only used for local refs.
687
+ const staged = storeManager.useOfflineUploadFile(
688
+ file.kind === 'local' && file.uploadId,
689
+ );
690
+
691
+ if (file.kind === 'server') return <img src={file.url} />;
692
+ if (staged.status === 'success') return <img src={staged.url} />;
693
+
694
+ // `missing` / `error`: the local file is gone or unreadable.
695
+ return <FilePlaceholder isLoading={staged.status === 'loading'} />;
696
+ }
697
+ ```
698
+
699
+ The hook returns an `OfflineUploadFile`, a union narrowed by `status`:
700
+
701
+ - `status` — `idle` (falsy id), `loading`, `success`, `missing` (no upload with this id is staged in the active session) or `error` (the upload adapter failed to read the file; the read is tried again once every component stops using the id, or right away when the id is staged again)
702
+ - `url` — object URL of the staged file, managed by TSDF. Only set on `success`
703
+ - `file` — the staged `File`, for reading its contents. Only set on `success`
704
+ - `error` — the read failure. Only set on `error`
705
+
706
+ Caching and URL lifetime:
707
+
708
+ - Components using the same id share one read and one object URL, so the hook can be called from as many components as needed.
709
+ - A staged file the session already holds is returned on the first render, with no `loading` state. `loading` only shows while the session is still restoring its uploads (right after a reload) or reading an upload it does not hold yet.
710
+ - The URL exists while at least one component uses the id. It is revoked about one second after the last one stops using it (unmount or falsy id), so remounts and React StrictMode keep the same URL.
711
+ - `replaceOfflineUpload` gives every consumer in the tab a new `url` / `file` and revokes the previous URL. Staging or replacing the id from another tab does not update a file this tab already read until the tab reloads; deletions from another tab apply right away.
712
+ - When the upload leaves the session (`deleteOfflineUpload`, retention expiry, or a mutation-attached file being consumed) the status becomes `missing` and the URL is revoked. Staging the same id again makes it available again.
713
+ - Use `url` directly in render (`<img src>`, `<a href>`). Do not revoke it, do not keep it outside of render, and do not create extra object URLs from `file`.
714
+
715
+ The file follows the upload record, not its upload state: it stays available while the upload is `pending`, `uploading` and `uploaded`. To move from the local file to the uploaded one without a gap, derive the id from the entity as in the example above, and write the server ref into the entity when the mutation replays:
716
+
717
+ - Uploads staged with `saveOfflineUpload` are deleted once the last queued work that declares them leaves the queue (see [Upload lifecycle](#upload-lifecycle)). Files attached with `performMutation({ upload })` are removed once their mutation replayed. Uploads no queued work declared stay until `deleteOfflineUpload` or retention removes them.
718
+ - A replayed mutation releases its uploads after its `onSuccessExecute` ran (and, for a temp entity create, after the result replaced the temp entity). When `onSuccessExecute` writes the server ref into the entity, the local file stays renderable until that render, and from then on the component passes a falsy id and renders the server file.
719
+ - Otherwise the entity keeps the local ref until it is revalidated after replay, so the hook can report `missing` for a moment in between. The same happens for work `shouldSkipSync` drops, and in other tabs, whose entities keep the local ref until they refetch.
720
+
721
+ Outside of these windows, a local ref paired with `missing` means the staged file was deleted or expired, not that it is about to appear.
722
+
723
+ ### Upload failure handling
724
+
725
+ The `upload` transport reports a failure by rejecting (throwing). What happens next depends on who started the upload.
726
+
727
+ #### Dependency uploads during replay
728
+
729
+ When a queued operation with `dependsOnUploads` replays, a transport failure is classified by the same session hooks as a failed `execute`: `classifyFailure(error, ctx)` and then `classifyRetryableFailure(error, ctx)`. `ctx` is the context of the operation being replayed (`phase: 'sync'`, `storeType`, `operationName`, `sessionKey`) plus `uploadId`, the id of the upload that failed. `execute` is not called for that attempt. Other failures while resolving that upload, such as a storage error reading the staged file, are classified the same way with `uploadId` set, so check the error type instead of assuming every failure with `uploadId` came from the transport.
730
+
731
+ - **Connection problem or outage** - `classifyFailure` returns `'network'` or `'outage'` (and that mode is enabled, as for any other failure). The session enters that mode, the upload goes back to `pending` (with `lastError` set) and the operation stays queued. Replay runs the upload again when the session recovers. The replay retry budget is not consumed, however long the outage lasts.
732
+ - **Transient failure that is safe to repeat** - `classifyFailure` returns `'ignore'` and `classifyRetryableFailure` returns `true`. The upload goes back to `pending` and is sent again on the `replayRetry` cadence (`intervalMs`, 5s by default). After `maxFailures` attempts (3 by default) it is handled as a permanent failure.
733
+ - **Permanent failure** (file too large, type not accepted) - no hook recognizes the error, which is the default. The upload becomes `failed` and the operation moves right away to a `retry-exhausted` resolution: `lastReplayError` carries the upload error and `dependencyUploadIds` lists the uploads it depends on. Resolving it with `retry` requeues the operation, which runs the upload again; `discard` removes the operation and, when no other queued work declares the upload, deletes the staged file (see "Upload lifecycle").
734
+
735
+ `lastError` is cleared when an upload succeeds.
736
+
737
+ The hooks are the only way to tell these cases apart, so the transport must throw errors they can recognize:
738
+
739
+ ```ts
740
+ class UploadError extends Error {
741
+ kind: 'connection' | 'server-down' | 'rejected';
742
+
743
+ constructor(kind: UploadError['kind'], message: string) {
744
+ super(message);
745
+ this.kind = kind;
746
+ }
747
+ }
748
+
749
+ const storeManager = createStoreManager({
750
+ getSessionKey: () => currentTenantId ?? false,
751
+ errorNormalizer: normalizeError,
752
+ offlineSession: {
753
+ network: { enabled: true, recoveryCheck: pingApi },
754
+ outage: { enabled: true, recoveryCheck: pingApi },
755
+ classifyFailure: (error) => {
756
+ if (error instanceof UploadError) {
757
+ if (error.kind === 'connection') return 'network';
758
+ if (error.kind === 'server-down') return 'outage';
759
+ return 'ignore'; // rejected file: manual resolution
760
+ }
761
+
762
+ return classifyApiError(error);
763
+ },
764
+ uploads: {
765
+ adapter: opfsOfflineUploadAdapter,
766
+ // Throws `UploadError` with the kind that matches what went wrong.
767
+ upload: ({ file, onProgress }) => uploadFile(file, onProgress),
768
+ },
769
+ },
770
+ });
771
+ ```
772
+
773
+ Check `ctx.uploadId !== undefined` when a classifier needs to treat upload failures differently from `execute` failures that throw the same error type.
774
+
775
+ #### `resolveOfflineUpload(s)`
776
+
777
+ When the app uploads a staged file itself, a transport failure is returned to the caller as `Result.err(error)` and the upload becomes `failed` with `lastError` set. The session hooks are not consulted, the session mode does not change, and nothing is retried automatically: the caller decides what to do, and calling `resolveOfflineUpload(s)` again runs the upload again.
778
+
779
+ #### Upload states
780
+
781
+ - `pending` - staged and waiting to be uploaded, including uploads waiting for an automatic retry (those have `lastError` set).
782
+ - `uploading` - the transport is running.
783
+ - `uploaded` - the transport returned the final ref (`resolvedRef`).
784
+ - `failed` - the last attempt failed and TSDF will not retry on its own. A `failed` upload is never blocked: it is uploaded again the next time an operation that depends on it is replayed or `resolveOfflineUpload(s)` is called for it.
785
+
786
+ Queued mutations and staged uploads live in browser storage (localStorage, IndexedDB, OPFS), which the browser may evict under storage pressure unless the origin was granted persistent storage. TSDF does not request it: `navigator.storage.persist()` is an origin-wide permission and some browsers prompt for it, so the app should call it at a moment of its choosing (for example when the first change is queued).
@@ -143,6 +143,8 @@ If you enable `showPartialAsRefetching`, the hook exposes `loadingFields` with t
143
143
 
144
144
  Invalidations are refetches, not new loads: when an invalidation (full or per-field) marks cached data as stale, hooks whose requested fields are still present keep the stale data visible while the refetch is in flight (with a `refetching` status when `returnRefetchingStatus` is enabled). Data is only hidden behind `loading` when a requested field was genuinely never loaded.
145
145
 
146
+ While the session of an [offline-enabled store](./offline.md#reading-while-offline) is in offline mode, missing fields cannot be fetched. A hook requesting fields that were never loaded does not wait on `loading`: it reports `status: 'error'` with the offline error (`isOfflineStoreError(error)`), keeping its data hidden (or visible with `loadingFields` under `showPartialAsRefetching`). Hooks whose requested fields are all cached — including invalidated ones — keep returning them with `status: 'success'`. The missing and the invalidated fields are fetched once the session recovers.
147
+
146
148
  The same holds across reloads with persistent storage: an item invalidated before the page was closed is persisted with every field its snapshot still holds, and is restored as stale cached data: shown right away, then refetched on mount (a hook with a `fields` selection refetches only the fields it requests). An invalidated fully-loaded (`'*'`) item still satisfies `fields: '*'` reads from cache, which keeps it readable when the app is reopened offline.
147
149
 
148
150
  ## Fields in Scheduling and Fetching
@@ -194,4 +196,6 @@ It is the only availability signal for snapshots without `itemLoadedFields` meta
194
196
 
195
197
  Because it can vouch for any snapshot, `inferFields` must only report fields whose data is genuinely usable — inspect the item, don't return `'*'` unconditionally unless every snapshot your store can ever hold is complete. Staleness is not its concern: fields awaiting an invalidation refetch are excluded by TSDF before `inferFields` is consulted.
196
198
 
199
+ Offline temp entities are metadata-free too, and they cannot be fetched before their mutation is replayed: a hook that requests a field `inferFields` does not vouch for stays in `loading`. An `inferFields` that lists the fields present in the snapshot never returns `'*'`, so it cannot satisfy `fields: '*'` hooks. Declare the loaded fields of the pending entity in the offline operation instead (`tempEntity.loadedFields`, or `loadedFields` in each `tempEntities` entry) — see [Temp Entities in List Queries](./offline.md#temp-entities-in-list-queries).
200
+
197
201
  TSDF does not infer fields by checking object keys internally. If your field names are top-level properties, implement that rule explicitly in `inferFields` (excluding keys with `undefined` values); if your fields are logical or nested, return those logical field names instead.
@@ -167,6 +167,21 @@ persistentStorage: {
167
167
 
168
168
  Use `createIndexedDbPersistentStorage({ databaseName })` from `tsdf/indexed-db-storage` when an app needs an isolated IndexedDB database.
169
169
 
170
+ #### Connection recovery
171
+
172
+ Browsers can take an IndexedDB connection away from a page that keeps running: the storage process restarts, a backgrounded mobile tab comes back with a dead connection, or another tab upgrades or deletes the database. The adapter recovers without a page reload:
173
+
174
+ - A failed open is not remembered. The next operation opens the database again.
175
+ - When the browser closes the connection (`close`), or another tab needs it released (`versionchange`), the adapter closes and forgets it, so the other tab is not blocked. The next operation opens a new connection.
176
+ - When an operation fails with a connection error (`InvalidStateError`, `AbortError`, or `UnknownError`, e.g. WebKit's "Connection to Indexed Database server lost"), the adapter drops the connection, opens a new one, and runs the operation once more. Every adapter operation is a self-contained transaction that writes whole values, so repeating it never applies a batch twice or leaves half of it behind. Quota, data, and version errors are not retried.
177
+ - When IndexedDB stops answering — an open or a transaction delivers no event at all — the operation is treated like a lost connection after two consecutive checks, 15 seconds apart, during which no event of the same database reached the page while the tab was visible (30 to 45 seconds). Progress is what is measured, not total duration: a large batch on a slow device is never cut short in the tab running it. Only events reaching this page count, so an operation of another tab that waits more than 30 seconds behind that batch can still be given up and retried. A check interval during which the tab was hidden at any point, or the page was not running at all (frozen tab, sleeping device), does not count, so an operation is never given up the moment a page resumes.
178
+
179
+ If the second attempt also fails, the error is reported through `onPersistentStorageError`. Recovery depends on the browser accepting a new connection; some Safari versions refuse one until the page is reloaded, in which case each failing operation is reported instead of staying pending.
180
+
181
+ #### When a write fails
182
+
183
+ A persistence write that still fails after the recovery above is reported through `onPersistentStorageError` and dropped. In-memory store state is not affected and the app keeps working; the entry keeps its previous persisted value (or stays absent) until the store saves it again. See [Offline](./offline.md#queuing-mutations) for what this means for queued mutations.
184
+
170
185
  ### Custom async adapters
171
186
 
172
187
  Use `createAsyncStorageAdapter(driver)` only when the built-in OPFS and IndexedDB adapters are not a fit. It wraps an `AsyncStorageDriver`, which is the low-level async backend contract used by TSDF persistence internals.
@@ -290,6 +305,7 @@ const settingsStore = createDocumentStore<Settings>({
290
305
  - `local-sync`: ~1 week old entries
291
306
  - `opfsPersistentStorage`: ~2 weeks old entries
292
307
  - `indexedDbPersistentStorage`: ~2 weeks old entries
308
+ - Queued offline mutations and unresolved offline resolutions never expire, in any adapter.
293
309
  - Entries referenced by queued offline mutations are protected from expiry until that queued work is replayed or discarded.
294
310
  - Expiry runs for an adapter only while at least one store uses it, and then covers every entry in that adapter, including ones left by stores that moved elsewhere. See [Changing a store's adapter](#changing-a-stores-adapter).
295
311
 
@@ -332,6 +348,20 @@ When the selected adapter does not support async preload, preload methods report
332
348
  - Can be an explicit list or predicate.
333
349
  - Takes precedence over pinned lists.
334
350
 
351
+ ### Cached list queries that lost rows
352
+
353
+ Items and queries are stored and evicted separately, so a cached list query can outlive some of its rows: `maxItemBytes` evicts the least recently read item entries while the query entry stays, and an item entry that fails `schema` (or is now covered by `ignoreItems`) is discarded when it is read.
354
+
355
+ A cached query is restored as a loaded query (`status: 'success'`, shown immediately and revalidated in the background) when every row it was saved with can be restored, or when only its last rows are missing: like a list cut by `maxQuerySize`, the rows that are left are restored as a loaded list with `hasMore: true`. This is what happens to a list larger than `maxItemBytes`: the budget evicts its last rows right after it is saved.
356
+
357
+ Eviction follows read recency, not the order of the rows in a list. A list larger than `maxItemBytes` is restored as loaded on the first start after its last rows were cut, but once an online refetch saves it again, the rows that were rewritten look more recent than the unchanged ones, so the budget can evict earlier rows instead. The next start then restores it as a list with a gap (see below). To keep such a list restorable, raise `maxItemBytes` or lower `maxQuerySize`.
358
+
359
+ When a row before one of the rows that are left is missing, or no row is left, the rows that are left are still restored, but the query is not restored as loaded (`wasLoaded: false`), so the list with a gap — or an empty list — is never presented as the complete one:
360
+
361
+ - Online, hooks report `status: 'loading'` and fetch the query right away, as for a query that was never cached. The remaining rows are available in `items` meanwhile (stores using [Partial Resources](./partial-resources.md) hide items while loading, as usual).
362
+ - Offline, the fetch fails with the offline error: hooks report `status: 'error'` with `error.id === 'offline'` and the remaining rows in `items`, so a screen can show what is left of the list together with a notice that it is incomplete. `awaitListQueryFetch` returns the offline error instead of the incomplete list. A loaded list doesn't load more rows from such a cached list while offline (`loadMore` is skipped and `hasMore` is `false`), since its next rows may come after a missing one.
363
+ - The stored query is left as it is until the list is fetched again, so the next start sees the same state. With `local-sync`, the query entry rewritten after an eviction lists only the rows that are left, and is flagged (`"m": true`) as incomplete unless only its last rows were evicted (then it is saved with `"h": true`).
364
+
335
365
  ## Clearing stored data
336
366
 
337
367
  - `clearSessionStorage(sessionKey, adapter)`: