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): keep mounted live data when a refetch fails (#8711)
gbirmanfdf98669607e
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex 48fb93c0c2..d9d66fc452 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -610,7 +610,9 @@ const accounts = () => accountQuery.data?.user.emailLinks ?? [];identity. `refetch`, request policies, loading/error state and selection functionsretain the existing urql-solid contract. Existing `createUrqlQuery` and`createUrqlInfiniteQuery` consumers use the same live projection path without-being rewritten; every loaded infinite-query page stays subscribed.+being rewritten; every loaded infinite-query page stays subscribed. A failed+refetch reports its error but leaves mounted live data as it was: its partial+nulls are neither persisted nor reconciled into the objects readers hold.Mutation predictions are keyed by mutation field and registered once per field,alongside domain query definitions. A representative generated document namesdiff --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 325f06225f..d8ade8b92c 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@@ -765,6 +765,172 @@ describe('normalizedCacheExchange', () => {});+ it('keeps mounted live data when a refresh of the same query fails with partial data', async () => {+ type Page = {+ user: { soup: { items: { __typename: string; id: string }[] } | null };+ };+ const soup = gql<Page>`query Soup { user { soup { items { __typename id } } } }`;+ const responses: Pick<OperationResult, 'data' | 'error'>[] = [+ { data: { user: { soup: { items: [{ __typename: 'Doc', id: '1' }] } } } },+ {+ data: { user: { soup: null } },+ error: new CombinedError({+ graphQLErrors: [+ { message: 'pool timed out while waiting for an open connection' },+ ],+ }),+ },+ ];+ const client = createClient({+ url: '/graphql',+ exchanges: [+ normalizedCacheExchange(host),+ () => (source) =>+ pipe(+ source,+ map((operation) => ({+ operation,+ stale: false,+ hasNext: false,+ ...responses.shift(),+ }))+ ),+ ],+ });+ const { mounted, dispose } = createRoot((dispose) => ({+ mounted: createUrqlQuery(() => ({+ client,+ query: soup,+ variables: {},+ requestPolicy: 'network-only' as const,+ })),+ dispose,+ }));+ try {+ await vi.waitFor(() => expect(mounted.isSuccess).toBe(true));+ const page = mounted.data!;++ const refresh = await client+ .query(soup, {}, { requestPolicy: 'network-only' })+ .toPromise();++ expect(refresh.error?.message).toContain('pool timed out');+ expect(page.user.soup?.items.map((item) => item.id)).toEqual(['1']);+ } finally {+ dispose();+ }+ });++ it('keeps the mounted live view through a refresh that fails without data', async () => {+ type Page = { rows: { __typename: string; id: string }[] };+ const rows = gql<Page>`query Rows { rows { __typename id } }`;+ const responses: Pick<OperationResult, 'data' | 'error'>[] = [+ { data: { rows: [{ __typename: 'Thread', id: '1' }] } },+ {+ data: undefined,+ error: new CombinedError({ networkError: new Error('offline') }),+ },+ { data: { rows: [{ __typename: 'Thread', id: '2' }] } },+ ];+ const client = createClient({+ url: '/graphql',+ exchanges: [+ normalizedCacheExchange(host),+ () => (source) =>+ pipe(+ source,+ map((operation) => ({+ operation,+ stale: false,+ hasNext: false,+ ...responses.shift(),+ }))+ ),+ ],+ });+ const { mounted, dispose } = createRoot((dispose) => ({+ mounted: createUrqlQuery(() => ({+ client,+ query: rows,+ variables: {},+ requestPolicy: 'network-only' as const,+ })),+ dispose,+ }));+ try {+ await vi.waitFor(() => expect(mounted.isSuccess).toBe(true));+ const page = mounted.data!;+ const refresh = () =>+ client.query(rows, {}, { requestPolicy: 'network-only' }).toPromise();++ expect((await refresh()).error?.networkError?.message).toBe('offline');+ expect(page.rows.map((row) => row.id)).toEqual(['1']);++ await refresh();+ expect(page.rows.map((row) => row.id)).toEqual(['2']);+ } finally {+ dispose();+ }+ });++ it('applies a cache hit that carries an earlier network failure', async () => {+ type Page = { rows: { __typename: string; id: string }[] };+ const rows = gql<Page>`query Rows { rows { __typename id } }`;+ const failure = () => ({+ data: { rows: [] },+ error: new CombinedError({+ graphQLErrors: [{ message: 'database unavailable' }],+ }),+ });+ host.scriptRead({+ kind: 'hit',+ data: { rows: [{ __typename: 'Thread', id: '1' }] },+ });+ const client = createClient({+ url: '/graphql',+ exchanges: [+ normalizedCacheExchange(host),+ () => (source) =>+ pipe(+ source,+ map((operation) => ({+ operation,+ stale: false,+ hasNext: false,+ ...failure(),+ }))+ ),+ ],+ });+ const { mounted, dispose } = createRoot((dispose) => ({+ mounted: createUrqlQuery(() => ({+ client,+ query: rows,+ variables: {},+ requestPolicy: 'cache-and-network' as const,+ })),+ dispose,+ }));+ try {+ await vi.waitFor(() => expect(mounted.error).toBeTruthy());+ expect(mounted.data?.rows.map((row) => row.id)).toEqual(['1']);++ host.scriptRead({+ kind: 'hit',+ data: { rows: [{ __typename: 'Thread', id: '2' }] },+ });+ await client+ .query(rows, {}, { requestPolicy: 'cache-and-network' })+ .toPromise();++ await vi.waitFor(() =>+ expect(mounted.data?.rows.map((row) => row.id)).toEqual(['2'])+ );+ } finally {+ dispose();+ }+ });+it('keeps live objects reactive through full reads on older cache hosts', async () => {type Rows = { rows: { __typename: string; id: string; isRead: boolean }[] };const first = gql<Rows>`query First { rows { __typename id isRead } }`;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 89b1b07749..56ae1eb475 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@@ -1565,6 +1565,26 @@ export function normalizedCacheExchange(!activeOps.has(result.operation.key))return result;+ const current = liveQueries.get(result.operation.key);+ // As with persistence, a failed network response (partial nulls or+ // no data at all) is not authoritative: mounted readers keep the view+ // they hold and later results keep updating it. Cache reads still+ // apply when they carry that failure's error.+ if (+ current &&+ result.error !== undefined &&+ normalizedCacheResultMetadata(result)?.source === 'live-network'+ ) {+ const liveResult = withLiveQueryData(+ { ...result },+ current.view.data+ );+ liveQueries.set(result.operation.key, {+ view: current.view,+ result: liveResult,+ });+ return liveResult;+ }if (!isQueryObject(result.data) ||!supportsStoreReconciliation(result.data)@@ -1572,7 +1592,6 @@ export function normalizedCacheExchange(liveQueries.delete(result.operation.key);return result;}- const current = liveQueries.get(result.operation.key);const view =current?.view ??new LiveQuery(result.data, queryShape(result.operation.query));diff --git a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.tsindex 406c900284..ad732a5257 100644--- a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts+++ b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts@@ -177,9 +177,14 @@ export function createSoupLiveQuery(let networkAuthorityInput: GraphqlSoupInput | undefined;let staleFallbackSpan: ReturnType<typeof Telemetry.span> | undefined;- const recordAuthority = (source: 'network' | 'local' | 'stale-fallback') => {+ const recordAuthority = (+ source: 'network' | 'failed-network' | 'local' | 'stale-fallback',+ pageIndex?: number+ ) => {const span = Telemetry.span('graphql_cache.soup_authority');span.setAttr('authority.source', source);+ if (pageIndex !== undefined)+ span.setAttr('authority.page_index', pageIndex);span.end();};const finishStaleFallback = (source: 'network' | 'local') => {@@ -349,12 +354,20 @@ export function createSoupLiveQuery(: 'cache-and-network',keepPreviousData: queryOptions.keepPreviousData ?? false,onResult: (result, page) => {- if (!result.data) return;- batch(() => {- setBaselineGeneration(cacheGeneration);- setBaselineInputKey(firstInputKey);- });const metadata = normalizedCacheResultMetadata(result);+ if (result.data) {+ batch(() => {+ setBaselineGeneration(cacheGeneration);+ setBaselineInputKey(firstInputKey);+ });+ }+ if (result.error && metadata?.source === 'live-network') {+ // The exchange keeps the rows already shown; a failed response's+ // partial data claims no authority over them or the local rows.+ recordAuthority('failed-network', page.pageIndex);+ return;+ }+ if (!result.data) return;if (metadata?.source !== 'live-network') {// An affected/cache result already reflects local state. Its pending// network acknowledgement may no longer claim authority over it.