Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(cache): prevent stale reads from replacing fresh query results (#9507)
gbirmanc3a194a0cd1f
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex ce64f51a1d..2c6aaa6eb3 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -482,6 +482,8 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to- Retry still-current query reads once when engine replacement invalidates theirsnapshot; 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.+ Fence affected cache rereads against newer published results too; reconcile+ pending edits against the persisted server snapshot instead of replaying an older one.- 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.mdindex 9739a51530..09bb86c33e 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -473,14 +473,21 @@ the engine directly from its multi-threaded runtime, and unbounded on wasm.### 4.5 urql exchange semantics-- On operation: RPC `readQuery` → full hit: emit (stale-flagged if- `cache-and-network`, then forward to network); partial/miss: forward.-- On network result: RPC `writeQuery`; normalization captures every record the+- On operation: read the cache and emit a full hit; partial/miss: forward.+ `cache-and-network` starts the cache read and network request concurrently,+ emitting a still-current cache hit as stale while the request is pending.+- On network result: publish foreground data before the ordered RPC `writeQuery`;+ normalization captures every record theresponse traverses and installs the active operation's dependencies in thesame write. Complete responses register exact keys; uncertain responses areconservatively affected by every visible change until a later exact read or- write. No post-write denormalizing read is performed. The engine returns the- changed record keys and the exchange re-executes affected active operations.+ write. Persistence acknowledges a revision without replaying the response.+- Initial and affected cache reads share a version guard: a newer published+ result, cache read, teardown, or generation change supersedes an older read.+ A late affected read must not restore old message membership after a fresh+ thread response. Hosts with watched queries reconcile pending local edits+ against the new server snapshot after persistence, including hosts whose watch+ endpoint falls back to a full read.- Hydration-only operations skip cache reads and active-operation registration.Client-only `@cacheOnly` fields are fetched and normalized but omitted fromthe result returned across the worker/Tauri boundary. The directive is@@ -488,7 +495,7 @@ the engine directly from its multi-threaded runtime, and unbounded on wasm.from the validated response during the write, avoiding a denormalizing read.- On teardown: unregister operation (unpins dependencies).- Cross-context: engine broadcasts changed-keys; every context's exchange- re-executes its own affected active operations.+ rereads its own affected active operations, preserving mounted live queries.### 4.6 Coexistence with normy / tanstackdiff --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.tsindex c3eb573ef8..be94a63b6a 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@@ -55,6 +55,7 @@ import {type WriteResult,} from '../protocol';import { entityFromArgument } from './entity-resolvers';+import { liveQueryData } from './live-query';import { NOOP_MUTATION_QUEUE_TELEMETRY } from './mutation-queue-telemetry';import {HYDRATE_ONLY_CONTEXT_KEY,@@ -1907,6 +1908,124 @@ describe('normalizedCacheExchange', () => {expect(forwarded).toHaveLength(1);});+ it.each([false, true])(+ 'never restores stale message membership after a newer network result (persisted: %s)',+ async (persisted) => {+ vi.useFakeTimers();+ try {+ const cached = { messages: ['first'], isRead: true };+ const fresh = { messages: ['first', 'second'], isRead: true };+ const affectedRead = deferred<ReadResult>();+ const write = deferred<WriteResult>();+ host.readQuery = vi+ .fn()+ .mockResolvedValueOnce({ kind: 'hit', data: cached })+ .mockImplementationOnce(() => affectedRead.promise)+ .mockResolvedValue({ kind: 'hit', data: fresh });+ host.writeQuery = vi.fn(() => write.promise);+ const { ops, results, forwarded, network } =+ controlledQueryHarness(host);++ ops.next(makeOp(1, 'cache-and-network'));+ await vi.advanceTimersByTimeAsync(0);+ host.pushAffected([1]);+ await vi.advanceTimersByTimeAsync(0);++ network.next(queryResult(forwarded[0]!, fresh));+ await vi.advanceTimersByTimeAsync(0);+ expect(results.map((result) => result.data)).toEqual([cached, fresh]);++ const acknowledgeWrite = () =>+ write.resolve({+ revision: INITIAL_CACHE_REVISION,+ revisionAdvanced: true,+ changed: [],+ affectedOps: [],+ reset: false,+ });+ if (persisted) {+ acknowledgeWrite();+ await vi.advanceTimersByTimeAsync(0);+ }+ affectedRead.resolve({ kind: 'hit', data: cached });+ await vi.advanceTimersByTimeAsync(0);+ if (!persisted) acknowledgeWrite();+ await vi.advanceTimersByTimeAsync(0);++ expect(results.map((result) => result.data)).toEqual([cached, fresh]);+ expect(forwarded).toHaveLength(1);+ } finally {+ vi.useRealTimers();+ }+ }+ );++ it.each(['watch', 'fallback'])(+ 'reconciles pending edits with fresh message membership after discarding an older %s read',+ async (reader) => {+ vi.useFakeTimers();+ try {+ const cached = { messages: ['first'], isRead: false };+ const fresh = { messages: ['first', 'second'], isRead: false };+ const reconciled = { ...fresh, isRead: true };+ const lateSnapshot = {+ kind: 'hit' as const,+ data: { ...cached, isRead: true },+ revision: parseCacheRevision('2'),+ };+ const affectedRead = deferred<typeof lateSnapshot>();+ const write = deferred<WriteResult>();+ const read = vi+ .fn()+ .mockResolvedValueOnce({+ kind: 'hit',+ data: cached,+ revision: parseCacheRevision('1'),+ })+ .mockImplementationOnce(() => affectedRead.promise)+ .mockResolvedValue({+ kind: 'hit',+ data: reconciled,+ revision: parseCacheRevision('3'),+ });+ host.watchQuery =+ reader === 'watch'+ ? read+ : vi.fn(async () => ({ kind: 'unsupported' as const }));+ host.readQuery = read;+ host.writeQuery = vi.fn(() => write.promise);+ const { ops, results, forwarded, network } =+ controlledQueryHarness(host);++ ops.next(makeOp(1, 'cache-and-network'));+ await vi.advanceTimersByTimeAsync(0);+ host.pushAffected([1]);+ await vi.advanceTimersByTimeAsync(0);+ network.next(queryResult(forwarded[0]!, fresh));+ await vi.advanceTimersByTimeAsync(0);+ const live = liveQueryData(results.at(-1)!);++ affectedRead.resolve(lateSnapshot);+ await vi.advanceTimersByTimeAsync(0);+ expect(live).toEqual(fresh);+ write.resolve({+ revision: parseCacheRevision('3'),+ revisionAdvanced: true,+ changed: [],+ affectedOps: [],+ reset: false,+ });+ await vi.advanceTimersByTimeAsync(0);++ expect(live).toEqual(reconciled);+ expect(results.map((result) => result.data)).toEqual([cached, fresh]);+ expect(forwarded).toHaveLength(1);+ } finally {+ vi.useRealTimers();+ }+ }+ );+it('preserves optimistic rereads that finish after network persistence', async () => {const write = deferred<WriteResult>();const affectedRead = deferred<ReadResult>();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.tsindex 4eedd0625c..c2827d0625 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@@ -670,11 +670,10 @@ export function normalizedCacheExchange(const operation = activeOps.get(key);if (!operation) return;const state = queryState(key);- // Supersede the initial cache snapshot. An affected reread carries newer- // local/optimistic state, so let it complete even if network persistence- // finishes first; only teardown/remount may discard that update.- state.cacheReadVersion += 1;- const generation = cacheGeneration;+ // Supersede the initial cache snapshot, but let a newer published result+ // supersede this read too. Pending local edits are reconciled against the+ // new server snapshot after persistence, never through an older snapshot.+ const readVersion = beginCacheRead(key);await documentReader.read({opKey: operation.key,@@ -686,12 +685,7 @@ export function normalizedCacheExchange(}).then((read) => {const active = activeOps.get(key);- if (- generation !== cacheGeneration ||- read.kind !== 'hit' ||- !active ||- queryStates.get(key) !== state- )+ if (!readVersion.isCurrent() || read.kind !== 'hit' || !active)return;// Preserve the authoritative request while immediately surfacing the// newer local view. Its eventual result still gets the deferred