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
Seanaye/perf/grouped query (#7224)
Sean Ayeb291624f3dac
diff --git a/apps/web/src/features/tasks-view/browser-test/property-optimism.browser.e2e.ts b/apps/web/src/features/tasks-view/browser-test/property-optimism.browser.e2e.tsindex 0a6dd3aa1d..967802156f 100644--- a/apps/web/src/features/tasks-view/browser-test/property-optimism.browser.e2e.ts+++ b/apps/web/src/features/tasks-view/browser-test/property-optimism.browser.e2e.ts@@ -71,6 +71,43 @@ for (const succeeds of [true, false]) {});}+for (const succeeds of [true, false]) {+ test(`grouped bulk moves ignore 130 historical pages and reconcile ${succeeds ? 'success' : 'partial failure'}`, async ({+ page,+ }) => {+ await page.goto(+ '/src/features/tasks-view/browser-test/property-optimism.html?grouped=1'+ );+ await expect(page.getByLabel('Historical grouped pages')).toHaveText(+ '130 ready'+ );+ await expect(page.getByLabel('Unset group')).toHaveText('1,2');+ await page.getByRole('button', { name: 'Set both Urgent' }).click();+ await expect(page.getByLabel('Urgent group')).toHaveText('1,2');+ await expect(page.getByLabel('Unset group')).toHaveText('');+ await expect(page.getByLabel('Membership reads')).toHaveText('1');+ await expect(page.getByLabel('Cache inspections')).toHaveText('0');+ await expect(page.getByText('HTTP requests: 1 · Settled: 0')).toBeVisible();+ await page.getByRole('button', { name: 'Commit next request' }).click();+ await expect(page.getByText('HTTP requests: 2 · Settled: 1')).toBeVisible();+ await page+ .getByRole('button', {+ name: succeeds ? 'Commit next request' : 'Fail next request',+ })+ .click();+ await expect(page.getByLabel('Save status')).toContainText('Pending: no');+ await expect(page.getByLabel('Urgent group')).toHaveText(+ succeeds ? '1,2' : '1'+ );+ await expect(page.getByLabel('Unset group')).toHaveText(+ succeeds ? '' : '2'+ );+ // Active-query cache misses may fetch too; no historical page may be fetched.+ await expect(page.getByLabel('Historical group fetches')).toHaveText('0');+ await expect(page.getByLabel('Cache inspections')).toHaveText('0');+ });+}+test('bulk layers appear before the first response and rollback stays task-scoped', async ({page,}) => {diff --git a/apps/web/src/features/tasks-view/browser-test/property-optimism.tsx b/apps/web/src/features/tasks-view/browser-test/property-optimism.tsxindex c67bd599e0..33d3d57304 100644--- a/apps/web/src/features/tasks-view/browser-test/property-optimism.tsx+++ b/apps/web/src/features/tasks-view/browser-test/property-optimism.tsx@@ -11,16 +11,23 @@ import type { Property, PropertyApiValues } from '@property/types';import { queryClient } from '@queries/client';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { propertiesKeys } from '@queries/properties/keys';+import { registerGraphqlSoupRevalidations } from '@queries/soup/graphql/active-queries';+import { NOT_SET_GROUP_KEY } from '@queries/soup/grouped/types';import {EntityPropertiesDocument,+ GroupSoupDocument,+ GroupSoupMembershipDocument,+ type GroupSoupMembershipQuery,type SoupPropertyFieldsFragment,} from '@service-storage/graphql/generated/graphql';import {+ getGraphqlCacheHost,getGraphqlSoupClient,mapGraphqlProperties,} from '@service-storage/graphql-soup';import { QueryClientProvider } from '@tanstack/solid-query';-import { createSignal, For, Show } from 'solid-js';+import { stringifyDocument } from '@urql/core';+import { createSignal, For, onCleanup, onMount, Show } from 'solid-js';import { render } from 'solid-js/web';enableGraphqlSoup.override = true;@@ -30,6 +37,48 @@ const taskIds = [];const definitionId = SYSTEM_PROPERTY_IDS.PRIORITY;const urgent = PROPERTY_OPTION_IDS.PRIORITY.URGENT;+const groupedMode = new URLSearchParams(location.search).has('grouped');+const groupedInput = {+ initial: {+ groupBy: { field: 'PROPERTY' as const, propertyDefinitionId: definitionId },+ limit: 2,+ },+};+const [historyReady, setHistoryReady] = createSignal(false);+const [membershipReads, setMembershipReads] = createSignal(0);+const [inspections, setInspections] = createSignal(0);+const [groupFetches, setGroupFetches] = createSignal(0);+const [historicalGroupFetches, setHistoricalGroupFetches] = createSignal(0);+function groupedData(): GroupSoupMembershipQuery {+ const idsFor = (key: string) =>+ taskIds.filter((id) => {+ const value = saved.get(id)?.value;+ return (+ (value?.__typename === 'GraphqlSelectOptionPropertyValue'+ ? value.optionIds[0]+ : NOT_SET_GROUP_KEY) === key+ );+ });+ return {+ user: {+ id: 'macro|[email protected]',+ groupSoup: {+ bins: [NOT_SET_GROUP_KEY, urgent].map((key) => {+ const ids = idsFor(key);+ return {+ key,+ totalCount: ids.length,+ nextCursor: null,+ items: ids.map((id) => ({+ __typename: 'GraphqlSoupDocument' as const,+ id,+ })),+ };+ }),+ },+ },+ };+}const placeholder = soupPropertyToProperty({id: `pending:${definitionId}`,definition: {@@ -59,7 +108,11 @@ window.fetch = async (input, init) => {const body = JSON.parse(String(init?.body)) as {query: string;variables: {- input: { entityId?: string; value?: { selectOption?: string } };+ input: {+ entityId?: string;+ value?: { selectOption?: string };+ initial?: { limit?: number };+ };};};if (body.query.includes('mutation SetEntityProperty')) {@@ -93,6 +146,13 @@ window.fetch = async (input, init) => {});});}+ if (body.query.includes('query GroupSoupMembership')) {+ setGroupFetches((value) => value + 1);+ if (body.variables.input.initial?.limit !== groupedInput.initial.limit) {+ setHistoricalGroupFetches((value) => value + 1);+ }+ return Response.json({ data: groupedData() });+ }return Response.json({data: {user: {@@ -116,6 +176,54 @@ function Fixture() {variables: { input: { initial: { limit: 2 } } },requestPolicy: 'cache-and-network',}));+ const grouped = createUrqlQuery(() => ({+ client: getGraphqlSoupClient(),+ query: GroupSoupMembershipDocument,+ variables: { input: groupedInput },+ enabled: groupedMode,+ requestPolicy: 'cache-and-network',+ }));+ onCleanup(+ registerGraphqlSoupRevalidations(() =>+ groupedMode+ ? [{ document: GroupSoupDocument, variables: { input: groupedInput } }]+ : []+ )+ );+ onMount(async () => {+ if (!groupedMode) return;+ const host = getGraphqlCacheHost()!;+ // Real historical query variants, none registered as an active view.+ for (let limit = 3; limit < 133; limit++) {+ await host.writeQuery({+ query: stringifyDocument(GroupSoupMembershipDocument),+ operationName: 'GroupSoupMembership',+ variables: { input: { initial: { ...groupedInput.initial, limit } } },+ data: groupedData(),+ });+ }+ const read = host.readQuery.bind(host);+ host.readQuery = (args) => {+ if (+ args.operationName === 'GroupSoupMembership' &&+ args.opKey === undefined+ )+ setMembershipReads((value) => value + 1);+ return read(args);+ };+ const inspect = host.inspectQueryVariants.bind(host);+ host.inspectQueryVariants = (args) => {+ setInspections((value) => value + 1);+ return inspect(args);+ };+ setHistoryReady(true);+ });+ const groupItems = (key: string) =>+ grouped.data?.user.groupSoup.bins+ .find((bin) => bin.key === key)+ ?.items.map((item) => taskIds.indexOf(item.id) + 1)+ .sort()+ .join(',') ?? '';const [successes, setSuccesses] = createSignal(0);const [failures, setFailures] = createSignal(0);const save = useBulkSaveEntityPropertiesMutation({@@ -157,6 +265,21 @@ function Fixture() {Pending: {save.isPending ? 'yes' : 'no'} · Succeeded: {successes()} ·Failed: {failures()}</p>+ <Show when={groupedMode}>+ <output aria-label="Historical grouped pages">+ {historyReady() ? '130 ready' : 'Loading'}+ </output>+ <output aria-label="Membership reads">{membershipReads()}</output>+ <output aria-label="Cache inspections">{inspections()}</output>+ <output aria-label="Group fetches">{groupFetches()}</output>+ <output aria-label="Historical group fetches">+ {historicalGroupFetches()}+ </output>+ <output aria-label="Unset group">+ {groupItems(NOT_SET_GROUP_KEY)}+ </output>+ <output aria-label="Urgent group">{groupItems(urgent)}</output>+ </Show><Show when={query.data} fallback={<p>Loading</p>}><For each={taskIds}>{(entityId, index) => (diff --git a/apps/web/src/lib/queries/properties/graphql/entity.test.ts b/apps/web/src/lib/queries/properties/graphql/entity.test.tsindex 1a4e5d2df3..c17068c5df 100644--- a/apps/web/src/lib/queries/properties/graphql/entity.test.ts+++ b/apps/web/src/lib/queries/properties/graphql/entity.test.ts@@ -1,8 +1,10 @@import type { CacheHost } from '@graphql-cache/host/types';import type { MutationSettlement } from '@graphql-cache/protocol';import type { Property } from '@property/types';+import { registerGraphqlSoupRevalidations } from '@queries/soup/graphql/active-queries';import type { EntityType } from '@service-properties/generated/schemas/entityType';import type { SoupProperty } from '@service-storage/generated/schemas/soupProperty';+import { GroupSoupDocument } from '@service-storage/graphql/generated/graphql';import {type Client,createClient,@@ -12,7 +14,15 @@ import {} from '@urql/core';import { createRoot, createSignal } from 'solid-js';import { validate as validateUuid } from 'uuid';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ onTestFinished,+ vi,+} from 'vitest';import { filter, makeSubject, mergeMap, pipe } from 'wonka';const graphqlClientState = vi.hoisted(() => ({@@ -461,6 +471,119 @@ describe('createGraphqlBulkSaveEntityPropertiesMutation', () => {expect(save.isPending).toBe(false);});+ it('prepares a bulk grouped edit once per active page without cache inspection', async () => {+ makeSettlementHost();+ const input = {+ initial: {+ groupBy: {+ field: 'PROPERTY' as const,+ propertyDefinitionId: 'priority',+ },+ },+ };+ onTestFinished(+ registerGraphqlSoupRevalidations(() => [+ { document: GroupSoupDocument, variables: { input } },+ { document: GroupSoupDocument, variables: { input } },+ ])+ );+ const readQuery = vi.fn(async () => ({+ kind: 'hit' as const,+ data: {+ user: {+ groupSoup: {+ bins: [+ {+ key: 'low',+ totalCount: 2,+ nextCursor: null,+ items: ['task-1', 'task-2'].map((id) => ({+ __typename: 'GraphqlSoupDocument',+ id,+ })),+ },+ ],+ },+ },+ },+ }));+ const inspect = vi.fn(async () => {+ throw new Error('query inspection variant count 129 exceeds limit 128');+ });+ graphqlClientState.host = {+ ...graphqlClientState.host,+ readQuery,+ inspectQuery: inspect,+ inspectQueryVariants: inspect,+ } as unknown as CacheHost;+ const mutation = vi.fn(+ (+ _document: unknown,+ _variables: unknown,+ context: Record<string, unknown>+ ) => ({+ toPromise: async () => {+ (context.normalizedCacheOptimisticEnqueued as () => void)();+ return {+ operation: { kind: 'mutation', context },+ data: { setEntityProperty: { id: 'assignment' } },+ stale: false,+ hasNext: false,+ };+ },+ })+ );+ graphqlClientState.current = { mutation } as unknown as Client;+ const save = createRoot((rootDispose) => {+ dispose = rootDispose;+ return createGraphqlBulkSaveEntityPropertiesMutation();+ });+ await save.mutateAsync({+ properties: ['task-1', 'task-2'].map((entityId) => ({+ entityId,+ entityType: 'TASK',+ property: {+ propertyId: `assignment-${entityId}`,+ propertyDefinitionId: 'priority',+ displayName: 'Priority',+ valueType: 'SELECT_STRING',+ value: ['low'],+ isMultiSelect: false,+ } as Property,+ apiValues: { valueType: 'SELECT_STRING', values: ['urgent'] },+ })),+ });+ expect(inspect).not.toHaveBeenCalled();+ expect(readQuery).toHaveBeenCalledOnce();+ expect(mutation).toHaveBeenCalledTimes(2);+ for (const [index, call] of mutation.mock.calls.entries()) {+ expect(call[2]).toMatchObject({+ normalizedCacheOptimistic: {+ linkPatches: [+ {+ operation: {+ kind: 'removeEmbeddedLink',+ entityKey: `GraphqlSoupDocument:task-${index + 1}`,+ },+ },+ {+ operation: {+ kind: 'upsertEmbeddedLink',+ entityKey: `GraphqlSoupDocument:task-${index + 1}`,+ },+ },+ ],+ revalidations: [+ {+ operationName: 'GroupSoupMembership',+ variablesJson: JSON.stringify({ input }),+ },+ ],+ },+ });+ }+ });+it.each(['committed', 'permanently-failed'] as const)('waits for later queued saves and reports their %s settlement',async (status) => {diff --git a/apps/web/src/lib/queries/properties/graphql/entity.ts b/apps/web/src/lib/queries/properties/graphql/entity.tsindex a1848a155b..0e66b89c73 100644--- a/apps/web/src/lib/queries/properties/graphql/entity.ts+++ b/apps/web/src/lib/queries/properties/graphql/entity.ts@@ -41,8 +41,10 @@ import { match } from 'ts-pattern';import { v5 as uuidv5 } from 'uuid';import { buildGraphqlEntitySoupInput } from '../../soup/graphql/entity-input';import {- buildOptimisticGroupedPropertyUpdates,+ type buildOptimisticGroupedPropertyUpdates,+ createGroupedPropertyPreparation,groupedPropertyKeys,+ type PrepareGroupedPropertyUpdates,} from '../../soup/grouped/graphql-optimistic';import {buildOptimisticSetEntityProperty,@@ -217,7 +219,8 @@ function getPropertyDefinitionId(}async function prepareMutationArgs(- input: GraphqlEntityPropertyMutationInput+ input: GraphqlEntityPropertyMutationInput,+ prepareGrouped?: PrepareGroupedPropertyUpdates): Promise<SetEntityPropertyArgs> {if (input.kind === 'add') {return {@@ -268,8 +271,9 @@ async function prepareMutationArgs(}const oldGroupKeys = groupedPropertyKeys(input.property);const newGroupKeys = groupedPropertyKeys(input.apiValues);- const grouped = await buildOptimisticGroupedPropertyUpdates({- host,+ const grouped = await (+ prepareGrouped ?? createGroupedPropertyPreparation(host)+ )({entityId: input.entityId,propertyDefinitionId,oldGroupKeys: oldGroupKeys ?? [],@@ -352,9 +356,10 @@ type EntityPropertyExecution = Parameters<async function executeGraphqlEntityPropertyMutation({ client, mutation, input, context }: EntityPropertyExecution,- onEnqueued?: () => void+ onEnqueued?: () => void,+ prepareGrouped?: PrepareGroupedPropertyUpdates) {- const args = await prepareMutationArgs(input);+ const args = await prepareMutationArgs(input, prepareGrouped);const variables: SetEntityPropertyMutationVariables = {input: {entityType: args.entityType,@@ -515,9 +520,11 @@ export function createGraphqlBulkSaveEntityPropertiesMutation<Context = void>(let permanentError: Error | undefined;const pending = [];- const settlements = observePropertyMutationSettlements(- getGraphqlCacheHost()- );+ const host = getGraphqlCacheHost();+ const prepareGrouped = host+ ? createGroupedPropertyPreparation(host)+ : undefined;+ const settlements = observePropertyMutationSettlements(host);try {for (const item of input.properties) {let acknowledge!: () => void;@@ -533,7 +540,8 @@ export function createGraphqlBulkSaveEntityPropertiesMutation<Context = void>(input: { kind: 'save', ...item },context,},- acknowledge+ acknowledge,+ prepareGrouped);acknowledge();const disposition = mutationDisposition(result);diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.tsindex abef4fb2ff..4fd05e9149 100644--- a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts@@ -3,9 +3,17 @@ import type {CacheReadArgs,InspectQueryVariantsArgs,} from '@graphql-cache/host/types';-import { describe, expect, it, vi } from 'vitest';+import {+ GroupSoupDocument,+ SoupDocument,+} from '@service-storage/graphql/generated/graphql';+import { describe, expect, it, onTestFinished, vi } from 'vitest';+import { registerGraphqlSoupRevalidations } from '../graphql/active-queries';import { registerGroupedSoupContinuation } from './graphql-operation-registry';-import { buildOptimisticGroupedPropertyUpdates } from './graphql-optimistic';+import {+ buildOptimisticGroupedPropertyUpdates,+ createGroupedPropertyPreparation,+} from './graphql-optimistic';function initialInput(propertyDefinitionId: string) {return {@@ -41,11 +49,13 @@ function host(args?: {continuation?: boolean;initialContainsItem?: boolean;miss?: boolean;- onDiscover?: (propertyDefinitionIds: string[]) => void;+ active?: () => boolean;+ register?: boolean;onInspect?: (request: InspectQueryVariantsArgs) => void;onRead?: (request: CacheReadArgs) => void;relevantPropertyDefinitionId?: string;sourceKey?: string;+ entityIds?: string[];typename?: 'GraphqlSoupCall' | 'GraphqlSoupDocument';unrelatedPropertyDefinitionIds?: readonly string[];}): CacheHost {@@ -56,12 +66,10 @@ function host(args?: {totalCount: 1,nextCursor: null,items: containsItem- ? [- {- __typename: args?.typename ?? 'GraphqlSoupDocument',- id: 'task-1',- },- ]+ ? (args?.entityIds ?? ['task-1']).map((id) => ({+ __typename: args?.typename ?? 'GraphqlSoupDocument',+ id,+ })): [],},...(args?.destination === false@@ -112,20 +120,24 @@ function host(args?: {});}+ if (args?.register !== false) {+ onTestFinished(+ registerGraphqlSoupRevalidations(() =>+ args?.active?.() === false+ ? []+ : instances.map(({ variables }) => ({+ document: GroupSoupDocument,+ variables,+ }))+ )+ );+ }+return {clientId: 'test',async inspectQueryVariants(request: InspectQueryVariantsArgs) {args?.onInspect?.(request);- args?.onDiscover?.(- instances.map(({ variables }) => {- const page =- 'initial' in variables.input- ? variables.input.initial- : variables.input.continuation;- return String(page.groupBy.propertyDefinitionId);- })- );- return instances.map(({ variables }) => ({ variables }));+ throw new Error('query inspection variant count 129 exceeds limit 128');},async readQuery(request: CacheReadArgs) {args?.onRead?.(request);@@ -177,13 +189,7 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {[{ field: 'user' }, { field: 'groupSoup' }, { field: 'bins' }],]);expect(result.revalidations).toHaveLength(1);- expect(onInspect).toHaveBeenCalledWith(- expect.objectContaining({- operationName: 'GroupSoupMembership',- path: [{ field: 'user' }, { field: 'groupSoup' }],- })- );- expect(onInspect.mock.calls[0]?.[0]).not.toHaveProperty('variableFilters');+ expect(onInspect).not.toHaveBeenCalled();expect(onRead).toHaveBeenCalledTimes(1);expect(onRead).toHaveBeenCalledWith(expect.objectContaining({@@ -193,12 +199,12 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {);});- it('discovers unrelated status, assignee, and priority variants without reading them', async () => {- const onDiscover = vi.fn();+ it('ignores unrelated active status, assignee, and priority views without inspecting the cache', async () => {+ const onInspect = vi.fn();const onRead = vi.fn();const result = await buildOptimisticGroupedPropertyUpdates({host: host({- onDiscover,+ onInspect,onRead,relevantPropertyDefinitionId: 'target-def',unrelatedPropertyDefinitionIds: [@@ -214,12 +220,7 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {});expect(result.updates).toHaveLength(2);- expect(onDiscover).toHaveBeenCalledWith([- 'target-def',- 'status-def',- 'assignee-def',- 'priority-def',- ]);+ expect(onInspect).not.toHaveBeenCalled();expect(onRead).toHaveBeenCalledTimes(1);expect(onRead.mock.calls.map(@@ -229,7 +230,101 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {).toEqual(['target-def']);});- it('derives the normalized key from the inspected typename and id', async () => {+ it('never visits historical cached pages, even when inspection would exceed its budget', async () => {+ const onRead = vi.fn();+ const onInspect = vi.fn();+ const result = await buildOptimisticGroupedPropertyUpdates({+ host: host({+ register: false,+ onRead,+ onInspect,+ unrelatedPropertyDefinitionIds: Array.from(+ { length: 200 },+ (_, i) => `historical-${i}`+ ),+ }),+ entityId: 'task-1',+ propertyDefinitionId: 'status-def',+ oldGroupKeys: ['in-progress'],+ newGroupKeys: ['completed'],+ });+ expect(result).toEqual({ updates: [], revalidations: [] });+ expect(onRead).not.toHaveBeenCalled();+ expect(onInspect).not.toHaveBeenCalled();+ });++ it('deduplicates split readers and drops disabled, changed, and unmounted views', async () => {+ const onRead = vi.fn();+ const cache = host({ register: false, onRead });+ let active = true;+ let currentInput = input;+ const unregister = registerGraphqlSoupRevalidations(() =>+ active+ ? [+ { document: GroupSoupDocument, variables: { input: currentInput } },+ { document: GroupSoupDocument, variables: { input: currentInput } },+ { document: SoupDocument, variables: { input: {} } },+ ]+ : []+ );+ onTestFinished(unregister);+ const prepare = () =>+ buildOptimisticGroupedPropertyUpdates({+ host: cache,+ entityId: 'task-1',+ propertyDefinitionId: 'status-def',+ oldGroupKeys: ['in-progress'],+ newGroupKeys: ['completed'],+ });+ expect((await prepare()).revalidations).toHaveLength(1);+ expect(onRead).toHaveBeenCalledOnce();+ active = false;+ expect(await prepare()).toEqual({ updates: [], revalidations: [] });+ active = true;+ currentInput = initialInput('priority-def');+ expect(await prepare()).toEqual({ updates: [], revalidations: [] });+ currentInput = input;+ unregister();+ expect(await prepare()).toEqual({ updates: [], revalidations: [] });+ expect(onRead).toHaveBeenCalledOnce();+ });++ it('shares reads across a bulk edit but retains each mutation’s durable recovery', async () => {+ const onRead = vi.fn();+ const prepare = createGroupedPropertyPreparation(+ host({ onRead, entityIds: ['task-1', 'task-2'] })+ );+ for (const entityId of ['task-1', 'task-2']) {+ const result = await prepare({+ entityId,+ propertyDefinitionId: 'status-def',+ oldGroupKeys: ['in-progress'],+ newGroupKeys: ['completed'],+ });+ expect(result.updates).toHaveLength(2);+ expect(result.updates[0].operation).toMatchObject({+ entityKey: `GraphqlSoupDocument:${entityId}`,+ });+ expect(result.revalidations).toHaveLength(1);+ }+ expect(onRead).toHaveBeenCalledOnce();+ });++ it('rereads membership for a repeat edit to an entity within a bulk save', async () => {+ const onRead = vi.fn();+ const prepare = createGroupedPropertyPreparation(host({ onRead }));+ const args = {+ entityId: 'task-1',+ propertyDefinitionId: 'status-def',+ oldGroupKeys: ['in-progress'],+ newGroupKeys: ['completed'],+ };+ await prepare(args);+ await prepare(args);+ expect(onRead).toHaveBeenCalledTimes(2);+ });++ it('derives the normalized key from the loaded typename and id', async () => {const result = await buildOptimisticGroupedPropertyUpdates({host: host({ typename: 'GraphqlSoupCall' }),entityId: 'task-1',@@ -367,7 +462,7 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {expect(onRead).toHaveBeenCalledOnce();});- it('skips inspection when group-key sets are equivalent', async () => {+ it('skips all reads when group-key sets are equivalent', async () => {const onInspect = vi.fn();const result = await buildOptimisticGroupedPropertyUpdates({host: host({ onInspect }),diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.tsindex d3f29bcc2c..73466482d8 100644--- a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts@@ -1,5 +1,3 @@-import { documentOperationName } from '@graphql-cache/exchange/generated-selection';-import { inspectVariants, selectAll } from '@graphql-cache/exchange/inspection';import {type OptimisticUpdate,type QueryRevalidation,@@ -8,13 +6,19 @@ import {upsertEmbeddedLink,} from '@graphql-cache/exchange/optimistic';import type { CacheHost } from '@graphql-cache/host/types';-import { stringifyDocument } from '@urql/core';+import { getOperationName, stringifyDocument } from '@urql/core';import {type GroupedSoupInput,+ GroupSoupDocument,GroupSoupMembershipDocument,type GroupSoupMembershipQuery,+ type GroupSoupQueryVariables,} from '../../../service-clients/service-storage/graphql/generated/graphql';-import { groupedSoupLogicalViewKey } from './graphql-operation-registry';+import { getActiveGraphqlSoupRevalidations } from '../graphql/active-queries';+import {+ groupedSoupInputKey,+ groupedSoupLogicalViewKey,+} from './graphql-operation-registry';import { NOT_SET_GROUP_KEY } from './types';type BuildArgs = {@@ -23,7 +27,7 @@ type BuildArgs = {propertyDefinitionId: string;oldGroupKeys: readonly string[];newGroupKeys: readonly string[];- /** Unsupported/date values still discover and revalidate relevant fields. */+ /** Unsupported/date values still revalidate relevant active fields. */revalidateOnly?: boolean;};@@ -89,52 +93,100 @@ export function groupPagesByLogicalView(return views;}+/** Only mounted, enabled readers participate; historical cache pages are irrelevant. */+function activePropertyGroupedInputs(+ propertyDefinitionId: string+): GroupedSoupInput[] {+ return getActiveGraphqlSoupRevalidations().flatMap((query) => {+ if (query.document !== GroupSoupDocument) return [];+ // This descriptor is registered by the generated GroupSoup readers.+ const { input } = query.variables as GroupSoupQueryVariables;+ return isRelevantPropertyGrouping(input, propertyDefinitionId)+ ? [input]+ : [];+ });+}++type ReadGroupPage = (input: GroupedSoupInput) => Promise<GroupPage | null>;+export type PrepareGroupedPropertyUpdates = (+ args: Omit<BuildArgs, 'host'>+) => Promise<OptimisticGroupedPropertyUpdates>;+/**- * Discovers every cached property-grouped field and creates constrained link- * recipes only where the loaded membership proves the move is applicable.- * Missing destination bins are created on initial pages; missing pages are- * left untouched and revalidated after success.+ * Share membership reads across distinct entities in one bulk edit. A repeat+ * edit to the same entity must read its newly installed optimistic membership,+ * not the earlier snapshot. This cache lives only for the bulk submission.+ * Revalidations remain on every durable mutation: moving them to the last one+ * would lose recovery if that mutation fails or the page closes during replay.*/-export async function buildOptimisticGroupedPropertyUpdates(+export function createGroupedPropertyPreparation(+ host: CacheHost+): PrepareGroupedPropertyUpdates {+ const pages = new Map<string, Promise<GroupPage | null>>();+ const preparedEntities = new Set<string>();+ const readPage: ReadGroupPage = (input) => {+ const key = groupedSoupInputKey(input);+ let pending = pages.get(key);+ if (!pending) {+ pending = readGroupPage(host, input);+ pages.set(key, pending);+ }+ return pending;+ };+ return async (args) => {+ if (preparedEntities.has(args.entityId)) pages.clear();+ preparedEntities.add(args.entityId);+ try {+ return await prepareGroupedPropertyUpdates(args, readPage);+ } catch (error) {+ // A transient cache failure must not poison the rest of a bulk edit.+ pages.clear();+ throw error;+ }+ };+}++async function readGroupPage(+ host: CacheHost,+ input: GroupedSoupInput+): Promise<GroupPage | null> {+ const result = await host.readQuery({+ query: stringifyDocument(GroupSoupMembershipDocument),+ operationName: getOperationName(GroupSoupMembershipDocument),+ variables: { input },+ priority: 'user-visible',+ });+ if (result.kind === 'miss') return null;+ const data = result.data as GroupSoupMembershipQuery;+ return { input, bins: data.user.groupSoup.bins };+}++/** Creates relation recipes from active grouped pages, never a cache-wide inspection. */+export function buildOptimisticGroupedPropertyUpdates(args: BuildArgs+): Promise<OptimisticGroupedPropertyUpdates> {+ return createGroupedPropertyPreparation(args.host)(args);+}++async function prepareGroupedPropertyUpdates(+ args: Omit<BuildArgs, 'host'>,+ readPage: ReadGroupPage): Promise<OptimisticGroupedPropertyUpdates> {const changes = diffGroupKeys(args.oldGroupKeys, args.newGroupKeys);if (!changes && !args.revalidateOnly) {return { updates: [], revalidations: [] };}- const selection = selectAll(GroupSoupMembershipDocument)- .field('user')- .field('groupSoup');- const variants = await inspectVariants(args.host, selection);- const relevantVariants = variants.filter(({ variables }) =>- isRelevantPropertyGrouping(variables.input, args.propertyDefinitionId)- );- const revalidations: QueryRevalidation[] = relevantVariants.map(- ({ variables }) => ({- document: GroupSoupMembershipDocument,- variables,- })- );+ const inputs = activePropertyGroupedInputs(args.propertyDefinitionId);+ const revalidations: QueryRevalidation[] = inputs.map((input) => ({+ document: GroupSoupMembershipDocument,+ variables: { input },+ }));if (args.revalidateOnly || !changes) {return { updates: [], revalidations };}- const query = stringifyDocument(selection.document);- const operationName = documentOperationName(selection.document);- const loadedPages = await Promise.all(- relevantVariants.map(async ({ variables }): Promise<GroupPage | null> => {- const result = await args.host.readQuery({- query,- operationName,- variables,- priority: 'user-visible',- });- if (result.kind === 'miss') return null;- const data = result.data as GroupSoupMembershipQuery;- return { input: variables.input, bins: data.user.groupSoup.bins };- })- );+ const loadedPages = await Promise.all(inputs.map(readPage));const views = groupPagesByLogicalView(loadedPages.filter((page): page is GroupPage => page !== null));diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/AGENT_GUIDE/tasks.mdindex 28091b828d..00f9c71204 100644--- a/docs/AGENT_GUIDE/tasks.md+++ b/docs/AGENT_GUIDE/tasks.md@@ -262,6 +262,13 @@ unset priority stays unchanged. First assignments target the normalized entitythrough a fragment-rooted relation recipe: no flat/grouped Soup page discoveryor pre-save network fetch is needed, even with more than 128 cached pages.Check a grouped-only row and an offline/reloaded queued edit as well.+Property-group moves read only mounted, enabled grouped queries and their loaded+continuations, never all historical cache variants. Verify that a move still works+with more than 128 cached grouped pages, that duplicate split views do not multiply+membership reads, and that closing/disabling a view stops its revalidation. Bulk+moves share membership reads for distinct entities; repeat edits to one entity+reread its installed optimism. Each durable mutation retains its own recovery+queries so partial failures and offline replay still reconcile correctly.On success the temporary assignment is replacedby the server assignment without a blank cell or duplicate property; failurerestores the unset cell. Bulk property edits install every optimistic layer before