Skip to content

armgit / macro

Public Imported from GitHub
0

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

Seanaye/feat/avoid read to register deps (#5742)

Sean Aye1531f5d57600
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index 709059bd98..1e6745a7f1 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -210,9 +210,12 @@ the engine directly from its multi-threaded runtime, and unbounded on wasm.
- 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`; engine returns the set of changed
- record keys; exchange re-executes affected active operations (mirrors
- graphcache `cache-and-network` re-emission behavior).
+- On network result: RPC `writeQuery`; normalization captures every record the
+ response traverses and installs the active operation's dependencies in the
+ same write. Complete responses register exact keys; uncertain responses are
+ conservatively 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.
- Hydration-only operations skip cache reads and active-operation registration.
Client-only `@cacheOnly` fields are fetched and normalized but omitted from
the result returned across the worker/Tauri boundary. The directive is
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index d49eeefe8b..ee7776146e 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
@@ -165,7 +165,13 @@ type FakeHost = CacheHost & {
priority?: 'user-visible';
entityResolvers?: readonly unknown[];
}>;
- writes: Array<{ opKey?: number; data: unknown; identity?: string }>;
+ writes: Array<{
+ opKey?: number;
+ data: unknown;
+ identity?: string;
+ registerDependencies?: boolean;
+ entityResolvers?: readonly unknown[];
+ }>;
begins: Array<{
query: string;
data: unknown;
@@ -266,6 +272,8 @@ function makeFakeHost(): FakeHost {
opKey: args.opKey,
data: args.data,
identity: args.identity,
+ registerDependencies: args.registerDependencies,
+ entityResolvers: args.entityResolvers,
});
host.cacheActions.push({ kind: 'write', value: args.data });
return { changed: [], affectedOps: [], reset: false };
@@ -778,16 +786,21 @@ describe('normalizedCacheExchange', () => {
ops.next(makeOp(1));
await tick();
- expect(host.reads).toHaveLength(2);
- expect(host.reads.map((read) => read.opKey)).toEqual([1, 1]);
+ expect(host.reads).toHaveLength(1);
+ expect(host.reads[0]?.opKey).toBe(1);
expect(forwarded.map((op) => op.key)).toEqual([1]);
expect(results).toHaveLength(1);
expect(results[0]?.data).toEqual({ from: 'network' });
expect(host.writes).toHaveLength(1);
- expect(host.writes[0]?.data).toEqual({ from: 'network' });
+ expect(host.writes[0]).toEqual(
+ expect.objectContaining({
+ data: { from: 'network' },
+ registerDependencies: true,
+ })
+ );
});
- it('compiles entity resolvers once and forwards them to initial and post-write reads', async () => {
+ it('compiles entity resolvers once and forwards them to reads and registered writes', async () => {
const options = {
entityResolvers: ENTITY_RESOLVER_OPTIONS.entityResolvers,
} satisfies NormalizedCacheExchangeOptions;
@@ -798,15 +811,15 @@ describe('normalizedCacheExchange', () => {
ops.next(makeOp(1));
await tick();
- expect(host.reads).toHaveLength(2);
+ expect(host.reads).toHaveLength(1);
expect(forwarded.map((operation) => operation.key)).toEqual([1]);
- expect(host.reads.every((read) => read.entityResolvers !== undefined)).toBe(
- true
+ expect(host.reads[0]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);
+ expect(host.writes[0]).toEqual(
+ expect.objectContaining({
+ registerDependencies: true,
+ entityResolvers: EXPECTED_ENTITY_RESOLVERS,
+ })
);
- expect(host.reads.map((read) => read.entityResolvers)).toEqual([
- EXPECTED_ENTITY_RESOLVERS,
- EXPECTED_ENTITY_RESOLVERS,
- ]);
});
it('cache-first resolver hit emits without reaching the network', async () => {
@@ -868,16 +881,21 @@ describe('normalizedCacheExchange', () => {
expect(host.reads).toHaveLength(1);
});
- it('network-only skips the initial read and refreshes dependencies after writing', async () => {
+ it('network-only registers dependencies without reading the cache', async () => {
const { ops, results } = harness(host, undefined, ENTITY_RESOLVER_OPTIONS);
ops.next(makeOp(1, 'network-only'));
await tick();
- expect(host.reads).toHaveLength(1);
- expect(host.reads[0]?.opKey).toBe(1);
- expect(host.reads[0]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);
+ expect(host.reads).toHaveLength(0);
expect(results[0]?.data).toEqual({ from: 'network' });
expect(host.writes).toHaveLength(1);
+ expect(host.writes[0]).toEqual(
+ expect.objectContaining({
+ opKey: 1,
+ registerDependencies: true,
+ entityResolvers: EXPECTED_ENTITY_RESOLVERS,
+ })
+ );
});
it('hydrate-only stores the full response and emits only the cache projection', async () => {
@@ -1063,7 +1081,7 @@ describe('normalizedCacheExchange', () => {
]);
});
- it('defers replacement reread behind a slow successful fallback network request', async () => {
+ it('registers a slow fallback write without a replacement reread', async () => {
let readCount = 0;
host.readQuery = async (args) => {
host.reads.push({ opKey: args.opKey, query: args.query });
@@ -1095,7 +1113,8 @@ describe('normalizedCacheExchange', () => {
expect(forwarded).toHaveLength(1);
expect(client.reexecuteOperation).not.toHaveBeenCalled();
expect(host.writes).toHaveLength(1);
- expect(host.reads).toHaveLength(2);
+ expect(host.writes[0]?.registerDependencies).toBe(true);
+ expect(host.reads).toHaveLength(1);
});
it('restores a fast successful fallback after replacement without another API request', async () => {
@@ -1155,12 +1174,13 @@ describe('normalizedCacheExchange', () => {
})
);
expect(cached).toEqual({ from: 'fast-network' });
- expect(host.reads).toHaveLength(2);
- expect(host.reads[1]).toEqual(
+ expect(host.reads).toHaveLength(1);
+ expect(host.writeQuery).toHaveBeenLastCalledWith(
expect.objectContaining({
opKey: 42,
variables: { input: { limit: 2 } },
entityResolvers: EXPECTED_ENTITY_RESOLVERS,
+ registerDependencies: true,
})
);
expect(client.reexecuteOperation).not.toHaveBeenCalled();
@@ -1210,7 +1230,10 @@ describe('normalizedCacheExchange', () => {
host.pushAffected([43]);
await vi.waitFor(() => expect(host.writeQuery).toHaveBeenCalledTimes(3));
- await vi.waitFor(() => expect(host.reads).toHaveLength(2));
+ expect(host.reads).toHaveLength(1);
+ expect(host.writeQuery).toHaveBeenLastCalledWith(
+ expect.objectContaining({ registerDependencies: true })
+ );
expect(client.reexecuteOperation).not.toHaveBeenCalled();
expect(forwarded).toHaveLength(1);
@@ -1276,14 +1299,19 @@ describe('normalizedCacheExchange', () => {
hasNext: false,
});
await vi.waitFor(() => expect(host.writeQuery).toHaveBeenCalledTimes(3));
- await vi.waitFor(() => expect(host.reads).toHaveLength(2));
+ expect(host.reads).toHaveLength(1);
expect(cached).toEqual({ version: 'B' });
- expect(host.reads[1]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);
+ expect(host.writeQuery).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ entityResolvers: EXPECTED_ENTITY_RESOLVERS,
+ registerDependencies: true,
+ })
+ );
host.pushAffected([46]);
await tick();
expect(client.reexecuteOperation).toHaveBeenCalledOnce();
- expect(host.reads).toHaveLength(3);
+ expect(host.reads).toHaveLength(2);
expect(host.writeQuery).toHaveBeenCalledTimes(3);
expect(cached).toEqual({ version: 'B' });
expect(forwarded.filter(({ kind }) => kind === 'query')).toHaveLength(2);
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index 3d4020ea80..a765f730e8 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
@@ -87,7 +87,7 @@ import {
const QUEUE_ATTEMPT_CONTEXT_KEY = 'normalizedCacheQueueAttempt';
/** Marks dependency-pushed reads as latency-sensitive worker work. */
const AFFECTED_READ_CONTEXT_KEY = 'normalizedCacheAffectedRead';
-/** Prevents a post-network dependency refresh from forwarding the API again. */
+/** Prevents a replacement-registration cache read from forwarding the API again. */
const REPLACEMENT_REGISTRATION_ONLY_CONTEXT_KEY =
'normalizedCacheReplacementRegistrationOnly';
/** Marks a query as network-to-cache hydration with a projected result. */
@@ -384,12 +384,6 @@ export function normalizedCacheExchange(
return ({ forward, client }) => {
/** Operations registered with the host, for push-driven re-execution. */
const activeOps = new Map<number, Operation>();
- /**
- * Network-bound queries whose initial cache read could not register their
- * complete normalized dependencies. Refresh these after write-through so
- * later optimistic entity writes can affect the active operation.
- */
- const dependencyRefreshOps = new Set<number>();
type RetainedReplacementFallback = {
version: number;
writeArgs: Parameters<CacheHost['writeQuery']>[0];
@@ -501,7 +495,10 @@ export function normalizedCacheExchange(
) {
retained.readyPending = false;
try {
- await host.writeQuery(retained.writeArgs);
+ await host.writeQuery({
+ ...retained.writeArgs,
+ registerDependencies: true,
+ });
if (
queryStates.get(key) !== state ||
state.retainedReplacementFallback !== retained ||
@@ -510,15 +507,6 @@ export function normalizedCacheExchange(
) {
return;
}
- // Register the complete normalized dependency set directly. This
- // cannot enqueue another API request or replay the old cache RPC.
- await host.readQuery({
- opKey: retained.writeArgs.opKey,
- query: retained.writeArgs.query,
- operationName: retained.writeArgs.operationName,
- variables: retained.writeArgs.variables,
- entityResolvers: retained.writeArgs.entityResolvers,
- });
if (
queryStates.get(key) !== state ||
state.retainedReplacementFallback !== retained ||
@@ -527,7 +515,6 @@ export function normalizedCacheExchange(
return;
}
state.retainedReplacementFallback = undefined;
- dependencyRefreshOps.delete(key);
state.replacementFallback = false;
state.deferredAffected = false;
state.completedReplacementFallback = false;
@@ -800,7 +787,6 @@ export function normalizedCacheExchange(
}
const policy = op.context.requestPolicy;
if (policy === 'network-only') {
- dependencyRefreshOps.add(op.key);
enqueueQueryForward(op);
return undefined;
}
@@ -824,7 +810,6 @@ export function normalizedCacheExchange(
if (policy === 'cache-only') {
return cacheResult(op, undefined, false);
}
- dependencyRefreshOps.add(op.key);
} catch (error) {
options.onCacheError?.(error, op);
if (isOwnerEpochLostError(error)) {
@@ -1042,6 +1027,7 @@ export function normalizedCacheExchange(
...readArgs,
data: result.data,
identity: options.extractIdentity?.(result.data),
+ registerDependencies: activeOps.has(op.key),
};
const retained: RetainedReplacementFallback | undefined =
result.error === undefined &&
@@ -1063,16 +1049,8 @@ export function normalizedCacheExchange(
}
try {
await host.writeQuery(writeArgs);
- if (
- activeOps.has(op.key) &&
- (dependencyRefreshOps.has(op.key) || state.deferredAffected)
- ) {
- // A miss or replacement fallback needs one successful read
- // on the current generation after network write-through.
- await host.readQuery(readArgs);
- dependencyRefreshOps.delete(op.key);
- state.networkRegistrationSatisfied = true;
- }
+ state.networkRegistrationSatisfied =
+ writeArgs.registerDependencies;
if (state.retainedReplacementFallback === retained) {
state.retainedReplacementFallback = undefined;
}
@@ -1081,7 +1059,6 @@ export function normalizedCacheExchange(
}
}
if (result.hasNext !== true) {
- dependencyRefreshOps.delete(op.key);
const registrationSatisfied = state.networkRegistrationSatisfied;
state.networkRegistrationSatisfied = false;
finishNetworkQuery(op.key, registrationSatisfied);
@@ -1226,7 +1203,6 @@ export function normalizedCacheExchange(
tap((op) => {
if (op.kind === 'teardown') {
activeOps.delete(op.key);
- dependencyRefreshOps.delete(op.key);
queryStates.delete(op.key);
host.teardown(op.key).catch(() => undefined);
}
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index 32545ea83f..392dd346e1 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -140,7 +140,7 @@ describe('createTauriCacheHost', () => {
});
});
- it('sends writes with origin op id and identity', async () => {
+ it('sends writes with origin and dependency registration', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
const writeResult = { changed: ['A:1'], affectedOps: [], reset: false };
invokeMock.mockImplementation((command: string) =>
@@ -149,13 +149,33 @@ describe('createTauriCacheHost', () => {
const result = await host.writeQuery({
opKey: 3,
+ registerDependencies: true,
query: '{ x }',
data: { x: 1 },
identity: 'user-1',
+ entityResolvers: [
+ {
+ parentType: 'GraphqlUser',
+ fieldName: 'emailThread',
+ targetType: 'GraphqlSoupEmailThread',
+ argumentPath: ['input', 'threadId'],
+ },
+ ],
});
expect(result).toEqual(writeResult);
expect(invokeMock).toHaveBeenCalledWith('graphql_cache_write', {
originOpId: `${host.clientId}:3`,
+ registration: {
+ opId: `${host.clientId}:3`,
+ entityResolvers: [
+ {
+ parentType: 'GraphqlUser',
+ fieldName: 'emailThread',
+ targetType: 'GraphqlSoupEmailThread',
+ argumentPath: ['input', 'threadId'],
+ },
+ ],
+ },
query: '{ x }',
operationName: undefined,
variables: undefined,
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 0dca1d4ac2..a12c435245 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -191,6 +191,13 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
await ready;
return await request<WriteResult>('graphql_cache_write', {
originOpId: args.opKey === undefined ? undefined : opId(args.opKey),
+ registration:
+ args.registerDependencies && args.opKey !== undefined
+ ? {
+ opId: opId(args.opKey),
+ entityResolvers: args.entityResolvers,
+ }
+ : undefined,
query: args.query,
operationName: args.operationName,
variables: args.variables,
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 5df11d902b..0e85c1c793 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -56,6 +56,8 @@ export type InspectQueryVariantsArgs = Omit<
export interface CacheWriteArgs extends Omit<CacheReadArgs, 'priority'> {
data: unknown;
+ /** Installs this active query's dependencies from the normalized response. */
+ registerDependencies?: boolean;
/** Opaque session tag; see protocol.ts `identity`. */
identity?: string;
}
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index d5808436bc..f3a8c8be63 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -353,9 +353,18 @@ describe('createWorkerCacheHost', () => {
}),
host.writeQuery({
opKey: 8,
+ registerDependencies: true,
query: 'query Read { user { id } }',
data: { user: { id: 'user-1' } },
identity: 'user-1',
+ entityResolvers: [
+ {
+ parentType: 'GraphqlUser',
+ fieldName: 'emailThread',
+ targetType: 'GraphqlSoupEmailThread',
+ argumentPath: ['input', 'threadId'],
+ },
+ ],
}),
host.enqueueOptimisticMutation(
{
@@ -436,7 +445,18 @@ describe('createWorkerCacheHost', () => {
},
});
expect(requests[4]).toEqual(
- expect.objectContaining({ originOpId: `${CLIENT_ID}:8` })
+ expect.objectContaining({
+ originOpId: `${CLIENT_ID}:8`,
+ registration: {
+ opId: `${CLIENT_ID}:8`,
+ entityResolvers: [
+ expect.objectContaining({
+ parentType: 'GraphqlUser',
+ fieldName: 'emailThread',
+ }),
+ ],
+ },
+ })
);
expect(requests[5]).toEqual(
expect.objectContaining({
@@ -752,7 +772,12 @@ describe('createWorkerCacheHost', () => {
await Promise.all([
host.readQuery({ opKey: 7, query: 'query Seven { seven }' }),
- host.readQuery({ opKey: 9, query: 'query Nine { nine }' }),
+ host.writeQuery({
+ opKey: 9,
+ registerDependencies: true,
+ query: 'query Nine { nine }',
+ data: { nine: 9 },
+ }),
host.readQuery({ query: 'query Untracked { untracked }' }),
]);
const adapter = requireAdapter();
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index 917ecc4900..8742e634fe 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -286,7 +286,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
pending.delete(msg.id);
if (entry.timer !== undefined) clearTimeout(entry.timer);
if (
- entry.kind === 'read' &&
+ (entry.kind === 'read' || entry.kind === 'write') &&
entry.opKey !== undefined &&
activeOpKeys.has(entry.opKey)
) {
@@ -305,9 +305,12 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
registeredOpKeys.clear();
}
- function markPendingReads(target: Set<number>): void {
+ function markPendingRegistrations(target: Set<number>): void {
for (const entry of pending.values()) {
- if (entry.kind === 'read' && entry.opKey !== undefined) {
+ if (
+ (entry.kind === 'read' || entry.kind === 'write') &&
+ entry.opKey !== undefined
+ ) {
target.add(entry.opKey);
}
}
@@ -331,7 +334,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
// No old response put this host into recovery. Requests still pending at
// replacement broadcast were queued by the coordinator while resetting
// and will be routed exactly once to this replacement generation.
- markPendingReads(replacementReadOpKeys);
+ markPendingRegistrations(replacementReadOpKeys);
}
if (state !== 'ready' && state !== 'awaiting-replacement') return;
void startInitialization().catch(() => undefined);
@@ -344,7 +347,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
beginRecoveryGeneration();
// A rejected old-epoch read may have registered dependencies before its
// response was lost. It belongs to the lost generation, not replacement.
- markPendingReads(lostRegisteredOpKeys);
+ markPendingRegistrations(lostRegisteredOpKeys);
replacementError = error;
initialization = undefined;
state = 'awaiting-replacement';
@@ -803,16 +806,30 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
},
async writeQuery(args: CacheWriteArgs): Promise<WriteResult> {
+ if (args.registerDependencies && args.opKey !== undefined) {
+ activeOpKeys.add(args.opKey);
+ if (recoveryInProgress) replacementReadOpKeys.add(args.opKey);
+ }
await ensureInitialized();
- return (await request({
- kind: 'write',
- originOpId: args.opKey === undefined ? undefined : opId(args.opKey),
- query: args.query,
- operationName: args.operationName,
- variables: args.variables,
- data: args.data,
- identity: args.identity,
- })) as WriteResult;
+ return (await request(
+ {
+ kind: 'write',
+ originOpId: args.opKey === undefined ? undefined : opId(args.opKey),
+ registration:
+ args.registerDependencies && args.opKey !== undefined
+ ? {
+ opId: opId(args.opKey),
+ entityResolvers: args.entityResolvers,
+ }
+ : undefined,
+ query: args.query,
+ operationName: args.operationName,
+ variables: args.variables,
+ data: args.data,
+ identity: args.identity,
+ },
+ args.registerDependencies ? args.opKey : undefined
+ )) as WriteResult;
},
async hydrateQuery(
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index 9f6dee6d72..870d19ebf7 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -323,6 +323,10 @@ export type CacheRequest = { id: number } & (
| {
kind: 'write';
originOpId?: string;
+ registration?: {
+ opId: string;
+ entityResolvers?: readonly EntityResolverWire[];
+ };
query: string;
operationName?: string;
variables?: Record<string, unknown>;
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts
index 6a0a6dd15f..16c745b015 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.test.ts
@@ -20,6 +20,35 @@ describe('coordinator runtime protocol', () => {
it('validates cache RPCs and rejects unknown fields or kinds', () => {
expect(isCacheRequest({ id: 0, kind: 'clear' })).toBe(true);
expect(isCacheRequest({ id: 1, kind: 'read', query: '{ x }' })).toBe(true);
+ expect(
+ isCacheRequest({
+ id: 2,
+ kind: 'write',
+ originOpId: 'client:1',
+ registration: {
+ opId: 'client:1',
+ entityResolvers: [
+ {
+ parentType: 'GraphqlUser',
+ fieldName: 'emailThread',
+ targetType: 'GraphqlSoupEmailThread',
+ argumentPath: ['input', 'threadId'],
+ },
+ ],
+ },
+ query: '{ user { id } }',
+ data: { user: { id: 'user-1' } },
+ })
+ ).toBe(true);
+ expect(
+ isCacheRequest({
+ id: 2,
+ kind: 'write',
+ registration: { opId: '', entityResolvers: [] },
+ query: '{ user { id } }',
+ data: { user: { id: 'user-1' } },
+ })
+ ).toBe(false);
expect(
isCacheRequest({
id: 2,
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
index 1b2feab9c0..2a01817709 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-protocol.ts
@@ -306,6 +306,13 @@ const isEntityResolvers = (value: unknown): boolean =>
isStringArray(resolver.argumentPath)
));
+const isWriteRegistration = (value: unknown): boolean =>
+ value === undefined ||
+ (isRecord(value) &&
+ hasOnlyKeys(value, ['opId', 'entityResolvers']) &&
+ isNonEmptyString(value.opId) &&
+ isEntityResolvers(value.entityResolvers));
+
const isSearchRequest = (value: unknown): boolean => {
if (!isRecord(value)) return false;
return (
@@ -365,6 +372,7 @@ export function isCacheRequest(value: unknown): value is CacheRequest {
'id',
'kind',
'originOpId',
+ 'registration',
'query',
'operationName',
'variables',
@@ -372,6 +380,7 @@ export function isCacheRequest(value: unknown): value is CacheRequest {
'identity',
]) &&
isOptionalString(value.originOpId) &&
+ isWriteRegistration(value.registration) &&
isString(value.query) &&
isOptionalString(value.operationName) &&
isOptionalRecord(value.variables) &&
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 814cf75b2e..b0bebc99a3 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -79,7 +79,13 @@ export interface CacheEngine {
request: SearchCacheArgs & { nowMs: number }
): Promise<SearchCachePage>;
writeQuery(
- originOpId: string | undefined,
+ context: {
+ originOpId?: string;
+ registration?: {
+ opId: string;
+ entityResolvers?: readonly EntityResolverWire[];
+ };
+ },
query: string,
operationName: string | undefined,
variables: Record<string, unknown> | undefined,
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
index 4701900f64..e758a15f0a 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts
@@ -605,10 +605,9 @@ describe('CacheWorkerCore', () => {
affectedOps: [],
reset: false,
};
+ const writeQuery = vi.fn().mockResolvedValue(writeResult);
loadCacheWasmMock.mockResolvedValue({
- openCache: vi.fn().mockResolvedValue({
- writeQuery: vi.fn().mockResolvedValue(writeResult),
- }),
+ openCache: vi.fn().mockResolvedValue({ writeQuery }),
});
const messages: unknown[] = [];
const port = { postMessage: (message: unknown) => messages.push(message) };
@@ -623,10 +622,26 @@ describe('CacheWorkerCore', () => {
await core.handleRequest(port, {
id: 2,
kind: 'write',
+ originOpId: 'client:7',
+ registration: {
+ opId: 'client:7',
+ entityResolvers: [],
+ },
query: 'query { user { id } }',
data: { user: { id: 'user-1' } },
});
+ expect(writeQuery).toHaveBeenCalledWith(
+ {
+ originOpId: 'client:7',
+ registration: { opId: 'client:7', entityResolvers: [] },
+ },
+ 'query { user { id } }',
+ undefined,
+ undefined,
+ { user: { id: 'user-1' } },
+ undefined
+ );
expect(messages).toContainEqual({ kind: 'cache-changed' });
});
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index ef802a61e5..b0dbb1fd1b 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -393,7 +393,10 @@ export class CacheWorkerCore {
.with({ kind: 'write' }, async (request) => {
const engine = this.requireEngine();
const result = await engine.writeQuery(
- request.originOpId,
+ {
+ originOpId: request.originOpId,
+ registration: request.registration,
+ },
request.query,
request.operationName,
request.variables,
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index 0f9380ee85..4e4c91e22f 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -11,7 +11,7 @@
use crate::engine::{
ClaimedMutationWire, EngineHandle, EnqueueOptimisticMutationResultWire, ReadResultWire,
- WriteResultWire,
+ WriteRegistration, WriteRequest, WriteResultWire,
};
use crate::{
CacheState, InitializedCache, emit_cache_changed, emit_mutation_settled, emit_ops_affected,
@@ -120,6 +120,17 @@ pub async fn graphql_cache_search(
engine_handle(&state)?.search(request).await
}
+/// Active-query registration installed by a network write.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WriteRegistrationWire {
+ /// Host operation id.
+ pub op_id: String,
+ /// Synthetic read relations used by the query.
+ #[serde(default)]
+ pub entity_resolvers: Vec<EntityResolver>,
+}
+
/// Normalizes and stores a network response; broadcasts affected operations
/// to every webview.
#[tauri::command]
@@ -127,6 +138,7 @@ pub async fn graphql_cache_write<R: Runtime>(
app: AppHandle<R>,
state: State<'_, CacheState>,
origin_op_id: Option<String>,
+ registration: Option<WriteRegistrationWire>,
query: String,
operation_name: Option<String>,
variables: Option<Variables>,
@@ -134,14 +146,18 @@ pub async fn graphql_cache_write<R: Runtime>(
identity: Option<String>,
) -> Result<WriteResultWire, String> {
let result = engine_handle(&state)?
- .write(
+ .write(WriteRequest {
origin_op_id,
+ registration: registration.map(|registration| WriteRegistration {
+ op_id: registration.op_id,
+ entity_resolvers: registration.entity_resolvers,
+ }),
query,
operation_name,
- variables.unwrap_or_default(),
+ variables: variables.unwrap_or_default(),
data,
identity,
- )
+ })
.await?;
emit_ops_affected(&app, &result.affected_ops, &result.changed);
emit_cache_changed(&app);
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 5745892f8e..951be2e1d4 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -13,7 +13,8 @@
use cache_core::deps::OpId;
use cache_core::engine::{
- BeginOptimisticWrite, Engine, InitialClaimOutcome, ReadResult, WriteResult,
+ BeginOptimisticWrite, Engine, InitialClaimOutcome, NetworkWrite, QueryRegistration, ReadResult,
+ WriteResult,
};
use cache_core::entity_resolver::EntityResolver;
use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
@@ -170,6 +171,32 @@ impl OpInterner {
type Variables = serde_json::Map<String, serde_json::Value>;
+/// Optional active-query registration installed by a network write.
+pub struct WriteRegistration {
+ /// Host operation id.
+ pub op_id: String,
+ /// Synthetic read relations used by the query.
+ pub entity_resolvers: Vec<EntityResolver>,
+}
+
+/// Owned inputs for a network response write.
+pub struct WriteRequest {
+ /// Origin operation excluded from immediate invalidation.
+ pub origin_op_id: Option<String>,
+ /// Active query registration to install.
+ pub registration: Option<WriteRegistration>,
+ /// GraphQL document.
+ pub query: String,
+ /// Selected operation name.
+ pub operation_name: Option<String>,
+ /// Operation variables.
+ pub variables: Variables,
+ /// GraphQL response data.
+ pub data: serde_json::Value,
+ /// Opaque identity witness.
+ pub identity: Option<String>,
+}
+
struct EngineState {
engine: Engine<TursoStorage>,
ops: OpInterner,
@@ -342,26 +369,39 @@ impl EngineHandle {
}
/// Normalizes and stores a network response.
- pub async fn write(
- &self,
- origin_op_id: Option<String>,
- query: String,
- operation_name: Option<String>,
- variables: Variables,
- data: serde_json::Value,
- identity: Option<String>,
- ) -> Result<WriteResultWire, String> {
+ pub async fn write(&self, request: WriteRequest) -> Result<WriteResultWire, String> {
+ let WriteRequest {
+ origin_op_id,
+ registration,
+ query,
+ operation_name,
+ variables,
+ data,
+ identity,
+ } = request;
let mut state = self.inner.lock().await;
let EngineState { engine, ops } = &mut *state;
let origin = origin_op_id.map(|name| ops.intern(&name));
+ let registration = registration.map(|registration| {
+ let op_id = ops.intern(&registration.op_id);
+ (op_id, registration.entity_resolvers)
+ });
engine
- .write_query(
+ .write_query_with_registration(
origin,
- &query,
- operation_name.as_deref(),
- &variables,
- &data,
- identity.as_deref(),
+ registration
+ .as_ref()
+ .map(|(op_id, entity_resolvers)| QueryRegistration {
+ op_id: *op_id,
+ entity_resolvers,
+ }),
+ NetworkWrite {
+ query: &query,
+ operation_name: operation_name.as_deref(),
+ variables: &variables,
+ data: &data,
+ identity: identity.as_deref(),
+ },
)
.await
.map(|result| wire_write_result(ops, result))
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index 37951ba9c2..489a7d7b1a 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -45,14 +45,15 @@ fn write(
data: serde_json::Value,
identity: Option<&str>,
) -> WriteResultWire {
- block_on(handle.write(
- origin.map(str::to_string),
- QUERY.to_string(),
- Some("Soup".to_string()),
- variables(),
+ block_on(handle.write(WriteRequest {
+ origin_op_id: origin.map(str::to_string),
+ registration: None,
+ query: QUERY.to_string(),
+ operation_name: Some("Soup".to_string()),
+ variables: variables(),
data,
- identity.map(str::to_string),
- ))
+ identity: identity.map(str::to_string),
+ }))
.unwrap()
}
@@ -192,14 +193,15 @@ fn explicit_key_selection_returns_native_cache_entities() {
}
}
});
- block_on(handle.write(
- None,
- query.to_string(),
- Some("Soup".to_string()),
- variables(),
+ block_on(handle.write(WriteRequest {
+ origin_op_id: None,
+ registration: None,
+ query: query.to_string(),
+ operation_name: Some("Soup".to_string()),
+ variables: variables(),
data,
- None,
- ))
+ identity: None,
+ }))
.unwrap();
let records = block_on(handle.read_records_by_keys(
@@ -230,12 +232,13 @@ fn search_uses_native_materialized_projection() {
}
}
}"#;
- block_on(handle.write(
- None,
- query.to_string(),
- Some("Soup".to_string()),
- variables(),
- serde_json::json!({
+ block_on(handle.write(WriteRequest {
+ origin_op_id: None,
+ registration: None,
+ query: query.to_string(),
+ operation_name: Some("Soup".to_string()),
+ variables: variables(),
+ data: serde_json::json!({
"user": {
"id": "user-1",
"soup": {
@@ -249,8 +252,8 @@ fn search_uses_native_materialized_projection() {
}
}
}),
- None,
- ))
+ identity: None,
+ }))
.unwrap();
let page = block_on(handle.search(SearchRequest {
@@ -321,10 +324,21 @@ fn query_variant_inspection_serializes_only_generated_variables() {
#[test]
fn registered_op_is_affected_by_later_writes() {
let handle = spawn_handle();
- write(&handle, None, soup_data(false), None);
+ block_on(handle.write(WriteRequest {
+ origin_op_id: Some("client:1".to_string()),
+ registration: Some(WriteRegistration {
+ op_id: "client:1".to_string(),
+ entity_resolvers: Vec::new(),
+ }),
+ query: QUERY.to_string(),
+ operation_name: Some("Soup".to_string()),
+ variables: variables(),
+ data: soup_data(false),
+ identity: None,
+ }))
+ .unwrap();
- // Register an active operation, then change its data from another op.
- read(&handle, Some("client:1"));
+ // The registered write avoids a read and still observes a later change.
let result = write(&handle, Some("client:2"), soup_data(true), None);
assert_eq!(result.affected_ops, vec!["client:1".to_string()]);
diff --git a/crates/client/cache-core/src/deps.rs b/crates/client/cache-core/src/deps.rs
index 4fc9e2c19a..b477a9635c 100644
--- a/crates/client/cache-core/src/deps.rs
+++ b/crates/client/cache-core/src/deps.rs
@@ -13,6 +13,7 @@ pub type OpId = u64;
pub struct DepIndex {
by_op: HashMap<OpId, BTreeSet<EntityKey<'static>>>,
by_key: HashMap<EntityKey<'static>, HashSet<OpId>>,
+ broad_ops: BTreeSet<OpId>,
}
impl DepIndex {
@@ -29,8 +30,16 @@ impl DepIndex {
self.by_op.insert(op, deps);
}
+ /// Registers an operation conservatively against every visible change.
+ pub fn set_op_broad(&mut self, op: OpId) {
+ self.remove_op(op);
+ self.broad_ops.insert(op);
+ self.by_op.insert(op, BTreeSet::new());
+ }
+
/// Unregisters an operation (urql teardown).
pub fn remove_op(&mut self, op: OpId) {
+ self.broad_ops.remove(&op);
if let Some(old) = self.by_op.remove(&op) {
for key in old {
if let Some(set) = self.by_key.get_mut(&key) {
@@ -49,11 +58,16 @@ impl DepIndex {
keys: impl IntoIterator<Item = &'a EntityKey<'static>>,
) -> BTreeSet<OpId> {
let mut out = BTreeSet::new();
+ let mut saw_key = false;
for key in keys {
+ saw_key = true;
if let Some(ops) = self.by_key.get(key) {
out.extend(ops.iter().copied());
}
}
+ if saw_key {
+ out.extend(self.broad_ops.iter().copied());
+ }
out
}
@@ -99,4 +113,21 @@ mod tests {
assert_eq!(idx.active_ops(), 0);
assert!(idx.ops_for_keys(&[key("B"), key("C")]).is_empty());
}
+
+ #[test]
+ fn broad_registration_is_replaced_and_removed() {
+ let mut idx = DepIndex::new();
+ idx.set_op_broad(1);
+ assert_eq!(idx.ops_for_keys(&[key("anything")]), [1].into());
+ assert!(idx.ops_for_keys(std::iter::empty()).is_empty());
+
+ idx.set_op_deps(1, [key("A")].into());
+ assert!(idx.ops_for_keys(&[key("B")]).is_empty());
+ assert_eq!(idx.ops_for_keys(&[key("A")]), [1].into());
+
+ idx.set_op_broad(1);
+ idx.remove_op(1);
+ assert!(idx.ops_for_keys(&[key("A")]).is_empty());
+ assert_eq!(idx.active_ops(), 0);
+ }
}
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index d98fb56659..440ecb5075 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -13,7 +13,10 @@ use crate::link_patch::{
LinkPatchError, OptimisticLinkPatch, QueryRevalidation, apply_link_patches,
deduplicate_patches, missing_patch_record,
};
-use crate::normalize::{NormalizeError, RecordUpdates, normalize, project_hydration_response};
+use crate::normalize::{
+ DependencyCompleteness, NormalizeError, RecordUpdates, normalize, normalize_with_dependencies,
+ project_hydration_response,
+};
use crate::query_inspection::{
CachedQueryInstance, CachedQueryVariant, OwnerResolution, QueryInspection,
QueryInspectionError, matches_variable_filters, prepare, recover_variants, resolve_owner,
@@ -79,6 +82,30 @@ pub enum ReadResult {
Miss,
}
+/// Borrowed inputs for one network response write.
+#[derive(Debug, Clone, Copy)]
+pub struct NetworkWrite<'a> {
+ /// GraphQL operation document.
+ pub query: &'a str,
+ /// Selected operation name.
+ pub operation_name: Option<&'a str>,
+ /// Resolved operation variables.
+ pub variables: &'a serde_json::Map<String, Json>,
+ /// GraphQL response data.
+ pub data: &'a Json,
+ /// Optional opaque session identity witness.
+ pub identity: Option<&'a str>,
+}
+
+/// An active query whose dependencies should be installed by a network write.
+#[derive(Debug, Clone, Copy)]
+pub struct QueryRegistration<'a> {
+ /// Host-scoped active operation id.
+ pub op_id: OpId,
+ /// Read-only relations that change which normalized entities the query uses.
+ pub entity_resolvers: &'a [EntityResolver],
+}
+
/// Result of writing a network response.
#[derive(Debug)]
pub struct WriteResult {
@@ -859,10 +886,51 @@ impl<S: Storage> Engine<S> {
data: &Json,
identity: Option<&str>,
) -> Result<WriteResult, EngineError<S::Error>> {
+ self.write_query_with_registration(
+ origin_op,
+ None,
+ NetworkWrite {
+ query,
+ operation_name,
+ variables,
+ data,
+ identity,
+ },
+ )
+ .await
+ }
+
+ /// Normalizes and stores a network response, installing the active query's
+ /// dependencies from the same response without denormalizing it again.
+ pub async fn write_query_with_registration(
+ &mut self,
+ origin_op: Option<OpId>,
+ registration: Option<QueryRegistration<'_>>,
+ input: NetworkWrite<'_>,
+ ) -> Result<WriteResult, EngineError<S::Error>> {
+ let NetworkWrite {
+ query,
+ operation_name,
+ variables,
+ data,
+ identity,
+ } = input;
self.hydrate_optimistic().await?;
+ let entity_resolvers = EntityResolverLookup::compile(
+ registration.map_or(&[][..], |registration| registration.entity_resolvers),
+ )?;
let doc = Self::document(&mut self.docs, query)?;
let op = doc.operation(operation_name)?;
- let updates = normalize(op, variables, data)?;
+ if registration.is_some() && op.kind != OperationKind::Query {
+ return Err(EngineError::Document(
+ DocumentError::UnsupportedOperationType(format!(
+ "{:?} (dependency registration is query-only)",
+ op.kind
+ )),
+ ));
+ }
+ let normalized = normalize_with_dependencies(op, variables, data, &entity_resolvers)?;
+ let updates = normalized.updates;
let mut reset = false;
if let Some(observed) = identity {
@@ -915,6 +983,16 @@ impl<S: Storage> Engine<S> {
if let Some(origin) = origin_op {
affected_ops.remove(&origin);
}
+ if let Some(registration) = registration {
+ if normalized.completeness == DependencyCompleteness::Exact
+ && self.optimistic.is_empty()
+ {
+ self.deps
+ .set_op_deps(registration.op_id, normalized.dependencies);
+ } else {
+ self.deps.set_op_broad(registration.op_id);
+ }
+ }
Ok(WriteResult {
changed,
affected_ops,
diff --git a/crates/client/cache-core/src/normalize.rs b/crates/client/cache-core/src/normalize.rs
index e9ae8aa4b3..099039a27c 100644
--- a/crates/client/cache-core/src/normalize.rs
+++ b/crates/client/cache-core/src/normalize.rs
@@ -1,12 +1,13 @@
//! Write path: response JSON → normalized records.
use crate::document::{
- FieldNode, MissingVariable, Operation, OperationKind, Selection, resolve_args_key,
+ FieldNode, MissingVariable, Operation, OperationKind, Selection, resolve_args, resolve_args_key,
};
+use crate::entity_resolver::EntityResolverLookup;
use crate::meta::{self, FieldKind, TypeKind};
use crate::value::{CacheValue, EntityKey, Record, field_key};
use serde_json::Value as Json;
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, BTreeSet};
use thiserror::Error;
#[derive(Debug, Error)]
@@ -38,6 +39,38 @@ pub enum NormalizeError {
/// records.
pub type RecordUpdates = BTreeMap<EntityKey<'static>, Record>;
+/// Whether response-derived dependencies exactly describe a future cache read.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum DependencyCompleteness {
+ Exact,
+ Broad,
+}
+
+/// Normalized updates and dependencies captured without reading records back.
+pub(crate) struct NormalizeResult {
+ pub updates: RecordUpdates,
+ pub dependencies: BTreeSet<EntityKey<'static>>,
+ pub completeness: DependencyCompleteness,
+}
+
+struct DependencyCapture<'a> {
+ keys: BTreeSet<EntityKey<'static>>,
+ completeness: DependencyCompleteness,
+ entity_resolvers: &'a EntityResolverLookup,
+}
+
+impl DependencyCapture<'_> {
+ fn mark_broad(&mut self) {
+ self.completeness = DependencyCompleteness::Broad;
+ }
+}
+
+struct WriteContext<'a, 'resolver> {
+ variables: &'a serde_json::Map<String, Json>,
+ records: &'a mut RecordUpdates,
+ dependencies: &'a mut DependencyCapture<'resolver>,
+}
+
/// Normalizes a response's `data` object into record updates.
///
/// Query responses are rooted at [`ROOT_QUERY`](crate::value::ROOT_QUERY).
@@ -49,6 +82,16 @@ pub fn normalize(
variables: &serde_json::Map<String, Json>,
data: &Json,
) -> Result<RecordUpdates, NormalizeError> {
+ Ok(normalize_with_dependencies(op, variables, data, &EntityResolverLookup::default())?.updates)
+}
+
+/// Normalizes a response and captures the records a cache read would depend on.
+pub(crate) fn normalize_with_dependencies(
+ op: &Operation,
+ variables: &serde_json::Map<String, Json>,
+ data: &Json,
+ entity_resolvers: &EntityResolverLookup,
+) -> Result<NormalizeResult, NormalizeError> {
let root_type = operation_root_type(op)?;
let Json::Object(data) = data else {
return Err(NormalizeError::Shape {
@@ -59,18 +102,32 @@ pub fn normalize(
};
let mut records = RecordUpdates::new();
let mut root = Record::default();
+ let mut dependencies = DependencyCapture {
+ keys: BTreeSet::new(),
+ completeness: DependencyCompleteness::Exact,
+ entity_resolvers,
+ };
+ let root_key = (op.kind == OperationKind::Query).then(EntityKey::root);
write_object_fields(
&op.selection_set,
root_type,
data,
- variables,
&mut root.fields,
- &mut records,
+ root_key.as_ref(),
+ &mut WriteContext {
+ variables,
+ records: &mut records,
+ dependencies: &mut dependencies,
+ },
)?;
- if op.kind == OperationKind::Query {
- merge_into(&mut records, EntityKey::root(), root);
+ if let Some(root_key) = root_key {
+ merge_into(&mut records, root_key, root);
}
- Ok(records)
+ Ok(NormalizeResult {
+ updates: records,
+ dependencies: dependencies.keys,
+ completeness: dependencies.completeness,
+ })
}
/// Projects fields not marked `@cacheOnly` directly from a network response.
@@ -228,15 +285,18 @@ fn write_object_fields(
selections: &[Selection],
type_name: &str,
data: &serde_json::Map<String, Json>,
- variables: &serde_json::Map<String, Json>,
target: &mut BTreeMap<String, CacheValue>,
- records: &mut RecordUpdates,
+ owner: Option<&EntityKey<'static>>,
+ context: &mut WriteContext<'_, '_>,
) -> Result<(), NormalizeError> {
// The concrete type: trust __typename in the response when present.
let concrete = match data.get("__typename") {
Some(Json::String(t)) => t.as_str(),
_ => type_name,
};
+ if let Some(owner) = owner {
+ context.dependencies.keys.insert(owner.clone());
+ }
target.insert(
"__typename".to_string(),
CacheValue::String(concrete.to_string()),
@@ -254,22 +314,37 @@ fn write_object_fields(
type_name: concrete.to_string(),
field: f.name.clone(),
})?;
- let args = resolve_args_key(f, variables)?;
+ let args = resolve_args_key(f, context.variables)?;
let storage_key = field_key(&f.name, args.as_deref());
- // GraphQL guarantees selected fields are present in data; tolerate
- // absence by skipping (defensive against non-conformant servers).
+ // GraphQL guarantees selected fields are present in data. Missing
+ // fields are still tolerated, but an exact dependency set cannot be
+ // proven because a merged record may retain an older relation.
let Some(value) = data.get(&f.response_key) else {
+ context.dependencies.mark_broad();
continue;
};
- let cache_value = write_value(f, fmeta.ty.name, fmeta.ty.kind, value, variables, records)
+ let cache_value = write_value(f, fmeta.ty.name, fmeta.ty.kind, value, owner, context)
.map_err(|detail| NormalizeError::Shape {
- type_name: concrete.to_string(),
- field: f.name.clone(),
- detail,
- })?;
- let cache_value = cache_value?;
+ type_name: concrete.to_string(),
+ field: f.name.clone(),
+ detail,
+ })??;
+
+ if let Some(resolver) = context.dependencies.entity_resolvers.get(concrete, &f.name) {
+ let expected_key = resolve_args(f, context.variables)
+ .ok()
+ .and_then(|arguments| resolver.entity_key(&arguments));
+ match (expected_key, value, &cache_value) {
+ (Some(expected), Json::Object(_), CacheValue::Ref(actual))
+ if expected == *actual =>
+ {
+ context.dependencies.keys.insert(expected);
+ }
+ _ => context.dependencies.mark_broad(),
+ }
+ }
target.insert(storage_key, cache_value);
}
Ok(())
@@ -283,15 +358,15 @@ fn write_value(
named_type: &str,
kind: FieldKind,
value: &Json,
- variables: &serde_json::Map<String, Json>,
- records: &mut RecordUpdates,
+ owner: Option<&EntityKey<'static>>,
+ context: &mut WriteContext<'_, '_>,
) -> Result<Result<CacheValue, NormalizeError>, &'static str> {
Ok(match value {
Json::Null => Ok(CacheValue::Null),
Json::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
- match write_value(field, named_type, kind, item, variables, records)? {
+ match write_value(field, named_type, kind, item, owner, context)? {
Ok(v) => out.push(v),
Err(e) => return Ok(Err(e)),
}
@@ -317,7 +392,7 @@ fn write_value(
FieldKind::OpaqueScalar => Ok(CacheValue::opaque(value)),
FieldKind::Leaf => return Err("expected scalar, got object"),
FieldKind::Composite => {
- match normalize_object(field, named_type, obj, variables, records) {
+ match normalize_object(field, named_type, obj, owner, context) {
Ok(v) => Ok(v),
Err(e) => return Ok(Err(e)),
}
@@ -332,8 +407,8 @@ fn normalize_object(
field: &FieldNode,
named_type: &str,
obj: &serde_json::Map<String, Json>,
- variables: &serde_json::Map<String, Json>,
- records: &mut RecordUpdates,
+ owner: Option<&EntityKey<'static>>,
+ context: &mut WriteContext<'_, '_>,
) -> Result<CacheValue, NormalizeError> {
let named_meta = meta::type_meta(named_type)
.ok_or_else(|| NormalizeError::UnknownType(named_type.to_string()))?;
@@ -375,11 +450,11 @@ fn normalize_object(
&field.selection_set,
concrete,
obj,
- variables,
&mut record.fields,
- records,
+ Some(&key),
+ context,
)?;
- merge_into(records, key.clone(), record);
+ merge_into(context.records, key.clone(), record);
Ok(CacheValue::Ref(key))
}
None => {
@@ -388,9 +463,9 @@ fn normalize_object(
&field.selection_set,
concrete,
obj,
- variables,
&mut embedded,
- records,
+ owner,
+ context,
)?;
Ok(CacheValue::Object(embedded))
}
diff --git a/crates/client/cache-core/tests/engine.rs b/crates/client/cache-core/tests/engine.rs
index ab19465863..8756a6d83d 100644
--- a/crates/client/cache-core/tests/engine.rs
+++ b/crates/client/cache-core/tests/engine.rs
@@ -1,7 +1,7 @@
//! Engine-level tests: read/write flow, hot-tier eviction falling back to
//! storage, dependency-driven re-execution, teardown, clear.
-use cache_core::engine::{Engine, ReadResult};
+use cache_core::engine::{Engine, NetworkWrite, QueryRegistration, ReadResult};
use cache_core::store::InMemoryStorage;
use pollster::block_on;
use serde_json::{Value as Json, json};
@@ -230,10 +230,11 @@ fn cross_operation_invalidation() {
let mut engine = Engine::new(InMemoryStorage::new());
// Op 1: limit 10; Op 2: limit 20 — different root fields, shared
- // entity doc-1.
+ // entity doc-1. Seed first so registration must include records that
+ // the registered write itself does not change.
engine
.write_query(
- Some(1),
+ None,
QUERY,
Some("Soup"),
&vars(10),
@@ -242,10 +243,24 @@ fn cross_operation_invalidation() {
)
.await
.unwrap();
- engine
- .read_query(Some(1), QUERY, Some("Soup"), &vars(10))
+ let registered = engine
+ .write_query_with_registration(
+ Some(1),
+ Some(QueryRegistration {
+ op_id: 1,
+ entity_resolvers: &[],
+ }),
+ NetworkWrite {
+ query: QUERY,
+ operation_name: Some("Soup"),
+ variables: &vars(10),
+ data: &page(&[("doc-1", "A")]),
+ identity: None,
+ },
+ )
.await
.unwrap();
+ assert!(registered.changed.is_empty());
// Op 2's response renames doc-1 → op 1 must be re-executed.
let write = engine
@@ -304,6 +319,95 @@ fn cross_operation_invalidation() {
});
}
+#[test]
+fn incomplete_registered_write_is_conservatively_affected() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ engine
+ .write_query_with_registration(
+ Some(1),
+ Some(QueryRegistration {
+ op_id: 1,
+ entity_resolvers: &[],
+ }),
+ NetworkWrite {
+ query: QUERY,
+ operation_name: Some("Soup"),
+ variables: &vars(10),
+ data: &json!({ "user": { "id": "user-1" } }),
+ identity: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let Json::Object(notification_variables) = json!({
+ "input": {
+ "notificationIds": ["unrelated-notification"],
+ "operation": "MARK_SEEN"
+ }
+ }) else {
+ unreachable!()
+ };
+ let write = engine
+ .write_query(
+ Some(2),
+ UPDATE_NOTIFICATIONS_MUTATION,
+ Some("UpdateNotifications"),
+ &notification_variables,
+ &json!({
+ "updateNotifications": [{
+ "__typename": "GraphqlNotification",
+ "id": "unrelated-notification",
+ "seen": true,
+ "viewedAt": null
+ }]
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(write.affected_ops, [1].into());
+
+ engine
+ .write_query_with_registration(
+ Some(1),
+ Some(QueryRegistration {
+ op_id: 1,
+ entity_resolvers: &[],
+ }),
+ NetworkWrite {
+ query: QUERY,
+ operation_name: Some("Soup"),
+ variables: &vars(10),
+ data: &page(&[("doc-1", "Complete")]),
+ identity: None,
+ },
+ )
+ .await
+ .unwrap();
+ let write = engine
+ .write_query(
+ Some(2),
+ UPDATE_NOTIFICATIONS_MUTATION,
+ Some("UpdateNotifications"),
+ &notification_variables,
+ &json!({
+ "updateNotifications": [{
+ "__typename": "GraphqlNotification",
+ "id": "another-unrelated-notification",
+ "seen": true,
+ "viewedAt": null
+ }]
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert!(write.affected_ops.is_empty());
+ });
+}
+
#[test]
fn channel_activity_and_notification_status_update_separate_normalized_records() {
block_on(async {
diff --git a/crates/client/cache-core/tests/entity_resolver.rs b/crates/client/cache-core/tests/entity_resolver.rs
index fc2f5b96a1..e7058c4d09 100644
--- a/crates/client/cache-core/tests/entity_resolver.rs
+++ b/crates/client/cache-core/tests/entity_resolver.rs
@@ -1,6 +1,6 @@
//! Entity-from-argument resolver behavior against the real Soup schema.
-use cache_core::engine::{Engine, ReadResult};
+use cache_core::engine::{Engine, NetworkWrite, QueryRegistration, ReadResult};
use cache_core::entity_resolver::EntityResolver;
use cache_core::store::InMemoryStorage;
use cache_core::value::EntityKey;
@@ -400,6 +400,63 @@ fn resolver_overrides_stored_links_and_null() {
});
}
+#[test]
+fn network_write_registers_matching_synthetic_dependencies_without_a_read() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let variables = direct_variables(json!("thread-1"));
+ let resolvers = [resolver()];
+ engine
+ .write_query_with_registration(
+ Some(41),
+ Some(QueryRegistration {
+ op_id: 41,
+ entity_resolvers: &resolvers,
+ }),
+ NetworkWrite {
+ query: DIRECT_EMAIL_QUERY,
+ operation_name: Some("EmailThread"),
+ variables: &variables,
+ data: &json!({
+ "viewer": {
+ "id": "user-1",
+ "thread": {
+ "__typename": "GraphqlSoupEmailThread",
+ "id": "thread-1",
+ "emailName": "Before",
+ "ownerId": "user-1"
+ }
+ }
+ }),
+ identity: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let update_variables = object(json!({ "input": { "threadId": "thread-1" } }));
+ let write = engine
+ .write_query(
+ Some(2),
+ UPDATE_EMAIL_MUTATION,
+ Some("UpdateEmail"),
+ &update_variables,
+ &json!({
+ "markEmailThreadSeen": {
+ "__typename": "GraphqlSoupEmailThread",
+ "id": "thread-1",
+ "name": "After",
+ "ownerId": "user-1"
+ }
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(write.affected_ops, [41].into());
+ });
+}
+
#[test]
fn synthetic_target_dependencies_are_registered_on_hits_and_misses() {
block_on(async {
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index 59696d6564..8a9e631aef 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -2,7 +2,8 @@ use async_lock::Mutex;
use cache_core::codec::cache_database_name;
use cache_core::deps::OpId;
use cache_core::engine::{
- BeginOptimisticWrite, Engine, EngineError, InitialClaimOutcome, ReadResult,
+ BeginOptimisticWrite, Engine, EngineError, InitialClaimOutcome, NetworkWrite,
+ QueryRegistration, ReadResult,
};
use cache_core::entity_resolver::EntityResolver;
use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
@@ -115,6 +116,21 @@ fn recovery_outcome(reason: PhysicalResetReason) -> CacheOpenOutcome {
}
}
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct JsWriteContext {
+ origin_op_id: Option<String>,
+ registration: Option<JsQueryRegistration>,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct JsQueryRegistration {
+ op_id: String,
+ #[serde(default)]
+ entity_resolvers: Vec<EntityResolver>,
+}
+
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct JsWriteResult {
@@ -798,7 +814,7 @@ impl CacheEngine {
#[wasm_bindgen(js_name = writeQuery)]
pub fn write_query(
&self,
- origin_op_id: Option<String>,
+ context: JsValue,
query: String,
operation_name: Option<String>,
variables: JsValue,
@@ -810,18 +826,34 @@ impl CacheEngine {
future_to_promise(async move {
let mut state = state.lock().await;
state.ensure_callable()?;
+ let context: JsWriteContext =
+ serde_wasm_bindgen::from_value(context).map_err(err_js)?;
let vars = parse_variables(variables)?;
let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;
- let origin = origin_op_id.map(|name| ops.borrow_mut().intern(&name));
+ let origin = context
+ .origin_op_id
+ .map(|name| ops.borrow_mut().intern(&name));
+ let registration = context.registration.map(|registration| {
+ let op_id = ops.borrow_mut().intern(&registration.op_id);
+ (op_id, registration.entity_resolvers)
+ });
let result = state
.engine_mut()?
- .write_query(
+ .write_query_with_registration(
origin,
- &query,
- operation_name.as_deref(),
- &vars,
- &data,
- identity.as_deref(),
+ registration
+ .as_ref()
+ .map(|(op_id, entity_resolvers)| QueryRegistration {
+ op_id: *op_id,
+ entity_resolvers,
+ }),
+ NetworkWrite {
+ query: &query,
+ operation_name: operation_name.as_deref(),
+ variables: &vars,
+ data: &data,
+ identity: identity.as_deref(),
+ },
)
.await;
let result = state.engine_result(result)?;