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.

fix(cache): preserve notifications and batch resume refreshes (#8954)

Sean Ayed05f22ec648d
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 184ff3a6e5..7d76123074 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -225,12 +225,20 @@ the user's newest account for that app from the last fifteen minutes.
- Reject already-routed optimistic enqueues with missing replies as uncertain on
every owner departure; never forward them through network fallback, because
their durable queue entries may survive the old engine.
+- Dispatch live GraphQL notification callbacks before cache persistence so hidden
+ tabs can show browser alerts; keep cache-dependent channel reconciliation
+ behind ordered writes and never replay alerts when the cache resumes. Link
+ cache queue/apply spans to receipt and mark listener failures without stopping
+ the remaining callbacks.
- Drain browser cache engines when their last visible consumer hides, then park
without retiring clients; queue background work until a visible owner reopens
storage, retaining accepted mutation settlements even if their caller leaves.
Publish recovery reset outcomes before parking while retaining the read pause.
Bound foreground resume reads to one second without killing an owner, stealing
its lock, replaying writes, or treating intentional parking as a failure.
+- Coalesce broad browser cache-change hints across the coordinator's in-flight
+ backlog, not the engine's per-message queue; keep reset fences, mutation
+ settlements, and query-specific invalidations immediate.
- Retry still-current query reads once when engine replacement invalidates their
snapshot; do not strand urql's in-flight key or revive torn-down or superseded reads.
Keep network forwarding deduplicated and cache-only reads off the network.
diff --git a/apps/web/docs/graphql-cache-testing.md b/apps/web/docs/graphql-cache-testing.md
index 72bf10fe46..afd552ce78 100644
--- a/apps/web/docs/graphql-cache-testing.md
+++ b/apps/web/docs/graphql-cache-testing.md
@@ -20,6 +20,7 @@ flashes, stale subscribers, and notifications to unrelated fields.
| [Project adapters](../src/features/projects/projects.test.tsx) and [mentions](../src/lib/queries/agent-session/mentions.test.tsx) | Changing lookup IDs, retained live records, disabling reads, permission denial followed by cache hits, uncached mutation/reconnect refresh | Stable lookups do not disappear as siblings mount. Disabled/denied identities stay hidden. |
| [Rename settlement](../src/features/entity/queries/rename.test.tsx) and [initiative transport](../src/lib/service-clients/service-storage/initiative.test.ts) | Queued partial responses, background rejection, permanent GraphQL permission failures | Legacy projections do not retain failed optimistic names. Queued responses are acknowledgements. Domain error codes survive optimistic settlement. |
| [Project creation](../src/features/projects/queries/create-project.test.ts) and [task assignment](../src/features/projects/queries/project-sources.test.ts) | Viewer/host/reset changes during creation; setting, clearing, and creating a task with its Project property | Old operations cannot publish into a replacement cache. Task assignment uses the shared optimistic property path and preserves per-task failures. |
+| [Coordinator catch-up](../src/lib/graphql-cache/worker/coordinator-cache-changes.test.ts) and [parked browser writes](../src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts) | Separate queued commit messages; failed/no-op tails; resets; hydration; continuous traffic; owner/caller departure | One broad refresh for a drained catch-up batch, with all writes retained. Search scopes union without promoting hydration. Reset/dependency/settlement pushes stay immediate; old revisions never leak across epochs. A real worker/WASM backlog of five commits produces one visible-cache refresh and reports its batch size. |
| [Refresh ordering](../src/lib/queries/trailing-refetch.test.ts) | Concurrent invalidations, failed earlier reads, owner disposal | A change during a pending read gets a trailing read; disposed owners stop requesting work. |
The shared [Rust oracle](../../../crates/client/cache-core/tests/support/optimistic_model.rs)
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index 034515b365..99e017b5f0 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -234,6 +234,20 @@ invalidate reset data/leases even if the next owner only opens existing storage.
Reset completion accounting likewise follows accepted readiness, not whether
that epoch remains active; its read pause stays in force during the drain.
+Catch-up writes keep their individual transactions and replies, but the
+coordinator coalesces broad `cache-changed` and `cache-hydrated` hints across its
+accepted in-flight backlog. The engine's local queue is insufficient: separate
+MessagePort deliveries can make it look idle between queued commits. Each channel
+keeps its latest revision and the union of search buckets; an unscoped hint stays
+unscoped, and hydration never becomes an authoritative invalidation. Publish when
+the last outstanding commit sends its hint or the remaining replies drain,
+including failed/no-op tails. A batch also flushes after 64 completed requests so
+continuous traffic cannot starve subscribers. Single-request updates, reset fences,
+query dependency pushes, and mutation settlements remain immediate. Flush accepted
+hints on owner departure/failure and when the last waiting caller leaves; never
+carry them into another engine's revision space. `graphql_cache.change_batch`
+records how many hints each coalesced broadcast replaced, without payloads.
+
While parked or transitioning, `waiting` pauses read/init deadlines without
creating a second page-side request queue. Reads, writes, and teardown retain
coordinator admission order. A visible consumer starts a one-second read budget
@@ -254,6 +268,20 @@ second request for this retry, and cache-only/replacement-registration-only read
never gain a network fallback. The anonymous page-side `graphql_cache.read_retry`
span times the extra read without exporting query contents or identities.
+Live notification receipt must not wait for this storage pause. The
+`notificationReceiptExchange`, placed between the normalized-cache exchange and
+the subscription transport, publishes notification callbacks before persistence
+in both cached and uncached clients. The normalized-cache exchange still applies
+subscription effects serially before cache-dependent channel reconciliation.
+Resuming storage never republishes the notification callback. `notification.receive`
+spans record the notification ID, patch type, and page visibility without content;
+listener failures mark this span while remaining listeners still run. Result-local
+weak context links `graphql.subscription.cache_queue` (the wait behind earlier
+subscription effects) and `graphql.subscription.cache_apply` (cache application,
+including parked-storage waits) to that receipt, even after its immediate span
+ends. Cache failures mark the application phase without recording payloads or
+replaying delivery. This context never enters GraphQL extensions or the wire.
+
Already-sent HTTP mutations may finish while parked. Their local commit, rollback,
or defer requests wait for storage and retain their position ahead of later
claims. Accepted settlement requests survive their caller disconnecting; their
@@ -268,7 +296,9 @@ failure/navigation recovery applies. Owner telemetry adds `park-started`, `parke
`unpark-started`, and `unpark-completed` alongside the `visibility-handoff-*` events.
The backend-free `parking.browser.e2e.ts` exercises physical release, retained
clients/storage, a query admitted while parked completing across replacement
-without network fallback, and a response settled after parking.
+without network fallback, a response settled after parking, and notification
+receipt while parked without duplicate delivery when persistence resumes, and
+five queued catch-up commits producing one visible-cache refresh on return.
Every departure rejects already-routed optimistic enqueues whose replies were
lost as `admitted-enqueue-uncertain`, including requests from surviving tabs.
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 cebccf3af9..4f2e2002a9 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
@@ -36,7 +36,7 @@
*/
import { fireAndForget } from '@core/util/fireAndForget';
-import { Telemetry } from '@macro-inc/observability';
+import { type Span, Telemetry } from '@macro-inc/observability';
import {
type Client,
CombinedError,
@@ -110,6 +110,7 @@ import {
withOptimisticMutationDisposition,
} from './optimistic';
import { queryShape } from './query-shape';
+import { runSubscriptionCacheEffects } from './subscription-cache-trace';
/** Server writes acknowledged since this query left for the network. */
const QUERY_MUTATION_VERSION_CONTEXT_KEY =
@@ -1234,7 +1235,8 @@ export function normalizedCacheExchange(
async function applyOperationCacheEffects(
op: Operation,
effects: CacheEffect[],
- isCurrent: () => boolean = () => true
+ isCurrent: () => boolean = () => true,
+ span?: Span
): Promise<boolean> {
let applied = true;
for (const effect of effects) {
@@ -1252,6 +1254,7 @@ export function normalizedCacheExchange(
}
} catch (error) {
applied = false;
+ span?.error('Subscription cache effect failed');
// One failed cache effect must neither skip later effects nor
// prevent delivery of the original operation result.
options.onCacheError?.(error, op);
@@ -1412,14 +1415,18 @@ export function normalizedCacheExchange(
const previousEffects =
subscriptionEffectChains.get(op.key) ?? Promise.resolve(true);
const generation = subscriptionGenerations.get(op.key);
- const effects = previousEffects.then(() =>
- applyOperationCacheEffects(
- op,
- operationCacheEffects(result.data),
- () =>
- generation !== undefined &&
- subscriptionGenerations.get(op.key) === generation
- )
+ const effects = runSubscriptionCacheEffects(
+ result,
+ previousEffects,
+ (span) =>
+ applyOperationCacheEffects(
+ op,
+ operationCacheEffects(result.data),
+ () =>
+ generation !== undefined &&
+ subscriptionGenerations.get(op.key) === generation,
+ span
+ )
);
subscriptionEffectChains.set(op.key, effects);
try {
diff --git a/apps/web/src/lib/graphql-cache/exchange/subscription-cache-trace.ts b/apps/web/src/lib/graphql-cache/exchange/subscription-cache-trace.ts
new file mode 100644
index 0000000000..71fd958485
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/subscription-cache-trace.ts
@@ -0,0 +1,48 @@
+import type { Span } from '@macro-inc/observability';
+import type { OperationResult } from '@urql/core';
+
+// Result-local context never enters GraphQL extensions, storage, or the wire.
+// Weak keys also retire receipts on uncached clients, which do not consume it.
+const RECEIPT_SPANS = new WeakMap<OperationResult, Span>();
+
+export function setSubscriptionCacheTrace(result: OperationResult, span: Span) {
+ RECEIPT_SPANS.set(result, span);
+}
+
+/** Keep cache phases linked to receipt without extending or delaying delivery. */
+export async function runSubscriptionCacheEffects(
+ result: OperationResult,
+ previous: Promise<boolean>,
+ apply: (span?: Span) => Promise<boolean>
+): Promise<boolean> {
+ const receipt = RECEIPT_SPANS.get(result);
+ RECEIPT_SPANS.delete(result);
+ if (!receipt) {
+ await previous;
+ return await apply();
+ }
+
+ const queued = receipt.span('graphql.subscription.cache_queue');
+ try {
+ await previous;
+ } catch (error) {
+ queued.error('Subscription cache queue failed');
+ throw error;
+ } finally {
+ queued.end();
+ }
+
+ return await receipt.span(
+ 'graphql.subscription.cache_apply',
+ async (span) => {
+ try {
+ const applied = await apply(span);
+ span.setAttr('cache.effects_applied', applied);
+ return applied;
+ } catch (error) {
+ span.error('Subscription cache application failed');
+ throw error;
+ }
+ }
+ );
+}
diff --git a/apps/web/src/lib/graphql-cache/telemetry.ts b/apps/web/src/lib/graphql-cache/telemetry.ts
index 7d17b5c6ca..abf310ba0c 100644
--- a/apps/web/src/lib/graphql-cache/telemetry.ts
+++ b/apps/web/src/lib/graphql-cache/telemetry.ts
@@ -22,6 +22,7 @@ export const CACHE_TELEMETRY_EVENT_NAMES = [
'graphql_cache.storage_reset_required',
'graphql_cache.logical_reset',
'graphql_cache.revision_advance',
+ 'graphql_cache.change_batch',
'graphql_cache.reset_wipe',
'graphql_cache.origin_storage_pressure',
'graphql_cache.linear_memory',
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
index 196be7f4a7..5cdad42e76 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/parking-harness.ts
@@ -1,9 +1,17 @@
+import { subscribeToVisibleCacheChanges } from '@queries/subscribe-to-visible-cache-changes';
+import {
+ NotificationUpdatesDocument,
+ type NotificationUpdatesSubscription,
+} from '@service-storage/graphql/generated/graphql';
+import { notificationReceiptExchange } from '@service-storage/graphql-notification-receipt';
import {
createClient,
fetchExchange,
gql,
stringifyDocument,
+ subscriptionExchange,
} from '@urql/core';
+import { createRoot } from 'solid-js';
import { normalizedCacheExchange } from '../../exchange/normalized-cache-exchange';
import type { CacheHost } from '../../host/types';
import { createWorkerCacheHost } from '../../host/worker-host';
@@ -52,13 +60,36 @@ const settling = Promise.withResolvers<void>();
let result: Promise<unknown> | undefined;
let readResult: Promise<{ data: unknown; error: boolean }> | undefined;
let readApiRequests = 0;
+const receivedNotifications: string[] = [];
+const persistedNotifications: string[] = [];
+const notificationPersisted = Promise.withResolvers<void>();
+let emitNotification: (() => void) | undefined;
+let stopNotifications: (() => void) | undefined;
+const catchupQuery = 'query Catchup { user { id } }';
+const catchupRefreshed = Promise.withResolvers<void>();
+const catchupRevisions: string[] = [];
+const catchupBatches: number[] = [];
+const catchupBatchReported = Promise.withResolvers<void>();
+let catchupRefreshes = 0;
+let catchupRead: unknown;
+let catchupWrites: Promise<unknown> | undefined;
+let stopCatchup: (() => void) | undefined;
function requireHost(): CacheHost {
if (!host) throw new Error('cache not started');
return host;
}
const api = {
async start(seed = false) {
- host ??= createWorkerCacheHost({ scope });
+ host ??= createWorkerCacheHost({
+ scope,
+ telemetrySink: {
+ emit(event) {
+ if (event.name !== 'graphql_cache.change_batch') return;
+ catchupBatches.push(event.count ?? 0);
+ catchupBatchReported.resolve();
+ },
+ },
+ });
if (seed) {
await host.writeQuery({ query, data });
seedUuid = crypto.randomUUID();
@@ -95,6 +126,119 @@ const api = {
visibility: document.visibilityState,
};
},
+ queueCatchup() {
+ const current = requireHost();
+ stopCatchup = createRoot((dispose) => {
+ const unsubscribe = current.onCacheChanged((revision) => {
+ catchupRevisions.push(revision);
+ });
+ const stopRefresh = subscribeToVisibleCacheChanges(current, async () => {
+ catchupRefreshes += 1;
+ catchupRead = await current.readQuery({ query: catchupQuery });
+ catchupRefreshed.resolve();
+ });
+ return () => {
+ unsubscribe();
+ stopRefresh();
+ dispose();
+ };
+ });
+ catchupWrites = Promise.all([
+ ...[
+ 'SoupUpdates',
+ 'ChannelUnreadPresence',
+ 'CalendarChanges',
+ 'Calendars',
+ ].map((name, index) =>
+ current.writeQuery({
+ query: `query ${name} { user { id } }`,
+ data: { user: { id: `catchup-${index}` } },
+ })
+ ),
+ current.calendarCommit({
+ coverage: [{ kind: 'timed', start: 0, end: 1 }],
+ freshness: 'fresh',
+ }),
+ ]);
+ },
+ async catchupDone() {
+ await catchupWrites;
+ await catchupRefreshed.promise;
+ await catchupBatchReported.promise;
+ },
+ catchupSnapshot: () => ({
+ revisions: [...catchupRevisions],
+ batches: [...catchupBatches],
+ refreshes: catchupRefreshes,
+ read: catchupRead,
+ }),
+ async startNotifications() {
+ const attached = Promise.withResolvers<void>();
+ const client = createClient({
+ url: 'https://parking.invalid/graphql',
+ exchanges: [
+ normalizedCacheExchange(requireHost()),
+ notificationReceiptExchange((patch) => {
+ if (patch.__typename === 'GraphqlNewNotification')
+ receivedNotifications.push(patch.notification.id);
+ }),
+ subscriptionExchange({
+ forwardSubscription: () => ({
+ subscribe(sink) {
+ emitNotification = () => {
+ const data: NotificationUpdatesSubscription = {
+ notificationUpdates: {
+ __typename: 'GraphqlNewNotification',
+ notification: {
+ __typename: 'GraphqlNotification',
+ id: 'synthetic-notification',
+ entityId: 'synthetic-reminder',
+ entityType: 'REMINDER',
+ eventType: 'reminder',
+ state: 'UNSEEN',
+ sent: true,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ viewedAt: null,
+ senderId: null,
+ metadata: {
+ __typename: 'GraphqlReminderMetadata',
+ reminderReminderId: 'synthetic-reminder',
+ reminderDescription: 'Review the document',
+ reminderScheduledFor: null,
+ },
+ },
+ },
+ };
+ sink.next({ data });
+ };
+ attached.resolve();
+ return { unsubscribe() {} };
+ },
+ }),
+ }),
+ ],
+ });
+ const subscription = client
+ .subscription(NotificationUpdatesDocument, {})
+ .subscribe((result) => {
+ const patch = result.data?.notificationUpdates;
+ if (patch?.__typename !== 'GraphqlNewNotification') return;
+ persistedNotifications.push(patch.notification.id);
+ notificationPersisted.resolve();
+ });
+ stopNotifications = () => subscription.unsubscribe();
+ await attached.promise;
+ },
+ emitNotification() {
+ if (!emitNotification) throw new Error('notifications not started');
+ emitNotification();
+ },
+ notifications: () => ({
+ received: [...receivedNotifications],
+ persisted: [...persistedNotifications],
+ }),
+ notificationPersisted: () => notificationPersisted.promise,
parked: () => parked.promise,
async locks() {
return (await navigator.locks.query()).held?.filter((lock) =>
@@ -195,6 +339,8 @@ const api = {
);
},
dispose() {
+ stopCatchup?.();
+ stopNotifications?.();
host?.dispose();
},
};
diff --git a/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts b/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
index 0319f6f5d4..3433aaa9c1 100644
--- a/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
+++ b/apps/web/src/lib/graphql-cache/worker/browser-test/parking.browser.e2e.ts
@@ -82,6 +82,88 @@ test('delivers a query admitted while parked across replacement without API fall
expect(after.queue?.map((item) => item.uuid)).toEqual([before.seedUuid]);
});
+test('coalesces parked catch-up commits into one visible-cache refresh', async ({
+ page,
+}, info) => {
+ await page.clock.install();
+ await page.goto(
+ `${path(info.project.name)}?scope=cache-parking-${crypto.randomUUID()}`
+ );
+ await page.evaluate(() => window.cacheParkingHarness.start());
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await page.evaluate(() => window.cacheParkingHarness.parked());
+ await page.evaluate(() => window.cacheParkingHarness.queueCatchup());
+ expect(
+ await page.evaluate(() => window.cacheParkingHarness.catchupSnapshot())
+ ).toMatchObject({ revisions: [], refreshes: 0 });
+
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'visible',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await page.evaluate(() => window.cacheParkingHarness.catchupDone());
+ // Any dirty trailing refresh would run here; no wall-clock sleep is needed.
+ await page.clock.runFor(1_000);
+ const caughtUp = await page.evaluate(() =>
+ window.cacheParkingHarness.catchupSnapshot()
+ );
+ expect(caughtUp.revisions).toHaveLength(1);
+ expect(caughtUp.batches).toEqual([5]);
+ expect(caughtUp.refreshes).toBe(1);
+ expect(caughtUp.read).toMatchObject({
+ kind: 'hit',
+ data: { user: { id: 'catchup-3' } },
+ });
+ await page.evaluate(() => window.cacheParkingHarness.dispose());
+});
+
+test('delivers a background notification before cache persistence without replaying it on resume', async ({
+ page,
+}, info) => {
+ await page.goto(
+ `${path(info.project.name)}?scope=cache-parking-${crypto.randomUUID()}`
+ );
+ await page.evaluate(() => window.cacheParkingHarness.start());
+ await page.evaluate(() => window.cacheParkingHarness.startNotifications());
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'hidden',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await page.evaluate(() => window.cacheParkingHarness.parked());
+ await page.evaluate(() => window.cacheParkingHarness.emitNotification());
+ expect(
+ await page.evaluate(() => window.cacheParkingHarness.notifications())
+ ).toEqual({ received: ['synthetic-notification'], persisted: [] });
+
+ await page.evaluate(() => {
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'visible',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+ });
+ await page.evaluate(() => window.cacheParkingHarness.notificationPersisted());
+ expect(
+ await page.evaluate(() => window.cacheParkingHarness.notifications())
+ ).toEqual({
+ received: ['synthetic-notification'],
+ persisted: ['synthetic-notification'],
+ });
+ await page.evaluate(() => window.cacheParkingHarness.dispose());
+});
+
test('settles a response received while parked before a competing expired-lease claim', async ({
context,
page,
diff --git a/apps/web/src/lib/graphql-cache/worker/cache-change-batch.ts b/apps/web/src/lib/graphql-cache/worker/cache-change-batch.ts
new file mode 100644
index 0000000000..0f7dc056b1
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/worker/cache-change-batch.ts
@@ -0,0 +1,67 @@
+import type { CachePush } from '../protocol';
+
+type CacheChangePush = Extract<
+ CachePush,
+ { kind: 'cache-changed' | 'cache-hydrated' }
+>;
+
+export type CoalescedCacheChange = { push: CacheChangePush; count: number };
+
+// A continuously busy coordinator must still let subscribers catch up. Bound
+// completed requests instead of relying on idle time or a transaction timer.
+const MAX_REQUESTS_PER_BATCH = 64;
+
+/** Coalesces broad refresh hints, never write replies or dependency/settlement pushes. */
+export class CacheChangeBatch {
+ private readonly pending = new Map<
+ CacheChangePush['kind'],
+ CoalescedCacheChange
+ >();
+ private requests = 0;
+
+ add(push: CacheChangePush): void {
+ if (push.kind === 'cache-changed' && push.reset) {
+ // A generation fence supersedes every earlier refresh hint.
+ this.pending.clear();
+ this.requests = 0;
+ }
+ const previous = this.pending.get(push.kind);
+ if (previous) {
+ const buckets =
+ previous.push.searchChangedBuckets !== undefined &&
+ push.searchChangedBuckets !== undefined
+ ? [
+ ...new Set([
+ ...previous.push.searchChangedBuckets,
+ ...push.searchChangedBuckets,
+ ]),
+ ]
+ : undefined;
+ // Missing scope means all buckets, and dominates any narrower hint.
+ push = {
+ kind: push.kind,
+ revision: push.revision,
+ ...(buckets === undefined ? {} : { searchChangedBuckets: buckets }),
+ };
+ }
+ // Emit the channels in revision order without promoting hydration to an
+ // authoritative foreground invalidation.
+ this.pending.delete(push.kind);
+ this.pending.set(push.kind, { push, count: (previous?.count ?? 0) + 1 });
+ }
+
+ requestCompleted(queueEmpty: boolean): CoalescedCacheChange[] {
+ if (this.pending.size === 0) return [];
+ this.requests += 1;
+ return queueEmpty || this.requests >= MAX_REQUESTS_PER_BATCH
+ ? this.flush()
+ : [];
+ }
+
+ flush(): CoalescedCacheChange[] {
+ const changes = [...this.pending.values()];
+ this.pending.clear();
+ this.requests = 0;
+ return changes;
+ }
+}
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-cache-changes.test.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-cache-changes.test.ts
new file mode 100644
index 0000000000..cf41440dff
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-cache-changes.test.ts
@@ -0,0 +1,357 @@
+import { expect, it } from 'vitest';
+import {
+ type CachePush,
+ type CacheRequest,
+ parseCacheRevision,
+} from '../protocol';
+import { CoordinatorCore } from './coordinator-core';
+import type { EngineOpenOutcome } from './coordinator-protocol';
+
+function ready(
+ core: CoordinatorCore,
+ tabId: string,
+ ownerEpoch: number,
+ openOutcome: EngineOpenOutcome = 'opened-existing'
+) {
+ core.beginOwnerLockWait(tabId, ownerEpoch);
+ core.beginEngineOpen(tabId, ownerEpoch);
+ return core.engineReady({
+ tabId,
+ ownerEpoch,
+ ownerLockName: 'lock',
+ expectedOwnerLockName: 'lock',
+ ownerLockHeld: true,
+ databaseActionProof: openOutcome.startsWith('reset-')
+ ? 'wiped-before-open'
+ : 'opened-existing',
+ openOutcome,
+ });
+}
+
+function resume(requests: CacheRequest[]) {
+ const core = new CoordinatorCore('synthetic');
+ core.registerTab('a');
+ ready(core, 'a', 1);
+ core.setTabVisibility('a', false);
+ core.engineDrained('a', 1);
+ expect(core.state.kind).toBe('parked');
+ for (const request of requests)
+ expect(core.request('a', request)).toEqual([]);
+ core.setTabVisibility('a', true);
+ const routes = ready(core, 'a', 2).filter(
+ (action) => action.kind === 'route-request'
+ );
+ expect(routes).toHaveLength(requests.length);
+ return {
+ core,
+ routes,
+ push: (push: CachePush) => core.enginePush(2, push),
+ reply: (index: number, ok = true) => {
+ const route = routes[index];
+ if (!route) throw new Error('missing route');
+ return core.engineResponse(
+ 2,
+ route.routeId,
+ ok
+ ? { id: route.routeId, ok: true, result: null }
+ : { id: route.routeId, ok: false, error: 'write rejected' }
+ );
+ },
+ };
+}
+
+it('announces the full resume backlog once, even when the engine executes each port message separately', () => {
+ const names = [
+ 'SoupUpdates',
+ 'ChannelUnreadPresence',
+ 'CalendarChanges',
+ 'Calendars',
+ ];
+ const { push, reply } = resume([
+ ...names.map(
+ (operationName, index): CacheRequest => ({
+ id: index + 1,
+ kind: 'write',
+ query: `query ${operationName} { value }`,
+ data: { value: index },
+ })
+ ),
+ { id: 5, kind: 'calendar-commit', commit: { freshness: 'fresh' } },
+ ]);
+ for (let index = 0; index < names.length; index += 1) {
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision(String(index + 1)),
+ searchChangedBuckets: index === 0 ? ['note'] : ['calendar'],
+ })
+ ).toEqual([]);
+ expect(reply(index)).toEqual([
+ {
+ kind: 'deliver-response',
+ tabId: 'a',
+ response: { id: index + 1, ok: true, result: null },
+ },
+ ]);
+ }
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('5'),
+ searchChangedBuckets: [],
+ })
+ ).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: {
+ kind: 'cache-changed',
+ revision: '5',
+ searchChangedBuckets: ['note', 'calendar'],
+ },
+ coalescedCount: 5,
+ },
+ ]);
+ expect(reply(4)).toHaveLength(1);
+});
+
+it.each([true, false])(
+ 'flushes committed hints when the last request has no push (success: %s)',
+ (ok) => {
+ const { push, reply } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ { id: 2, kind: 'read', query: '{ value }' },
+ ]);
+ expect(
+ push({ kind: 'cache-changed', revision: parseCacheRevision('1') })
+ ).toEqual([]);
+ reply(0);
+ expect(reply(1, ok)).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '1' },
+ },
+ {
+ kind: 'deliver-response',
+ tabId: 'a',
+ response: ok
+ ? { id: 2, ok: true, result: null }
+ : { id: 2, ok: false, error: 'write rejected' },
+ },
+ ]);
+ }
+);
+
+it('never delays dependency pushes or mutation settlements behind broad refreshes', () => {
+ const { push } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ { id: 2, kind: 'read', query: '{ value }' },
+ ]);
+ expect(
+ push({ kind: 'cache-changed', revision: parseCacheRevision('1') })
+ ).toEqual([]);
+ const affected: CachePush = {
+ kind: 'ops-affected',
+ opIds: ['a:1'],
+ keys: ['Record:1'],
+ };
+ const settled: CachePush = {
+ kind: 'mutation-settled',
+ settlement: {
+ transactionId: '1',
+ mutationUuid: 'synthetic',
+ status: 'committed',
+ },
+ };
+ expect(push(affected)).toEqual([{ kind: 'broadcast-push', push: affected }]);
+ expect(push(settled)).toEqual([{ kind: 'broadcast-push', push: settled }]);
+});
+
+it('fences a reset immediately and never replays pre-reset revisions or scopes', () => {
+ const { push, reply } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ { id: 2, kind: 'clear' },
+ { id: 3, kind: 'write', query: '{ value }', data: { value: 2 } },
+ ]);
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('7'),
+ searchChangedBuckets: ['note'],
+ });
+ reply(0);
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('0'),
+ reset: true,
+ })
+ ).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '0', reset: true },
+ },
+ ]);
+ reply(1);
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('1'),
+ searchChangedBuckets: [],
+ })
+ ).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '1', searchChangedBuckets: [] },
+ },
+ ]);
+ expect(reply(2)).toHaveLength(1);
+});
+
+it.each([
+ { buckets: undefined, expected: undefined },
+ { buckets: [], expected: ['note'] },
+ { buckets: ['calendar', 'note'], expected: ['note', 'calendar'] },
+])(
+ 'unions authoritative scopes without promoting hydration: $buckets',
+ ({ buckets, expected }) => {
+ const { push, reply } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ { id: 2, kind: 'hydrate', query: '{ value }', data: { value: 2 } },
+ { id: 3, kind: 'write', query: '{ value }', data: { value: 3 } },
+ ]);
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('1'),
+ searchChangedBuckets: ['note'],
+ });
+ reply(0);
+ push({
+ kind: 'cache-hydrated',
+ revision: parseCacheRevision('2'),
+ searchChangedBuckets: ['task'],
+ });
+ reply(1);
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('3'),
+ ...(buckets === undefined ? {} : { searchChangedBuckets: buckets }),
+ })
+ ).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: {
+ kind: 'cache-hydrated',
+ revision: '2',
+ searchChangedBuckets: ['task'],
+ },
+ },
+ {
+ kind: 'broadcast-push',
+ push: {
+ kind: 'cache-changed',
+ revision: '3',
+ ...(expected === undefined ? {} : { searchChangedBuckets: expected }),
+ },
+ coalescedCount: 2,
+ },
+ ]);
+ }
+);
+
+it('bounds refresh suppression while more requests remain in flight', () => {
+ const { push, reply } = resume(
+ Array.from({ length: 65 }, (_, index) => ({
+ id: index + 1,
+ kind: 'write',
+ query: '{ value }',
+ data: { value: index },
+ }))
+ );
+ for (let index = 0; index < 64; index += 1) {
+ expect(
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision(String(index + 1)),
+ })
+ ).toEqual([]);
+ const actions = reply(index);
+ if (index < 63) expect(actions).toHaveLength(1);
+ else
+ expect(actions[0]).toEqual({
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '64' },
+ coalescedCount: 64,
+ });
+ }
+ expect(
+ push({ kind: 'cache-changed', revision: parseCacheRevision('65') })
+ ).toEqual([
+ { kind: 'broadcast-push', push: { kind: 'cache-changed', revision: '65' } },
+ ]);
+});
+
+it('flushes accepted changes on owner loss and keeps the new epoch separate', () => {
+ const { core, push } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ { id: 2, kind: 'read', query: '{ value }' },
+ ]);
+ push({
+ kind: 'cache-changed',
+ revision: parseCacheRevision('7'),
+ searchChangedBuckets: ['note'],
+ });
+ expect(core.ownerLost('a', 2, 'synthetic loss')[0]).toEqual({
+ kind: 'broadcast-push',
+ push: {
+ kind: 'cache-changed',
+ revision: '7',
+ searchChangedBuckets: ['note'],
+ },
+ });
+ core.resumeAfterLoss();
+ ready(core, 'a', 3, 'reset-storage-uncertain');
+ expect(
+ core.enginePush(2, {
+ kind: 'cache-changed',
+ revision: parseCacheRevision('8'),
+ })[0]
+ ).toMatchObject({ kind: 'drop-stale-engine-message' });
+ expect(
+ core.enginePush(3, {
+ kind: 'cache-changed',
+ revision: parseCacheRevision('1'),
+ searchChangedBuckets: [],
+ })
+ ).toEqual([
+ {
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '1', searchChangedBuckets: [] },
+ },
+ ]);
+});
+
+it('flushes when the last waiting caller leaves without waiting for its discarded reply', () => {
+ const { core, push } = resume([]);
+ core.registerTab('b');
+ core.request('b', { id: 1, kind: 'read', query: '{ value }' });
+ core.request('b', { id: 2, kind: 'read', query: '{ value }' });
+ expect(
+ push({ kind: 'cache-changed', revision: parseCacheRevision('1') })
+ ).toEqual([]);
+ expect(core.tabLost('b')).toContainEqual({
+ kind: 'broadcast-push',
+ push: { kind: 'cache-changed', revision: '1' },
+ });
+ expect(core.snapshot().inFlightRequestCount).toBe(0);
+});
+
+it('keeps ordinary single-request updates immediate', () => {
+ const { push } = resume([
+ { id: 1, kind: 'write', query: '{ value }', data: { value: 1 } },
+ ]);
+ expect(
+ push({ kind: 'cache-changed', revision: parseCacheRevision('1') })
+ ).toEqual([
+ { kind: 'broadcast-push', push: { kind: 'cache-changed', revision: '1' } },
+ ]);
+});
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-core.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-core.ts
index 37c2903263..07b0d2dd46 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-core.ts
@@ -7,6 +7,10 @@ import {
OWNER_EPOCH_LOST_ERROR_CODE,
OWNER_LOCK_UNAVAILABLE_ERROR_CODE,
} from '../protocol';
+import {
+ CacheChangeBatch,
+ type CoalescedCacheChange,
+} from './cache-change-batch';
import type {
DatabaseAction,
DatabaseActionProof,
@@ -76,7 +80,7 @@ export type CoordinatorAction =
request: CacheRequest;
}
| { kind: 'deliver-response'; tabId: string; response: CacheResponse }
- | { kind: 'broadcast-push'; push: CachePush }
+ | { kind: 'broadcast-push'; push: CachePush; coalescedCount?: number }
| {
kind: 'reject-request';
tabId: string;
@@ -164,6 +168,7 @@ export class CoordinatorCore {
private supersededReason: string | undefined;
private readonly queuedRequests: QueuedRequest[] = [];
private readonly inFlight = new Map<RouteId, InFlightRequest>();
+ private readonly cacheChanges = new CacheChangeBatch();
private currentEpoch = 0;
private nextRouteId = 1;
private staleMessageDrops = 0;
@@ -439,21 +444,46 @@ export class CoordinatorCore {
}
this.inFlight.delete(routeId);
- if (!this.tabs.includes(request.tabId)) return [];
- return [
- {
+ const actions = this.broadcastCacheChanges(
+ this.cacheChanges.requestCompleted(this.inFlight.size === 0)
+ );
+ if (this.tabs.includes(request.tabId)) {
+ actions.push({
kind: 'deliver-response',
tabId: request.tabId,
response: { ...response, id: request.request.id },
- },
- ];
+ });
+ }
+ return actions;
}
enginePush(ownerEpoch: OwnerEpoch, push: CachePush): CoordinatorAction[] {
if (!this.acceptsEngineMessages(ownerEpoch)) {
return [this.dropStale(ownerEpoch, undefined, 'stale-epoch')];
}
- return [{ kind: 'broadcast-push', push }];
+ if (push.kind !== 'cache-changed' && push.kind !== 'cache-hydrated') {
+ return [{ kind: 'broadcast-push', push }];
+ }
+ // The engine's local queue can look empty between MessagePort deliveries.
+ // Only the coordinator knows how much accepted work remains in transit.
+ this.cacheChanges.add(push);
+ if (
+ this.inFlight.size <= 1 ||
+ (push.kind === 'cache-changed' && push.reset)
+ ) {
+ return this.broadcastCacheChanges(this.cacheChanges.flush());
+ }
+ return [];
+ }
+
+ private broadcastCacheChanges(
+ changes: CoalescedCacheChange[]
+ ): CoordinatorAction[] {
+ return changes.map(({ push, count }) => ({
+ kind: 'broadcast-push',
+ push,
+ ...(count > 1 ? { coalescedCount: count } : {}),
+ }));
}
beginGracefulDeparture(
@@ -540,11 +570,14 @@ export class CoordinatorCore {
}
const reason = SUPERSEDED_REASON;
this.supersededReason = reason;
- const actions: CoordinatorAction[] = this.queuedRequests
- .splice(0)
- .map(({ tabId, request }) =>
- this.rejectUnavailable(tabId, request.id, reason)
- );
+ const actions: CoordinatorAction[] = [
+ ...this.broadcastCacheChanges(this.cacheChanges.flush()),
+ ...this.queuedRequests
+ .splice(0)
+ .map(({ tabId, request }) =>
+ this.rejectUnavailable(tabId, request.id, reason)
+ ),
+ ];
for (const tabId of this.tabs) this.unavailableTabs.set(tabId, reason);
actions.push({ kind: 'broadcast-cache-superseded', reason });
this.assertInvariants();
@@ -567,6 +600,7 @@ export class CoordinatorCore {
};
this.assertInvariants();
return [
+ ...this.broadcastCacheChanges(this.cacheChanges.flush()),
{
kind: 'terminal-failure',
error: reason,
@@ -635,6 +669,9 @@ export class CoordinatorCore {
}
this.removeTabRecord(tabId);
this.retiringTabs.delete(tabId);
+ if (this.inFlight.size === 0) {
+ actions.push(...this.broadcastCacheChanges(this.cacheChanges.flush()));
+ }
this.assertInvariants();
return actions;
}
@@ -721,7 +758,8 @@ export class CoordinatorCore {
error: string,
errorCode?: CacheResponseErrorCode
): CoordinatorAction[] {
- const actions: CoordinatorAction[] = [];
+ // Never carry a committed hint into another engine's revision space.
+ const actions = this.broadcastCacheChanges(this.cacheChanges.flush());
for (const [routeId, request] of this.inFlight) {
if (request.ownerEpoch !== ownerEpoch) continue;
this.inFlight.delete(routeId);
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
index 69bd02bd63..68b9964b77 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-router.ts
@@ -925,6 +925,14 @@ export class CoordinatorRouter {
this.postCacheResponse(action.tabId, action.response);
break;
case 'broadcast-push':
+ if (action.coalescedCount !== undefined) {
+ this.telemetry.record({
+ name: 'graphql_cache.change_batch',
+ operationCategory: 'invalidation',
+ outcome: 'success',
+ count: action.coalescedCount,
+ });
+ }
this.broadcast(
envelope<CoordinatorToTabEnvelope>({
kind: 'cache-message',
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.test.ts
new file mode 100644
index 0000000000..58a82aeba7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.test.ts
@@ -0,0 +1,306 @@
+import { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';
+import { createNoopCacheHost } from '@graphql-cache/host/noop-host';
+import type { CacheHost } from '@graphql-cache/host/types';
+import { type Span, Telemetry } from '@macro-inc/observability';
+import {
+ createClient,
+ type Exchange,
+ type OperationResult,
+ subscriptionExchange,
+} from '@urql/core';
+import { afterEach, expect, it, vi } from 'vitest';
+import {
+ NotificationUpdatesDocument,
+ type NotificationUpdatesSubscription,
+} from './graphql/generated/graphql';
+import { notificationReceiptExchange } from './graphql-notification-receipt';
+import type { GraphqlNotificationPatch } from './graphql-soup-websocket';
+
+const NEW_NOTIFICATION: GraphqlNotificationPatch = {
+ __typename: 'GraphqlNewNotification',
+ notification: {
+ __typename: 'GraphqlNotification',
+ id: 'notification-1',
+ entityId: 'reminder-1',
+ entityType: 'REMINDER',
+ eventType: 'reminder',
+ sent: true,
+ state: 'UNSEEN',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ viewedAt: null,
+ senderId: null,
+ metadata: {
+ __typename: 'GraphqlReminderMetadata',
+ reminderReminderId: 'reminder-1',
+ reminderDescription: 'Review the document',
+ reminderScheduledFor: null,
+ },
+ },
+};
+const DELETION: GraphqlNotificationPatch = {
+ __typename: 'GraphqlCacheDeletion',
+ graphqlTypeName: 'GraphqlNotification',
+ entityId: 'notification-1',
+};
+
+class RecordedSpan implements Span {
+ readonly children: RecordedSpan[] = [];
+ readonly attributes: Record<string, unknown> = {};
+ readonly errors: unknown[] = [];
+ ends = 0;
+
+ constructor(readonly name: string) {}
+ span(name: string): Span;
+ span<T>(name: string, operation: (span: Span) => Promise<T>): Promise<T>;
+ span<T>(
+ name: string,
+ operation?: (span: Span) => Promise<T>
+ ): Span | Promise<T> {
+ const child = new RecordedSpan(name);
+ this.children.push(child);
+ if (!operation) return child;
+ return child.run(async () => {
+ try {
+ return await operation(child);
+ } finally {
+ child.end();
+ }
+ });
+ }
+ run<T>(operation: () => T): T {
+ return operation();
+ }
+ setAttr(name: string, value: unknown) {
+ this.attributes[name] = value;
+ }
+ event() {}
+ error(error: unknown) {
+ this.errors.push(error);
+ }
+ traceparent() {
+ return undefined;
+ }
+ injectTraceHeaders() {}
+ end() {
+ this.ends += 1;
+ }
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+});
+
+function subscribe(
+ exchanges: Exchange[],
+ onResult: (result: OperationResult<NotificationUpdatesSubscription>) => void
+) {
+ let receive: (result: { data: NotificationUpdatesSubscription }) => void =
+ () => {
+ throw new Error('subscription is not attached');
+ };
+ const attached = Promise.withResolvers<void>();
+ const unsubscribe = vi.fn();
+ const client = createClient({
+ url: 'https://notification.test/graphql',
+ exchanges: [
+ ...exchanges,
+ subscriptionExchange({
+ forwardSubscription: () => ({
+ subscribe(sink) {
+ receive = (result) => sink.next(result);
+ attached.resolve();
+ return { unsubscribe };
+ },
+ }),
+ }),
+ ],
+ });
+ const subscription = client
+ .subscription(NotificationUpdatesDocument, {})
+ .subscribe(onResult);
+ return {
+ attached: attached.promise,
+ emit: (patch: GraphqlNotificationPatch) =>
+ receive({ data: { notificationUpdates: patch } }),
+ dispose: () => subscription.unsubscribe(),
+ unsubscribe,
+ };
+}
+
+it('delivers hidden-tab events before parked writes, preserving cache order without replaying alerts', async () => {
+ vi.useFakeTimers();
+ vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden');
+ const first = new RecordedSpan('first receipt');
+ const second = new RecordedSpan('second receipt');
+ vi.spyOn(Telemetry, 'span')
+ .mockReturnValueOnce(first)
+ .mockReturnValueOnce(second);
+ const resume = Promise.withResolvers<void>();
+ const writeStarted = Promise.withResolvers<void>();
+ const caughtUp = Promise.withResolvers<void>();
+ const noop = createNoopCacheHost();
+ const host: CacheHost = {
+ ...noop,
+ disabled: false,
+ writeQuery: vi.fn(async (args) => {
+ writeStarted.resolve();
+ await resume.promise;
+ return await noop.writeQuery(args);
+ }),
+ deleteRecords: vi.fn(noop.deleteRecords),
+ };
+ const onPatch = vi.fn();
+ const onResult = vi.fn(
+ (result: OperationResult<NotificationUpdatesSubscription>) => {
+ if (
+ result.data?.notificationUpdates.__typename === 'GraphqlCacheDeletion'
+ )
+ caughtUp.resolve();
+ }
+ );
+ const stream = subscribe(
+ [normalizedCacheExchange(host), notificationReceiptExchange(onPatch)],
+ onResult
+ );
+ try {
+ await stream.attached;
+ stream.emit(NEW_NOTIFICATION);
+ await writeStarted.promise;
+ stream.emit(DELETION);
+ expect(onPatch.mock.calls.map(([patch]) => patch)).toEqual([
+ NEW_NOTIFICATION,
+ DELETION,
+ ]);
+ expect(onResult).not.toHaveBeenCalled();
+ expect(host.deleteRecords).not.toHaveBeenCalled();
+ expect(first.ends).toBe(1);
+ expect(first.children.map((span) => [span.name, span.ends])).toEqual([
+ ['graphql.subscription.cache_queue', 1],
+ ['graphql.subscription.cache_apply', 0],
+ ]);
+ expect(second.ends).toBe(1);
+ expect(second.children.map((span) => [span.name, span.ends])).toEqual([
+ ['graphql.subscription.cache_queue', 0],
+ ]);
+
+ resume.resolve();
+ await caughtUp.promise;
+ expect(host.writeQuery).toHaveBeenCalledOnce();
+ expect(host.deleteRecords).toHaveBeenCalledExactlyOnceWith([
+ 'GraphqlNotification:notification-1',
+ ]);
+ expect(onResult).toHaveBeenCalledTimes(2);
+ expect(onPatch).toHaveBeenCalledTimes(2);
+ for (const receipt of [first, second]) {
+ expect(receipt.children.map((span) => [span.name, span.ends])).toEqual([
+ ['graphql.subscription.cache_queue', 1],
+ ['graphql.subscription.cache_apply', 1],
+ ]);
+ expect(receipt.children[1].attributes['cache.effects_applied']).toBe(
+ true
+ );
+ expect(receipt.children.flatMap((span) => span.errors)).toEqual([]);
+ expect(JSON.stringify(receipt)).not.toContain('Review the document');
+ }
+ } finally {
+ stream.dispose();
+ host.dispose();
+ }
+});
+
+it('does not let a notification callback failure stop persistence or the next event', async () => {
+ vi.useFakeTimers();
+ const error = new Error('notification callback failed');
+ const report = vi.spyOn(Telemetry, 'error').mockImplementation(() => {});
+ const onPatch = vi.fn().mockImplementationOnce(() => {
+ throw error;
+ });
+ const caughtUp = Promise.withResolvers<void>();
+ const noop = createNoopCacheHost();
+ const host: CacheHost = {
+ ...noop,
+ writeQuery: vi.fn(noop.writeQuery),
+ deleteRecords: vi.fn(noop.deleteRecords),
+ };
+ const stream = subscribe(
+ [normalizedCacheExchange(host), notificationReceiptExchange(onPatch)],
+ (result) => {
+ if (
+ result.data?.notificationUpdates.__typename === 'GraphqlCacheDeletion'
+ )
+ caughtUp.resolve();
+ }
+ );
+ try {
+ await stream.attached;
+ stream.emit(NEW_NOTIFICATION);
+ stream.emit(DELETION);
+ await caughtUp.promise;
+ expect(report).toHaveBeenCalledWith(error, {
+ surface: 'graphql-notifications',
+ });
+ expect(onPatch).toHaveBeenCalledTimes(2);
+ expect(host.writeQuery).toHaveBeenCalledOnce();
+ expect(host.deleteRecords).toHaveBeenCalledOnce();
+ } finally {
+ stream.dispose();
+ }
+});
+
+it('marks failed persistence in the receipt trace without failing or replaying delivery', async () => {
+ const receipt = new RecordedSpan('receipt');
+ vi.spyOn(Telemetry, 'span').mockReturnValueOnce(receipt);
+ const failure = new Error('private cache failure details');
+ const onCacheError = vi.fn();
+ const delivered = Promise.withResolvers<void>();
+ const onPatch = vi.fn();
+ const stream = subscribe(
+ [
+ normalizedCacheExchange(
+ {
+ ...createNoopCacheHost(),
+ async writeQuery() {
+ throw failure;
+ },
+ },
+ { onCacheError }
+ ),
+ notificationReceiptExchange(onPatch),
+ ],
+ () => delivered.resolve()
+ );
+ try {
+ await stream.attached;
+ stream.emit(NEW_NOTIFICATION);
+ await delivered.promise;
+ expect(onPatch).toHaveBeenCalledOnce();
+ expect(onCacheError).toHaveBeenCalledWith(failure, expect.any(Object));
+ expect(receipt.ends).toBe(1);
+ expect(receipt.errors).toEqual([]);
+ expect(receipt.children.map((span) => span.ends)).toEqual([1, 1]);
+ expect(receipt.children[1].errors).toEqual([
+ 'Subscription cache effect failed',
+ ]);
+ expect(receipt.children[1].attributes['cache.effects_applied']).toBe(false);
+ expect(JSON.stringify(receipt)).not.toContain(failure.message);
+ } finally {
+ stream.dispose();
+ }
+});
+
+it('delivers without a cache and stops receipt when the subscription is disposed', async () => {
+ const onPatch = vi.fn();
+ const stream = subscribe([notificationReceiptExchange(onPatch)], vi.fn());
+ await stream.attached;
+ stream.emit(NEW_NOTIFICATION);
+ expect(onPatch).toHaveBeenCalledExactlyOnceWith(
+ NEW_NOTIFICATION,
+ expect.objectContaining({ error: expect.any(Function) })
+ );
+ stream.dispose();
+ expect(stream.unsubscribe).toHaveBeenCalledOnce();
+ stream.emit(DELETION);
+ expect(onPatch).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.ts b/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.ts
new file mode 100644
index 0000000000..6129f40f19
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-notification-receipt.ts
@@ -0,0 +1,60 @@
+import { setSubscriptionCacheTrace } from '@graphql-cache/exchange/subscription-cache-trace';
+import { type Span, Telemetry } from '@macro-inc/observability';
+import { createRequest, type Exchange } from '@urql/core';
+import { pipe, tap } from 'wonka';
+import {
+ NotificationUpdatesDocument,
+ type NotificationUpdatesSubscription,
+} from './graphql/generated/graphql';
+import type { GraphqlNotificationPatch } from './graphql-soup-websocket';
+
+const NOTIFICATION_UPDATES_KEY = createRequest(
+ NotificationUpdatesDocument,
+ {}
+).key;
+
+/**
+ * Place after the normalized-cache exchange (toward the transport). Notification
+ * callbacks must receive live events before cache writes, which wait while every
+ * browser tab is hidden. Cache-dependent subscribers still await ordered writes.
+ */
+export function notificationReceiptExchange(
+ onPatch: (patch: GraphqlNotificationPatch, span: Pick<Span, 'error'>) => void
+): Exchange {
+ return ({ forward }) =>
+ (operations) =>
+ pipe(
+ forward(operations),
+ tap((result) => {
+ if (
+ result.operation.kind !== 'subscription' ||
+ result.operation.key !== NOTIFICATION_UPDATES_KEY ||
+ result.data == null
+ ) {
+ return;
+ }
+ const patch = (result.data as NotificationUpdatesSubscription)
+ .notificationUpdates;
+ if (!patch) return;
+ const span = Telemetry.span('notification.receive');
+ span.setAttr('notification.patch_type', patch.__typename);
+ span.setAttr('notification.visibility', document.visibilityState);
+ if (
+ patch.__typename === 'GraphqlNewNotification' ||
+ patch.__typename === 'GraphqlUpdatedNotification'
+ ) {
+ span.setAttr('notification.id', patch.notification.id);
+ }
+ setSubscriptionCacheTrace(result, span);
+ try {
+ span.run(() => onPatch(patch, span));
+ } catch (error) {
+ // An alert callback must not stop cache persistence or later events.
+ span.error(error);
+ Telemetry.error(error, { surface: 'graphql-notifications' });
+ } finally {
+ span.end();
+ }
+ })
+ );
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
index 806a41e1dd..15c6ef824a 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.test.ts
@@ -45,6 +45,7 @@ import {
createGraphqlSoupSubscriptionsLifecycle,
createGraphqlSoupWebSocketUrlResolver,
GraphqlSoupWebSocketAuthUnavailableError,
+ publishNotificationPatch,
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
shouldRetryGraphqlSoupWebSocket,
subscribeToGraphqlNotificationPatches,
@@ -184,6 +185,32 @@ describe('GraphQL Soup websocket retry policy', () => {
});
describe('GraphQL Soup subscription lifecycle', () => {
+ it('marks listener failures on the receipt span and continues delivery', () => {
+ const failure = new Error('notification listener failed');
+ const stopFailed = subscribeToGraphqlNotificationPatches(() => {
+ throw failure;
+ });
+ const received = vi.fn();
+ const stopReceived = subscribeToGraphqlNotificationPatches(received);
+ const span = { error: vi.fn() };
+ const patch = {
+ __typename: 'GraphqlCacheDeletion' as const,
+ graphqlTypeName: 'GraphqlNotification',
+ entityId: 'synthetic-notification',
+ };
+ try {
+ publishNotificationPatch(patch, span);
+ expect(span.error).toHaveBeenCalledExactlyOnceWith(failure);
+ expect(telemetryError).toHaveBeenCalledWith(failure, {
+ surface: 'graphql-notifications',
+ });
+ expect(received).toHaveBeenCalledExactlyOnceWith(patch);
+ } finally {
+ stopFailed();
+ stopReceived();
+ }
+ });
+
it('keeps notification and activity updates active with or without a cache host', () => {
const unsubscribes: Array<ReturnType<typeof vi.fn>> = [];
const receive = new Map<unknown, (result: { data?: unknown }) => void>();
@@ -223,7 +250,8 @@ describe('GraphQL Soup subscription lifecycle', () => {
receive.get(NotificationUpdatesDocument)?.({
data: { notificationUpdates: patch },
});
- expect(listener).toHaveBeenLastCalledWith(patch);
+ // Network receipt owns alerts; cache catch-up must never replay them.
+ expect(listener).not.toHaveBeenCalled();
}
lifecycle.dispose();
unregister();
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
index 105a02e2b5..da389c5599 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup-websocket.ts
@@ -2,7 +2,7 @@ import { subscribeNativeNetworkStatus } from '@core/mobile/native-network-status
import { fireAndForget } from '@core/util/fireAndForget';
import { normalizedCacheResultMetadata } from '@graphql-cache/exchange/normalized-cache-exchange';
import type { CacheHost } from '@graphql-cache/host/types';
-import { Telemetry } from '@macro-inc/observability';
+import { type Span, Telemetry } from '@macro-inc/observability';
import type { Client, OperationResult } from '@urql/core';
import type { Result } from 'neverthrow';
import {
@@ -171,7 +171,7 @@ type NotificationPatchListener = (patch: GraphqlNotificationPatch) => void;
const notificationPatchListeners = new Set<NotificationPatchListener>();
-/** Subscribes to typed notification patches received from GraphQL. */
+/** Subscribes to live notification receipt, without waiting for persistence. */
export function subscribeToGraphqlNotificationPatches(
listener: NotificationPatchListener
): () => void {
@@ -179,8 +179,18 @@ export function subscribeToGraphqlNotificationPatches(
return () => notificationPatchListeners.delete(listener);
}
-function publishNotificationPatch(patch: GraphqlNotificationPatch): void {
- for (const listener of notificationPatchListeners) listener(patch);
+export function publishNotificationPatch(
+ patch: GraphqlNotificationPatch,
+ span: Pick<Span, 'error'>
+): void {
+ for (const listener of notificationPatchListeners) {
+ try {
+ listener(patch);
+ } catch (error) {
+ span.error(error);
+ Telemetry.error(error, { surface: 'graphql-notifications' });
+ }
+ }
}
const LIVE_UPDATE_SUBSCRIPTIONS: readonly {
@@ -304,7 +314,8 @@ export function createGraphqlSoupSubscriptionsLifecycle(
) {
const patch = (result.data as NotificationUpdatesSubscription)
.notificationUpdates;
- publishNotificationPatch(patch);
+ // Cache-dependent channel reconciliation stays behind persistence;
+ // notificationReceiptExchange already dispatched the live event.
const metadata = normalizedCacheResultMetadata(result);
fireAndForget(
channelHandler.onPatch(
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
index d8d04a4d28..d174938fcf 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.test.ts
@@ -468,7 +468,11 @@ vi.mock('./graphql/generated/graphql', () => ({
GroupSoupDocument: {},
SoupDocument: {},
}));
+vi.mock('./graphql-notification-receipt', () => ({
+ notificationReceiptExchange: () => ({ kind: 'notification-receipt' }),
+}));
vi.mock('./graphql-soup-websocket', () => ({
+ publishNotificationPatch: vi.fn(),
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS: 0,
shouldRetryGraphqlSoupWebSocket: () => false,
waitToRetryGraphqlSoupWebSocket: vi.fn(),
@@ -484,9 +488,21 @@ vi.mock('@urql/core', () => ({
createClient: (options: {
exchanges: Array<{ kind?: string; host?: typeof mocks.host }>;
}) => {
- const cacheExchange = options.exchanges.find(
+ const cacheIndex = options.exchanges.findIndex(
({ kind }) => kind === 'cache'
);
+ const subscriptionIndex = options.exchanges.findIndex(
+ ({ kind }) => kind === 'subscription'
+ );
+ if (subscriptionIndex >= 0) {
+ const receiptIndex = options.exchanges.findIndex(
+ ({ kind }) => kind === 'notification-receipt'
+ );
+ expect(receiptIndex).toBeGreaterThanOrEqual(0);
+ expect(receiptIndex).toBeLessThan(subscriptionIndex);
+ if (cacheIndex >= 0) expect(receiptIndex).toBeGreaterThan(cacheIndex);
+ }
+ const cacheExchange = options.exchanges[cacheIndex];
if (!cacheExchange?.host) {
return options.exchanges.some(({ kind }) => kind === 'subscription')
? mocks.realtimeClient
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index b61966c4e2..783a385e17 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -106,9 +106,11 @@ import {
type SoupQuery,
} from './graphql/generated/graphql';
import { shouldRetryGraphqlMutation } from './graphql-mutation-retry';
+import { notificationReceiptExchange } from './graphql-notification-receipt';
import {
createGraphqlSoupSubscriptionsLifecycle,
createGraphqlSoupWebSocketUrlResolver,
+ publishNotificationPatch,
SOUP_GRAPHQL_WEBSOCKET_RETRY_ATTEMPTS,
shouldRetryGraphqlSoupWebSocket,
waitToRetryGraphqlSoupWebSocket,
@@ -477,6 +479,7 @@ function getUncachedRealtimeClient(): Client {
preferGetMethod: false,
exchanges: [
networkRevalidationExchange(),
+ notificationReceiptExchange(publishNotificationPatch),
graphqlSoupSubscriptionExchange(websocketClient),
fetchExchange,
],
@@ -817,6 +820,7 @@ export function getGraphqlSoupClient(): Client {
mutationQueueTelemetry,
delegateRevalidation: delegateChannelNotificationRefresh,
}),
+ notificationReceiptExchange(publishNotificationPatch),
graphqlSoupSubscriptionExchange(graphqlWsClient),
fetchExchange,
],
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 1658e833fb..fd6da51d85 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -56,6 +56,17 @@ normal warmup; if foreground handoff/resume exceeds one second, ordinary queries
use network fallback while cache-only reads never forward. Writes and received
mutation confirmations wait for storage instead of being sent twice.
+On return, queued commits should produce a coalesced cache refresh, not rebuild
+every cache-driven view after each intermediate write. Open Calendar, switch to
+an unrelated tab (or fully cover Chrome with another macOS app), let remote
+updates arrive, then return and immediately click an event and change the date.
+Check that input is handled and the final events appear without repeated chip
+rebuilds. Repeat with several hidden Macro tabs. `graphql_cache.change_batch`
+reports the number of hints combined; individual commits and mutation replies
+remain separate. The backend-free parking regression verifies five queued commits
+produce one visible-cache refresh, but real macOS occlusion and calendar input
+still need this manual check.
+
Verify the all-hidden case without activating the former owner: no held physical
owner lock after parking, preserved generation/queue, and successful reads/writes
from a returning tab. Start a query while parked, resume storage from another
diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.md
index 811bc33380..75ab289e06 100644
--- a/docs/agent-guide/notifications.md
+++ b/docs/agent-guide/notifications.md
@@ -2,6 +2,26 @@
## Notifications
+Browser notifications must arrive while Macro is in a background tab, not just
+when it is visible. With browser permission and in-app delivery enabled, switch
+to an unrelated tab and trigger a notification from another session. Check that
+the alert arrives before returning to Macro and does not repeat on return. Try
+with one Macro tab and with several all hidden; only the elected notification
+leader should show the alert. This does not promise delivery after every Macro
+tab is closed or the browser suspends the page.
+
+GraphQL notification callbacks run on network receipt, independently of the local
+cache, which parks while all Macro tabs are hidden. Cache updates and channel
+reconciliation catch up afterward. The backend-free `parking.browser.e2e.ts`
+regression exercises that boundary with real storage and simulated visibility;
+OS banner presentation still needs the manual check above.
+
+For delayed cache catch-up, find `notification.receive` by `notification.id`.
+Its linked `graphql.subscription.cache_queue` and
+`graphql.subscription.cache_apply` phases distinguish waiting behind an earlier
+event from applying the event to storage. Receipt completes without waiting for
+these phases; listener errors mark receipt, while cache errors mark application.
+
In the desktop app, **Settings → Notifications → Delivery → Desktop notifications**
controls system notification delivery for this installation. The Notifications
page is always present, in the same place on web, desktop, and mobile; Account