Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(replica): remove every query variant, resource-wide clear, and guard late hydrates/errors (#20754)

Arvin Xucb76e4e38746
diff --git a/packages/replica/README.md b/packages/replica/README.md
index b001c173319..c0cf1e0ac9f 100644
--- a/packages/replica/README.md
+++ b/packages/replica/README.md
@@ -51,6 +51,22 @@ A persisted read is asynchronous, so a list hydrated only by `useSync` paints it
Inside LobeHub, use `@/libs/replica`. It presets the cache scope, IndexedDB / localStorage storage and the app's SWR driver.
+## Invalidation
+
+Persisted rows are kept per entry key **and** per query (`key?<query>`), so a resource can hold several rows for one key. Never delete through a plain `set` or by clearing SWR keys: the persisted rows survive and a reload paints the deleted data. Use the primitive that matches what is gone:
+
+| What is gone | Call | What it does |
+| ------------------------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| One entity (a deleted topic, file, memory) | `linkReplicaEntity(...).remove(id)` / `slice.removeEntity(id)` | Drops it from every loaded entry and from persisted rows of unloaded entries. A value hydrated later β€” even by a read already in flight β€” comes back without it until a server value holds it again. |
+| One entry key, under every filter / sort | `slice.remove(key)` | Drops the entry and every persisted query variant of the key. No variant hydrates again until a server `replace` for the key supersedes the removal. |
+| The whole resource ("delete all", a reset) | `slice.clear()` / `linkReplicaEntity(...).clear()` | Empties memory in one commit, deletes every persisted row and the index of the active scope, and drops hydrates and `useSync` responses that started before it. Resolves `true` once storage is purged. |
+
+`slice.updateEntity(id, (item) => undefined)` also drops the entity from loaded values and persisted rows, but it is a plain patch: only `removeEntity` (which `linkReplicaEntity.remove` and an optimistic `'remove'` call) guards hydrates already in flight.
+
+A `ReplicaStorage` must reject from `remove` when a delete did not land, and should implement `getStrict` (a read that rejects on I/O failure) so an unreadable index fails a purge instead of passing for an empty one. `get` and `set` stay best-effort. The engine then keeps the row indexed and the removal unpurged, so the next `remove(key)` / `clear()` retries it.
+
+Prefer the narrowest call: an entity delete keeps the rest of every list; `remove(key)` is for a key whose whole value is gone or denied (NOT_FOUND / FORBIDDEN); `clear()` is for flows that invalidate everything the user has of that resource. `clear()` does not refetch: mounted views show their loading state until the next sync, so call `slice.revalidate()` after it when the server still has data to show.
+
## Transcripts and other irregular pages
Message-like resources page backward by cursor, with windows whose length changes on every refresh. The paging config covers them:
diff --git a/packages/replica/src/core/defineReplica.ts b/packages/replica/src/core/defineReplica.ts
index 16069c06ec5..e3b8111f037 100644
--- a/packages/replica/src/core/defineReplica.ts
+++ b/packages/replica/src/core/defineReplica.ts
@@ -4,6 +4,28 @@ import type { ReplicaResource, ReplicaScope, ReplicaStorage } from './types';
/** Persisted row key: one row per entry key and query. */
export const replicaStorageKey = (key: string, query?: string) => (query ? `${key}?${query}` : key);
+/**
+ * Whether `storageKey` is a persisted row of entry `key`, under any query.
+ *
+ * Entry keys are free-form, so a `?` prefix alone cannot tell `foo` + a query
+ * from a plain entry `foo?bar`. A row only counts as a variant when it is
+ * exactly `replicaStorageKey(key, query)` for a query this module could have
+ * written: the rest after `key?` must be a canonical `stableQueryKey` (it
+ * parses as JSON and serializes back to itself). Row keys and the index keep
+ * their existing flat format, so rows already persisted on devices match the
+ * same way.
+ */
+export const isReplicaStorageKeyOf = (storageKey: string, key: string): boolean => {
+ if (storageKey === key) return true;
+ if (!storageKey.startsWith(`${key}?`)) return false;
+ const query = storageKey.slice(key.length + 1);
+ try {
+ return stableQueryKey(JSON.parse(query)) === query;
+ } catch {
+ return false;
+ }
+};
+
/** Deterministic JSON: sorted keys, `undefined` dropped. */
export const stableQueryKey = (value: unknown): string =>
JSON.stringify(value, (_key, item) =>
diff --git a/packages/replica/src/core/engine.ts b/packages/replica/src/core/engine.ts
index f07fb452571..94aca68e07b 100644
--- a/packages/replica/src/core/engine.ts
+++ b/packages/replica/src/core/engine.ts
@@ -1,6 +1,6 @@
import isEqual from 'fast-deep-equal';
-import { replicaStorageKey, stableQueryKey } from './defineReplica';
+import { isReplicaStorageKeyOf, replicaStorageKey, stableQueryKey } from './defineReplica';
import {
applyHeadPage,
applyNextPage,
@@ -175,6 +175,47 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const markPurged = (scope: string, key: string) => purgedEntries.add(scope, key);
const isPurged = (scope: string, key: string) => purgedEntries.has(scope, key);
+ // ---- entity removal guards ---------------------------------------------
+ // A hydrate that read its row before `removeEntity` patched storage still
+ // holds the entity, so it is stripped from every value that hydrates while
+ // such a read may be pending. A guard's lifetime follows the hydrates, not a
+ // count: it is released once its storage patch landed (`releasedAt`) and is
+ // dropped as soon as no hydrate that started before that point is pending.
+ // So memory stays bounded by in-flight reads, and no guard a pending read
+ // still needs is ever evicted. A server value holding the entity again
+ // (restored) lifts it early.
+ /** Logical clock shared by hydrate starts and guard releases. */
+ let guardClock = 0;
+ /** Start ticks of the hydrates in flight, per scope. */
+ const pendingHydrates = new Map<string, Set<number>>();
+ /** Removed entity ids per scope; `releasedAt` is unset until the storage patch landed. */
+ const removedEntities = new Map<string, Map<string, { releasedAt?: number }>>();
+ const removedIds = (scope: string) => [...(removedEntities.get(scope)?.keys() ?? [])];
+
+ /** Drop the guards no pending hydrate of `scope` can still need. */
+ const pruneEntityGuards = (scope: string) => {
+ const guards = removedEntities.get(scope);
+ if (!guards) return;
+ let oldestPending = Infinity;
+ for (const start of pendingHydrates.get(scope) ?? [])
+ oldestPending = Math.min(oldestPending, start);
+ for (const [id, guard] of guards)
+ if (guard.releasedAt !== undefined && guard.releasedAt <= oldestPending) guards.delete(id);
+ if (guards.size === 0) removedEntities.delete(scope);
+ };
+
+ // ---- resource-wide clear ----------------------------------------------
+ /** Bumped by every `clear()` of a scope; reads started before it are stale. */
+ const clearGenerations = new Map<string, number>();
+ const clearGeneration = (scope: string) => clearGenerations.get(scope) ?? 0;
+ /**
+ * The persisted-row purge of the last `clear()` per scope: `true` once every
+ * row delete landed. A hydrate waits for it, and refuses to read while the
+ * purge failed (an untrusted scope, a storage error) so a wiped resource can
+ * never paint a row that survived it.
+ */
+ const scopePurges = new Map<string, Promise<boolean>>();
+
const getSlot = port.getState;
const storageKey = (key: string, query?: string) => ({
queryKey: replicaStorageKey(key, query),
@@ -194,31 +235,128 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
/** Keys known to be in the index row, per scope (skips redundant index writes). */
const indexed = new Map<string, Set<string>>();
- const trackStorageKey = (scope: string, queryKey: string, present: boolean) => {
+ /**
+ * Latest queued write per row (`scope` + storage key), from one monotonic
+ * counter. A confirmed delete only takes its key out of the index when no
+ * later write re-created the row in the meantime.
+ */
+ const rowWrites = new Map<string, number>();
+ let writeCounter = 0;
+ const rowId = (scope: string, queryKey: string) => `${scope}\u0000${queryKey}`;
+ const noteWrite = (scope: string, queryKey: string) => {
+ const seq = ++writeCounter;
+ rowWrites.set(rowId(scope, queryKey), seq);
+ return seq;
+ };
+
+ /** Record a persisted row in the index (queued after the row write). */
+ const trackStorageKey = (scope: string, queryKey: string) => {
if (!writeQueue) return;
+ noteWrite(scope, queryKey);
const known = indexed.get(scope) ?? new Set<string>();
indexed.set(scope, known);
- // `known` only holds the keys THIS instance wrote. A row an earlier session
- // persisted is absent from it yet still listed in the index, so an addition
- // already made needs no second write, but a removal must always reach the
- // index β€” the updater leaves it alone when the key is genuinely gone.
- if (present && known.has(queryKey)) return;
- if (present) known.add(queryKey);
- else known.delete(queryKey);
+ if (known.has(queryKey)) return;
+ known.add(queryKey);
writeQueue.update(indexKey(scope), (current) => {
const keys = new Set((current?.data as unknown as string[] | undefined) ?? []);
- if (keys.has(queryKey) === present) return undefined;
- if (present) keys.add(queryKey);
- else keys.delete(queryKey);
+ if (keys.has(queryKey)) return undefined;
+ keys.add(queryKey);
return { data: [...keys] as unknown as TData, updatedAt: Date.now() };
});
};
+ /**
+ * Read the index for a destructive pass (remove / clear / entity patch).
+ * Uses the storage's strict read when it has one, so an unreadable index
+ * rejects instead of looking empty β€” a purge must never report success for
+ * rows it could not enumerate.
+ */
const readIndex = async (scope: string): Promise<string[]> => {
- const row = await resource.storage?.get(indexKey(scope));
+ const storage = resource.storage!;
+ // Call through `storage`: a class-based storage needs its receiver.
+ const row = await (storage.getStrict
+ ? storage.getStrict(indexKey(scope))
+ : storage.get(indexKey(scope)));
return (row?.data as unknown as string[] | undefined) ?? [];
};
+ /**
+ * Drop storage keys from the index (both the session's view of it and the
+ * persisted row, which may list keys this session never wrote).
+ */
+ const untrackStorageKeys = (scope: string, queryKeys: string[]) => {
+ if (!writeQueue || queryKeys.length === 0) return;
+ const known = indexed.get(scope);
+ for (const queryKey of queryKeys) known?.delete(queryKey);
+ const dropped = new Set(queryKeys);
+ writeQueue.update(indexKey(scope), (current) => {
+ const keys = (current?.data as unknown as string[] | undefined) ?? [];
+ const next = keys.filter((queryKey) => !dropped.has(queryKey));
+ if (!current || next.length === keys.length) return undefined;
+ return { data: next as unknown as TData, updatedAt: Date.now() };
+ });
+ };
+
+ /** Take rows whose delete landed out of the index, unless rewritten since. */
+ const confirmDeleted = (scope: string, deleted: [queryKey: string, seq: number][]) => {
+ const gone = deleted
+ .filter(([queryKey, seq]) => rowWrites.get(rowId(scope, queryKey)) === seq)
+ .map(([queryKey]) => queryKey);
+ for (const queryKey of gone) rowWrites.delete(rowId(scope, queryKey));
+ untrackStorageKeys(scope, gone);
+ };
+
+ /**
+ * Queue row deletes now (ordered before any later write to the same rows).
+ * A key leaves the index only once its delete is confirmed: a failed delete
+ * stays indexed, so the next `remove` / `clear` finds and retries it.
+ * Resolves `true` when every delete landed.
+ */
+ const deleteRows = (scope: string, queryKeys: string[]): Promise<boolean> => {
+ const queue = writeQueue!;
+ const queued = queryKeys.map((queryKey) => {
+ const seq = noteWrite(scope, queryKey);
+ return queue
+ .remove({ queryKey, scope })
+ .then((removed): [string, number] | undefined => (removed ? [queryKey, seq] : undefined));
+ });
+ return Promise.all(queued).then((results) => {
+ confirmDeleted(
+ scope,
+ results.filter((result): result is [string, number] => !!result),
+ );
+ return results.every(Boolean);
+ });
+ };
+
+ /**
+ * Delete every persisted row of entry `key` in `scope` β€” `current` (the row
+ * memory knows about, queued right away so it orders before any later write)
+ * plus every other query variant the index lists. Resolves `true` once all
+ * deletes landed.
+ */
+ const removeStoredVariants = (scope: string, key: string, current: string) => {
+ const first = deleteRows(scope, [current]);
+ const rest = readIndex(scope).then(
+ (persisted) => {
+ // A server value that superseded the removal while the index was read
+ // owns its (fresh) row: keep it, delete only the stale variants.
+ const slot = getSlot();
+ const live = !isRemoved(scope, key) && slot.scope === scope ? slot.entries[key] : undefined;
+ const liveKey = live && replicaStorageKey(key, live.query);
+ const variants = new Set(
+ [...(indexed.get(scope) ?? []), ...persisted].filter(
+ (queryKey) =>
+ queryKey !== current && queryKey !== liveKey && isReplicaStorageKeyOf(queryKey, key),
+ ),
+ );
+ return variants.size === 0 ? true : deleteRows(scope, [...variants]);
+ },
+ () => false,
+ );
+ return Promise.all([first, rest]).then((results) => results.every(Boolean));
+ };
+
const runEffects = (effects: ReplicaEffect<TData>[]) => {
if (!writeQueue || effects.length === 0) return;
// Until identity resolves the scope is a guess; never write into it.
@@ -232,10 +370,11 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
// the delete (a closed IndexedDB, a quota error) must leave the key
// unpurged, so the next terminal answer retries it instead of letting a
// stale row survive to hydrate again.
- void writeQueue.remove(key).then((removed) => {
+ // Every query variant goes: a row persisted under other filters would
+ // otherwise hydrate the removed entry once the guard is superseded.
+ void removeStoredVariants(effect.scope, effect.key, key.queryKey).then((removed) => {
if (removed) markPurged(effect.scope, effect.key);
});
- trackStorageKey(effect.scope, key.queryKey, false);
continue;
}
const data = toPersisted(effect.data);
@@ -243,12 +382,11 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
if (data === null) {
// Server-confirmed absence: remove the prior projection rather than
// leaving it to be hydrated as if the value were still current.
- writeQueue.remove(key);
- trackStorageKey(effect.scope, key.queryKey, false);
+ void deleteRows(effect.scope, [key.queryKey]);
continue;
}
writeQueue.set(key, { data, updatedAt: Date.now() });
- trackStorageKey(effect.scope, key.queryKey, true);
+ trackStorageKey(effect.scope, key.queryKey);
}
};
@@ -321,15 +459,39 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
// A removed entry is not read back: only a later server value supersedes
// the removal (see `replace`), so a stale row can never repaint it.
if (isRemoved(scope, key)) return false;
+ // Pending until settled: entity guards outlive every read that may hold them.
+ const start = ++guardClock;
+ const pending = pendingHydrates.get(scope) ?? new Set<number>();
+ pendingHydrates.set(scope, pending);
+ pending.add(start);
+ try {
+ return await readAndHydrate(params, key, scope);
+ } finally {
+ pending.delete(start);
+ if (pending.size === 0) pendingHydrates.delete(scope);
+ pruneEntityGuards(scope);
+ }
+ };
+
+ const readAndHydrate = async (params: TParams, key: string, scope: string) => {
+ const storage = resource.storage!;
+ // A read started before a `clear()` of this scope holds a wiped row.
+ const generation = clearGeneration(scope);
+ // After a `clear()`, read only once its row deletes landed.
+ const purge = scopePurges.get(scope);
+ if (purge && !(await purge)) return false;
const query = resource.query(params);
- const cached = await resource.storage.get({ ...storageKey(key, query), scope });
+ const cached = await storage.get({ ...storageKey(key, query), scope });
if (!cached) return false;
- // Re-check after the read: a removal that landed while it was in flight must
- // not resurrect the row it just dropped.
- if (isRemoved(scope, key)) return false;
+ // Re-check after the read: a removal or a clear that landed while it was in
+ // flight must not resurrect the row it just dropped.
+ if (isRemoved(scope, key) || clearGeneration(scope) !== generation) return false;
if (options.isHydratable && !options.isHydratable(cached.data, params)) return false;
+ // Entities deleted while the read was in flight may still be in the row.
+ const data = withoutRemovedEntities(scope, cached.data);
+ if (data === undefined) return false;
return dispatch({
- data: cached.data,
+ data,
key,
params,
query,
@@ -390,7 +552,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
const reset = entry
? entry.query !== query
: paging !== undefined && !viewMatchesFields(port.read(key), params);
- return dispatch({
+ const applied = dispatch({
data: (confirmed) =>
paging
? mergeHead(key, incoming, confirmed, params, reset)
@@ -403,6 +565,8 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
scope,
type: 'replace',
});
+ if (applied) forgetRestoredEntities(scope, getConfirmed(key));
+ return applied;
};
/** Confirmed local write: patches the view (and the base under any overlay). */
@@ -436,9 +600,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return false;
}
if (!resource.scope.canPersist()) return false;
- const target = { ...storageKey(key), scope };
- trackStorageKey(scope, target.queryKey, false);
- void writeQueue.remove(target).then((removed) => {
+ void removeStoredVariants(scope, key, storageKey(key).queryKey).then((removed) => {
if (removed) markPurged(scope, key);
});
return true;
@@ -480,6 +642,44 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
runEffects([{ data, key, query: getSlot().entries[key]?.query, scope, type: 'persist' }]);
};
+ /**
+ * Wipe the resource in the active scope: every entry leaves memory in one
+ * host commit, every persisted row (all keys, all query variants) and the
+ * index are deleted, and reads already in flight are dropped β€” a hydrate
+ * started before the clear never dispatches, and `useSync` discards head
+ * responses whose request started before it. Requests started afterwards
+ * apply normally. Resolves `true` once the persisted rows are gone.
+ */
+ const clear = (): Promise<boolean> => {
+ const scope = resource.scope.get();
+ clearGenerations.set(scope, clearGeneration(scope) + 1);
+ port.commit([{ type: 'clear' }], { entries: {}, scope }, `${prefix}/clear`);
+ const purge = purgeScope(scope);
+ scopePurges.set(scope, purge);
+ return purge;
+ };
+
+ /** Delete every persisted row of `scope` (see `clear`). */
+ const purgeScope = async (scope: string): Promise<boolean> => {
+ if (!writeQueue) return true;
+ // Until identity resolves the scope is a guess; never write into it.
+ if (!resource.scope.canPersist()) return false;
+ // Rows this session knows about are queued now, ahead of any later write.
+ const queued = deleteRows(scope, [...(indexed.get(scope) ?? [])]);
+ let persisted: string[];
+ try {
+ persisted = await readIndex(scope);
+ } catch {
+ return false;
+ }
+ // Keys this session tracks are already queued above, or were written by a
+ // newer response since the clear (their row is fresh): skip both.
+ const known = indexed.get(scope);
+ const stale = persisted.filter((queryKey) => !known?.has(queryKey));
+ const [first, rest] = await Promise.all([queued, deleteRows(scope, stale)]);
+ return first && rest;
+ };
+
const revalidate = (key?: string): Promise<unknown> =>
options.revalidate ? options.revalidate(key) : Promise.resolve();
@@ -619,12 +819,43 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return entity.map(data, id, fn);
};
+ /** Which of `ids` are held by `data`. */
+ const heldEntities = (data: TData, ids: string[]): string[] => {
+ if (paging) {
+ const items = (data as unknown as ReplicaPagedData<unknown, unknown>).items ?? [];
+ const present = new Set(items.map((item) => paging.getId(item)));
+ return ids.filter((id) => present.has(id));
+ }
+ const entity = options.entity;
+ return entity ? ids.filter((id) => entity.has(data, id)) : [];
+ };
+
+ /** Strip entities removed in `scope` from a value read back from storage. */
+ const withoutRemovedEntities = (scope: string, data: TData): TData | undefined => {
+ const removed = removedIds(scope);
+ if (removed.length === 0) return data;
+ let next: TData | undefined = data;
+ for (const id of heldEntities(data, removed)) {
+ next = mapEntity(next!, id, () => undefined);
+ if (next === undefined) break;
+ }
+ return next;
+ };
+
+ /** A server value holding a removed entity again (restored) lifts its guard. */
+ const forgetRestoredEntities = (scope: string, data: TData | undefined) => {
+ const removed = removedIds(scope);
+ if (removed.length === 0 || data === undefined) return;
+ const guards = removedEntities.get(scope)!;
+ for (const id of heldEntities(data, removed)) guards.delete(id);
+ if (guards.size === 0) removedEntities.delete(scope);
+ };
+
/**
* Apply an entity change to persisted rows that memory does not hold (the
* memory path already persists loaded entries). Read-modify-write runs in
* the per-key write queue, so it sees every earlier write; a missing row is
- * never recreated. Resolves once the index has been read and the patches
- * are queued.
+ * never recreated. Resolves once the patches have settled.
*/
const patchStoredEntity = async <TItem>(
id: string,
@@ -638,30 +869,48 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
? Object.entries(slot.entries).map(([key, entry]) => storageKey(key, entry.query).queryKey)
: [],
);
- const keys = await readIndex(scope);
+ let keys: string[];
+ try {
+ keys = await readIndex(scope);
+ } catch (error) {
+ // Rows cannot be enumerated: nothing to patch. Loaded entries are already
+ // updated, and a removal still guards later hydrates (`removeEntity`).
+ console.error(`[replica:${resource.name}] failed to read the persisted index`, error);
+ return;
+ }
// Identity changed while reading the index: those rows are not ours to touch.
if (resource.scope.get() !== scope) return;
+ const patches: Promise<void>[] = [];
for (const queryKey of keys) {
if (loaded.has(queryKey)) continue;
- writeQueue.update({ queryKey, scope }, (current) => {
- if (!current) return undefined;
- const next = mapEntity(current.data, id, fn);
- if (next === current.data) return undefined;
- if (next === undefined) {
- trackStorageKey(scope, queryKey, false);
- return null;
- }
- return { data: next, updatedAt: Date.now() };
- });
+ const seq = noteWrite(scope, queryKey);
+ let dropped = false;
+ const patch = writeQueue
+ .update({ queryKey, scope }, (current) => {
+ if (!current) return undefined;
+ const next = mapEntity(current.data, id, fn);
+ if (next === current.data) return undefined;
+ if (next === undefined) {
+ dropped = true;
+ return null;
+ }
+ return { data: next, updatedAt: Date.now() };
+ })
+ .then((written) => {
+ if (written && dropped) confirmDeleted(scope, [[queryKey, seq]]);
+ });
+ patches.push(patch);
}
+ await Promise.all(patches);
};
- const updateEntity = <TItem>(
+ /** `updateEntity`, returning the persisted-row patch (if any) to wait on. */
+ const applyEntity = <TItem>(
id: string,
fn: (item: TItem) => TItem | undefined,
{ persist = true }: { persist?: boolean } = {},
- ) => {
- if (persist) void patchStoredEntity(id, fn);
+ ): Promise<void> | undefined => {
+ const patch = persist ? patchStoredEntity(id, fn) : undefined;
for (const key of entityKeys(id)) {
const current = port.read(key);
if (current === undefined) continue;
@@ -672,6 +921,40 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
persist,
});
}
+ return patch;
+ };
+
+ const updateEntity = <TItem>(
+ id: string,
+ fn: (item: TItem) => TItem | undefined,
+ options?: { persist?: boolean },
+ ) => {
+ void applyEntity(id, fn, options);
+ };
+
+ /**
+ * Confirmed removal of one entity everywhere (see `updateEntity`). Unlike a
+ * plain mapper returning `undefined`, it is also remembered for this scope:
+ * a value hydrated afterwards β€” even by a read already in flight β€” comes
+ * back without the entity (see `removedEntities`).
+ */
+ const removeEntity = (id: string, options?: { persist?: boolean }) => {
+ const scope = resource.scope.get();
+ const guard: { releasedAt?: number } = {};
+ const guards = removedEntities.get(scope) ?? new Map<string, { releasedAt?: number }>();
+ removedEntities.set(scope, guards);
+ guards.set(id, guard);
+ const release = () => {
+ // A newer removal of the same id owns the slot now.
+ if (guards.get(id) !== guard) return;
+ guard.releasedAt = ++guardClock;
+ pruneEntityGuards(scope);
+ };
+ const patch = applyEntity(id, () => undefined, options);
+ // Without a storage patch (`persist: false`) only reads already in flight
+ // can hold the entity; with one, reads that start before it lands can too.
+ if (patch) void patch.then(release, release);
+ else release();
};
const beginEntityOptimistic = <TItem>(
@@ -690,6 +973,8 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
return {
beginEntityOptimistic,
beginOptimistic,
+ clear,
+ clearGeneration,
collapse,
dispatch,
ensureScope,
@@ -703,6 +988,7 @@ export const createReplicaEngine = <TParams, TData, TFetched = TData>(
patchStoredEntity,
persist,
remove,
+ removeEntity,
replace,
resource,
revalidate,
diff --git a/packages/replica/src/core/entity.ts b/packages/replica/src/core/entity.ts
index 56b2addb31f..d5b0dea7a7d 100644
--- a/packages/replica/src/core/entity.ts
+++ b/packages/replica/src/core/entity.ts
@@ -6,8 +6,15 @@ export interface ReplicaEntityTarget {
id: string,
fn: (item: TItem) => TItem | undefined,
) => ReplicaOptimisticToken<any>[];
+ /** Wipe the resource in the active scope (memory + every persisted row). */
+ clear?: () => Promise<boolean>;
/** Patch persisted rows whose entry is not loaded in memory. */
patchStoredEntity: <TItem>(id: string, fn: (item: TItem) => TItem | undefined) => Promise<void>;
+ /**
+ * Explicit entity removal that also guards later hydrates. Optional for
+ * custom targets; `linkReplicaEntity` falls back to `updateEntity`.
+ */
+ removeEntity?: (id: string, options?: { persist?: boolean }) => void;
revalidate: (key?: string) => Promise<unknown>;
updateEntity: <TItem>(
id: string,
@@ -38,9 +45,26 @@ export const linkReplicaEntity = <TItem>(targets: ReplicaEntityTarget[]) => {
for (const target of targets) target.updateEntity<TItem>(id, fn, options);
};
- /** Confirmed removal everywhere (list rows dropped, single-entity values removed). */
+ /**
+ * Confirmed removal everywhere (list rows dropped, single-entity values
+ * removed). A value hydrated later β€” even one whose read was already in
+ * flight β€” comes back without the entity.
+ */
const remove = (id: string, options?: { persist?: boolean }): void => {
- for (const target of targets) target.updateEntity<TItem>(id, () => undefined, options);
+ for (const target of targets) {
+ if (target.removeEntity) target.removeEntity(id, options);
+ else target.updateEntity<TItem>(id, () => undefined, options);
+ }
+ };
+
+ /**
+ * Wipe every linked resource in the active scope (e.g. "delete all"): memory,
+ * every persisted row and reads in flight. Resolves `true` once every
+ * persisted row is gone.
+ */
+ const clear = async (): Promise<boolean> => {
+ const purged = await Promise.all(targets.map((target) => target.clear?.() ?? true));
+ return purged.every(Boolean);
};
/**
@@ -70,5 +94,5 @@ export const linkReplicaEntity = <TItem>(targets: ReplicaEntityTarget[]) => {
const revalidate = () => Promise.all(targets.map((target) => target.revalidate()));
- return { optimistic, remove, revalidate, update };
+ return { clear, optimistic, remove, revalidate, update };
};
diff --git a/packages/replica/src/core/types.ts b/packages/replica/src/core/types.ts
index c62686740df..48feca6be14 100644
--- a/packages/replica/src/core/types.ts
+++ b/packages/replica/src/core/types.ts
@@ -15,11 +15,27 @@ export interface ReplicaRow<T> {
/**
* Where a replica keeps its rows between sessions (IndexedDB, localStorage …).
- * Best-effort by contract: the server stays the durable source of truth, so
- * an implementation should swallow its own I/O failures.
+ * Reads and writes are best-effort: the server stays the durable source of
+ * truth, so `get` and `set` should swallow their own I/O failures (a failed
+ * read is a cache miss, a failed write is retried by the next one).
*/
export interface ReplicaStorage<T> {
get: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;
+ /**
+ * Strict read for destructive passes: like `get`, but **rejects** when the
+ * row could not be read (I/O error, unparsable value) instead of reporting a
+ * miss. The engine reads its per-scope index through it before `remove` /
+ * `clear`, so an unreadable index fails the purge rather than passing for an
+ * empty one. Optional: without it `get` is used, which is only correct for a
+ * storage whose `get` already rejects on failure.
+ */
+ getStrict?: (key: ReplicaRowKey) => Promise<ReplicaRow<T> | undefined>;
+ /**
+ * Delete a row. Must **reject** when the delete did not land (a closed
+ * IndexedDB, a quota or security error): the engine keeps the row indexed
+ * and the removal unpurged, so the next `remove` / `clear` retries it instead
+ * of letting a row the user deleted hydrate again. A missing row is a success.
+ */
remove: (key: ReplicaRowKey) => Promise<void>;
set: (key: ReplicaRowKey, row: ReplicaRow<T>) => Promise<void>;
}
diff --git a/packages/replica/src/core/writeQueue.ts b/packages/replica/src/core/writeQueue.ts
index 5f88552dbb4..89d12becc32 100644
--- a/packages/replica/src/core/writeQueue.ts
+++ b/packages/replica/src/core/writeQueue.ts
@@ -14,6 +14,7 @@ export class ReplicaWriteQueue<T> {
#id = ({ queryKey, scope }: ReplicaRowKey) => `${scope}:${queryKey}`;
+ /** Resolves `false` when storage rejected the delete (see `ReplicaStorage.remove`). */
remove = (key: ReplicaRowKey): Promise<boolean> =>
this.#enqueue(key, () => this.#storage.remove(key));
diff --git a/packages/replica/src/zustand/createReplicaSlice.test.ts b/packages/replica/src/zustand/createReplicaSlice.test.ts
index d1df76cc712..7adbb0d6465 100644
--- a/packages/replica/src/zustand/createReplicaSlice.test.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.test.ts
@@ -40,6 +40,7 @@ const createMemoryStorage = (delays: Record<string, number> = {}) => {
? (indexRows.get(scope) as ReplicaRow<string[]> | undefined)
: rows.get(`${scope}|${queryKey}`),
remove: async ({ queryKey, scope }) => {
+ if (queryKey === REPLICA_INDEX_KEY) return void indexRows.delete(scope);
rows.delete(`${scope}|${queryKey}`);
},
set: async ({ queryKey, scope }, projection) => {
@@ -721,6 +722,441 @@ describe('createReplicaSlice', () => {
});
});
+ describe('invalidation', () => {
+ interface QueryParams {
+ id: string;
+ q?: string;
+ }
+ /** A resource whose rows are persisted per query (`a`, `a?{"q":"x"}` …). */
+ const setupQueried = ({
+ driver: queryDriver = driver,
+ storage = createMemoryStorage(),
+ }: {
+ driver?: Parameters<typeof createReplicaSlice>[1]['driver'];
+ storage?: ReturnType<typeof createMemoryStorage>;
+ } = {}) => {
+ const resource = defineReplica<QueryParams, string[]>({
+ fetcher: async () => ['server'],
+ key: ({ id }) => id,
+ name: 'queriedList',
+ query: ({ q }) => ({ q }),
+ scope,
+ storage: storage.storage,
+ version: 1,
+ });
+ const store = createStore<TestState>()(() => ({
+ lists: {},
+ listsReplica: createReplicaState(),
+ }));
+ const slice = createReplicaSlice<TestState, QueryParams, string[]>(resource, {
+ driver: queryDriver,
+ get: store.getState,
+ set: (partial) => store.setState(partial),
+ stateKey: 'listsReplica',
+ view: recordLens('lists'),
+ });
+ return { resource, slice, storage, store };
+ };
+ const row = (resource: { storageKey: (params: QueryParams) => string }, params: QueryParams) =>
+ `user-1:personal|${resource.storageKey(params)}`;
+
+ /** Persist `a` (unfiltered + filtered) and `ab` in one session. */
+ const persistVariants = async () => {
+ const first = setupQueried();
+ act(() => {
+ first.slice.replace({ id: 'a' }, ['a-all']);
+ first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);
+ first.slice.replace({ id: 'ab' }, ['ab-all']);
+ });
+ await waitFor(() => expect(first.storage.rows.size).toBe(3));
+ return first;
+ };
+
+ it('remove drops every persisted query variant of the key, not only the one in memory', async () => {
+ const { resource, slice, storage } = await persistVariants();
+
+ // Memory holds the filtered query; the unfiltered row was persisted earlier.
+ act(() => slice.remove('a'));
+
+ await waitFor(() => {
+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);
+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);
+ });
+ // Another key that merely shares the prefix is untouched.
+ expect(storage.rows.get(row(resource, { id: 'ab' }))?.data).toEqual(['ab-all']);
+ });
+
+ it('remove drops variants persisted by an earlier session, through the index', async () => {
+ const first = await persistVariants();
+ // Reload: memory is empty, only the persisted index knows the variants.
+ const { resource, slice, storage, store } = setupQueried({ storage: first.storage });
+
+ act(() => slice.remove('a'));
+
+ await waitFor(() => {
+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);
+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);
+ });
+ // No variant of the removed key hydrates.
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a', q: 'x' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('an off-scope purge drops every query variant of its scope', async () => {
+ const { resource, slice, storage } = await persistVariants();
+
+ scopeState.current = 'user-2:personal';
+ act(() => slice.remove('a', 'user-1:personal'));
+
+ await waitFor(() => {
+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);
+ expect(storage.rows.has(row(resource, { id: 'a', q: 'x' }))).toBe(false);
+ });
+ });
+
+ /** Make storage reject the first delete of `queryKey` (a closed IndexedDB). */
+ const failFirstDelete = (storage: ReturnType<typeof createMemoryStorage>, queryKey: string) => {
+ const original = storage.storage.remove;
+ let failed = false;
+ storage.storage.remove = async (key) => {
+ if (key.queryKey === queryKey && !failed) {
+ failed = true;
+ throw new Error('IndexedDB delete failed');
+ }
+ return original(key);
+ };
+ };
+
+ it('keeps a variant whose delete failed indexed, so a later remove retries it', async () => {
+ const { resource, slice, storage } = await persistVariants();
+ const filtered = row(resource, { id: 'a', q: 'x' });
+ failFirstDelete(storage, resource.storageKey({ id: 'a', q: 'x' }));
+ // Memory holds another variant, so the failing row is found through the index.
+ act(() => slice.replace({ id: 'a' }, ['a-all']));
+
+ act(() => slice.remove('a'));
+ await waitFor(() => expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.rows.has(filtered)).toBe(true);
+
+ // The next removal still knows about the failed row and retries it.
+ act(() => slice.remove('a'));
+ await waitFor(() => expect(storage.rows.has(filtered)).toBe(false));
+ });
+
+ it('keeps a row whose delete failed indexed, so a later clear retries it', async () => {
+ const { resource, slice, storage } = await persistVariants();
+ failFirstDelete(storage, resource.storageKey({ id: 'ab' }));
+
+ let purge!: Promise<boolean>;
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(await purge).toBe(false);
+ expect([...storage.rows.keys()]).toEqual([row(resource, { id: 'ab' })]);
+
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(await purge).toBe(true);
+ expect(storage.rows.size).toBe(0);
+ });
+
+ /**
+ * Storage whose index read fails the way the app adapters do: `get`
+ * swallows it into a miss, only `getStrict` reports it.
+ */
+ const failIndexReads = (storage: ReturnType<typeof createMemoryStorage>) => {
+ const state = { failing: true };
+ const original = storage.storage.get;
+ storage.storage.get = async (key) =>
+ key.queryKey === REPLICA_INDEX_KEY && state.failing ? undefined : original(key);
+ storage.storage.getStrict = async (key) => {
+ if (key.queryKey === REPLICA_INDEX_KEY && state.failing)
+ throw new Error('IndexedDB read failed');
+ return original(key);
+ };
+ return state;
+ };
+
+ it('reports a clear as failed when the index cannot be read, and a later clear retries', async () => {
+ const first = await persistVariants();
+ // Reload: only the persisted index knows the earlier session's rows.
+ const { slice, storage, store } = setupQueried({ storage: first.storage });
+ const index = failIndexReads(storage);
+
+ let purge!: Promise<boolean>;
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(await purge).toBe(false);
+ expect(storage.rows.size).toBe(3);
+ // Hydration stays off while the wipe is incomplete.
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+
+ index.failing = false;
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(await purge).toBe(true);
+ expect(storage.rows.size).toBe(0);
+ });
+
+ it('keeps a removal unpurged when the index cannot be read, so it retries', async () => {
+ const first = await persistVariants();
+ const { resource, slice, storage } = setupQueried({ storage: first.storage });
+ const filtered = row(resource, { id: 'a', q: 'x' });
+ const index = failIndexReads(storage);
+
+ // Memory is empty, so every variant is known only through the index.
+ act(() => slice.remove('a'));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(true);
+ expect(storage.rows.has(filtered)).toBe(true);
+
+ index.failing = false;
+ act(() => slice.remove('a'));
+ await waitFor(() => {
+ expect(storage.rows.has(row(resource, { id: 'a' }))).toBe(false);
+ expect(storage.rows.has(filtered)).toBe(false);
+ });
+ });
+
+ it('never mistakes a plain key containing `?` for a query variant', async () => {
+ const storage = createMemoryStorage();
+ const { slice } = setup({ storage });
+ act(() => {
+ slice.replace({ id: 'foo' }, ['foo']);
+ slice.replace({ id: 'foo?bar' }, ['foo?bar']);
+ });
+ await waitFor(() => expect(storage.rows.size).toBe(2));
+
+ act(() => slice.remove('foo'));
+
+ await waitFor(() => expect(storage.rows.has('user-1:personal|foo')).toBe(false));
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(storage.rows.get('user-1:personal|foo?bar')?.data).toEqual(['foo?bar']);
+ });
+
+ it('cleans variants listed by an index written in the existing flat format', async () => {
+ const storage = createMemoryStorage();
+ // Rows and index as an earlier release persisted them on a device.
+ for (const queryKey of ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'])
+ storage.rows.set(`user-1:personal|${queryKey}`, { data: [queryKey], updatedAt: 1 });
+ storage.indexRows.set('user-1:personal', {
+ data: ['foo?{}', 'foo?{"q":"x"}', 'foo?bar?{}'],
+ updatedAt: 1,
+ });
+ const { slice } = setupQueried({ storage });
+
+ act(() => slice.remove('foo'));
+
+ await waitFor(() => expect([...storage.rows.keys()]).toEqual(['user-1:personal|foo?bar?{}']));
+ await waitFor(() =>
+ expect(storage.indexRows.get('user-1:personal')?.data).toEqual(['foo?bar?{}']),
+ );
+ });
+
+ it('calls a class-based storage with its receiver on every index pass', async () => {
+ /** Prototype methods that rely on `this`, like most storage classes. */
+ class ClassStorage implements ReplicaStorage<string[]> {
+ rows = new Map<string, ReplicaRow<string[]>>();
+ #id({ queryKey, scope }: { queryKey: string; scope: string }) {
+ return `${scope}|${queryKey}`;
+ }
+ async get(key: { queryKey: string; scope: string }) {
+ return this.rows.get(this.#id(key));
+ }
+ async getStrict(key: { queryKey: string; scope: string }) {
+ return this.rows.get(this.#id(key));
+ }
+ async remove(key: { queryKey: string; scope: string }) {
+ this.rows.delete(this.#id(key));
+ }
+ async set(key: { queryKey: string; scope: string }, row: ReplicaRow<string[]>) {
+ this.rows.set(this.#id(key), row);
+ }
+ }
+ const backing = new ClassStorage();
+ const storage = { ...createMemoryStorage(), storage: backing };
+ const dataRows = () =>
+ [...backing.rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));
+ const first = setupQueried({ storage });
+ act(() => {
+ first.slice.replace({ id: 'a' }, ['a-all']);
+ first.slice.replace({ id: 'a', q: 'x' }, ['a-x']);
+ first.slice.replace({ id: 'b' }, ['b-all']);
+ });
+ await waitFor(() => expect(dataRows()).toHaveLength(3));
+ const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ // A fresh engine only finds the rows through the index.
+ const { slice } = setupQueried({ storage });
+ slice.updateEntity('x', (item) => item);
+ act(() => slice.remove('a'));
+ await waitFor(() => expect(dataRows()).toEqual(['user-1:personal|b?{}']));
+ expect(await slice.clear()).toBe(true);
+ expect(dataRows()).toEqual([]);
+ expect(errors).not.toHaveBeenCalled();
+ errors.mockRestore();
+ });
+
+ it('drops the request record of a failure even without an onError', async () => {
+ const requests: { fetch: () => Promise<unknown>; onError?: (error: unknown) => void }[] = [];
+ const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {
+ if (key?.[0] === 'replica:sync') requests.push({ fetch, onError: options.onError });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });
+ const deletes = vi.spyOn(Map.prototype, 'delete');
+
+ const { rerender } = renderHook((props: QueryParams) => slice.useSync(props), {
+ initialProps: { id: 'k1' } as QueryParams,
+ });
+ for (const id of ['k1', 'k2', 'k3']) {
+ rerender({ id });
+ const request = requests.at(-1)!;
+ await request.fetch();
+ act(() => request.onError!(new Error('forbidden')));
+ }
+
+ const dropped = deletes.mock.calls.map(([id]) => String(id));
+ for (const id of ['k1', 'k2', 'k3'])
+ expect(
+ dropped.some((record) => record.includes('replica:sync') && record.includes(id)),
+ ).toBe(true);
+ deletes.mockRestore();
+ });
+
+ it('clear wipes memory, every persisted row and the index of the active scope', async () => {
+ const first = await persistVariants();
+ // A later session loads only one entry; the rest is known only to the index.
+ const { slice, storage, store } = setupQueried({ storage: first.storage });
+ act(() => slice.replace({ id: 'b' }, ['b-all']));
+ storage.rows.set('user-2:personal|a', { data: ['other-user'], updatedAt: 1 });
+
+ let purge!: Promise<boolean>;
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(store.getState().lists).toEqual({});
+ expect(store.getState().listsReplica.entries).toEqual({});
+
+ await act(async () => {
+ expect(await purge).toBe(true);
+ });
+ // Only the other identity's row survives; the index lists nothing.
+ expect([...storage.rows.keys()]).toEqual(['user-2:personal|a']);
+ await waitFor(() => expect(storage.indexRows.get('user-1:personal')?.data).toEqual([]));
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ });
+
+ it('clear refuses a hydrate that was already reading', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['wiped'], updatedAt: 1 });
+ const originalGet = storage.storage.get;
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => (release = resolve));
+ storage.storage.get = async (key) => {
+ const value = await originalGet(key);
+ if (key.queryKey === 'a') await held;
+ return value;
+ };
+ const { slice, store } = setup({ storage });
+
+ let hydration!: Promise<boolean>;
+ await act(async () => {
+ hydration = slice.hydrate({ id: 'a' });
+ });
+ act(() => {
+ void slice.clear();
+ });
+ await act(async () => {
+ release();
+ expect(await hydration).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('clear discards a head response that started before it, and applies one started after', () => {
+ const requests: { fetch: () => Promise<unknown>; onSuccess: (data: string[]) => void }[] = [];
+ const useQuery = vi.fn((key: any, fetch: () => Promise<unknown>, options: any) => {
+ if (key?.[0] === 'replica:sync') requests.push({ fetch, onSuccess: options.onSuccess });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const { slice, store } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });
+ renderHook(() => slice.useSync({ id: 'a' }));
+ const request = requests.at(-1)!;
+
+ // The request is issued, then the resource is wiped before it settles.
+ void request.fetch();
+ act(() => {
+ void slice.clear();
+ });
+ act(() => request.onSuccess(['before-clear']));
+ expect(store.getState().lists.a).toBeUndefined();
+
+ // A request issued after the clear is ordinary.
+ void request.fetch();
+ act(() => request.onSuccess(['after-clear']));
+ expect(store.getState().lists.a).toEqual(['after-clear']);
+ });
+
+ it('a clear whose purge could not run keeps refusing hydration', async () => {
+ const storage = createMemoryStorage();
+ storage.rows.set('user-1:personal|a', { data: ['stale'], updatedAt: 1 });
+ const { slice, store } = setup({ storage });
+
+ // Identity is not resolved yet, so the row deletes are refused.
+ scopeState.trusted = false;
+ let purge!: Promise<boolean>;
+ act(() => {
+ purge = slice.clear();
+ });
+ expect(await purge).toBe(false);
+ scopeState.trusted = true;
+
+ await act(async () => {
+ expect(await slice.hydrate({ id: 'a' })).toBe(false);
+ });
+ expect(store.getState().lists.a).toBeUndefined();
+ });
+
+ it('does not surface the error of a query the entry has moved past', () => {
+ const requests: { onError: (error: unknown) => void; params: { q?: string } }[] = [];
+ const useQuery = vi.fn((key: any, _fetch: unknown, options: any) => {
+ if (key?.[0] === 'replica:sync')
+ requests.push({ onError: options.onError, params: key.at(-1) });
+ return { isValidating: false, mutate: vi.fn() };
+ });
+ const { slice } = setupQueried({ driver: { revalidate: vi.fn(), useQuery } });
+ const onError = vi.fn();
+
+ const { rerender } = renderHook((props: QueryParams) => slice.useSync(props, { onError }), {
+ initialProps: { id: 'a' } as QueryParams,
+ });
+ rerender({ id: 'a', q: 'b' });
+
+ const base = requests.find((request) => request.params.q === undefined)!;
+ const search = requests.find((request) => request.params.q === 'b')!;
+
+ // The superseded query fails late: the search on screen must not see it.
+ act(() => base.onError(new Error('stale')));
+ expect(onError).not.toHaveBeenCalled();
+
+ const failure = new Error('search failed');
+ act(() => search.onError(failure));
+ expect(onError).toHaveBeenCalledWith(failure, { key: 'a', scope: 'user-1:personal' });
+ });
+ });
+
describe('missing responses', () => {
it('applies a response the resource marks as missing as an explicit removal', () => {
// A nullable detail (e.g. the acceptance attached to a subject): the
diff --git a/packages/replica/src/zustand/createReplicaSlice.ts b/packages/replica/src/zustand/createReplicaSlice.ts
index 82ed35756b4..602b6f98cf6 100644
--- a/packages/replica/src/zustand/createReplicaSlice.ts
+++ b/packages/replica/src/zustand/createReplicaSlice.ts
@@ -1,5 +1,6 @@
import { useLayoutEffect } from 'react';
+import { stableQueryKey } from '../core/defineReplica';
import { createReplicaEngine, type ReplicaEngineOptions } from '../core/engine';
import { isReplicaSyncKey, replicaKeys } from '../core/keys';
import type { ReplicaPagedData } from '../core/paging';
@@ -121,7 +122,7 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
},
revalidate,
});
- const { ensureScope, fetcher, hydrate, replace } = engine;
+ const { clearGeneration, ensureScope, fetcher, hydrate, replace } = engine;
/**
* Row key of the head query each entry last asked for. One entry backs a
@@ -133,6 +134,15 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
*/
const headQuery = new Map<string, string>();
+ /**
+ * `clear()` generation each in-flight head request started under, by sync
+ * key. A response to a request that started before a `clear()` of its scope
+ * holds wiped data and is discarded. The driver settles one request per key
+ * at a time (a newer request supersedes the older one), so the latest start
+ * is the one that settles.
+ */
+ const requestGeneration = new Map<string, number>();
+
/**
* Hydrates the persisted row once per scope/key/query, then lets the driver
* fetch and revalidate the head. Read the data from the store.
@@ -168,21 +178,44 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
{ once: true },
);
- const sync = driver.useQuery<TFetched>(
+ const syncKey =
active && fetcher
? (resource.syncKey?.(params!) ??
- replicaKeys.sync(resource.name, resource.version, scope, key!, params))
- : null,
- () => fetcher!(params!, undefined),
+ replicaKeys.sync(resource.name, resource.version, scope, key!, params))
+ : null;
+ const requestId = () => `${scope}\u0000${stableQueryKey(syncKey)}`;
+ /** Whether the request settling now still belongs to the entry's active query. */
+ const isActiveQuery = () => queryKey !== undefined && headQuery.get(key!) === queryKey;
+ /** Whether the settling request started after the latest `clear()` of its scope. */
+ const isSinceClear = () => {
+ const id = requestId();
+ const started = requestGeneration.get(id);
+ requestGeneration.delete(id);
+ return started === undefined || started === clearGeneration(scope);
+ };
+
+ const sync = driver.useQuery<TFetched>(
+ syncKey,
+ () => {
+ requestGeneration.set(requestId(), clearGeneration(scope));
+ return fetcher!(params!, undefined);
+ },
{
...schedule,
- // Bind the captured key/scope to the error callback: a late terminal
- // removal must not land in a scope that became active after the request.
- onError: onError ? (error: unknown) => onError(error, { key, scope }) : undefined,
+ // A failure of a query the entry has moved past (or of a request from
+ // before a clear) must not surface on the query now on screen. The
+ // captured key/scope is bound so a late terminal removal cannot land in
+ // a scope that became active after the request.
+ // Always installed, so a failed request's generation record is dropped
+ // even when the caller has no error side effects.
+ onError: (error: unknown) => {
+ if (!isSinceClear() || !isActiveQuery()) return;
+ onError?.(error, { key, scope });
+ },
onSuccess: (data) => {
- // Discard a head response the entry has moved past: the newer query
- // owns the view (see `headQuery`).
- if (queryKey === undefined || headQuery.get(key!) !== queryKey) return;
+ // Discard a head response the entry has moved past (the newer query
+ // owns the view, see `headQuery`) or one that started before a clear.
+ if (!isSinceClear() || !isActiveQuery()) return;
replace(params!, data, scope);
onSuccess?.(data);
},
@@ -213,9 +246,11 @@ export const createReplicaSlice = <TStore, TParams, TData, TFetched = TData>(
* still matches), `replace` the entry and persist pre-mutation rows back over
* an invalidation that has already completed.
*/
- remove: (key: string) => {
- headQuery.delete(key);
- return engine.remove(key);
+ remove: (key: string, scope?: string) => {
+ // Only the active scope's marker belongs to the entry on screen; an
+ // off-scope removal (see `engine.remove`) must not drop it.
+ if (scope === undefined || scope === resource.scope.get()) headQuery.delete(key);
+ return engine.remove(key, scope);
},
useSync,
};
diff --git a/packages/replica/src/zustand/pagedSlice.test.ts b/packages/replica/src/zustand/pagedSlice.test.ts
index 2f057cbc10c..326ff9d0eca 100644
--- a/packages/replica/src/zustand/pagedSlice.test.ts
+++ b/packages/replica/src/zustand/pagedSlice.test.ts
@@ -3,6 +3,7 @@ import { createStore } from 'zustand/vanilla';
import { testDriver as driver } from '../../tests/testDriver';
import { definePagedReplica, defineReplica } from '../core/defineReplica';
+import { REPLICA_INDEX_KEY } from '../core/engine';
import { linkReplicaEntity } from '../core/entity';
import { singleEntity } from '../core/entityAdapters';
import type { ReplicaPagedData, ReplicaPageResult } from '../core/paging';
@@ -365,3 +366,161 @@ describe('entity changes for entries that are not loaded', () => {
expect(listStorage.rows.get(listKey)?.data.items[0].title).toBe('a');
});
});
+
+describe('entity removals vs reads in flight', () => {
+ /** Hold every `get` of `storage` for `queryKey` until released (the row is read first). */
+ const holdReads = <T>(storage: ReplicaStorage<T>, queryKey: string) => {
+ const originalGet = storage.get;
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => (release = resolve));
+ storage.get = async (key) => {
+ const value = await originalGet(key);
+ if (key.queryKey === queryKey) await held;
+ return value;
+ };
+ return () => release();
+ };
+
+ const persisted = async () => {
+ const first = setup();
+ first.list.replace(params, pageOf(params));
+ first.detail.replace('a', row('a'));
+ await vi.waitFor(() => {
+ expect(
+ first.listStorage.rows.get(`user-1|${first.listResource.storageKey(params)}`),
+ ).toBeDefined();
+ expect(first.detailStorage.rows.get('user-1|a')).toBeDefined();
+ });
+ const second = setup(undefined, {
+ detailStorage: first.detailStorage,
+ listStorage: first.listStorage,
+ });
+ return { ...second, topic: linkReplicaEntity<Row>([second.list, second.detail]) };
+ };
+
+ it('a hydrate that read its row before the entity was deleted paints it without the entity', async () => {
+ const { detail, detailStorage, list, listResource, listStorage, store, topic } =
+ await persisted();
+ const releaseList = holdReads(listStorage.storage, listResource.storageKey(params));
+ const releaseDetail = holdReads(detailStorage.storage, 'a');
+
+ const listHydrate = list.hydrate(params);
+ const detailHydrate = detail.hydrate('a');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ topic.remove('a');
+ releaseList();
+ releaseDetail();
+ await Promise.all([listHydrate, detailHydrate]);
+
+ expect(ids(store.getState().lists.o1)).toEqual(['b']);
+ expect(store.getState().lists.o1.total).toBe(4);
+ expect(store.getState().details.a).toBeUndefined();
+ });
+
+ it('an explicit slice.removeEntity beats a hydrate already reading', async () => {
+ const { list, listResource, listStorage, store } = await persisted();
+ const release = holdReads(listStorage.storage, listResource.storageKey(params));
+
+ const hydration = list.hydrate(params);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ list.removeEntity('a');
+ release();
+ await hydration;
+
+ expect(ids(store.getState().lists.o1)).toEqual(['b']);
+ });
+
+ it('updateEntity with a mapper returning undefined still deletes, whatever its arity', async () => {
+ const { list, listResource, listStorage, store } = await persisted();
+ list.replace({ owner: 'o2', pageSize: 2 }, { items: [row('a'), row('x')], total: 2 });
+
+ list.updateEntity<Row>('a', (_item) => undefined);
+
+ expect(ids(store.getState().lists.o2)).toEqual(['x']);
+ // The unloaded persisted row loses it too.
+ await vi.waitFor(() =>
+ expect(ids(listStorage.rows.get(`user-1|${listResource.storageKey(params)}`)?.data)).toEqual([
+ 'b',
+ ]),
+ );
+ });
+
+ it('never invokes an entity mapper speculatively', () => {
+ const ctx = setup();
+ ctx.list.replace(params, pageOf(params));
+ const mapper = vi.fn(() => row('a', 'renamed'));
+
+ ctx.list.updateEntity<Row>('a', mapper, { persist: false });
+
+ // Once to probe the loaded value, once inside the confirmed update.
+ expect(mapper).toHaveBeenCalledTimes(2);
+ expect(ctx.store.getState().lists.o1.items[0].title).toBe('renamed');
+ });
+
+ it('keeps every guard a pending hydrate needs, however many, and releases them after', async () => {
+ const { list, listResource, listStorage, store } = await persisted();
+ const many = { owner: 'o9', pageSize: 600 };
+ const items = Array.from({ length: 600 }, (_, index) => row(`x${index}`));
+ listStorage.rows.set(`user-1|${listResource.storageKey(many)}`, {
+ data: { currentPage: 0, hasMore: false, items, pageSize: 600, total: 600 },
+ updatedAt: 1,
+ });
+ const release = holdReads(listStorage.storage, listResource.storageKey(many));
+
+ const hydration = list.hydrate(many);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ // A batch delete larger than any fixed window, while the read is pending.
+ for (const item of items) list.removeEntity(item.id);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ release();
+ await hydration;
+ expect(ids(store.getState().lists.o9)).toEqual([]);
+
+ // Once that read settled the guards are released: a row this session never
+ // patched (not indexed) hydrates as stored.
+ const later = { owner: 'o10', pageSize: 2 };
+ listStorage.rows.set(`user-1|${listResource.storageKey(later)}`, {
+ data: { currentPage: 0, hasMore: false, items: [row('x0')], pageSize: 2, total: 1 },
+ updatedAt: 1,
+ });
+ await list.hydrate(later);
+ expect(ids(store.getState().lists.o10)).toEqual(['x0']);
+ });
+
+ it('a server value holding the entity again lifts the removal', async () => {
+ const { list, listResource, listStorage, store, topic } = await persisted();
+ topic.remove('a');
+ // Restored on the server: a head response holds it again.
+ list.replace(params, pageOf(params));
+ expect(ids(store.getState().lists.o1)).toEqual(['a', 'b']);
+
+ // Another entry persisted with the entity hydrates it as stored.
+ const other = { owner: 'o3', pageSize: 2 };
+ listStorage.rows.set(`user-1|${listResource.storageKey(other)}`, {
+ data: { currentPage: 0, hasMore: false, items: [row('a')], pageSize: 2, total: 1 },
+ updatedAt: 1,
+ });
+ await list.hydrate(other);
+ expect(ids(store.getState().lists.o3)).toEqual(['a']);
+ });
+});
+
+describe('linkReplicaEntity.clear', () => {
+ it('wipes every linked resource in memory and storage', async () => {
+ const ctx = setup();
+ ctx.list.replace(params, pageOf(params));
+ ctx.detail.replace('a', row('a'));
+ await vi.waitFor(() => expect(ctx.detailStorage.rows.get('user-1|a')).toBeDefined());
+ const topic = linkReplicaEntity<Row>([ctx.list, ctx.detail]);
+
+ const purge = topic.clear();
+ expect(ctx.store.getState().lists).toEqual({});
+ expect(ctx.store.getState().details).toEqual({});
+ expect(await purge).toBe(true);
+ // Only the (emptied) index rows remain.
+ const dataRows = (rows: Map<string, unknown>) =>
+ [...rows.keys()].filter((key) => !key.endsWith(REPLICA_INDEX_KEY));
+ expect(dataRows(ctx.listStorage.rows)).toEqual([]);
+ expect(dataRows(ctx.detailStorage.rows)).toEqual([]);
+ });
+});
diff --git a/src/libs/queryProjectionStorage/indexedDB.test.ts b/src/libs/queryProjectionStorage/indexedDB.test.ts
index 6827e1bf211..0541243cf59 100644
--- a/src/libs/queryProjectionStorage/indexedDB.test.ts
+++ b/src/libs/queryProjectionStorage/indexedDB.test.ts
@@ -27,4 +27,24 @@ describe('IndexedDBQueryProjectionStorage', () => {
await expect(storage.get({ queryKey: 'all', scope: 'personal' })).resolves.toBeUndefined();
});
+
+ it('reports a failed delete so the caller can retry it', async () => {
+ vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
+ vi.spyOn(localDatabase, 'delete').mockRejectedValue(new Error('database closed'));
+ const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+
+ await expect(storage.remove({ queryKey: 'all', scope: 'personal' })).rejects.toThrow(
+ 'database closed',
+ );
+ });
+
+ it('rejects a strict read that failed, while get stays a cache miss', async () => {
+ vi.spyOn(localDatabase, 'initialize').mockResolvedValue();
+ vi.spyOn(localDatabase, 'get').mockRejectedValue(new Error('database closed'));
+ const storage = new IndexedDBQueryProjectionStorage<string[]>({ namespace: 'projects' });
+ const key = { queryKey: '__replica:index', scope: 'personal' };
+
+ await expect(storage.getStrict(key)).rejects.toThrow('database closed');
+ await expect(storage.get(key)).resolves.toBeUndefined();
+ });
});
diff --git a/src/libs/queryProjectionStorage/indexedDB.ts b/src/libs/queryProjectionStorage/indexedDB.ts
index 732d7cf2e79..891573c044a 100644
--- a/src/libs/queryProjectionStorage/indexedDB.ts
+++ b/src/libs/queryProjectionStorage/indexedDB.ts
@@ -20,20 +20,25 @@ export class IndexedDBQueryProjectionStorage<T> implements QueryProjectionStorag
get = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {
try {
- await localDatabase.initialize();
- return await localDatabase.get<QueryProjection<T>>(COLLECTION, this.#key(key));
+ return await this.getStrict(key);
} catch {
return undefined;
}
};
+ /**
+ * Rejects when the delete did not land, unlike reads and writes: a caller
+ * that removes a row the user deleted must be able to retry it.
+ */
+ /** Like `get`, but rejects when the row could not be read (see `ReplicaStorage.getStrict`). */
+ getStrict = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {
+ await localDatabase.initialize();
+ return localDatabase.get<QueryProjection<T>>(COLLECTION, this.#key(key));
+ };
+
remove = async (key: QueryProjectionKey): Promise<void> => {
- try {
- await localDatabase.initialize();
- await localDatabase.delete(COLLECTION, this.#key(key));
- } catch {
- // Projection persistence is best-effort; the server remains the durable SoT.
- }
+ await localDatabase.initialize();
+ await localDatabase.delete(COLLECTION, this.#key(key));
};
set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {
diff --git a/src/libs/queryProjectionStorage/localStorage.test.ts b/src/libs/queryProjectionStorage/localStorage.test.ts
index d1d48142653..a174235867c 100644
--- a/src/libs/queryProjectionStorage/localStorage.test.ts
+++ b/src/libs/queryProjectionStorage/localStorage.test.ts
@@ -1,8 +1,9 @@
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { LocalStorageQueryProjectionStorage } from './localStorage';
afterEach(() => {
+ vi.restoreAllMocks();
localStorage.clear();
});
@@ -45,4 +46,26 @@ describe('LocalStorageQueryProjectionStorage', () => {
expect((await storage.get(key))?.data.createdAt).toEqual(new Date(0));
});
+
+ it('reports a failed delete so the caller can retry it', async () => {
+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
+ throw new Error('access denied');
+ });
+
+ await expect(storage.remove({ queryKey: 'display', scope: 'user-a' })).rejects.toThrow(
+ 'access denied',
+ );
+ });
+
+ it('rejects a strict read that failed, while get stays a cache miss', async () => {
+ const storage = new LocalStorageQueryProjectionStorage<string[]>({ namespace: 'test' });
+ const key = { queryKey: '__replica:index', scope: 'user-a' };
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('access denied');
+ });
+
+ await expect(storage.getStrict(key)).rejects.toThrow('access denied');
+ await expect(storage.get(key)).resolves.toBeUndefined();
+ });
});
diff --git a/src/libs/queryProjectionStorage/localStorage.ts b/src/libs/queryProjectionStorage/localStorage.ts
index a08dac1659a..ec34a2b73d7 100644
--- a/src/libs/queryProjectionStorage/localStorage.ts
+++ b/src/libs/queryProjectionStorage/localStorage.ts
@@ -42,14 +42,23 @@ export class LocalStorageQueryProjectionStorage<T> implements QueryProjectionSto
}
};
+ /** Like `get`, but rejects when the row could not be read or parsed (see `ReplicaStorage.getStrict`). */
+ getStrict = async (key: QueryProjectionKey): Promise<QueryProjection<T> | undefined> => {
+ if (typeof window === 'undefined') return undefined;
+
+ const value = localStorage.getItem(this.#key(key));
+ return value ? this.#codec.parse(value) : undefined;
+ };
+
+ /**
+ * Rejects when the delete did not land (e.g. storage access denied), unlike
+ * reads and writes: a caller removing a row the user deleted must be able to
+ * retry it.
+ */
remove = async (key: QueryProjectionKey): Promise<void> => {
if (typeof window === 'undefined') return;
- try {
- localStorage.removeItem(this.#key(key));
- } catch {
- // Projection persistence is best-effort; the server remains the durable SoT.
- }
+ localStorage.removeItem(this.#key(key));
};
set = async (key: QueryProjectionKey, projection: QueryProjection<T>): Promise<void> => {
diff --git a/src/libs/queryProjectionStorage/types.ts b/src/libs/queryProjectionStorage/types.ts
index dd95a02a00c..772f3e90348 100644
--- a/src/libs/queryProjectionStorage/types.ts
+++ b/src/libs/queryProjectionStorage/types.ts
@@ -10,6 +10,9 @@ export interface QueryProjection<T> {
export interface QueryProjectionStorage<T> {
get: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;
+ /** Like `get`, but rejects when the row could not be read (destructive passes). */
+ getStrict?: (key: QueryProjectionKey) => Promise<QueryProjection<T> | undefined>;
+ /** Rejects when the delete did not land (reads and writes stay best-effort). */
remove: (key: QueryProjectionKey) => Promise<void>;
set: (key: QueryProjectionKey, projection: QueryProjection<T>) => Promise<void>;
}
diff --git a/src/store/user/displaySnapshot.ts b/src/store/user/displaySnapshot.ts
index 1d8751fcbad..a9d0a631d91 100644
--- a/src/store/user/displaySnapshot.ts
+++ b/src/store/user/displaySnapshot.ts
@@ -71,5 +71,7 @@ export const writeUserDisplaySnapshot = (
*/
export const clearUserDisplaySnapshot = (userId: string | undefined): void => {
if (!userId) return;
- void storage.remove(snapshotKey(userId));
+ storage.remove(snapshotKey(userId)).catch((error) => {
+ console.error('[displaySnapshot] failed to clear the display snapshot', error);
+ });
};