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(notification): speed up read updates and reconcile stale state (#6931)

Sean Ayefe8a71f083c0
diff --git a/.sqlx/query-11aa415053064f569057bd100e3aa8686566813f38bd7e90d8d076b3cc5a8b94.json b/.sqlx/query-11aa415053064f569057bd100e3aa8686566813f38bd7e90d8d076b3cc5a8b94.json
new file mode 100644
index 0000000000..31c867aa8c
--- /dev/null
+++ b/.sqlx/query-11aa415053064f569057bd100e3aa8686566813f38bd7e90d8d076b3cc5a8b94.json
@@ -0,0 +1,44 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH requested_entities AS (\n SELECT entity_type, entity_id\n FROM UNNEST($2::text[], $3::text[]) AS entity(entity_type, entity_id)\n )\n SELECT un.notification_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND (un.state = ANY($4::notification_state[]) OR ($5 AND un.seen_at IS NULL))\n AND EXISTS (\n SELECT 1\n FROM requested_entities entity\n WHERE (\n n.event_item_type = entity.entity_type\n AND n.event_item_id = entity.entity_id\n )\n OR (\n n.secondary_event_item_type = entity.entity_type\n AND n.secondary_event_item_id = entity.entity_id\n )\n OR (\n entity.entity_type = 'channel_message'\n AND COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = entity.entity_id\n )\n )\n ORDER BY un.created_at, un.notification_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "TextArray",
+ "TextArray",
+ {
+ "Custom": {
+ "name": "notification_state[]",
+ "kind": {
+ "Array": {
+ "Custom": {
+ "name": "notification_state",
+ "kind": {
+ "Enum": [
+ "unseen",
+ "seen",
+ "done"
+ ]
+ }
+ }
+ }
+ }
+ }
+ },
+ "Bool"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "11aa415053064f569057bd100e3aa8686566813f38bd7e90d8d076b3cc5a8b94"
+}
diff --git a/.sqlx/query-239ca21de9709a5c5e1876863d9d6f1ebd4a1e3b229d3901297a0b8af47ea65b.json b/.sqlx/query-239ca21de9709a5c5e1876863d9d6f1ebd4a1e3b229d3901297a0b8af47ea65b.json
new file mode 100644
index 0000000000..493d0fa706
--- /dev/null
+++ b/.sqlx/query-239ca21de9709a5c5e1876863d9d6f1ebd4a1e3b229d3901297a0b8af47ea65b.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "UPDATE user_notification SET state = $3, seen_at = $4 WHERE user_id = $1 AND notification_id = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ {
+ "Custom": {
+ "name": "notification_state",
+ "kind": {
+ "Enum": [
+ "unseen",
+ "seen",
+ "done"
+ ]
+ }
+ }
+ },
+ "Timestamp"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "239ca21de9709a5c5e1876863d9d6f1ebd4a1e3b229d3901297a0b8af47ea65b"
+}
diff --git a/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json b/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json
deleted file mode 100644
index 847561ee8a..0000000000
--- a/.sqlx/query-d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8.json
+++ /dev/null
@@ -1,24 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n WITH requested_entities AS (\n SELECT entity_type, entity_id\n FROM UNNEST($2::text[], $3::text[]) AS entity(entity_type, entity_id)\n )\n SELECT un.notification_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND EXISTS (\n SELECT 1\n FROM requested_entities entity\n WHERE (\n n.event_item_type = entity.entity_type\n AND n.event_item_id = entity.entity_id\n )\n OR (\n n.secondary_event_item_type = entity.entity_type\n AND n.secondary_event_item_id = entity.entity_id\n )\n OR (\n entity.entity_type = 'channel_message'\n AND COALESCE(n.metadata->>'messageId', n.metadata->>'message_id', '') = entity.entity_id\n )\n )\n ORDER BY un.created_at, un.notification_id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "notification_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "TextArray",
- "TextArray"
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "d164a8fc7b761c64c8da24a9cdbae3c5a8a716f2f391656ac0b0aef4b12e78b8"
-}
diff --git a/apps/web/src/lib/queries/notification/entity-mutations.ts b/apps/web/src/lib/queries/notification/entity-mutations.ts
index d5773335b2..49821f9e4b 100644
--- a/apps/web/src/lib/queries/notification/entity-mutations.ts
+++ b/apps/web/src/lib/queries/notification/entity-mutations.ts
@@ -115,9 +115,10 @@ export function toNotificationEntityInput(
/**
* Mark all notifications associated with the supplied entities seen or done.
- * The authoritative response updates the normalized GraphQL cache directly;
- * it is deliberately not mirrored into the legacy TanStack notification cache.
- * Returned rows include the exact IDs needed by a later ID-scoped undo.
+ * The changed-row response updates the normalized GraphQL cache; the client
+ * also revalidates mounted readers to reconcile stale rows omitted by a no-op.
+ * It is deliberately not mirrored into the legacy TanStack notification cache.
+ * Returned rows include only the exact IDs needed by a later ID-scoped undo.
*/
export async function updateNotificationsForEntities(args: {
entities: NotificationEntityRef[];
diff --git a/apps/web/src/lib/queries/notification/graphql/user-notifications.ts b/apps/web/src/lib/queries/notification/graphql/user-notifications.ts
index 791961f23c..cfa3e74534 100644
--- a/apps/web/src/lib/queries/notification/graphql/user-notifications.ts
+++ b/apps/web/src/lib/queries/notification/graphql/user-notifications.ts
@@ -20,7 +20,8 @@ import {
} from '@service-storage/graphql-soup';
import { executeGraphqlUpdateNotifications } from '@service-storage/graphql-update-notifications';
import { CombinedError } from '@urql/core';
-import type { Accessor } from 'solid-js';
+import { type Accessor, onCleanup } from 'solid-js';
+import { registerNotificationReader } from '../revalidation';
const DEFAULT_NOTIFICATION_LIMIT = 20;
const MAX_NOTIFICATION_LIMIT = 500;
@@ -116,6 +117,15 @@ export function createGraphqlNotificationsQuery(
};
});
+ onCleanup(
+ registerNotificationReader({
+ client: getGraphqlSoupClient,
+ isEnabled: () => query.isEnabled,
+ refresh: () =>
+ query.refetch({ requestPolicy: 'network-only', throwOnError: true }),
+ })
+ );
+
return query;
}
diff --git a/apps/web/src/lib/queries/notification/revalidation.ts b/apps/web/src/lib/queries/notification/revalidation.ts
new file mode 100644
index 0000000000..ea7098f9eb
--- /dev/null
+++ b/apps/web/src/lib/queries/notification/revalidation.ts
@@ -0,0 +1,67 @@
+import type { QueryRevalidation } from '@graphql-cache/exchange/optimistic';
+import {
+ ChannelListSoupDocument,
+ ChannelUnreadPresenceDocument,
+ GroupSoupDocument,
+ SoupDocument,
+ SoupNotificationsDocument,
+} from '@service-storage/graphql/generated/graphql';
+import type { Client } from '@urql/core';
+import { getActiveGraphqlSoupRevalidations } from '../soup/graphql/active-queries';
+
+type NotificationReader = {
+ client: () => Client;
+ isEnabled: () => boolean;
+ refresh: () => Promise<unknown>;
+};
+
+const notificationReaders = new Set<NotificationReader>();
+const notificationDocuments = new Set<QueryRevalidation['document']>([
+ ChannelListSoupDocument,
+ ChannelUnreadPresenceDocument,
+ GroupSoupDocument,
+ SoupDocument,
+ SoupNotificationsDocument,
+]);
+
+/** Registers an existing notification feed without activating its lazy query. */
+export function registerNotificationReader(reader: NotificationReader) {
+ notificationReaders.add(reader);
+ return () => notificationReaders.delete(reader);
+}
+
+async function refreshSafely(refresh: () => Promise<unknown>): Promise<void> {
+ try {
+ await refresh();
+ } catch (error) {
+ // A failed refresh cannot undo a committed write or discard its exact undo IDs.
+ console.error('Failed to reconcile notification state', error);
+ }
+}
+
+/**
+ * Entity writes return only changed rows. Empty AND partial responses can leave
+ * stale notifications behind, so refresh mounted readers after every commit.
+ * Reuse loaded page variables instead of resetting pagination or reading all
+ * cached history. Disabled/unstarted notification feeds remain dormant.
+ */
+export async function revalidateNotificationReaders(
+ client: Client
+): Promise<void> {
+ const pages = getActiveGraphqlSoupRevalidations().filter(({ document }) =>
+ notificationDocuments.has(document)
+ );
+ await Promise.all([
+ ...pages.map(({ document, variables }) =>
+ refreshSafely(async () => {
+ const result = await client
+ .query(document, variables, { requestPolicy: 'network-only' })
+ .toPromise();
+ if (result.error) throw result.error;
+ })
+ ),
+ ...[...notificationReaders]
+ .filter((reader) => reader.isEnabled() && reader.client() === client)
+ .map((reader) => refreshSafely(reader.refresh)),
+ ]);
+}
diff --git a/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts b/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts
new file mode 100644
index 0000000000..1171721eaf
--- /dev/null
+++ b/apps/web/src/lib/queries/notification/tests/graphql-revalidation.test.ts
@@ -0,0 +1,62 @@
+import type { Client } from '@urql/core';
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ client: {} as Client,
+ query: {
+ isEnabled: false,
+ get data(): never {
+ throw new Error('revalidation must not read the suspense resource');
+ },
+ refetch: vi.fn(async () => undefined),
+ },
+}));
+
+vi.mock('@app/lib/urql-solid', () => ({
+ createUrqlInfiniteQuery: () => mocks.query,
+ createUrqlMutation: vi.fn(),
+}));
+vi.mock('@service-storage/graphql-soup', () => ({
+ getGraphqlSoupClient: () => mocks.client,
+ mapGraphqlNotification: vi.fn(),
+}));
+
+import { createGraphqlNotificationsQuery } from '../graphql/user-notifications';
+import { revalidateNotificationReaders } from '../revalidation';
+
+const cleanup: Array<() => void> = [];
+beforeEach(() => {
+ mocks.query.isEnabled = false;
+ vi.clearAllMocks();
+});
+afterEach(() => {
+ for (const dispose of cleanup.splice(0)) dispose();
+});
+
+it('leaves an uncreated lazy notification feed dormant', async () => {
+ await revalidateNotificationReaders(mocks.client);
+ expect(mocks.query.refetch).not.toHaveBeenCalled();
+});
+
+it('tracks enabled state without reading data, preserves the query pagination, and unregisters on cleanup', async () => {
+ const dispose = createRoot((dispose) => {
+ createGraphqlNotificationsQuery(() => ({ limit: 20 }));
+ return dispose;
+ });
+ cleanup.push(dispose);
+
+ await revalidateNotificationReaders(mocks.client);
+ expect(mocks.query.refetch).not.toHaveBeenCalled();
+
+ mocks.query.isEnabled = true;
+ await revalidateNotificationReaders(mocks.client);
+ expect(mocks.query.refetch).toHaveBeenCalledExactlyOnceWith({
+ requestPolicy: 'network-only',
+ throwOnError: true,
+ });
+
+ dispose();
+ await revalidateNotificationReaders(mocks.client);
+ expect(mocks.query.refetch).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts
new file mode 100644
index 0000000000..2de0782782
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-notification-revalidation.test.ts
@@ -0,0 +1,190 @@
+import { registerNotificationReader } from '@queries/notification/revalidation';
+import { registerGraphqlSoupRevalidations } from '@queries/soup/graphql/active-queries';
+import { type Client, CombinedError } from '@urql/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ ChannelListSoupDocument,
+ ChannelUnreadPresenceDocument,
+ GroupSoupDocument,
+ MailAccountsDocument,
+ SoupDocument,
+ UpdateNotificationsForEntityDocument,
+} from './graphql/generated/graphql';
+import { executeGraphqlUpdateNotificationsForEntities } from './graphql-update-notifications';
+
+const cleanup: Array<() => void> = [];
+afterEach(() => {
+ for (const dispose of cleanup.splice(0)) dispose();
+ vi.restoreAllMocks();
+});
+
+function setup() {
+ const query = vi.fn(() => ({ toPromise: async () => ({ data: {} }) }));
+ const mutation = vi.fn(() => ({
+ toPromise: async () => ({ data: { updateNotificationsForEntity: [] } }),
+ }));
+ const client = { query, mutation } as unknown as Client;
+ const initial = { input: { initial: { limit: 20 } } };
+ const continuation = { input: { continuation: { cursor: 'loaded-page' } } };
+ const pages = [
+ { document: SoupDocument, variables: initial },
+ { document: SoupDocument, variables: continuation },
+ { document: GroupSoupDocument, variables: initial },
+ { document: ChannelListSoupDocument, variables: initial },
+ { document: ChannelUnreadPresenceDocument, variables: initial },
+ ];
+ cleanup.push(
+ registerGraphqlSoupRevalidations(() => [
+ ...pages,
+ pages[0],
+ { document: MailAccountsDocument, variables: {} },
+ ])
+ );
+ return { client, query, mutation, pages };
+}
+
+const input = {
+ entities: [{ entityType: 'CHANNEL' as const, entityId: 'channel-1' }],
+ operation: 'MARK_SEEN' as const,
+};
+
+describe('entity notification reconciliation', () => {
+ it.each(['MARK_SEEN', 'MARK_DONE'] as const)(
+ 'reconciles an empty %s response without changing its undo IDs',
+ async (operation) => {
+ const { client, query, mutation, pages } = setup();
+ const cached = { state: 'UNSEEN' };
+ const freshState = operation === 'MARK_SEEN' ? 'SEEN' : 'DONE';
+ // Model a normalized notification shared by mounted Soup and feed readers.
+ // The server was already fresh, so the mutation contains no patch for it.
+ query.mockImplementation(() => ({
+ toPromise: async () => {
+ cached.state = freshState;
+ return { data: {} };
+ },
+ }));
+
+ const result = await executeGraphqlUpdateNotificationsForEntities(
+ client,
+ {
+ ...input,
+ operation,
+ }
+ );
+
+ expect(cached.state).toBe(freshState);
+ expect(result.data?.updateNotificationsForEntity).toEqual([]);
+ expect(mutation).toHaveBeenCalledWith(
+ UpdateNotificationsForEntityDocument,
+ {
+ input: { ...input, operation },
+ }
+ );
+ expect(query).toHaveBeenCalledTimes(pages.length);
+ for (const { document, variables } of pages) {
+ expect(query).toHaveBeenCalledWith(document, variables, {
+ requestPolicy: 'network-only',
+ });
+ }
+ }
+ );
+
+ it('reconciles omitted stale rows even when some notifications changed', async () => {
+ const { client, query } = setup();
+ const changed = [
+ { __typename: 'GraphqlNotification', id: 'changed', state: 'SEEN' },
+ ];
+ const response = { data: { updateNotificationsForEntity: changed } };
+ const mutation = vi.fn(() => ({ toPromise: async () => response }));
+ const mixedClient = { ...client, mutation } as unknown as Client;
+ const result = await executeGraphqlUpdateNotificationsForEntities(
+ mixedClient,
+ input
+ );
+
+ expect(query).toHaveBeenCalled();
+ expect(result).toBe(response);
+ expect(result.data?.updateNotificationsForEntity).toBe(changed);
+ });
+
+ it('refreshes only enabled feeds belonging to this client and unregisters disposed feeds', async () => {
+ const { client } = setup();
+ const active = vi.fn(async () => undefined);
+ const disabled = vi.fn(async () => undefined);
+ const otherClient = vi.fn(async () => undefined);
+ const disposed = vi.fn(async () => undefined);
+ for (const [refresh, enabled, owner] of [
+ [active, true, client],
+ [disabled, false, client],
+ [otherClient, true, {} as Client],
+ ] as const) {
+ cleanup.push(
+ registerNotificationReader({
+ client: () => owner,
+ isEnabled: () => enabled,
+ refresh,
+ })
+ );
+ }
+ registerNotificationReader({
+ client: () => client,
+ isEnabled: () => true,
+ refresh: disposed,
+ })();
+
+ await executeGraphqlUpdateNotificationsForEntities(client, input);
+
+ expect(active).toHaveBeenCalledOnce();
+ expect(disabled).not.toHaveBeenCalled();
+ expect(otherClient).not.toHaveBeenCalled();
+ expect(disposed).not.toHaveBeenCalled();
+ });
+
+ it('does not turn a refresh failure into a failed committed mutation', async () => {
+ const { client, query, pages } = setup();
+ const error = new CombinedError({
+ networkError: new Error('offline during refresh'),
+ });
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
+ query.mockReturnValue({ toPromise: async () => ({ data: {}, error }) });
+ const feed = vi.fn(async () => {
+ throw error;
+ });
+ cleanup.push(
+ registerNotificationReader({
+ client: () => client,
+ isEnabled: () => true,
+ refresh: feed,
+ })
+ );
+
+ const result = await executeGraphqlUpdateNotificationsForEntities(
+ client,
+ input
+ );
+
+ expect(result.data?.updateNotificationsForEntity).toEqual([]);
+ expect(result.error).toBeUndefined();
+ expect(query).toHaveBeenCalledTimes(pages.length);
+ expect(feed).toHaveBeenCalledOnce();
+ expect(log).toHaveBeenCalledWith(
+ 'Failed to reconcile notification state',
+ error
+ );
+ });
+
+ it.each([
+ {
+ error: new CombinedError({ networkError: new Error('mutation failed') }),
+ },
+ {},
+ ])('does not revalidate an unsuccessful mutation', async (response) => {
+ const { client, query } = setup();
+ const mutation = vi.fn(() => ({ toPromise: async () => response }));
+ await executeGraphqlUpdateNotificationsForEntities(
+ { ...client, mutation } as unknown as Client,
+ input
+ );
+ expect(query).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts b/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts
index da8b2c4494..2e657bdb93 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-update-notifications.ts
@@ -3,6 +3,7 @@ import {
optimisticMutationDispositionOf,
} from '@graphql-cache/exchange/optimistic';
import type { Client, OperationResult } from '@urql/core';
+import { revalidateNotificationReaders } from '../../queries/notification/revalidation';
import {
getChannelListRevalidations,
revalidateChannelLists,
@@ -152,6 +153,6 @@ export async function executeGraphqlUpdateNotificationsForEntities(
const result = await client
.mutation(UpdateNotificationsForEntityDocument, variables)
.toPromise();
- if (!result.error) await revalidateChannelLists(client);
+ if (!result.error && result.data) await revalidateNotificationReaders(client);
return result;
}
diff --git a/crates/notification/src/domain/models/request.rs b/crates/notification/src/domain/models/request.rs
index faf10a5b21..77cff9de7f 100644
--- a/crates/notification/src/domain/models/request.rs
+++ b/crates/notification/src/domain/models/request.rs
@@ -273,6 +273,17 @@ pub enum NotificationStatus {
}
impl NotificationStatus {
+ /// States needing an entity-scoped update, plus whether to include rows missing a view time.
+ /// ID-scoped writes still return every requested owned row to reconcile retries.
+ pub(crate) fn entity_update_filter(&self) -> (&'static [super::NotificationState], bool) {
+ use super::NotificationState;
+ match self {
+ Self::Seen => (&[NotificationState::Unseen], true),
+ Self::Done(true) => (&NotificationState::ACTIVE, false),
+ Self::Done(false) => (&[NotificationState::Done], false),
+ }
+ }
+
/// returns true if we should be clearing the relevant push notifications
/// for this notification
pub(crate) fn should_clear_push_notifs(&self) -> bool {
diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rs
index a0cbb7ca75..45bbf2264f 100644
--- a/crates/notification/src/domain/ports.rs
+++ b/crates/notification/src/domain/ports.rs
@@ -20,7 +20,7 @@ use crate::domain::models::device::DeviceType;
use crate::domain::models::{NotificationStatusPayload, TaggedContent};
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
-use crate::domain::models::request::NotificationListFilters;
+use crate::domain::models::request::{NotificationListFilters, NotificationStatus};
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
SendNotificationRequestBuilder, UserNotificationRow, VoipPushTarget,
@@ -112,11 +112,13 @@ pub trait NotificationRepository: Send + Sync + 'static {
done: bool,
) -> impl Future<Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>> + Send;
- /// Get active user-owned notification IDs associated with any primary or secondary entity.
+ /// Get non-deleted, user-owned notification IDs associated with any primary or secondary
+ /// entity that need the requested status transition or an initial viewing timestamp.
fn get_notification_ids_for_entities(
&self,
user_id: MacroUserIdStr<'_>,
entities: &[Entity<'_>],
+ status: &NotificationStatus,
) -> impl Future<Output = Result<Vec<Uuid>, Report>> + Send;
/// Get basic notification data (collapse keys) needed for push clearing.
diff --git a/crates/notification/src/domain/service/device/test.rs b/crates/notification/src/domain/service/device/test.rs
index cbdcca56eb..0e4fa1ef36 100644
--- a/crates/notification/src/domain/service/device/test.rs
+++ b/crates/notification/src/domain/service/device/test.rs
@@ -183,6 +183,7 @@ impl NotificationRepository for MockNotifRepo {
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[model_entity::Entity<'_>],
+ _: &crate::domain::models::request::NotificationStatus,
) -> Result<Vec<uuid::Uuid>, Report> {
unimplemented!()
}
diff --git a/crates/notification/src/domain/service/ingress.rs b/crates/notification/src/domain/service/ingress.rs
index 58e1656b27..9d473cfe30 100644
--- a/crates/notification/src/domain/service/ingress.rs
+++ b/crates/notification/src/domain/service/ingress.rs
@@ -534,13 +534,15 @@ where
}
}
- if !req.status.should_clear_push_notifs() {
+ if changed.is_empty() || !req.status.should_clear_push_notifs() {
return deserialize_updated_notifications(changed);
}
+ // Only clear notifications the repository confirmed belong to this user.
+ let notification_ids: Vec<_> = changed.iter().map(|row| row.notification_id).collect();
let notifications_with_keys = self
.repository
- .get_basic_notifications(req.notification_ids)
+ .get_basic_notifications(&notification_ids)
.await?;
if notifications_with_keys.is_empty() {
@@ -580,12 +582,16 @@ where
return deserialize_updated_notifications(changed);
}
+ // A channel's notifications commonly share a collapse key. Clear each push once,
+ // rather than enqueueing an identical background push for every historical row.
+ let collapse_keys: HashSet<_> = notifications_with_keys
+ .into_iter()
+ .map(|notification| notification.apns_collapse_key)
+ .collect();
let messages: Vec<QueueMessage<'_, ClearPushIdentifier, ClearPushIdentifier>> =
- notifications_with_keys
+ collapse_keys
.into_iter()
- .map(|n| {
- let collapse_key = n.apns_collapse_key;
-
+ .map(|collapse_key| {
let notif = ClearPushIdentifier {
identifier: collapse_key.clone(),
};
@@ -675,7 +681,7 @@ where
) -> Result<Vec<UserNotificationRow<T>>, Report> {
let notification_ids = self
.repository
- .get_notification_ids_for_entities(req.user_id.copied(), &req.entities)
+ .get_notification_ids_for_entities(req.user_id.copied(), &req.entities, &req.status)
.await?;
if notification_ids.is_empty() {
diff --git a/crates/notification/src/domain/service/push_notification_event/test.rs b/crates/notification/src/domain/service/push_notification_event/test.rs
index 417c1dde7e..4f0e2347bb 100644
--- a/crates/notification/src/domain/service/push_notification_event/test.rs
+++ b/crates/notification/src/domain/service/push_notification_event/test.rs
@@ -114,6 +114,7 @@ impl NotificationRepository for MockNotifRepo {
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
_: &[model_entity::Entity<'_>],
+ _: &crate::domain::models::request::NotificationStatus,
) -> Result<Vec<uuid::Uuid>, Report> {
unimplemented!()
}
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index 7731f78817..289b93938b 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -1,5 +1,7 @@
//! Unit tests for the notification services.
+mod status_updates;
+
use crate::domain::models::apple::APNSPushNotification;
use crate::domain::models::device::DeviceType;
use crate::domain::models::email_notification_digest::BulkDigestStateMachine;
@@ -115,6 +117,8 @@ struct MockRepository {
entity_notification_ids: Vec<Uuid>,
updated_notifications: Option<Vec<UserNotificationRow<serde_json::Value>>>,
entity_lookup_calls: Mutex<Vec<(String, Vec<(EntityType, String)>)>>,
+ entity_lookup_filters: Mutex<Vec<(Vec<crate::domain::models::NotificationState>, bool)>>,
+ basic_notification_calls: Mutex<Vec<Vec<Uuid>>>,
mark_seen_calls: Mutex<Vec<(String, Vec<Uuid>)>>,
mark_done_calls: Mutex<Vec<(String, Vec<Uuid>, bool)>>,
}
@@ -134,6 +138,8 @@ impl MockRepository {
entity_notification_ids: Vec::new(),
updated_notifications: None,
entity_lookup_calls: Mutex::new(Vec::new()),
+ entity_lookup_filters: Mutex::new(Vec::new()),
+ basic_notification_calls: Mutex::new(Vec::new()),
mark_seen_calls: Mutex::new(Vec::new()),
mark_done_calls: Mutex::new(Vec::new()),
}
@@ -358,7 +364,13 @@ impl NotificationRepository for MockRepository {
&self,
user_id: MacroUserIdStr<'_>,
entities: &[model_entity::Entity<'_>],
+ status: &NotificationStatus,
) -> Result<Vec<Uuid>, Report> {
+ let (states, include_unviewed) = status.entity_update_filter();
+ self.entity_lookup_filters
+ .lock()
+ .unwrap()
+ .push((states.to_vec(), include_unviewed));
self.entity_lookup_calls.lock().unwrap().push((
user_id.to_string(),
entities
@@ -371,9 +383,18 @@ impl NotificationRepository for MockRepository {
async fn get_basic_notifications(
&self,
- _notification_ids: &[Uuid],
+ notification_ids: &[Uuid],
) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {
- Ok(self.basic_notifications.clone())
+ self.basic_notification_calls
+ .lock()
+ .unwrap()
+ .push(notification_ids.to_vec());
+ Ok(self
+ .basic_notifications
+ .iter()
+ .filter(|notification| notification_ids.contains(&notification.id))
+ .cloned()
+ .collect())
}
async fn get_digest_eligible_notification_ids(
@@ -598,9 +619,10 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
&self,
user_id: MacroUserIdStr<'_>,
entities: &[model_entity::Entity<'_>],
+ status: &NotificationStatus,
) -> Result<Vec<Uuid>, Report> {
(**self)
- .get_notification_ids_for_entities(user_id, entities)
+ .get_notification_ids_for_entities(user_id, entities, status)
.await
}
@@ -1922,6 +1944,10 @@ async fn test_update_notifications_for_entities_uses_single_batch_lookup() {
repo.mark_seen_calls.lock().unwrap().as_slice(),
[(user.to_string(), vec![first, second])]
);
+ assert_eq!(
+ repo.entity_lookup_filters.lock().unwrap().as_slice(),
+ [(vec![crate::domain::models::NotificationState::Unseen], true)]
+ );
}
#[tokio::test]
@@ -1952,6 +1978,13 @@ async fn test_update_notifications_for_entities_supports_done_status() {
repo.mark_done_calls.lock().unwrap().as_slice(),
[(user.to_string(), vec![notification_id], true)]
);
+ assert_eq!(
+ repo.entity_lookup_filters.lock().unwrap().as_slice(),
+ [(
+ crate::domain::models::NotificationState::ACTIVE.to_vec(),
+ false
+ )]
+ );
}
#[tokio::test]
@@ -1979,6 +2012,7 @@ async fn test_update_notifications_for_entities_noops_when_no_notifications_matc
assert!(updated.is_empty());
assert!(repo.mark_done_calls.lock().unwrap().is_empty());
+ assert!(repo.basic_notification_calls.lock().unwrap().is_empty());
}
#[tokio::test]
diff --git a/crates/notification/src/domain/service/test/status_updates.rs b/crates/notification/src/domain/service/test/status_updates.rs
new file mode 100644
index 0000000000..58231032b1
--- /dev/null
+++ b/crates/notification/src/domain/service/test/status_updates.rs
@@ -0,0 +1,144 @@
+use super::*;
+
+#[tokio::test]
+async fn deduplicates_push_clears_by_collapse_key() {
+ let user = test_user_id("[email protected]");
+ let ids: Vec<_> = (0..200).map(|_| Uuid::now_v7()).collect();
+ let mut repo = MockRepository::new().with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::Ios("ios-endpoint".to_string()),
+ );
+ for (index, id) in ids.iter().enumerate() {
+ repo = repo.with_basic_notification(*id, format!("channel-{}", index % 2));
+ }
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationReaderService {
+ repository: Arc::new(repo),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ let rows = service
+ .update_notifications_and_return::<TestNotifEvent>(UpdateNotificationsRequest {
+ user_id: user,
+ notification_ids: &ids,
+ status: NotificationStatus::Seen,
+ })
+ .await
+ .unwrap();
+
+ assert_eq!(
+ rows.len(),
+ ids.len(),
+ "push deduplication must not truncate the response"
+ );
+ let published = queue.get_published();
+ if !cfg!(feature = "clear_ios_push") {
+ assert!(published.is_empty());
+ return;
+ }
+ assert_eq!(published.len(), 2);
+ let keys: HashSet<_> = published
+ .iter()
+ .map(|message| {
+ message["content"]["Ios"]["notif"]["identifier"]
+ .as_str()
+ .unwrap()
+ })
+ .collect();
+ assert_eq!(keys, HashSet::from(["channel-0", "channel-1"]));
+}
+
+#[tokio::test]
+async fn clears_pushes_only_for_authoritative_owned_rows() {
+ let user = test_user_id("[email protected]");
+ let owned_id = Uuid::now_v7();
+ let other_id = Uuid::now_v7();
+ let now = Utc::now();
+ let repo = Arc::new(
+ MockRepository::new()
+ .with_updated_notifications(vec![updated_notification(
+ user.clone(),
+ owned_id,
+ false,
+ Some(now),
+ now,
+ )])
+ .with_basic_notification(owned_id, "owned".to_string())
+ .with_basic_notification(other_id, "other-user".to_string())
+ .with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::Ios("ios-endpoint".to_string()),
+ ),
+ );
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ service
+ .update_notifications(UpdateNotificationsRequest {
+ user_id: user,
+ notification_ids: &[owned_id, other_id],
+ status: NotificationStatus::Seen,
+ })
+ .await
+ .unwrap();
+
+ let published = queue.get_published();
+ if !cfg!(feature = "clear_ios_push") {
+ assert!(repo.basic_notification_calls.lock().unwrap().is_empty());
+ assert!(published.is_empty());
+ return;
+ }
+ assert_eq!(
+ repo.basic_notification_calls.lock().unwrap().as_slice(),
+ [vec![owned_id]]
+ );
+ assert_eq!(published.len(), 1);
+ assert_eq!(
+ published[0]["content"]["Ios"]["notif"]["identifier"],
+ "owned"
+ );
+}
+
+#[tokio::test]
+async fn no_owned_rows_skips_push_lookup_and_publication() {
+ let user = test_user_id("[email protected]");
+ let id = Uuid::now_v7();
+ let repo = Arc::new(
+ MockRepository::new()
+ .with_updated_notifications(vec![])
+ .with_basic_notification(id, "other-user".to_string())
+ .with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::Ios("ios-endpoint".to_string()),
+ ),
+ );
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationReaderService {
+ repository: repo.clone(),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+
+ service
+ .update_notifications(UpdateNotificationsRequest {
+ user_id: user,
+ notification_ids: &[id],
+ status: NotificationStatus::Seen,
+ })
+ .await
+ .unwrap();
+
+ assert!(repo.basic_notification_calls.lock().unwrap().is_empty());
+ assert!(queue.get_published().is_empty());
+}
diff --git a/crates/notification/src/domain/service/voip/test.rs b/crates/notification/src/domain/service/voip/test.rs
index f91f000c2e..7d3ff0d710 100644
--- a/crates/notification/src/domain/service/voip/test.rs
+++ b/crates/notification/src/domain/service/voip/test.rs
@@ -149,6 +149,7 @@ impl NotificationRepository for MockRepo {
&self,
_: MacroUserIdStr<'_>,
_: &[model_entity::Entity<'_>],
+ _: &crate::domain::models::request::NotificationStatus,
) -> Result<Vec<uuid::Uuid>, Report> {
unimplemented!()
}
diff --git a/crates/notification/src/outbound/queue.rs b/crates/notification/src/outbound/queue.rs
index b614f93998..b158ddb437 100644
--- a/crates/notification/src/outbound/queue.rs
+++ b/crates/notification/src/outbound/queue.rs
@@ -1,6 +1,12 @@
//! SQS queue adapter for notification delivery.
+#[cfg(test)]
+mod test;
+
+use std::future::Future;
+
use aws_sdk_sqs::Client as SqsClient;
+use futures::{StreamExt, stream};
use rootcause::Report;
use serde::Serialize;
@@ -9,8 +15,17 @@ use crate::domain::models::queue_message::{
};
use crate::domain::ports::{NotificationIngressQueue, NotificationQueue};
-#[cfg(test)]
-mod test;
+const MAX_CONCURRENT_SENDS: usize = 10;
+
+/// Await every send, including after an error, without unbounded SQS fanout.
+async fn send_concurrently(
+ sends: impl IntoIterator<Item = impl Future<Output = Result<(), Report>>>,
+) -> Result<(), Report> {
+ stream::iter(sends)
+ .buffer_unordered(MAX_CONCURRENT_SENDS)
+ .fold(Ok(()), |result, next| async move { result.and(next) })
+ .await
+}
/// SQS-backed implementation of the notification queue ports.
///
@@ -56,10 +71,11 @@ impl NotificationQueue for SqsQueue {
&self,
messages: Vec<QueueMessage<'a, T, U>>,
) -> Result<(), Report> {
- for message in messages {
- self.send_json(&message).await?;
- }
- Ok(())
+ let sends: Vec<_> = messages
+ .into_iter()
+ .map(|message| async move { self.send_json(&message).await })
+ .collect();
+ send_concurrently(sends).await
}
async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {
diff --git a/crates/notification/src/outbound/queue/test.rs b/crates/notification/src/outbound/queue/test.rs
index e345e54802..89d1d98e1a 100644
--- a/crates/notification/src/outbound/queue/test.rs
+++ b/crates/notification/src/outbound/queue/test.rs
@@ -1,6 +1,8 @@
use super::*;
use aws_sdk_sqs::config::{BehaviorVersion, Credentials, Region, retry::RetryConfig};
use serde_json::json;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Duration;
use wiremock::matchers::{body_json, header, method};
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -122,3 +124,57 @@ async fn ingress_delete_failure_does_not_block_valid_messages() {
assert_eq!(server.received_requests().await.unwrap().len(), 2);
server.verify().await;
}
+
+#[tokio::test(start_paused = true)]
+async fn sends_in_parallel_with_bounded_concurrency() {
+ let active = AtomicUsize::new(0);
+ let peak = AtomicUsize::new(0);
+ let completed = AtomicUsize::new(0);
+ let count = MAX_CONCURRENT_SENDS * 2 + 1;
+ let delay = Duration::from_secs(1);
+ let start = tokio::time::Instant::now();
+
+ send_concurrently((0..count).map(|_| async {
+ let current = active.fetch_add(1, Ordering::SeqCst) + 1;
+ peak.fetch_max(current, Ordering::SeqCst);
+ tokio::time::sleep(delay).await;
+ active.fetch_sub(1, Ordering::SeqCst);
+ completed.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }))
+ .await
+ .unwrap();
+
+ assert_eq!(peak.load(Ordering::SeqCst), MAX_CONCURRENT_SENDS);
+ assert_eq!(completed.load(Ordering::SeqCst), count);
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ assert_eq!(start.elapsed(), delay * 3);
+}
+
+#[tokio::test(start_paused = true)]
+async fn reports_send_failure_without_abandoning_other_sends() {
+ let completed = AtomicUsize::new(0);
+ let count = MAX_CONCURRENT_SENDS * 2;
+ let result = send_concurrently((0..count).map(|index| {
+ let completed = &completed;
+ async move {
+ if index == 0 {
+ return Err(rootcause::report!("SQS send failed"));
+ }
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ completed.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ }
+ }))
+ .await;
+
+ assert!(result.unwrap_err().to_string().contains("SQS send failed"));
+ assert_eq!(completed.load(Ordering::SeqCst), count - 1);
+}
+
+#[tokio::test]
+async fn empty_publish_succeeds_without_sending() {
+ send_concurrently(std::iter::empty::<std::future::Ready<Result<(), Report>>>())
+ .await
+ .unwrap();
+}
diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rs
index 205dc2d2ae..73f1afd3f3 100644
--- a/crates/notification/src/outbound/repository.rs
+++ b/crates/notification/src/outbound/repository.rs
@@ -4,7 +4,9 @@
mod test;
use crate::domain::models::device::DeviceType;
-use crate::domain::models::request::{NotificationCategory, NotificationListFilters};
+use crate::domain::models::request::{
+ NotificationCategory, NotificationListFilters, NotificationStatus,
+};
use crate::domain::models::{
DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,
SendNotificationRequestBuilder, TaggedContent, UserNotificationRow,
@@ -448,11 +450,12 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
Output = Result<Vec<UserNotificationRow<serde_json::Value>>, Report>,
> + Send;
- /// Get active user-owned notification IDs associated with any primary or secondary entity.
+ /// Get matching user-owned IDs that need a status transition or initial viewing timestamp.
fn get_notification_ids_for_entities(
&self,
user_id: &MacroUserIdStr<'_>,
entities: &[Entity<'_>],
+ status: &NotificationStatus,
) -> impl std::future::Future<Output = Result<Vec<Uuid>, Report>> + Send;
/// Get basic notification data (collapse keys) for push clearing.
@@ -901,7 +904,9 @@ impl NotificationDbOps for PgPool {
&self,
user_id: &MacroUserIdStr<'_>,
entities: &[Entity<'_>],
+ status: &NotificationStatus,
) -> Result<Vec<Uuid>, Report> {
+ let (states, include_unviewed) = status.entity_update_filter();
let entity_types = entities
.iter()
.map(|entity| entity.entity_type.as_ref().to_owned())
@@ -921,6 +926,7 @@ impl NotificationDbOps for PgPool {
JOIN notification n ON n.id = un.notification_id
WHERE un.user_id = $1
AND un.deleted_at IS NULL
+ AND (un.state = ANY($4::notification_state[]) OR ($5 AND un.seen_at IS NULL))
AND EXISTS (
SELECT 1
FROM requested_entities entity
@@ -942,6 +948,8 @@ impl NotificationDbOps for PgPool {
user_id.as_ref(),
&entity_types,
&entity_ids,
+ states as _,
+ include_unviewed,
)
.fetch_all(self)
.await?;
@@ -1629,9 +1637,10 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
&self,
user_id: MacroUserIdStr<'_>,
entities: &[Entity<'_>],
+ status: &NotificationStatus,
) -> Result<Vec<Uuid>, Report> {
self.db
- .get_notification_ids_for_entities(&user_id, entities)
+ .get_notification_ids_for_entities(&user_id, entities, status)
.await
}
diff --git a/crates/notification/src/outbound/repository/test.rs b/crates/notification/src/outbound/repository/test.rs
index f09217c5ca..0e74036bb4 100644
--- a/crates/notification/src/outbound/repository/test.rs
+++ b/crates/notification/src/outbound/repository/test.rs
@@ -461,7 +461,7 @@ async fn test_get_notification_ids_for_entities_matches_multiple_primary_and_sec
EntityType::Project.with_entity_str("entity-1"),
];
let notification_ids = pool
- .get_notification_ids_for_entities(&user, &entities)
+ .get_notification_ids_for_entities(&user, &entities, &NotificationStatus::Seen)
.await
.unwrap()
.into_iter()
@@ -500,6 +500,7 @@ async fn test_get_notification_ids_for_entities_matches_task_entity(pool: Pool<P
.get_notification_ids_for_entities(
&user,
&[EntityType::Document.with_entity_str(task_entity_id)],
+ &NotificationStatus::Seen,
)
.await
.unwrap();
@@ -528,6 +529,7 @@ async fn test_get_notification_ids_for_entities_matches_message_entity(pool: Poo
.get_notification_ids_for_entities(
&user,
&[EntityType::ChannelMessage.with_entity_str(&message_id)],
+ &NotificationStatus::Seen,
)
.await
.unwrap();
@@ -584,6 +586,7 @@ async fn test_get_notification_ids_for_entities_matches_foreign_entities_includi
.get_notification_ids_for_entities(
&user,
&[EntityType::ForeignEntity.with_entity_str(&foreign_entity_id)],
+ &NotificationStatus::Seen,
)
.await
.unwrap();
diff --git a/crates/notification/src/outbound/repository/test/state.rs b/crates/notification/src/outbound/repository/test/state.rs
index c8526ca60c..d2671df805 100644
--- a/crates/notification/src/outbound/repository/test/state.rs
+++ b/crates/notification/src/outbound/repository/test/state.rs
@@ -76,6 +76,86 @@ async fn persisted_transitions_match_domain_policy(pool: Pool<Postgres>) -> Resu
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn entity_updates_skip_noops_and_retries(pool: Pool<Postgres>) -> Result<(), Report> {
+ let user = test_user("[email protected]");
+ let original_viewed_at = chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ for (status, action) in [
+ (NotificationStatus::Seen, NotificationAction::MarkSeen),
+ (NotificationStatus::Done(true), NotificationAction::MarkDone),
+ (NotificationStatus::Done(false), NotificationAction::Reopen),
+ ] {
+ let entity = EntityType::Channel.with_entity_string(Uuid::now_v7().to_string());
+ let mut expected = HashSet::new();
+ let mut initial = Vec::new();
+ for before in [
+ NotificationState::Unseen,
+ NotificationState::Seen,
+ NotificationState::Done,
+ ] {
+ for viewed_at in [None, Some(original_viewed_at)] {
+ let id = Uuid::now_v7();
+ pool.create_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: entity.clone(),
+ secondary_notification_entity: None,
+ notification: TaggedContent::new(TestNotification {
+ message: "history".to_string(),
+ }),
+ sender_id: None,
+ recipient_ids: HashSet::from([user.clone()]),
+ },
+ id,
+ "test_service",
+ None,
+ )
+ .await?;
+ sqlx::query!(
+ "UPDATE user_notification SET state = $3, seen_at = $4 WHERE user_id = $1 AND notification_id = $2",
+ user.as_ref(), id, before as _, viewed_at.map(|time| time.naive_utc()),
+ ).execute(&pool).await?;
+ if before.apply(action) != before
+ || (matches!(action, NotificationAction::MarkSeen) && viewed_at.is_none())
+ {
+ expected.insert(id);
+ }
+ initial.push((id, before, viewed_at));
+ }
+ }
+ let ids = pool
+ .get_notification_ids_for_entities(&user, std::slice::from_ref(&entity), &status)
+ .await?;
+ assert_eq!(ids.iter().copied().collect::<HashSet<_>>(), expected);
+ let updated = match status {
+ NotificationStatus::Seen => pool.mark_notifications_seen(&user, &ids).await?,
+ NotificationStatus::Done(done) => {
+ pool.mark_notifications_done(&user, &ids, done).await?
+ }
+ };
+ assert_eq!(updated.len(), expected.len());
+ assert!(
+ pool.get_notification_ids_for_entities(&user, &[entity], &status)
+ .await?
+ .is_empty()
+ );
+ for (id, before, viewed_at) in initial {
+ let row = pool
+ .get_user_notification_by_id::<serde_json::Value>(user.clone(), id)
+ .await?
+ .unwrap();
+ assert_eq!(row.state, before.apply(action));
+ if matches!(action, NotificationAction::MarkSeen) && viewed_at.is_none() {
+ assert!(row.viewed_at.is_some());
+ } else {
+ assert_eq!(row.viewed_at, viewed_at);
+ }
+ }
+ }
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../fixtures", scripts("user_notifications"))
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 0746659103..d32c5d443e 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -533,8 +533,13 @@ after the network failure must remain usable without erasing the refresh error.
If more unread notifications
remain, the limited edge must refresh to the next one rather than staying empty.
Refreshing unread indicators while composing must preserve the conversation,
-scroll position, and input focus. The backend must support the new edge arguments
-before deploying the frontend that requests them.
+scroll position, and input focus. To check stale-cache recovery, mark notifications
+read/done in another tab, then repeat the action in a stale tab. Empty or partial
+changed-row responses must still reconcile mounted Soup and notification readers,
+without resetting loaded pages or starting an unused global notification feed.
+Undo must use only the mutation's returned IDs, not IDs from the subsequent refresh.
+The backend must support the new edge arguments before deploying the frontend
+that requests them.
## Call lifecycle
diff --git a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
index 3bd88529f8..1ddda5aa28 100644
--- a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -2,7 +2,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
use models_pagination::{CreatedAt, Query};
use notification::domain::models::TaggedContent;
-use notification::domain::models::request::NotificationListFilters;
+use notification::domain::models::request::{NotificationListFilters, NotificationStatus};
use notification::domain::models::{
DeviceEndpoint, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,
UserNotificationRow, device::DeviceType,
@@ -111,9 +111,10 @@ impl NotificationRepository for SandboxNotificationRepository {
&self,
user_id: MacroUserIdStr<'_>,
entities: &[Entity<'_>],
+ status: &NotificationStatus,
) -> Result<Vec<Uuid>, Report> {
self.inner
- .get_notification_ids_for_entities(user_id, entities)
+ .get_notification_ids_for_entities(user_id, entities, status)
.await
}