Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(cache): complete reads across owner replacement (#8905)

Sean Aye225c82797c7a
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 6771af6d37..eb05f8180a 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -195,6 +195,9 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
Publish recovery reset outcomes before parking while retaining the read pause.
Bound foreground resume reads to one second without killing an owner, stealing
its lock, replaying writes, or treating intentional parking as a failure.
+- Retry still-current query reads once when engine replacement invalidates their
+ snapshot; do not strand urql's in-flight key or revive torn-down or superseded reads.
+ Keep network forwarding deduplicated and cache-only reads off the network.
- Mobile dock customization shares the navigation island’s measured capacity; persist ordering per user with `mobile-dock-order.ts`, preserve gated destinations, and keep Search and More fixed. Reorder handles drag without a hold delay; the rest of each row scrolls.
- Share sidebar and mobile dock unread presence through `components/app/use-navigation-unread.ts`; keep badges reactive to read/done changes, guard all query data with `queryReadyGate` so pending preferences or paused queries cannot suspend the shell, and avoid fetching extra pages for counts.
- Name Home thread rows from their latest scoped notification, including document mentions and reactions; use the thread author only when no notification exists. Document rows whose newest outstanding notification is a comment, and calendar event rows whose newest is a join request, say who did it (`row-notification.ts`).
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index 774140ae5b..d71f3ec98e 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -244,6 +244,16 @@ Only read callers are canceled, not admitted engine work or writes. Readiness
restores deadlines and refreshes dependency registrations with preserved-storage
semantics, including when startup finishes on its original owner.
+A replacement also invalidates document-read cursors and in-flight snapshots.
+The exchange retries a still-current read once against the new generation instead
+of dropping its only result: urql deduplicates a reexecution while that operation
+is still pending. Teardown, remount, and newer cache/network results still fence
+old reads. This applies to initial queries and affected watched rereads; continued
+churn uses normal request-policy handling. Cache-and-network never forwards a
+second request for this retry, and cache-only/replacement-registration-only reads
+never gain a network fallback. The anonymous page-side `graphql_cache.read_retry`
+span times the extra read without exporting query contents or identities.
+
Already-sent HTTP mutations may finish while parked. Their local commit, rollback,
or defer requests wait for storage and retain their position ahead of later
claims. Accepted settlement requests survive their caller disconnecting; their
@@ -257,7 +267,8 @@ write. If a drain itself stalls, writes wait until it can finish or existing
failure/navigation recovery applies. Owner telemetry adds `park-started`, `parked`,
`unpark-started`, and `unpark-completed` alongside the `visibility-handoff-*` events.
The backend-free `parking.browser.e2e.ts` exercises physical release, retained
-clients/storage, and a response settled after parking.
+clients/storage, a query admitted while parked completing across replacement
+without network fallback, and a response settled after parking.
Every departure rejects already-routed optimistic enqueues whose replies were
lost as `admitted-enqueue-uncertain`, including requests from surviving tabs.
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index d8ade8b92c..aa5ea3faf6 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -1740,26 +1740,22 @@ describe('normalizedCacheExchange', () => {
}
);
- it.each(['teardown', 'generation change'] as const)(
- 'does not report a cache read cancelled by %s',
- async (cancel) => {
- const read = deferred<ReadResult>();
- host.readQuery = vi.fn(() => read.promise);
- const onCacheError = vi.fn();
- const { ops, results } = harness(host, undefined, { onCacheError });
- const op = makeOp(1);
- ops.next(op);
- await tick();
+ it('does not report a cache read cancelled by teardown', async () => {
+ const read = deferred<ReadResult>();
+ host.readQuery = vi.fn(() => read.promise);
+ const onCacheError = vi.fn();
+ const { ops, results } = harness(host, undefined, { onCacheError });
+ const op = makeOp(1);
+ ops.next(op);
+ await tick();
- if (cancel === 'teardown') ops.next(teardownOf(op));
- else host.pushGeneration({ storage: 'preserved' });
- read.resolve({ kind: 'hit', data: { from: 'cache' } });
- await tick();
+ ops.next(teardownOf(op));
+ read.resolve({ kind: 'hit', data: { from: 'cache' } });
+ await tick();
- expect(onCacheError).not.toHaveBeenCalled();
- expect(results.filter((r) => r.operation.kind === 'query')).toEqual([]);
- }
- );
+ expect(onCacheError).not.toHaveBeenCalled();
+ expect(results.filter((r) => r.operation.kind === 'query')).toEqual([]);
+ });
it('does not report a watched reread cancelled by teardown', async () => {
const reread = deferred<QueryUpdate>();
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index b18a34665e..cebccf3af9 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -36,6 +36,7 @@
*/
import { fireAndForget } from '@core/util/fireAndForget';
+import { Telemetry } from '@macro-inc/observability';
import {
type Client,
CombinedError,
@@ -77,6 +78,7 @@ import {
isOwnerEpochLostError,
isOwnerLockUnavailableError,
type QueryRevalidationWire,
+ type ReadResult,
} from '../protocol';
import { createDeferredQueryRereads } from './deferred-query-rereads';
import {
@@ -499,15 +501,18 @@ export function normalizedCacheExchange(
// Async reads must not resurrect a torn-down operation, overwrite a newer
// network result, or undo a subsequent optimistic/affected cache reread.
- const beginCacheRead = (key: number): (() => boolean) => {
+ const beginCacheRead = (key: number) => {
const state = queryState(key);
const version = ++state.cacheReadVersion;
const generation = cacheGeneration;
- return () =>
- generation === cacheGeneration &&
+ const isLatest = () =>
activeOps.has(key) &&
queryStates.get(key) === state &&
state.cacheReadVersion === version;
+ return {
+ isCurrent: () => generation === cacheGeneration && isLatest(),
+ isLatest,
+ };
};
const acquireQueryResultTurn = async (key: number): Promise<() => void> => {
@@ -696,12 +701,16 @@ export function normalizedCacheExchange(
// Deliver cache changes directly. Reexecuting through urql first replays
// the previous network result as stale, which can reset collection sources
// and replay their persistence acknowledgements during an optimistic edit.
- const emitWatchedQuery = async (key: number): Promise<void> => {
+ const emitWatchedQuery = async (
+ key: number,
+ retrying = false
+ ): Promise<void> => {
const operation = activeOps.get(key);
if (!operation) return;
- const isCurrent = beginCacheRead(key);
+ const readVersion = beginCacheRead(key);
+ let read: ReadResult | undefined;
try {
- const read = await documentReader.read({
+ read = await documentReader.read({
opKey: key,
query: queryText(operation),
operationName: operationName(operation),
@@ -709,16 +718,28 @@ export function normalizedCacheExchange(
priority: 'user-visible',
entityResolvers,
});
- if (!isCurrent()) return;
- if (read.kind === 'hit') {
- emitAffectedResult(
- cacheResult(operation, read.data, false, 'affected-cache-reread')
+ } catch (error) {
+ reportReadError(error, operation);
+ }
+ if (!readVersion.isCurrent()) {
+ if (!readVersion.isLatest()) return;
+ if (!retrying) {
+ await Telemetry.anonymousSpan(
+ 'graphql_cache.read_retry',
+ async (span) => {
+ span.setAttr('cache.retry.reason', 'generation-change');
+ span.setAttr('cache.retry.count', 1);
+ span.setAttr('cache.retry.read_type', 'affected');
+ await emitWatchedQuery(key, true);
+ }
);
return;
}
- } catch (error) {
- reportReadError(error, operation);
- if (!isCurrent()) return;
+ } else if (read?.kind === 'hit') {
+ emitAffectedResult(
+ cacheResult(operation, read.data, false, 'affected-cache-reread')
+ );
+ return;
}
reexecuteAffected(key);
};
@@ -968,14 +989,15 @@ export function normalizedCacheExchange(
}
async function readThenRoute(
- op: Operation
+ op: Operation,
+ previousAttempt?: { networkForwarded: boolean }
): Promise<OperationResult | undefined> {
if (isHydrateOnly(op)) {
enqueueHydrationForward(op);
return undefined;
}
const readState = queryState(op.key);
- const isCurrentRead = beginCacheRead(op.key);
+ const readVersion = beginCacheRead(op.key);
const policy = op.context.requestPolicy;
if (policy === 'network-only') {
enqueueQueryForward(op);
@@ -983,7 +1005,8 @@ export function normalizedCacheExchange(
}
const registrationOnly =
op.context[REPLACEMENT_REGISTRATION_ONLY_CONTEXT_KEY] === true;
- let networkForwarded = false;
+ let networkForwarded = previousAttempt?.networkForwarded ?? false;
+ let read: ReadResult | undefined;
try {
const pendingRead = documentReader.read({
opKey: op.key,
@@ -998,41 +1021,63 @@ export function normalizedCacheExchange(
});
// Admit the cache read first, but never wait for the worker's queue
// before starting a request that needs the network regardless.
- if (policy === 'cache-and-network' && !registrationOnly) {
+ if (
+ policy === 'cache-and-network' &&
+ !registrationOnly &&
+ !networkForwarded
+ ) {
networkForwarded = true;
enqueueQueryForward(op);
}
- const read = await pendingRead;
- if (!isCurrentRead()) return undefined;
- if (read.kind === 'hit') {
- const state = queryState(op.key);
- const stale = networkForwarded && state.networkRequestsInFlight > 0;
- return {
- ...cacheResult(op, read.data, stale),
- // A fast offline failure must not discard a slower usable cache
- // hit, nor may that hit erase the failed revalidation's error.
- error: networkForwarded ? state.networkError : undefined,
- };
- }
- if (policy === 'cache-only') {
- return cacheResult(op, undefined, false);
- }
+ read = await pendingRead;
} catch (error) {
reportReadError(error, op);
if (
isOwnerEpochLostError(error) &&
queryStates.get(op.key) === readState &&
- (isCurrentRead() || readState.networkBoundQueries > 0)
+ (readVersion.isCurrent() || readState.networkBoundQueries > 0)
) {
readState.replacementFallback = true;
}
- if (!isCurrentRead()) return undefined;
- // `cache-only` must never touch the network, even when the cache
- // itself fails — degrade to an empty result instead.
- if (policy === 'cache-only') {
- return cacheResult(op, undefined, false);
+ }
+ if (!readVersion.isCurrent()) {
+ // Teardown, remount, or a newer result still fences this attempt.
+ if (!readVersion.isLatest()) return undefined;
+ if (!previousAttempt) {
+ // Only the generation changed. The host may have routed this read
+ // to the replacement without emitting another affected-key push.
+ // Retry here: urql deduplicates reexecutions of a pending query.
+ return await Telemetry.anonymousSpan(
+ 'graphql_cache.read_retry',
+ async (span) => {
+ span.setAttr('cache.retry.reason', 'generation-change');
+ span.setAttr('cache.retry.count', 1);
+ span.setAttr('cache.retry.read_type', 'operation');
+ span.setAttr('cache.request_policy', policy);
+ const result = await readThenRoute(op, { networkForwarded });
+ span.setAttr('cache.retry.cache_result', result !== undefined);
+ span.setAttr(
+ 'cache.retry.has_data',
+ result?.data !== undefined
+ );
+ return result;
+ }
+ );
}
+ // Bound churn to one fresh read, then use the normal policy fallback.
+ // Never publish a snapshot from the invalidated generation.
+ } else if (read?.kind === 'hit') {
+ const state = queryState(op.key);
+ const stale = networkForwarded && state.networkRequestsInFlight > 0;
+ return {
+ ...cacheResult(op, read.data, stale),
+ // A fast offline failure must not discard a slower usable cache
+ // hit, nor may that hit erase the failed revalidation's error.
+ error: networkForwarded ? state.networkError : undefined,
+ };
}
+ // `cache-only` must never touch the network, including after churn.
+ if (policy === 'cache-only') return cacheResult(op, undefined, false);
if (!networkForwarded && !registrationOnly) enqueueQueryForward(op);
return undefined;
}
diff --git a/apps/web/src/lib/graphql-cache/exchange/replacement-read.test.ts b/apps/web/src/lib/graphql-cache/exchange/replacement-read.test.ts
new file mode 100644
index 0000000000..c977e1f11e
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/replacement-read.test.ts
@@ -0,0 +1,459 @@
+import {
+ createClient,
+ fetchExchange,
+ gql,
+ type OperationResult,
+} from '@urql/core';
+import { describe, expect, it, vi } from 'vitest';
+import { createNoopCacheHost } from '../host/noop-host';
+import type {
+ AffectedOperationsListener,
+ CacheGenerationChange,
+ CacheHost,
+} from '../host/types';
+import {
+ parseCacheRevision,
+ type QueryUpdate,
+ type ReadResult,
+} from '../protocol';
+import { normalizedCacheExchange } from './normalized-cache-exchange';
+
+const QUERY = gql`query ReplacementRead { user { id } }`;
+const OTHER_QUERY = gql`query ReplacementOther { user { id } }`;
+type Data = { user: { id: string } };
+
+function setup() {
+ const first = Promise.withResolvers<ReadResult>();
+ const second = Promise.withResolvers<ReadResult>();
+ const firstStarted = Promise.withResolvers<void>();
+ const secondStarted = Promise.withResolvers<void>();
+ const network = Promise.withResolvers<{ data: Data }>();
+ const networkStarted = Promise.withResolvers<void>();
+ let generationChanged: ((change: CacheGenerationChange) => void) | undefined;
+ let affected: AffectedOperationsListener | undefined;
+ const read = vi
+ .fn<CacheHost['readQuery']>()
+ .mockImplementationOnce(async () => {
+ firstStarted.resolve();
+ return await first.promise;
+ })
+ .mockImplementationOnce(async () => {
+ secondStarted.resolve();
+ return await second.promise;
+ })
+ .mockResolvedValue({ kind: 'hit', data: { user: { id: 'later-read' } } });
+ const fetch = vi.fn(async () => {
+ networkStarted.resolve();
+ return new Response(JSON.stringify(await network.promise), {
+ headers: { 'content-type': 'application/json' },
+ });
+ });
+ const host: CacheHost = {
+ ...createNoopCacheHost(),
+ disabled: false,
+ clientId: 'replacement-read-test',
+ async currentStorageGeneration() {
+ return '00000000-0000-4000-8000-000000000001';
+ },
+ readQuery: read,
+ onOpsAffected(listener) {
+ affected = listener;
+ return () => {};
+ },
+ onCacheGenerationChanged(listener) {
+ generationChanged = listener;
+ return () => {};
+ },
+ };
+ const onCacheError = vi.fn();
+ const client = createClient({
+ url: 'https://replacement-read.invalid/graphql',
+ fetch,
+ exchanges: [normalizedCacheExchange(host, { onCacheError }), fetchExchange],
+ });
+ return {
+ client,
+ host,
+ read,
+ fetch,
+ first,
+ second,
+ firstStarted,
+ secondStarted,
+ network,
+ networkStarted,
+ onCacheError,
+ affect(key: number) {
+ affected?.([key]);
+ },
+ replace(storage: CacheGenerationChange['storage'] = 'preserved') {
+ generationChanged?.({ storage });
+ },
+ };
+}
+
+describe('query reads across engine replacement', () => {
+ it.each(['preserved', 'reset'] as const)(
+ 'delivers a fresh snapshot after a %s generation change',
+ async (storage) => {
+ const s = setup();
+ const pending = s.client.query<Data>(QUERY, {}).toPromise();
+ await s.firstStarted.promise;
+ s.replace(storage);
+ s.first.resolve({
+ kind: 'hit',
+ data: { user: { id: 'old-generation' } },
+ });
+ await s.secondStarted.promise;
+ s.second.resolve({
+ kind: 'hit',
+ data: { user: { id: 'current-generation' } },
+ });
+ expect((await pending).data).toEqual({
+ user: { id: 'current-generation' },
+ });
+ expect(s.read).toHaveBeenCalledTimes(2);
+ expect(s.fetch).not.toHaveBeenCalled();
+ expect(s.onCacheError).not.toHaveBeenCalled();
+ }
+ );
+
+ it('retries cache-only reads without forwarding the network', async () => {
+ const s = setup();
+ const pending = s.client
+ .query<Data>(QUERY, {}, { requestPolicy: 'cache-only' })
+ .toPromise();
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'miss' });
+ await s.secondStarted.promise;
+ s.second.resolve({ kind: 'hit', data: { user: { id: 'current' } } });
+ expect((await pending).data).toEqual({ user: { id: 'current' } });
+ expect(s.fetch).not.toHaveBeenCalled();
+ });
+
+ it('keeps one cache-and-network request and marks its retried hit stale', async () => {
+ const s = setup();
+ const cached = Promise.withResolvers<OperationResult<Data>>();
+ const source = s.client.query<Data>(
+ QUERY,
+ {},
+ { requestPolicy: 'cache-and-network' }
+ );
+ const subscription = source.subscribe((result) => {
+ if (result.data?.user.id === 'current-cache') cached.resolve(result);
+ });
+ const pending = source.toPromise();
+ try {
+ await s.firstStarted.promise;
+ await s.networkStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'old-cache' } } });
+ await s.secondStarted.promise;
+ s.second.resolve({
+ kind: 'hit',
+ data: { user: { id: 'current-cache' } },
+ });
+ expect((await cached.promise).stale).toBe(true);
+ s.network.resolve({ data: { user: { id: 'network' } } });
+ expect((await pending).data).toEqual({ user: { id: 'network' } });
+ expect(s.fetch).toHaveBeenCalledTimes(1);
+ expect(s.read).toHaveBeenCalledTimes(2);
+ } finally {
+ subscription.unsubscribe();
+ }
+ });
+
+ it.each(['miss', 'error'] as const)(
+ 'falls back once when the retry returns a %s',
+ async (outcome) => {
+ const s = setup();
+ const pending = s.client.query<Data>(QUERY, {}).toPromise();
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'old' } } });
+ await s.secondStarted.promise;
+ if (outcome === 'miss') s.second.resolve({ kind: 'miss' });
+ else s.second.reject(new Error('read failed'));
+ await s.networkStarted.promise;
+ s.network.resolve({ data: { user: { id: 'network' } } });
+ expect((await pending).data).toEqual({ user: { id: 'network' } });
+ expect(s.fetch).toHaveBeenCalledTimes(1);
+ expect(s.read).toHaveBeenCalledTimes(2);
+ }
+ );
+
+ it.each(['cache-first', 'cache-only', 'cache-and-network'] as const)(
+ 'bounds retries during repeated generation changes (%s)',
+ async (requestPolicy) => {
+ const s = setup();
+ const pending = s.client
+ .query<Data>(QUERY, {}, { requestPolicy })
+ .toPromise();
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'old-first' } } });
+ await s.secondStarted.promise;
+ s.replace();
+ s.second.resolve({ kind: 'hit', data: { user: { id: 'old-second' } } });
+ if (requestPolicy === 'cache-only') {
+ expect((await pending).data).toBeUndefined();
+ expect(s.fetch).not.toHaveBeenCalled();
+ } else {
+ await s.networkStarted.promise;
+ s.network.resolve({ data: { user: { id: 'network' } } });
+ expect((await pending).data).toEqual({ user: { id: 'network' } });
+ expect(s.fetch).toHaveBeenCalledTimes(1);
+ }
+ expect(s.read).toHaveBeenCalledTimes(2);
+ }
+ );
+
+ it('does not forward a replacement-registration-only read when retrying is exhausted', async () => {
+ const s = setup();
+ const results: OperationResult<Data>[] = [];
+ const subscription = s.client
+ .query<Data>(
+ QUERY,
+ {},
+ {
+ normalizedCacheReplacementRegistrationOnly: true,
+ }
+ )
+ .subscribe((result) => results.push(result));
+ try {
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'miss' });
+ await s.secondStarted.promise;
+ s.replace();
+ s.second.resolve({ kind: 'miss' });
+ // A later successful read also lets the earlier reply finish processing.
+ await s.client.query<Data>(OTHER_QUERY, {}).toPromise();
+ expect(s.fetch).not.toHaveBeenCalled();
+ expect(results).toEqual([]);
+ expect(s.read).toHaveBeenCalledTimes(3);
+ } finally {
+ subscription.unsubscribe();
+ }
+ });
+
+ it('does not resurrect a torn-down query when its key is reused', async () => {
+ const s = setup();
+ const oldResults: OperationResult<Data>[] = [];
+ const subscription = s.client
+ .query<Data>(QUERY, {})
+ .subscribe((result) => oldResults.push(result));
+ await s.firstStarted.promise;
+ s.replace();
+ subscription.unsubscribe();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'retired' } } });
+ const current = s.client.query<Data>(QUERY, {}).toPromise();
+ await s.secondStarted.promise;
+ s.second.resolve({ kind: 'hit', data: { user: { id: 'remounted' } } });
+ expect((await current).data).toEqual({ user: { id: 'remounted' } });
+ expect(oldResults).toEqual([]);
+ expect(s.read).toHaveBeenCalledTimes(2);
+ expect(s.fetch).not.toHaveBeenCalled();
+ });
+
+ it('restarts a watched snapshot without reusing the old cursor', async () => {
+ const s = setup();
+ const started = Promise.withResolvers<void>();
+ const stale = Promise.withResolvers<QueryUpdate>();
+ const watch = vi
+ .fn<NonNullable<CacheHost['watchQuery']>>()
+ .mockImplementationOnce(async () => {
+ started.resolve();
+ return await stale.promise;
+ })
+ .mockResolvedValue({
+ kind: 'hit',
+ revision: parseCacheRevision('2'),
+ data: { user: { id: 'current' } },
+ });
+ s.host.watchQuery = watch;
+ const pending = s.client.query<Data>(QUERY, {}).toPromise();
+ await started.promise;
+ s.replace();
+ stale.resolve({
+ kind: 'hit',
+ revision: parseCacheRevision('1'),
+ data: { user: { id: 'old' } },
+ });
+ expect((await pending).data).toEqual({ user: { id: 'current' } });
+ expect(watch).toHaveBeenCalledTimes(2);
+ expect(watch.mock.calls[1]?.[0].since).toBeUndefined();
+ expect(s.read).not.toHaveBeenCalled();
+ expect(s.fetch).not.toHaveBeenCalled();
+ });
+
+ it('delivers an affected watched read interrupted by replacement', async () => {
+ const s = setup();
+ const initial = Promise.withResolvers<void>();
+ const updated = Promise.withResolvers<void>();
+ const started = Promise.withResolvers<void>();
+ const stale = Promise.withResolvers<QueryUpdate>();
+ let key = 0;
+ const watch = vi
+ .fn<NonNullable<CacheHost['watchQuery']>>()
+ .mockImplementationOnce(async (args) => {
+ key = args.opKey;
+ return {
+ kind: 'hit',
+ revision: parseCacheRevision('1'),
+ data: { user: { id: 'initial' } },
+ };
+ })
+ .mockImplementationOnce(async () => {
+ started.resolve();
+ return await stale.promise;
+ })
+ .mockResolvedValue({
+ kind: 'hit',
+ revision: parseCacheRevision('3'),
+ data: { user: { id: 'current' } },
+ });
+ s.host.watchQuery = watch;
+ const ids: (string | undefined)[] = [];
+ const subscription = s.client.query<Data>(QUERY, {}).subscribe((result) => {
+ ids.push(result.data?.user.id);
+ if (result.data?.user.id === 'initial') initial.resolve();
+ if (result.data?.user.id === 'current') updated.resolve();
+ });
+ try {
+ await initial.promise;
+ s.affect(key);
+ await started.promise;
+ s.replace();
+ stale.resolve({
+ kind: 'hit',
+ revision: parseCacheRevision('2'),
+ data: { user: { id: 'old' } },
+ });
+ await updated.promise;
+ expect(ids).toEqual(['initial', 'current']);
+ expect(watch).toHaveBeenCalledTimes(3);
+ expect(s.fetch).not.toHaveBeenCalled();
+ expect(s.onCacheError).not.toHaveBeenCalled();
+ } finally {
+ subscription.unsubscribe();
+ }
+ });
+
+ it('bounds affected-read retries before normal policy fallback', async () => {
+ const s = setup();
+ const initial = Promise.withResolvers<void>();
+ const updated = Promise.withResolvers<void>();
+ const firstStarted = Promise.withResolvers<void>();
+ const secondStarted = Promise.withResolvers<void>();
+ const first = Promise.withResolvers<QueryUpdate>();
+ const second = Promise.withResolvers<QueryUpdate>();
+ let key = 0;
+ const watch = vi
+ .fn<NonNullable<CacheHost['watchQuery']>>()
+ .mockImplementationOnce(async (args) => {
+ key = args.opKey;
+ return {
+ kind: 'hit',
+ revision: parseCacheRevision('1'),
+ data: { user: { id: 'initial' } },
+ };
+ })
+ .mockImplementationOnce(async () => {
+ firstStarted.resolve();
+ return await first.promise;
+ })
+ .mockImplementationOnce(async () => {
+ secondStarted.resolve();
+ return await second.promise;
+ })
+ .mockResolvedValue({ kind: 'miss', revision: parseCacheRevision('4') });
+ s.host.watchQuery = watch;
+ const ids: (string | undefined)[] = [];
+ const subscription = s.client.query<Data>(QUERY, {}).subscribe((result) => {
+ ids.push(result.data?.user.id);
+ if (result.data?.user.id === 'initial') initial.resolve();
+ if (result.data?.user.id === 'network') updated.resolve();
+ });
+ try {
+ await initial.promise;
+ s.affect(key);
+ await firstStarted.promise;
+ s.replace();
+ first.resolve({
+ kind: 'hit',
+ revision: parseCacheRevision('2'),
+ data: { user: { id: 'invalidated' } },
+ });
+ await secondStarted.promise;
+ s.replace();
+ second.resolve({
+ kind: 'hit',
+ revision: parseCacheRevision('3'),
+ data: { user: { id: 'invalidated' } },
+ });
+ await s.networkStarted.promise;
+ s.network.resolve({ data: { user: { id: 'network' } } });
+ await updated.promise;
+ expect(ids).not.toContain('invalidated');
+ expect(s.fetch).toHaveBeenCalledTimes(1);
+ expect(watch).toHaveBeenCalledTimes(4);
+ } finally {
+ subscription.unsubscribe();
+ }
+ });
+
+ it('discards a retry after teardown and remount of the same key', async () => {
+ const s = setup();
+ const oldResults: OperationResult<Data>[] = [];
+ const subscription = s.client
+ .query<Data>(QUERY, {})
+ .subscribe((result) => oldResults.push(result));
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'old' } } });
+ await s.secondStarted.promise;
+ subscription.unsubscribe();
+ s.second.resolve({ kind: 'hit', data: { user: { id: 'old-retry' } } });
+ s.read.mockResolvedValue({
+ kind: 'hit',
+ data: { user: { id: 'remounted' } },
+ });
+ const result = await s.client.query<Data>(QUERY, {}).toPromise();
+ expect(result.data).toEqual({ user: { id: 'remounted' } });
+ expect(oldResults).toEqual([]);
+ expect(s.read).toHaveBeenCalledTimes(3);
+ expect(s.fetch).not.toHaveBeenCalled();
+ });
+
+ it('does not retry over a newer network result', async () => {
+ const s = setup();
+ const delivered = Promise.withResolvers<void>();
+ const results: OperationResult<Data>[] = [];
+ const subscription = s.client
+ .query<Data>(QUERY, {}, { requestPolicy: 'cache-and-network' })
+ .subscribe((result) => {
+ results.push(result);
+ if (result.data?.user.id === 'network') delivered.resolve();
+ });
+ try {
+ await s.firstStarted.promise;
+ s.replace();
+ s.first.resolve({ kind: 'hit', data: { user: { id: 'old-first' } } });
+ await s.secondStarted.promise;
+ s.network.resolve({ data: { user: { id: 'network' } } });
+ await delivered.promise;
+ s.replace();
+ s.second.resolve({ kind: 'hit', data: { user: { id: 'old-retry' } } });
+ await s.client.query<Data>(OTHER_QUERY, {}).toPromise();
+ expect(results.map((result) => result.data)).toEqual([
+ { user: { id: 'network' } },
+ ]);
+ expect(s.read).toHaveBeenCalledTimes(3);
+ expect(s.fetch).toHaveBeenCalledTimes(1);
+ } finally {
+ subscription.unsubscribe();
+ }
+ });
+});
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
index 2b5264e877..196be7f4a7 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
@@ -50,6 +50,8 @@ const response = Promise.withResolvers<Response>();
const sent = Promise.withResolvers<void>();
const settling = Promise.withResolvers<void>();
let result: Promise<unknown> | undefined;
+let readResult: Promise<{ data: unknown; error: boolean }> | undefined;
+let readApiRequests = 0;
function requireHost(): CacheHost {
if (!host) throw new Error('cache not started');
return host;
@@ -89,6 +91,7 @@ const api = {
seedUuid,
epochs: [...epochs],
apiRequests,
+ readApiRequests,
visibility: document.visibilityState,
};
},
@@ -98,6 +101,41 @@ const api = {
lock.name?.includes(scope)
);
},
+ async beginRead() {
+ const current = requireHost();
+ const watchQuery = current.watchQuery;
+ if (!watchQuery) throw new Error('worker query watches unavailable');
+ const started = Promise.withResolvers<void>();
+ const client = createClient({
+ url: 'https://parking.invalid/graphql',
+ fetch: async () => {
+ readApiRequests += 1;
+ return new Response(JSON.stringify({ data }), {
+ headers: { 'content-type': 'application/json' },
+ });
+ },
+ exchanges: [
+ normalizedCacheExchange({
+ ...current,
+ async watchQuery(args) {
+ const pending = watchQuery(args);
+ started.resolve();
+ return await pending;
+ },
+ }),
+ fetchExchange,
+ ],
+ });
+ readResult = client
+ .query(query, {})
+ .toPromise()
+ .then((result) => ({
+ data: result.data,
+ error: !!result.error,
+ }));
+ await started.promise;
+ },
+ readResult: () => readResult,
async beginMutation() {
const current = requireHost();
await current.writeQuery({ query, data });
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
index eff3ceb153..0319f6f5d4 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
@@ -44,6 +44,44 @@ test('all-hidden storage parks and another page reopens it without waking the ol
expect(old.visibility).toBe('hidden');
});
+test('delivers a query admitted while parked across replacement without API fallback', async ({
+ context,
+ page,
+}, info) => {
+ const url = `${path(info.project.name)}?scope=cache-parking-${crypto.randomUUID()}`;
+ await page.goto(url);
+ await page.evaluate(() => window.cacheParkingHarness.start(true));
+ const before = await page.evaluate(() =>
+ window.cacheParkingHarness.snapshot()
+ );
+ const other = await context.newPage();
+ await other.goto(url);
+ await other.bringToFront();
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await page.evaluate(() => window.cacheParkingHarness.parked());
+ await page.evaluate(() => window.cacheParkingHarness.beginRead());
+ await other.evaluate(() => window.cacheParkingHarness.start());
+ expect(
+ await page.evaluate(() => window.cacheParkingHarness.readResult())
+ ).toEqual({
+ data: { user: { id: 'macro|parking-fixture' } },
+ error: false,
+ });
+ const after = await page.evaluate(() =>
+ window.cacheParkingHarness.snapshot()
+ );
+ expect(after.readApiRequests).toBe(0);
+ expect(after.clientId).toBe(before.clientId);
+ expect(after.generation).toBe(before.generation);
+ expect(after.queue?.map((item) => item.uuid)).toEqual([before.seedUuid]);
+});
+
test('settles a response received while parked before a competing expired-lease claim', async ({
context,
page,
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 267515dfdb..0ff0c72c0b 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -58,8 +58,11 @@ mutation confirmations wait for storage instead of being sent twice.
Verify the all-hidden case without activating the former owner: no held physical
owner lock after parking, preserved generation/queue, and successful reads/writes
-from a returning tab. Also verify a pending HTTP response settling after parking
-and multiple surviving clients. A drain that Safari has already suspended still
+from a returning tab. Start a query while parked, resume storage from another
+tab, and verify that the original query completes—not just a fresh query key.
+Replacement must not strand an in-flight query when it invalidates its snapshot;
+cache-only reads still never use the network. Also verify a pending HTTP response
+settling after parking and multiple surviving clients. A drain that Safari has already suspended still
waits for that worker to resume; no deadline kills it or steals its lock. Lifecycle
telemetry uses `park-started`, `parked`, `unpark-started`, `unpark-completed`, and
`visibility-handoff-*` owner events.