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
refactor(cache): key optimistic resolvers by mutation field (#7822)
teo59cca480ed0a
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex 728977afc7..718cd8e504 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -584,7 +584,10 @@ retain the existing urql-solid contract. Existing `createUrqlQuery` and`createUrqlInfiniteQuery` consumers use the same live projection path withoutbeing rewritten; every loaded infinite-query page stays subscribed.-Mutation predictions are registered once, alongside domain query definitions:+Mutation predictions are keyed by mutation field and registered once per field,+alongside domain query definitions. A representative generated document names+the field, types its arguments through the document's variables, and types the+predicted value through its selection:```tsoptimisticResolver(MarkEmailThreadSeenDocument, ({ input }) => ({@@ -593,12 +596,29 @@ optimisticResolver(MarkEmailThreadSeenDocument, ({ input }) => ({isRead: true,}));-// Any caller can then execute the ordinary generated mutation.+// Any caller can then execute the ordinary generated mutation, or any other+// document that selects markEmailThreadSeen.await client.mutation(MarkEmailThreadSeenDocument, {input: { threadId },}).toPromise();```+The representative must pass every field argument as a same-named variable, so+its variables and the field's arguments coincide. For each mutation without an+explicit optimistic context, the exchange evaluates every root field's arguments+against the operation's variables (substituting variables and applying variable+defaults) and places the resolver's value under that document's response key.+Predictions are all or nothing: if any root field has no resolver, carries a+directive such as `@include` or `@skip`, or its resolver returns `undefined`, the+operation is sent without a prediction. Registering two resolvers for one field+is an error.++Cache-core normalizes the prediction through the executing document's selection.+Fields that document does not select are ignored, and selected fields missing+from the prediction keep their cached values on existing entities. Nested+response keys come from the representative, so a document that selects a field+under a different alias does not receive that field's predicted value.+The durable optimistic queue owns ordering, retries, commit and rollback. Thequery author supplies no optimistic callbacks, result traversal or cache writes.Both the list and a detail query for that thread observe the same effective@@ -629,13 +649,20 @@ Invalidations arriving during a refresh cause a trailing authorized read insteadof being discarded; simultaneous refresh requests share one read.[Mutation coverage](../src/lib/queries/mutation-coverage.test.ts) enumerates all-33 mutation documents and fails when a document has no declared strategy:+35 mutation documents and fails when a document has no declared strategy.+Because predictions are keyed by mutation field, it also checks that local+resolver documents select only resolved fields, and that any other document+reaching a field resolver is a listed exception the resolver declines.+RenameDatabase and RenameForm call `renameEntities` and so reach its resolver,+which declines database and form entities; they stay authoritative, and the test+proves they receive no prediction. Each representative document must declare+every schema argument of its field with the schema's type:| Strategy | Operations || --- | --- || Local resolver (7) | MarkEmailThreadSeen, MarkEmailThreadUnread, SetEmailThreadArchived, UpdateNotifications, RenameEntities, UpdateInitiative, DeleteEntityProperty |-| Existing domain optimistic recipe (10) | SaveEmailDraft, DeleteEmailDraft, SetFavorite, ReorderFavorites, SetEntityProperty, UpdateEntityPropertyOptions, CreateCalendarEvent, UpdateCalendarEvent, DeleteCalendarEvent, RespondToCalendarEvent |-| Authoritative outcome (9) | CreateInitiative, DeleteInitiative, EnsureInitiativeDescriptionSurface, RenameDatabase, TrashDatabase, RenameForm, TrashForm, RecordChannelActivity, UpdateNotificationsForEntity |+| Existing domain optimistic recipe (11) | SaveEmailDraft, DeleteEmailDraft, SetFavorite, ReorderFavorites, SetEntityProperty, UpdateEntityPropertyOptions, CreateCalendarEvent, UpdateCalendarEvent, DeleteCalendarEvent, RespondToCalendarEvent, MarkWorkFeedItemsDone |+| Authoritative outcome (10) | CreateInitiative, DeleteInitiative, EnsureInitiativeDescriptionSurface, RenameDatabase, TrashDatabase, RenameForm, TrashForm, RecordChannelActivity, UpdateNotificationsForEntity, UndoWorkFeedItemsDone || Document only; no production caller (7) | MoveEntities, UpdateEntitySharePolicies, TrashEntities, RestoreEntities, DeleteEntitiesPermanently, DuplicateEntities, SetEntityFavorite |The project resolver predicts names and members; sharing waits for the server.diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic-authoring.typecheck.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic-authoring.typecheck.tsindex 933fadc233..b8806db02a 100644--- a/apps/web/src/lib/graphql-cache/exchange/optimistic-authoring.typecheck.ts+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic-authoring.typecheck.ts@@ -3,14 +3,22 @@ import { optimisticResolver } from './optimistic-resolvers';/** Compile-time contract: recipes are checked against their generated documents. */export function checkOptimisticMutationTypes() {- optimisticResolver(MarkEmailThreadSeenDocument, (variables) => {- // @ts-expect-error Variables must come from the generated mutation.- variables.threadId;- return {- id: String(variables.input.threadId),- isRead: true,- };- });+ optimisticResolver(+ MarkEmailThreadSeenDocument,+ (args) => {+ // @ts-expect-error Arguments are typed by the generated mutation variables.+ args.threadId;+ return {+ id: String(args.input.threadId),+ isRead: true,+ };+ },+ (args) => {+ // @ts-expect-error Options receive the same typed arguments.+ args.threadId;+ return {};+ }+ );// @ts-expect-error Changed records must retain their normalized identity.optimisticResolver(MarkEmailThreadSeenDocument, () => ({ isRead: true }));optimisticResolver(MarkEmailThreadSeenDocument, () => ({diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.test.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.test.tsindex d142fcc20c..1d53ec716e 100644--- a/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.test.ts+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.test.ts@@ -10,8 +10,13 @@ import {} from './optimistic-resolvers';describe('automatic local mutation resolvers', () => {- function setup(resolvers?: readonly OptimisticResolver[]) {+ function setup(+ resolvers = (seen: OptimisticResolver): readonly OptimisticResolver[] => [+ seen,+ ]+ ) {const forwarded: Operation[] = [];+ const resolved: unknown[] = [];const capture: Exchange = () => (source) =>pipe(source,@@ -25,48 +30,166 @@ describe('automatic local mutation resolvers', () => {});}));- const resolver = optimisticResolver(- MarkEmailThreadSeenDocument,- ({ input }) => {- if (input.threadId === 'invalid')- throw new Error('Invalid local prediction');- return { id: String(input.threadId), isRead: true };- }- );+ const resolver = optimisticResolver(MarkEmailThreadSeenDocument, (args) => {+ resolved.push(args);+ if (args.input.threadId === 'invalid')+ throw new Error('Invalid local prediction');+ return { id: String(args.input.threadId), isRead: true };+ });const client = createClient({url: 'http://test.invalid',- exchanges: [- optimisticResolversExchange(resolvers ?? [resolver]),- capture,- ],+ exchanges: [optimisticResolversExchange(resolvers(resolver)), capture],});- return { client, forwarded, resolver };+ return { client, forwarded, resolved, resolver };}- it('uses the selected response alias without requiring a response envelope', async () => {+ it('predicts the field for another document under its own response key', async () => {+ const { client, forwarded, resolved } = setup();+ await client+ .mutation(+ gql`+ mutation Seen($id: ID!) {+ __typename+ changed: markEmailThreadSeen(input: { threadId: $id }) {+ isRead+ }+ }+ `,+ { id: 'thread' }+ )+ .toPromise();+ expect(resolved).toEqual([{ input: { threadId: 'thread' } }]);+ expect(optimisticContextOf(forwarded[0])?.optimisticResponse).toEqual({+ changed: { id: 'thread', isRead: true },+ });+ });++ it('evaluates literal arguments with variable defaults and omits absent variables', async () => {+ const resolved: unknown[] = [];const document = gql<- { __typename: 'Mutation'; changed: { id: string; isRead: boolean } },- { id: string }- >`- mutation Seen($id: ID!) {- __typename- changed: markEmailThreadSeen(input: { threadId: $id }) {- id- isRead- }+ { apply: boolean },+ {+ input?: { id?: string; tags?: string[]; mode?: string };+ limit?: number;}- `;- const resolver = optimisticResolver(document, ({ id }) => ({- id,- isRead: true,- }));- const { client, forwarded } = setup([resolver]);- await client.mutation(document, { id: 'thread' }).toPromise();+ >`mutation Apply($input: ApplyInput, $limit: Int) { apply(input: $input, limit: $limit) }`;+ const { client, forwarded } = setup(() => [+ optimisticResolver(document, (args) => {+ resolved.push(args);+ return true;+ }),+ ]);+ await client+ .mutation(+ gql`+ mutation ApplyFast($id: ID = "default", $tag: String, $limit: Int) {+ apply(input: { id: $id, tags: [$tag, "fixed"], mode: FAST }, limit: $limit)+ }+ `,+ { tag: 'one' }+ )+ .toPromise();+ expect(resolved).toEqual([+ { input: { id: 'default', tags: ['one', 'fixed'], mode: 'FAST' } },+ ]);+ expect(Object.keys(resolved[0] as object)).toEqual(['input']);expect(optimisticContextOf(forwarded[0])?.optimisticResponse).toEqual({- changed: { id: 'thread', isRead: true },+ apply: true,});});+ it('predicts every root field and merges their options', async () => {+ const lookup = gql`query Thread($id: ID!) { thread(id: $id) { id } }`;+ const archive = gql<+ { archived: boolean },+ { threadId: string }+ >`mutation Archive($threadId: ID!) { archived(threadId: $threadId) }`;+ const { client, forwarded } = setup(() => [+ optimisticResolver(+ MarkEmailThreadSeenDocument,+ ({ input }) => ({ id: String(input.threadId), isRead: true }),+ ({ input }) => ({+ revalidations: [+ { document: lookup, variables: { id: input.threadId } },+ ],+ })+ ),+ optimisticResolver(+ archive,+ () => true,+ ({ threadId }) => ({+ revalidations: [{ document: lookup, variables: { id: threadId } }],+ })+ ),+ ]);+ await client+ .mutation(+ gql`+ mutation SeenAndArchived {+ first: markEmailThreadSeen(input: { threadId: "first" }) { id }+ archived(threadId: "second")+ third: markEmailThreadSeen(input: { threadId: "third" }) { id }+ }+ `,+ {},+ {+ optimisticMutation: {+ revalidations: [{ document: lookup, variables: { id: 'caller' } }],+ },+ }+ )+ .toPromise();+ const context = optimisticContextOf(forwarded[0]);+ expect(context?.optimisticResponse).toEqual({+ first: { id: 'first', isRead: true },+ archived: true,+ third: { id: 'third', isRead: true },+ });+ expect(+ context?.revalidations.map((entry) => JSON.parse(entry.variablesJson).id)+ ).toEqual(['first', 'second', 'third', 'caller']);+ });++ it.each([+ [+ 'an unregistered field',+ gql`mutation Mixed { markEmailThreadSeen(input: { threadId: "thread" }) { id } other }`,+ ],+ [+ 'a conditional field',+ gql`mutation Conditional($skip: Boolean!) { markEmailThreadSeen(input: { threadId: "thread" }) @skip(if: $skip) { id } }`,+ ],+ [+ 'a root fragment',+ gql`mutation Spread { ...Root } fragment Root on Mutation { markEmailThreadSeen(input: { threadId: "thread" }) { id } }`,+ ],+ ])('sends %s without any prediction', async (_, document) => {+ const { client, forwarded, resolved } = setup();+ await client.mutation(document, { skip: false }).toPromise();+ expect(forwarded).toHaveLength(1);+ expect(optimisticContextOf(forwarded[0])).toBeUndefined();+ expect(resolved).toEqual([]);+ });++ it('sends no partial prediction when one root field declines', async () => {+ const declined = gql<{+ declined: boolean;+ }>`mutation Declined { declined }`;+ const { client, forwarded, resolved } = setup((seen) => [+ seen,+ optimisticResolver(declined, () => undefined),+ ]);+ await client+ .mutation(+ gql`mutation Both { markEmailThreadSeen(input: { threadId: "thread" }) { id } declined }`,+ {}+ )+ .toPromise();+ expect(resolved).toHaveLength(1);+ expect(forwarded).toHaveLength(1);+ expect(optimisticContextOf(forwarded[0])).toBeUndefined();+ });+it('combines variable-dependent resolver options with caller options', async () => {const lookup = gql`query Thread($id: ID!) { thread(id: $id) { id } }`;const resolver = optimisticResolver(@@ -78,7 +201,7 @@ describe('automatic local mutation resolvers', () => {],}));- const { client, forwarded } = setup([resolver]);+ const { client, forwarded } = setup(() => [resolver]);await client.mutation(MarkEmailThreadSeenDocument,@@ -103,7 +226,7 @@ describe('automatic local mutation resolvers', () => {const document = gql<{applied: boolean | null;}>`mutation Apply { applied }`;- const { client, forwarded } = setup([+ const { client, forwarded } = setup(() => [optimisticResolver(document, () => value),]);await client.mutation(document, {}).toPromise();@@ -153,10 +276,17 @@ describe('automatic local mutation resolvers', () => {expect(forwarded).toHaveLength(1);});- it('rejects ambiguous registration and non-mutation documents', () => {+ it('rejects a second resolver for the same field and non-mutation documents', () => {const { resolver } = setup();- expect(() => optimisticResolversExchange([resolver, resolver])).toThrow(- 'Duplicate'+ const aliased = optimisticResolver(+ gql<+ { seen: { id: string } },+ { input: { threadId: string } }+ >`mutation Aliased($input: MarkEmailThreadSeenInput!) { seen: markEmailThreadSeen(input: $input) { id } }`,+ ({ input }) => ({ id: input.threadId })+ );+ expect(() => optimisticResolversExchange([resolver, aliased])).toThrow(+ 'Duplicate optimistic resolver for mutation field markEmailThreadSeen');expect(() =>optimisticResolver(gql`query Read { id }`, () => undefined)@@ -174,4 +304,18 @@ describe('automatic local mutation resolvers', () => {'one unconditional top-level mutation field');});++ it.each([+ gql`mutation Nested($id: ID!) { first(input: { id: $id }) { id } }`,+ gql`mutation Renamed($other: ID!) { first(id: $other) { id } }`,+ gql`mutation Constant { first(id: "id") { id } }`,+ gql`mutation Unused($id: ID!, $extra: Boolean) { first(id: $id) { id } }`,+ ])(+ 'requires representative arguments to be same-named variables',+ (document) => {+ expect(() => optimisticResolver(document, () => undefined)).toThrow(+ 'same-named variable'+ );+ }+ );});diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.tsindex cf38939bc8..7f5254a8eb 100644--- a/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.ts+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic-resolvers.ts@@ -1,11 +1,13 @@import type { TypedDocumentNode } from '@graphql-typed-document-node/core';+import { type AnyVariables, type Exchange, makeOperation } from '@urql/core';import {- type AnyVariables,- type Exchange,- makeOperation,- stringifyDocument,-} from '@urql/core';-import { getOperationAST, Kind } from 'graphql';+ type DocumentNode,+ type FieldNode,+ getOperationAST,+ Kind,+ type OperationDefinitionNode,+ valueFromASTUntyped,+} from 'graphql';import {type OptimisticCallOptions,type OptimisticPatch,@@ -14,21 +16,33 @@ import {} from './optimistic';import { prepareOptimisticExchange } from './prepare-optimistic';-type LocalMutation = {- response: unknown;+type FieldPrediction = {+ value: unknown;options?: OptimisticCallOptions;};+type LocalMutation = {+ response: Record<string, unknown>;+ options: OptimisticCallOptions;+};+type MutationValue<TData> = TData[Exclude<keyof TData, '__typename'>];export type OptimisticResolver = {- document: string;- resolve: (variables: AnyVariables) => LocalMutation | undefined;+ /** Mutation root field predicted in every document that selects it. */+ field: string;+ /** Representative document whose variables type the field's arguments. */+ document: DocumentNode;+ resolve: (args: Record<string, unknown>) => FieldPrediction | undefined;};/**- * Predict the value of one unconditional top-level mutation field. The document- * supplies its response key (including aliases); return undefined to skip the+ * Predict one mutation root field for every document that selects it. The+ * representative document must pass each field argument as a same-named+ * variable, so its variables type the evaluated arguments. The value is typed+ * by the representative's selection and placed under each document's own+ * response key; normalization ignores fields that document does not select,+ * including nested aliases it does not share. Return undefined to skip the* prediction. Define optional queue/link behavior separately from field values.*/export function optimisticResolver<@@ -37,8 +51,8 @@ export function optimisticResolver<const TPatch extends OptimisticPatch<NoInfer<MutationValue<TData>>>,>(document: TypedDocumentNode<TData, TVariables>,- resolve: (variables: TVariables) => TPatch | undefined,- options?: (variables: TVariables) => OptimisticCallOptions+ resolve: (args: TVariables) => TPatch | undefined,+ options?: (args: TVariables) => OptimisticCallOptions): OptimisticResolver {const operation = getOperationAST(document);if (operation?.operation !== 'mutation') {@@ -61,33 +75,142 @@ export function optimisticResolver<'An optimistic resolver requires one unconditional top-level mutation field');}- const responseKey = field.alias?.value ?? field.name.value;+ const variables = new Set(+ operation.variableDefinitions?.map(({ variable }) => variable.name.value)+ );+ const args = field.arguments ?? [];+ if (+ args.length !== variables.size ||+ args.some(+ ({ name, value }) =>+ value.kind !== Kind.VARIABLE ||+ value.name.value !== name.value ||+ !variables.has(name.value)+ )+ ) {+ throw new TypeError(+ 'An optimistic resolver document must pass each field argument as a same-named variable'+ );+ }return {- document: stringifyDocument(document),- // Type erasure is private to the document/variables binding above.- resolve: (variables) => {- const typedVariables = variables as TVariables;- const value = resolve(typedVariables);+ field: field.name.value,+ document,+ // Type erasure is private to the argument/variable binding checked above.+ resolve: (args) => {+ const typedArgs = args as TVariables;+ const value = resolve(typedArgs);if (value === undefined) return undefined;- return {- response: { [responseKey]: value },- options: options?.(typedVariables),- };+ return { value, options: options?.(typedArgs) };},};}-/** Install immediately before normalizedCacheExchange, which owns settlement. */-export function optimisticResolversExchange(+function resolversByField(resolvers: readonly OptimisticResolver[]-): Exchange {- const byDocument = new Map<string, OptimisticResolver>();+): ReadonlyMap<string, OptimisticResolver> {+ const byField = new Map<string, OptimisticResolver>();for (const resolver of resolvers) {- if (byDocument.has(resolver.document)) {- throw new TypeError('Duplicate optimistic mutation resolver');+ if (byField.has(resolver.field)) {+ throw new TypeError(+ `Duplicate optimistic resolver for mutation field ${resolver.field}`+ );}- byDocument.set(resolver.document, resolver);+ byField.set(resolver.field, resolver);}+ return byField;+}++function mergeOptions(+ base: OptimisticCallOptions,+ next: OptimisticCallOptions = {}+): OptimisticCallOptions {+ return {+ ...base,+ ...next,+ updates: [...(base.updates ?? []), ...(next.updates ?? [])],+ revalidations: [+ ...(base.revalidations ?? []),+ ...(next.revalidations ?? []),+ ],+ identityBindings: [+ ...(base.identityBindings ?? []),+ ...(next.identityBindings ?? []),+ ],+ };+}++/** Runtime variables, with the operation's defaults for omitted ones. */+function variableValues(+ operation: OperationDefinitionNode,+ variables: AnyVariables+): Record<string, unknown> {+ const values: Record<string, unknown> = { ...(variables ?? {}) };+ for (const { variable, defaultValue } of operation.variableDefinitions ??+ []) {+ if (defaultValue && values[variable.name.value] === undefined) {+ values[variable.name.value] = valueFromASTUntyped(defaultValue);+ }+ }+ return values;+}++/** An argument bound to an omitted variable is omitted, as on the server. */+function fieldArguments(+ field: FieldNode,+ variables: Record<string, unknown>+): Record<string, unknown> {+ const args: Record<string, unknown> = {};+ for (const argument of field.arguments ?? []) {+ const value = valueFromASTUntyped(argument.value, variables);+ if (value !== undefined) args[argument.name.value] = value;+ }+ return args;+}++function predict(+ byField: ReadonlyMap<string, OptimisticResolver>,+ document: DocumentNode,+ variables: AnyVariables+): LocalMutation | undefined {+ const operation = getOperationAST(document);+ if (operation?.operation !== 'mutation') return undefined;+ // All or nothing: a queued mutation reports its prediction as the result,+ // so an unpredicted root field would surface as missing data.+ const fields: [FieldNode, OptimisticResolver][] = [];+ for (const selection of operation.selectionSet.selections) {+ if (selection.kind !== Kind.FIELD) return undefined;+ if (selection.name.value === '__typename') continue;+ const resolver = byField.get(selection.name.value);+ if (!resolver || selection.directives?.length) return undefined;+ fields.push([selection, resolver]);+ }+ if (!fields.length) return undefined;+ const values = variableValues(operation, variables);+ const response: Record<string, unknown> = {};+ let options: OptimisticCallOptions = {};+ for (const [field, resolver] of fields) {+ const local = resolver.resolve(fieldArguments(field, values));+ if (!local) return undefined;+ response[field.alias?.value ?? field.name.value] = local.value;+ options = mergeOptions(options, local.options);+ }+ return { response, options };+}++/** The prediction the exchange attaches to one mutation, if any. */+export function predictOptimisticMutation(+ resolvers: readonly OptimisticResolver[],+ document: DocumentNode,+ variables: AnyVariables+): LocalMutation | undefined {+ return predict(resolversByField(resolvers), document, variables);+}++/** Install immediately before normalizedCacheExchange, which owns settlement. */+export function optimisticResolversExchange(+ resolvers: readonly OptimisticResolver[]+): Exchange {+ const byField = resolversByField(resolvers);return prepareOptimisticExchange((operation) => {if (operation.kind !== 'mutation' ||@@ -96,31 +219,17 @@ export function optimisticResolversExchange() {return operation;}- const local = byDocument- .get(stringifyDocument(operation.query))- ?.resolve(operation.variables);+ const local = predict(byField, operation.query, operation.variables);if (!local) return operation;const options = operation.context.optimisticMutation as| OptimisticCallOptions| undefined;return makeOperation('mutation', operation, {...operation.context,- ...optimisticMutationContext(local.response, {- ...local.options,- ...options,- updates: [- ...(local.options?.updates ?? []),- ...(options?.updates ?? []),- ],- revalidations: [- ...(local.options?.revalidations ?? []),- ...(options?.revalidations ?? []),- ],- identityBindings: [- ...(local.options?.identityBindings ?? []),- ...(options?.identityBindings ?? []),- ],- }),+ ...optimisticMutationContext(+ local.response,+ mergeOptions(local.options, options)+ ),});});}diff --git a/apps/web/src/lib/queries/email/integration.test.ts b/apps/web/src/lib/queries/email/integration.test.tsindex d8b88bb12e..707f021aa8 100644--- a/apps/web/src/lib/queries/email/integration.test.ts+++ b/apps/web/src/lib/queries/email/integration.test.ts@@ -1,4 +1,4 @@-import { CombinedError, stringifyDocument } from '@urql/core';+import { CombinedError } from '@urql/core';import { err, ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -29,6 +29,7 @@ vi.mock('../soup/graphql/active-queries', () => ({getActiveGraphqlSoupRevalidations: mocks.revalidations,}));+import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';import {SetEmailThreadArchivedDocument,SoupDocument,@@ -71,14 +72,12 @@ describe('GraphQL email archive writes', () => {{ input: { threadId: 'thread', archived: value } },expect.objectContaining({ optimisticMutation: { revalidations: [] } }));- const resolver = soupOptimisticResolvers.find(- (resolver) =>- resolver.document ===- stringifyDocument(SetEmailThreadArchivedDocument)- );expect(- resolver?.resolve({ input: { threadId: 'thread', archived: value } })- ?.response+ predictOptimisticMutation(+ soupOptimisticResolvers,+ SetEmailThreadArchivedDocument,+ { input: { threadId: 'thread', archived: value } }+ )?.response).toEqual({setEmailThreadArchived: {__typename: 'GraphqlSoupEmailThread',diff --git a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx b/apps/web/src/lib/queries/email/read-state-graphql.test.tsxindex e8b2726f86..2121a64075 100644--- a/apps/web/src/lib/queries/email/read-state-graphql.test.tsx+++ b/apps/web/src/lib/queries/email/read-state-graphql.test.tsx@@ -56,12 +56,12 @@ vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: () => ({ mutation: mocks.graphqlMutation }),}));+import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';import {MarkEmailThreadSeenDocument,MarkEmailThreadUnreadDocument,SoupDocument,} from '@service-storage/graphql/generated/graphql';-import { stringifyDocument } from '@urql/core';import { soupOptimisticResolvers } from '../optimistic-resolvers';import { registerGraphqlSoupRevalidations } from '../soup/graphql/active-queries';import { emailKeys } from './keys';@@ -182,12 +182,11 @@ describe('email read state with GraphQL Soup', () => {});expect(hasReadPatch(- soupOptimisticResolvers- .find(- (resolver) =>- resolver.document === stringifyDocument(document)- )- ?.resolve(variables)?.response,+ predictOptimisticMutation(+ soupOptimisticResolvers,+ document,+ variables+ )?.response,read),'A legacy Soup patch does not update GraphqlSoupEmailThread.isRead'@@ -257,11 +256,11 @@ describe('email read state with GraphQL Soup', () => {expect(variables).toEqual({ input: { threadId: 'thread' } });expect(hasReadPatch(- soupOptimisticResolvers- .find(- (resolver) => resolver.document === stringifyDocument(document)- )- ?.resolve(variables)?.response,+ predictOptimisticMutation(+ soupOptimisticResolvers,+ document,+ variables+ )?.response,false)).toBe(true);diff --git a/apps/web/src/lib/queries/entity-optimistic-resolvers.test.ts b/apps/web/src/lib/queries/entity-optimistic-resolvers.test.tsindex 2a6038dc1a..1b6bcb458c 100644--- a/apps/web/src/lib/queries/entity-optimistic-resolvers.test.ts+++ b/apps/web/src/lib/queries/entity-optimistic-resolvers.test.ts@@ -1,12 +1,16 @@-import { getOperationAST, parse } from 'graphql';+import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';+import {+ DeleteEntityPropertyDocument,+ RenameEntitiesDocument,+ UpdateInitiativeDocument,+} from '@service-storage/graphql/generated/graphql';+import type { AnyVariables } from '@urql/core';+import type { DocumentNode } from 'graphql';import { describe, expect, it } from 'vitest';import { entityOptimisticResolvers } from './entity-optimistic-resolvers';-const resolver = (name: string) =>- entityOptimisticResolvers.find(- (resolver) =>- getOperationAST(parse(resolver.document))?.name?.value === name- )!;+const predict = (document: DocumentNode, variables: AnyVariables) =>+ predictOptimisticMutation(entityOptimisticResolvers, document, variables);describe('entity local resolvers', () => {it.each([@@ -21,9 +25,7 @@ describe('entity local resolvers', () => {const input = { entity: { type, id: 'entity' }, displayName: 'Renamed' };// GraphQL also accepts a singleton for a list input.for (const inputs of [input, [input]]) {- expect(- resolver('RenameEntities').resolve({ inputs })?.response- ).toEqual({+ expect(predict(RenameEntitiesDocument, { inputs })?.response).toEqual({renameEntities: {results: [{@@ -49,7 +51,7 @@ describe('entity local resolvers', () => {it('does not fabricate success for unsupported entities in a mixed batch', () => {expect(- resolver('RenameEntities').resolve({+ predict(RenameEntitiesDocument, {inputs: [{ entity: { type: 'DOCUMENT', id: 'one' }, displayName: 'A' },{ entity: { type: 'EMAIL_THREAD', id: 'two' }, displayName: 'B' },@@ -60,7 +62,7 @@ describe('entity local resolvers', () => {it('changes only supplied project fields, including an empty member list', () => {expect(- resolver('UpdateInitiative').resolve({+ predict(UpdateInitiativeDocument, {initiativeId: 'project',input: { memberIds: [] },})?.response@@ -72,7 +74,7 @@ describe('entity local resolvers', () => {},});expect(- resolver('UpdateInitiative').resolve({+ predict(UpdateInitiativeDocument, {initiativeId: 'project',input: { name: 'Name' },})?.response@@ -92,7 +94,7 @@ describe('entity local resolvers', () => {{ name: 'Name', sharePermission: { teamShareAccessLevel: null } },])expect(- resolver('UpdateInitiative').resolve({ initiativeId: 'project', input })+ predict(UpdateInitiativeDocument, { initiativeId: 'project', input })).toBeUndefined();});@@ -104,7 +106,7 @@ describe('entity local resolvers', () => {])('removes the assignment from its %s parent without deleting it before commit',(entityType, typename) => {- const local = resolver('DeleteEntityProperty').resolve({+ const local = predict(DeleteEntityPropertyDocument, {entityType,entityId: 'parent',entityPropertyId: 'assignment',@@ -119,7 +121,7 @@ describe('entity local resolvers', () => {operation: { kind: 'remove', entityKey: 'GraphqlProperty:assignment' },});expect(- resolver('DeleteEntityProperty').resolve({+ predict(DeleteEntityPropertyDocument, {entityType: 'USER',entityId: 'viewer',entityPropertyId: 'assignment',diff --git a/apps/web/src/lib/queries/mutation-coverage.test.ts b/apps/web/src/lib/queries/mutation-coverage.test.tsindex d182315096..b4580bb059 100644--- a/apps/web/src/lib/queries/mutation-coverage.test.ts+++ b/apps/web/src/lib/queries/mutation-coverage.test.ts@@ -1,5 +1,14 @@-import { getOperationAST, Kind, parse } from 'graphql';+import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';+import {+ buildSchema,+ getOperationAST,+ Kind,+ type OperationDefinitionNode,+ parse,+ print,+} from 'graphql';import { expect, it } from 'vitest';+import schemaSource from '../../../../../static_assets/schema.graphql?raw';import { soupOptimisticResolvers } from './optimistic-resolvers';// New documents must choose a strategy. Exceptions describe a real server-owned@@ -56,33 +65,103 @@ const policies = {| `inactive: ${string}`>;-it('requires an explicit optimistic strategy for every GraphQL mutation', () => {- const documents = import.meta.glob(- '../service-clients/service-storage/graphql/*.graphql',- {- query: '?raw',- import: 'default',- eager: true,- }- );- const mutations = Object.values(documents).flatMap((source) =>- parse(String(source)).definitions.flatMap((definition) =>+// Resolvers are keyed by mutation field, so these documents reach one but must+// stay unpredicted. A prediction for a sample means its policy has changed.+const declinedByResolver = {+ RenameDatabase: { id: 'database', displayName: 'Renamed' },+ RenameForm: { id: 'form', displayName: 'Renamed' },+} satisfies Partial<Record<keyof typeof policies, Record<string, unknown>>>;++const mutations = Object.values(+ import.meta.glob('../service-clients/service-storage/graphql/*.graphql', {+ query: '?raw',+ import: 'default',+ eager: true,+ })+).flatMap((source) =>+ parse(String(source)).definitions.filter(+ (definition): definition is OperationDefinitionNode =>definition.kind === Kind.OPERATION_DEFINITION &&definition.operation === 'mutation'- ? [definition.name?.value]- : []- )+ )+);+const policyOf = (operation: OperationDefinitionNode) =>+ policies[operation.name?.value as keyof typeof policies];+const resolvedFields = new Set(+ soupOptimisticResolvers.map((resolver) => resolver.field)+);+const reachesResolvers = (operation: OperationDefinitionNode) =>+ operation.selectionSet.selections.every(+ (selection) =>+ selection.kind === Kind.FIELD &&+ !selection.directives?.length &&+ (selection.name.value === '__typename' ||+ resolvedFields.has(selection.name.value)));- expect(mutations.sort()).toEqual(Object.keys(policies).sort());- expect(new Set(mutations).size).toBe(mutations.length);+const names = (operations: OperationDefinitionNode[]) =>+ operations.map((operation) => operation.name?.value).sort();++it('requires an explicit optimistic strategy for every GraphQL mutation', () => {+ expect(names(mutations)).toEqual(Object.keys(policies).sort());+ expect(new Set(names(mutations)).size).toBe(mutations.length);+});++it('routes exactly the resolver policies through mutation field resolvers', () => {expect(- soupOptimisticResolvers- .map((resolver) => getOperationAST(parse(resolver.document))?.name?.value)- .sort()- ).toEqual(- Object.entries(policies)- .filter(([, policy]) => policy === 'resolver')- .map(([name]) => name)- .sort()- );+ names(+ mutations.filter(+ (operation) =>+ (policyOf(operation) === 'resolver') !== reachesResolvers(operation)+ )+ )+ ).toEqual(Object.keys(declinedByResolver).sort());+ expect(+ soupOptimisticResolvers.map(+ (resolver) =>+ policies[+ getOperationAST(resolver.document)?.name+ ?.value as keyof typeof policies+ ]+ )+ ).toEqual(soupOptimisticResolvers.map(() => 'resolver'));+});++it.each(Object.entries(declinedByResolver))(+ 'keeps %s unpredicted although it reaches a field resolver',+ (name, variables) => {+ const operation = mutations.find(+ (mutation) => mutation.name?.value === name+ );+ expect(operation && reachesResolvers(operation)).toBe(true);+ expect(+ predictOptimisticMutation(+ soupOptimisticResolvers,+ { kind: Kind.DOCUMENT, definitions: [operation!] },+ variables+ )+ ).toBeUndefined();+ }+);++it('types resolver arguments with every schema argument of their field', () => {+ const fields = buildSchema(schemaSource).getMutationType()?.getFields();+ for (const resolver of soupOptimisticResolvers) {+ const variables = getOperationAST(resolver.document)?.variableDefinitions;+ expect(+ Object.fromEntries(+ variables?.map(({ variable, type }) => [+ variable.name.value,+ print(type),+ ]) ?? []+ ),+ resolver.field+ ).toEqual(+ Object.fromEntries(+ fields?.[resolver.field]?.args.map(({ name, type }) => [+ name,+ String(type),+ ]) ?? []+ )+ );+ }});diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-activity-notifications.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-activity-notifications.test.tsindex 981e84e6fd..d7fe538be5 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql-activity-notifications.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql-activity-notifications.test.ts@@ -1,6 +1,6 @@+import { predictOptimisticMutation } from '@graphql-cache/exchange/optimistic-resolvers';import { notificationStateFromGraphql } from '@notifications/notification-state';import { soupOptimisticResolvers } from '@queries/optimistic-resolvers';-import { stringifyDocument } from '@urql/core';import { ok } from 'neverthrow';import { beforeEach, describe, expect, it, vi } from 'vitest';import type { EntityData } from '../../../features/entity/types/entity';@@ -157,10 +157,13 @@ describe('channel activity and notification GraphQL cache separation', () => {it('does not optimistically reopen done or overwrite a historic view on seen', async () => {mutationMock.mockImplementation((document, variables, context) => ({toPromise: async () => {- const resolver = soupOptimisticResolvers.find(- (resolver) => resolver.document === stringifyDocument(document)- );- expect(resolver?.resolve(variables)?.response).toEqual({+ expect(+ predictOptimisticMutation(+ soupOptimisticResolvers,+ document,+ variables+ )?.response+ ).toEqual({updateNotifications: [{ __typename: 'GraphqlNotification', id: 'done-notification' },],diff --git a/apps/web/tests/functional/optimistic-mutations.spec.ts b/apps/web/tests/functional/optimistic-mutations.spec.tsindex 1777bab317..15ad511cf9 100644--- a/apps/web/tests/functional/optimistic-mutations.spec.ts+++ b/apps/web/tests/functional/optimistic-mutations.spec.ts@@ -80,7 +80,7 @@ async function mount(page: Page, mode: CacheMode, initial?: string[]) {if (!request.query.includes('mutation ')) reads.push(request.operationName);let outcome: Outcome = 'commit';if (- ['UpdateEntityPropertyOptions', 'RenameEntities'].includes(+ ['UpdateEntityPropertyOptions', 'RenameEntities', 'RenameTitle'].includes(request.operationName)) {@@ -218,16 +218,20 @@ async function mount(page: Page, mode: CacheMode, initial?: string[]) {};}-for (const outcome of ['commit', 'reject'] as const) {- test(`a local rename resolver changes only the subscribed field and ${outcome}s correctly`, async ({+for (const [button, outcome] of [+ ['Rename task', 'commit'],+ ['Rename task', 'reject'],+ // The resolver is keyed by mutation field, not by the document's text.+ ['Rename task by field', 'commit'],+ ['Rename task by field', 'reject'],+] as const) {+ test(`a local rename resolver changes only the subscribed field and ${outcome}s correctly via ${button}`, async ({page,}) => {const server = await mount(page, 'cached', [DOCS_TAG]);await expect(page.getByTestId('name')).toHaveText('Task under test');const before = await page.evaluate(() => window.optimisticMutations.read());- await page- .getByRole('button', { name: 'Rename task', exact: true })- .click();+ await page.getByRole('button', { name: button, exact: true }).click();await expect(page.getByTestId('name')).toHaveText('Renamed task');await expectTags(page, ['docs']);await expect.poll(() => server.mutations.length).toBe(1);diff --git a/apps/web/tests/functional/optimistic-mutations/fixture.tsx b/apps/web/tests/functional/optimistic-mutations/fixture.tsxindex 245e942f01..65710f69f7 100644--- a/apps/web/tests/functional/optimistic-mutations/fixture.tsx+++ b/apps/web/tests/functional/optimistic-mutations/fixture.tsx@@ -21,7 +21,7 @@ import {getGraphqlSoupClient,} from '@service-storage/graphql-soup';import { QueryClientProvider } from '@tanstack/solid-query';-import type { OperationResult } from '@urql/core';+import { gql, type OperationResult } from '@urql/core';import { createComputed, createSignal, Show } from 'solid-js';import { render } from 'solid-js/web';import {@@ -34,6 +34,34 @@ import {tagSets,} from './data';+// Another document for the renameEntities field: it reaches the field+// resolver through its own variables, response alias, and narrower selection.+const RenameTitleDocument = gql`+ mutation RenameTitle($id: ID!, $name: String!) {+ renamed: renameEntities(+ inputs: [{ entity: { type: DOCUMENT, id: $id }, displayName: $name }]+ ) {+ results {+ __typename+ ... on GraphqlMutationSuccess {+ effects {+ __typename+ ... on SoupUpdated {+ item {+ __typename+ id+ ... on GraphqlSoupDocument {+ documentName: name+ }+ }+ }+ }+ }+ }+ }+ }+`;+const mode = new URLSearchParams(location.search).get('cache') ?? 'cached';disableBrowserTursoCache.override = mode === 'disabled';queryClient.setQueryData(propertiesKeys.tags.queryKey, tagSets);@@ -171,9 +199,21 @@ function Readers() {.toPromise();if (result.error) throw result.error;}+ async function renameByField() {+ const result = await getGraphqlSoupClient()+ .mutation(RenameTitleDocument, {+ id: DOCUMENT_ID,+ name: 'Renamed task',+ })+ .toPromise();+ if (result.error) throw result.error;+ }return (<><button onClick={() => void edit(rename)}>Rename task</button>+ <button onClick={() => void edit(renameByField)}>+ Rename task by field+ </button><button onClick={() => void edit(() => tags.applyTag('user', DOCS_TAG))}>Add docs</button>diff --git a/crates/client/cache-core/tests/mutation_field_prediction.rs b/crates/client/cache-core/tests/mutation_field_prediction.rsnew file mode 100644index 0000000000..e133fa4b4c--- /dev/null+++ b/crates/client/cache-core/tests/mutation_field_prediction.rs@@ -0,0 +1,150 @@+//! Web resolvers predict a mutation field once, shaped by a representative+//! document. Another document selecting that field normalizes the same+//! prediction through its own selection.++use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};+use cache_core::store::InMemoryStorage;+use pollster::block_on;+use serde_json::{Map, Value, json};++const QUERY: &str = r#"query Items($input: SoupInput!) {+ user { id soup(input: $input) { items {+ __typename id displayName+ ... on GraphqlSoupDocument { documentName: name ownerId }+ } nextCursor } }+}"#;++/// The rename resolver's value, shaped by `RenameEntities` and its+/// `SoupItemFields` selection, including the `documentName: name` alias.+fn prediction() -> Value {+ json!({"results": [{+ "__typename": "GraphqlMutationSuccess",+ "effects": [{+ "__typename": "SoupUpdated",+ "item": {+ "__typename": "GraphqlSoupDocument",+ "id": "doc",+ "displayName": "Renamed",+ "documentName": "Renamed",+ },+ }],+ }]})+}++fn object(value: Value) -> Map<String, Value> {+ value.as_object().unwrap().clone()+}++/// Seeds one document, then installs the prediction through `mutation`,+/// placed under `response_key` as the web exchange does.+async fn predicted_item(mutation: &str, operation: &str, response_key: &str) -> Value {+ let mut engine = Engine::new(InMemoryStorage::new());+ let list = object(json!({"input": {"initial": {"limit": 100}}}));+ engine+ .write_query(+ None,+ QUERY,+ Some("Items"),+ &list,+ &json!({"user": {"id": "viewer", "soup": {"items": [{+ "__typename": "GraphqlSoupDocument", "id": "doc", "displayName": "Draft",+ "documentName": "Draft", "ownerId": "owner",+ }], "nextCursor": null}}}),+ None,+ )+ .await+ .unwrap();+ engine+ .begin_optimistic_write(+ None,+ BeginOptimisticWrite {+ client_metadata: None,+ identity_bindings: &[],+ uuid: "11111111-1111-4111-8111-111111111111",+ query: mutation,+ operation_name: Some(operation),+ variables: &object(json!({"id": "doc", "name": "Renamed"})),+ data: &json!({ response_key: prediction() }),+ link_patches: &[],+ revalidations: &[],+ created_at_ms: 0,+ },+ )+ .await+ .unwrap();+ let ReadResult::Hit { data } = engine+ .read_query(None, QUERY, Some("Items"), &list)+ .await+ .unwrap()+ else {+ panic!("the seeded list must stay readable");+ };+ data["user"]["soup"]["items"][0].clone()+}++#[test]+fn a_narrower_document_applies_only_the_fields_it_selects() {+ let item = block_on(predicted_item(+ r#"mutation RenameTitle($id: ID!, $name: String!) {+ renamed: renameEntities(+ inputs: [{ entity: { type: DOCUMENT, id: $id }, displayName: $name }]+ ) { results { __typename ... on GraphqlMutationSuccess { effects {+ __typename ... on SoupUpdated { item { __typename id displayName } }+ } } } }+ }"#,+ "RenameTitle",+ "renamed",+ ));+ assert_eq!(item["displayName"], "Renamed");+ assert_eq!(+ item["documentName"], "Draft",+ "an unselected predicted field must be ignored"+ );+ assert_eq!(item["ownerId"], "owner");+}++#[test]+fn a_wider_document_patches_the_existing_entity() {+ let item = block_on(predicted_item(+ r#"mutation RenameWithOwner($id: ID!, $name: String!) {+ renameEntities(+ inputs: [{ entity: { type: DOCUMENT, id: $id }, displayName: $name }]+ ) { results { __typename ... on GraphqlMutationSuccess { effects {+ __typename ... on SoupUpdated { item {+ __typename id displayName+ ... on GraphqlSoupDocument { documentName: name ownerId updatedAt }+ } }+ } } } }+ }"#,+ "RenameWithOwner",+ "renameEntities",+ ));+ assert_eq!(item["displayName"], "Renamed");+ assert_eq!(item["documentName"], "Renamed");+ assert_eq!(+ item["ownerId"], "owner",+ "a selected field missing from the prediction must keep its cached value"+ );+}++#[test]+fn nested_response_keys_must_match_the_representative_aliases() {+ let item = block_on(predicted_item(+ r#"mutation RenameName($id: ID!, $name: String!) {+ renameEntities(+ inputs: [{ entity: { type: DOCUMENT, id: $id }, displayName: $name }]+ ) { results { __typename ... on GraphqlMutationSuccess { effects {+ __typename ... on SoupUpdated { item {+ __typename id displayName ... on GraphqlSoupDocument { name }+ } }+ } } } }+ }"#,+ "RenameName",+ "renameEntities",+ ));+ assert_eq!(item["displayName"], "Renamed");+ assert_eq!(+ item["documentName"], "Draft",+ "the prediction names `name` only through the `documentName` alias"+ );+}