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(calendar): sort reminder-surfaced inbox rows by delivery time (#6086)

gbirman3228cb21f59a
diff --git a/.sqlx/query-1bede2b2eb81d0630d25445b218c0c40defd431d4986e4470cf9139487c47dac.json b/.sqlx/query-1bede2b2eb81d0630d25445b218c0c40defd431d4986e4470cf9139487c47dac.json
new file mode 100644
index 0000000000..eb87b3fc3f
--- /dev/null
+++ b/.sqlx/query-1bede2b2eb81d0630d25445b218c0c40defd431d4986e4470cf9139487c47dac.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE calendar_events\n SET last_reminder_fired_at = GREATEST(last_reminder_fired_at, $2)\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1bede2b2eb81d0630d25445b218c0c40defd431d4986e4470cf9139487c47dac"
+}
diff --git a/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json b/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
deleted file mode 100644
index 1b6e64017a..0000000000
--- a/.sqlx/query-5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO \"UserApiKey\" (id, name, user_id, hash)\n VALUES ($1, $2, $3, $4)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Bytea"
- ]
- },
- "nullable": []
- },
- "hash": "5392d04a21e2f3c41dc84a6193f1cd004c9c571ae61a47c448a4f1e28f678255"
-}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 59cf12bfa4..5e46c0dea0 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -1009,6 +1009,7 @@ export * from './soupCalendarEventSoupPropertiesFieldConferenceProvider';
export * from './soupCalendarEventSoupPropertiesFieldConferenceUrl';
export * from './soupCalendarEventSoupPropertiesFieldDescription';
export * from './soupCalendarEventSoupPropertiesFieldExtra';
+export * from './soupCalendarEventSoupPropertiesFieldLastReminderFiredAt';
export * from './soupCalendarEventSoupPropertiesFieldLocation';
export * from './soupCalendarEventSoupPropertiesFieldOrganizerEmail';
export * from './soupCalendarEventSoupPropertiesFieldOrganizerName';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesField.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesField.ts
index 6376b72707..6a118f6cc5 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesField.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesField.ts
@@ -8,6 +8,7 @@ import type { SoupCalendarEventSoupPropertiesFieldConferenceProvider } from './s
import type { SoupCalendarEventSoupPropertiesFieldConferenceUrl } from './soupCalendarEventSoupPropertiesFieldConferenceUrl';
import type { SoupCalendarEventSoupPropertiesFieldDescription } from './soupCalendarEventSoupPropertiesFieldDescription';
import type { SoupCalendarEventSoupPropertiesFieldExtra } from './soupCalendarEventSoupPropertiesFieldExtra';
+import type { SoupCalendarEventSoupPropertiesFieldLastReminderFiredAt } from './soupCalendarEventSoupPropertiesFieldLastReminderFiredAt';
import type { SoupCalendarEventSoupPropertiesFieldLocation } from './soupCalendarEventSoupPropertiesFieldLocation';
import type { SoupCalendarEventSoupPropertiesFieldOrganizerEmail } from './soupCalendarEventSoupPropertiesFieldOrganizerEmail';
import type { SoupCalendarEventSoupPropertiesFieldOrganizerName } from './soupCalendarEventSoupPropertiesFieldOrganizerName';
@@ -33,6 +34,8 @@ export interface SoupCalendarEventSoupPropertiesField {
id: string;
/** Whether the selected canonical source is read-only. */
isReadOnly: boolean;
+ /** When this event's most recent reminder notification was delivered. */
+ lastReminderFiredAt?: SoupCalendarEventSoupPropertiesFieldLastReminderFiredAt;
/** Optional location label. */
location?: SoupCalendarEventSoupPropertiesFieldLocation;
/** Organizer email. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesFieldLastReminderFiredAt.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesFieldLastReminderFiredAt.ts
new file mode 100644
index 0000000000..ef489927f2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/soupCalendarEventSoupPropertiesFieldLastReminderFiredAt.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When this event's most recent reminder notification was delivered.
+ */
+export type SoupCalendarEventSoupPropertiesFieldLastReminderFiredAt =
+ | string
+ | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index e722c4b2ae..46c919d5e6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -10363,6 +10363,12 @@ export const getItemsSoupResponse = zod
.describe(
'Whether the selected canonical source is read-only.'
),
+ lastReminderFiredAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "When this event's most recent reminder notification was delivered."
+ ),
location: zod
.string()
.nullish()
@@ -14006,6 +14012,12 @@ export const postItemsSoupResponse = zod
.describe(
'Whether the selected canonical source is read-only.'
),
+ lastReminderFiredAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "When this event's most recent reminder notification was delivered."
+ ),
location: zod
.string()
.nullish()
@@ -17115,6 +17127,12 @@ export const postItemsSoupAstResponse = zod
.describe(
'Whether the selected canonical source is read-only.'
),
+ lastReminderFiredAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "When this event's most recent reminder notification was delivered."
+ ),
location: zod
.string()
.nullish()
@@ -20559,6 +20577,12 @@ export const postItemsSoupAstGroupedResponse = zod
.describe(
'Whether the selected canonical source is read-only.'
),
+ lastReminderFiredAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "When this event's most recent reminder notification was delivered."
+ ),
location: zod
.string()
.nullish()
@@ -23669,6 +23693,12 @@ export const postItemsSoupAstGroupedResponse = zod
.describe(
'Whether the selected canonical source is read-only.'
),
+ lastReminderFiredAt: zod.iso
+ .datetime({})
+ .nullish()
+ .describe(
+ "When this event's most recent reminder notification was delivered."
+ ),
location: zod
.string()
.nullish()
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 12d504ca64..90e9d25dce 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -22915,6 +22915,11 @@
"type": "boolean",
"description": "Whether the selected canonical source is read-only."
},
+ "lastReminderFiredAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When this event's most recent reminder notification was delivered."
+ },
"location": {
"type": ["string", "null"],
"description": "Optional location label."
diff --git a/crates/calendar_events/src/domain/ports.rs b/crates/calendar_events/src/domain/ports.rs
index e87144ee65..4cbc7f252e 100644
--- a/crates/calendar_events/src/domain/ports.rs
+++ b/crates/calendar_events/src/domain/ports.rs
@@ -777,6 +777,15 @@ pub trait CalendarReminderDispatchRepo: Send + Sync + 'static {
&self,
firing: &CalendarReminderFiring,
) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Record when the event's latest reminder notification was delivered, so
+ /// recency-sorted listings surface the event at delivery time instead of
+ /// its last-modified time.
+ fn record_reminder_fired(
+ &self,
+ event_id: Uuid,
+ fired_at: DateTime<Utc>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
}
/// Notification egress for due calendar reminders.
diff --git a/crates/calendar_events/src/domain/reminder_dispatch.rs b/crates/calendar_events/src/domain/reminder_dispatch.rs
index 7b56b0381c..29c4019737 100644
--- a/crates/calendar_events/src/domain/reminder_dispatch.rs
+++ b/crates/calendar_events/src/domain/reminder_dispatch.rs
@@ -91,6 +91,22 @@ where
return Err(error);
}
+ // The delivered alarm is what puts the event into the owner's inbox,
+ // and recency-sorted listings position it by this timestamp. Non-fatal:
+ // a stale sort position is no reason to fail (and redeliver) a
+ // notification that already went out.
+ if let Err(error) = self
+ .repo
+ .record_reminder_fired(due.firing.event_id, now)
+ .await
+ {
+ tracing::error!(
+ error = ?error,
+ event_id = %due.firing.event_id,
+ "failed to record a calendar reminder delivery time; the event keeps its previous sort position",
+ );
+ }
+
self.repo.complete_reminder_delivery(&due.firing).await?;
Ok(CalendarReminderDeliveryOutcome::Delivered)
}
diff --git a/crates/calendar_events/src/domain/reminder_dispatch/test.rs b/crates/calendar_events/src/domain/reminder_dispatch/test.rs
index f0192e5be0..6d5e7433d2 100644
--- a/crates/calendar_events/src/domain/reminder_dispatch/test.rs
+++ b/crates/calendar_events/src/domain/reminder_dispatch/test.rs
@@ -49,6 +49,7 @@ struct FakeRepoState {
claimed: Vec<Uuid>,
released: Vec<Uuid>,
completed: Vec<Uuid>,
+ fired: Vec<(Uuid, DateTime<Utc>)>,
}
#[derive(Clone, Default)]
@@ -120,6 +121,15 @@ impl CalendarReminderDispatchRepo for FakeRepo {
self.0.lock().unwrap().completed.push(firing.event_id);
Ok(())
}
+
+ async fn record_reminder_fired(
+ &self,
+ event_id: Uuid,
+ fired_at: DateTime<Utc>,
+ ) -> Result<(), Report> {
+ self.0.lock().unwrap().fired.push((event_id, fired_at));
+ Ok(())
+ }
}
#[derive(Clone, Default)]
@@ -261,6 +271,8 @@ async fn deliver_claims_notifies_and_completes() {
assert_eq!(state.claimed, vec![uuid(1)]);
assert_eq!(state.completed, vec![uuid(1)]);
assert!(state.released.is_empty());
+ assert_eq!(state.fired.len(), 1);
+ assert_eq!(state.fired[0].0, uuid(1));
assert_eq!(*notifier.notified.lock().unwrap(), vec![uuid(1)]);
}
@@ -298,4 +310,5 @@ async fn failed_notification_releases_the_claim_and_errors() {
assert_eq!(state.claimed, vec![uuid(1)]);
assert_eq!(state.released, vec![uuid(1)]);
assert!(state.completed.is_empty());
+ assert!(state.fired.is_empty());
}
diff --git a/crates/calendar_events/src/outbound/pg.rs b/crates/calendar_events/src/outbound/pg.rs
index c6ec9ccfa5..0e0f09b9c6 100644
--- a/crates/calendar_events/src/outbound/pg.rs
+++ b/crates/calendar_events/src/outbound/pg.rs
@@ -3734,6 +3734,29 @@ impl CalendarReminderDispatchRepo for PgCalendarRepository {
Ok(())
}
+
+ #[tracing::instrument(err, skip(self))]
+ async fn record_reminder_fired(
+ &self,
+ event_id: Uuid,
+ fired_at: DateTime<Utc>,
+ ) -> Result<(), Report> {
+ // GREATEST also covers the first delivery: it ignores the NULL.
+ sqlx::query!(
+ r#"
+ UPDATE calendar_events
+ SET last_reminder_fired_at = GREATEST(last_reminder_fired_at, $2)
+ WHERE id = $1
+ "#,
+ event_id,
+ fired_at,
+ )
+ .execute(&self.pool)
+ .await
+ .map_err(report)?;
+
+ Ok(())
+ }
}
fn event_reconciliation_lock(source_link_id: Uuid, ical_uid: &str) -> i64 {
diff --git a/crates/macro_db_client/migrations/20260831210545_calendar_events_last_reminder_fired_at.sql b/crates/macro_db_client/migrations/20260831210545_calendar_events_last_reminder_fired_at.sql
new file mode 100644
index 0000000000..a475f08ea5
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260831210545_calendar_events_last_reminder_fired_at.sql
@@ -0,0 +1,20 @@
+-- When the event's most recent reminder notification was delivered. Soup
+-- recency sorts use GREATEST(updated_at, last_reminder_fired_at) so the inbox
+-- row a fired alarm surfaces sits at delivery time instead of the event's
+-- Google last-modified time.
+ALTER TABLE calendar_events
+ ADD COLUMN last_reminder_fired_at timestamptz;
+
+-- Backfill from already-delivered reminder notifications so rows currently
+-- misplaced in inboxes move to their delivery time without waiting for the
+-- next firing. notification.created_at is a bare timestamp stored as UTC.
+UPDATE calendar_events e
+SET last_reminder_fired_at = delivered.fired_at
+FROM (
+ SELECT n.event_item_id, MAX(n.created_at AT TIME ZONE 'UTC') AS fired_at
+ FROM notification n
+ WHERE n.event_item_type = 'calendar_event'
+ AND n.notification_event_type = 'calendar_event_reminder'
+ GROUP BY n.event_item_id
+) delivered
+WHERE e.id::text = delivered.event_item_id;
diff --git a/crates/macro_db_client/migrations/20260831210608_calendar_events_owner_activity_index.sql b/crates/macro_db_client/migrations/20260831210608_calendar_events_owner_activity_index.sql
new file mode 100644
index 0000000000..19dde075d8
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260831210608_calendar_events_owner_activity_index.sql
@@ -0,0 +1,9 @@
+-- no-transaction
+-- Recency-sorted soup listings now order calendar events by
+-- GREATEST(updated_at, last_reminder_fired_at); this mirrors
+-- calendar_events_owner_updated_idx for that expression. Must stay a single
+-- statement: sqlx sends no-transaction migrations with multiple statements as
+-- one batch, which wraps them in an implicit transaction that CONCURRENTLY
+-- forbids.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS calendar_events_owner_activity_idx
+ ON calendar_events (owner_id, GREATEST(updated_at, last_reminder_fired_at) DESC, id DESC);
diff --git a/crates/models_soup/src/calendar_event.rs b/crates/models_soup/src/calendar_event.rs
index 14fbaaa843..ad1c65228b 100644
--- a/crates/models_soup/src/calendar_event.rs
+++ b/crates/models_soup/src/calendar_event.rs
@@ -72,6 +72,9 @@ pub struct SoupCalendarEvent<T = ()> {
pub created_at: DateTime<Utc>,
/// Entity update timestamp.
pub updated_at: DateTime<Utc>,
+ /// When this event's most recent reminder notification was delivered.
+ #[serde(default)]
+ pub last_reminder_fired_at: Option<DateTime<Utc>>,
/// Additional enriched data such as properties.
pub extra: T,
}
diff --git a/crates/models_soup/src/item.rs b/crates/models_soup/src/item.rs
index f86346e6ef..94744dd78c 100644
--- a/crates/models_soup/src/item.rs
+++ b/crates/models_soup/src/item.rs
@@ -100,7 +100,11 @@ impl<T> SoupItem<T> {
SoupItem::ChannelThread(thread) => thread.effective_updated_at(),
// Calls intentionally lack `updated_at`; recency follows their lifecycle timestamps.
SoupItem::Call(record) => record.ended_at.unwrap_or(record.started_at),
- SoupItem::CalendarEvent(event) => event.updated_at,
+ // Includes the fired-reminder timestamp so the frecency fallback
+ // cursor agrees with the GREATEST-based recency sort.
+ SoupItem::CalendarEvent(event) => event
+ .last_reminder_fired_at
+ .map_or(event.updated_at, |fired| fired.max(event.updated_at)),
SoupItem::CrmCompany(company) => company.updated_at,
SoupItem::ForeignEntity(foreign_entity) => foreign_entity.updated_at,
SoupItem::Reminder(reminder) => reminder.updated_at,
@@ -166,7 +170,14 @@ impl<T> SoupItem<T> {
(SoupItem::Call(record), _) => record.ended_at.unwrap_or(record.started_at),
(SoupItem::CalendarEvent(event), SimpleSortMethod::CreatedAt) => event.created_at,
(SoupItem::CalendarEvent(_), SimpleSortMethod::ViewedAt) => DateTime::<Utc>::default(),
- (SoupItem::CalendarEvent(event), _) => event.updated_at,
+ // A fired alarm is the event's latest activity: without it the row
+ // a reminder surfaces in the inbox would sort at the event's Google
+ // last-modified time, i.e. into the past. Must mirror the SQL sort
+ // expression GREATEST(updated_at, last_reminder_fired_at) or keyset
+ // pagination breaks.
+ (SoupItem::CalendarEvent(event), _) => event
+ .last_reminder_fired_at
+ .map_or(event.updated_at, |fired| fired.max(event.updated_at)),
(SoupItem::CrmCompany(company), SimpleSortMethod::CreatedAt) => company.created_at,
(SoupItem::CrmCompany(company), SimpleSortMethod::ViewedAt) => {
company.viewed_at.unwrap_or_default()
@@ -377,6 +388,7 @@ impl<T> SoupItem<T> {
is_read_only,
created_at,
updated_at,
+ last_reminder_fired_at,
extra,
}) => SoupItem::CalendarEvent(SoupCalendarEvent {
id,
@@ -396,6 +408,7 @@ impl<T> SoupItem<T> {
is_read_only,
created_at,
updated_at,
+ last_reminder_fired_at,
extra: f(extra),
}),
SoupItem::CrmCompany(SoupCrmCompany {
diff --git a/crates/soup/src/outbound/pg_soup_repo/calendar_event.rs b/crates/soup/src/outbound/pg_soup_repo/calendar_event.rs
index 79c4f6fa7a..90e053c006 100644
--- a/crates/soup/src/outbound/pg_soup_repo/calendar_event.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/calendar_event.rs
@@ -38,6 +38,7 @@ struct CalendarEventRow {
is_read_only: bool,
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
+ last_reminder_fired_at: Option<DateTime<Utc>>,
}
struct CursorParts {
@@ -115,7 +116,9 @@ pub(super) async fn by_ids(
query.push_bind(req.user_id.as_ref().to_string());
query.push(")) AND event.id = ANY(");
query.push_bind(ids);
- query.push(") ORDER BY event.updated_at DESC, event.id DESC");
+ query.push(
+ ") ORDER BY GREATEST(event.updated_at, event.last_reminder_fired_at) DESC, event.id DESC",
+ );
query
.build_query_as::<CalendarEventRow>()
.fetch_all(db)
@@ -191,7 +194,8 @@ fn select_sql() -> &'static str {
event.conference_provider,
event.is_read_only,
event.created_at,
- event.updated_at
+ event.updated_at,
+ event.last_reminder_fired_at
FROM calendar_events event
"#
}
@@ -199,7 +203,14 @@ fn select_sql() -> &'static str {
fn sort_sql(sort: SimpleSortMethod) -> &'static str {
match sort {
SimpleSortMethod::CreatedAt => "event.created_at",
- SimpleSortMethod::UpdatedAt | SimpleSortMethod::ViewedUpdated => "event.updated_at",
+ // A fired alarm counts as the event's latest activity, so the inbox
+ // row a reminder surfaces sorts at delivery time rather than at the
+ // event's Google last-modified time. GREATEST ignores the NULL when
+ // no reminder has fired. Must mirror `cursor_timestamp` in
+ // models_soup or keyset pagination breaks.
+ SimpleSortMethod::UpdatedAt | SimpleSortMethod::ViewedUpdated => {
+ "GREATEST(event.updated_at, event.last_reminder_fired_at)"
+ }
SimpleSortMethod::ViewedAt => "'1970-01-01 00:00:00+00'::timestamptz",
}
}
@@ -322,6 +333,7 @@ fn row_to_item(row: CalendarEventRow) -> Result<SoupItem<()>, sqlx::Error> {
is_read_only: row.is_read_only,
created_at: row.created_at,
updated_at: row.updated_at,
+ last_reminder_fired_at: row.last_reminder_fired_at,
extra: (),
}))
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/calendar_event/test.rs b/crates/soup/src/outbound/pg_soup_repo/calendar_event/test.rs
index 9df5afaa3a..db954ca25e 100644
--- a/crates/soup/src/outbound/pg_soup_repo/calendar_event/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/calendar_event/test.rs
@@ -74,3 +74,90 @@ async fn frecency_fallback_keeps_calendar_events_with_aggregates(
));
Ok(())
}
+
+/// A fired reminder counts as the event's latest activity: recency sorting
+/// must place the event at its delivery time, not at the older Google
+/// last-modified time that made reminder rows surface in the past.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn recency_sort_uses_reminder_delivery_time(pool: PgPool) -> anyhow::Result<()> {
+ let owner_id = "macro|[email protected]";
+ let link_id = Uuid::now_v7();
+ let reminded_id = Uuid::now_v7();
+ let edited_id = Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO email_links (
+ id, macro_id, fusionauth_user_id, email_address, provider
+ )
+ VALUES ($1, $2, $2, '[email protected]', 'GMAIL')
+ "#,
+ link_id,
+ owner_id,
+ )
+ .execute(&pool)
+ .await?;
+ // Created long ago and never edited since, but its alarm just fired.
+ sqlx::query!(
+ r#"
+ INSERT INTO calendar_events (
+ id, owner_id, source_link_id, ical_uid, title,
+ starts_at, ends_at, canonical_source_kind,
+ canonical_source_updated_at, updated_at, last_reminder_fired_at
+ )
+ VALUES (
+ $1, $2, $3, '[email protected]', 'Reminded event',
+ now(), now() + interval '1 hour', 'google', now(),
+ now() - interval '10 days', now()
+ )
+ "#,
+ reminded_id,
+ owner_id,
+ link_id,
+ )
+ .execute(&pool)
+ .await?;
+ // Edited more recently than the reminded event, no alarm fired.
+ sqlx::query!(
+ r#"
+ INSERT INTO calendar_events (
+ id, owner_id, source_link_id, ical_uid, title,
+ starts_at, ends_at, canonical_source_kind,
+ canonical_source_updated_at, updated_at
+ )
+ VALUES (
+ $1, $2, $3, '[email protected]', 'Edited event',
+ now(), now() + interval '1 hour', 'google', now(),
+ now() - interval '1 day'
+ )
+ "#,
+ edited_id,
+ owner_id,
+ link_id,
+ )
+ .execute(&pool)
+ .await?;
+
+ let items = cursor_soup(
+ &pool,
+ SimpleSortRequest {
+ limit: 10,
+ cursor: SimpleSortQuery::NoFilter(Query::Sort(SimpleSortMethod::UpdatedAt, ())),
+ user_id: MacroUserIdStr::parse_from_str(owner_id)?,
+ },
+ )
+ .await?;
+
+ let ids: Vec<Uuid> = items
+ .iter()
+ .map(|item| match item {
+ SoupItem::CalendarEvent(event) => event.id,
+ other => panic!("unexpected soup item: {other:?}"),
+ })
+ .collect();
+ assert_eq!(ids, vec![reminded_id, edited_id]);
+ assert!(matches!(
+ &items[0],
+ SoupItem::CalendarEvent(event) if event.last_reminder_fired_at.is_some()
+ ));
+ Ok(())
+}
diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index 1622ec8f20..0584c40989 100644
--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -138,7 +138,7 @@ static GROUPED_CALENDAR_EVENT_TOP_CLAUSE: &str = r#"
CASE $2
WHEN 'created_at' THEN event.created_at
WHEN 'viewed_at' THEN '1970-01-01 00:00:00+00'::timestamptz
- ELSE event.updated_at
+ ELSE GREATEST(event.updated_at, event.last_reminder_fired_at)
END::timestamptz as sort_ts,
NULL::text as project_id,
'CALENDAR_EVENT'::property_entity_type as property_entity_type
@@ -461,6 +461,7 @@ static GROUPED_CALENDAR_EVENT_DETAIL_CLAUSE: &str = r#"
'isReadOnly', event.is_read_only,
'createdAt', event.created_at,
'updatedAt', event.updated_at,
+ 'lastReminderFiredAt', event.last_reminder_fired_at,
'extra', NULL
) as "calendar_event",
gi.group_key as "group_key",
diff --git a/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs b/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
index 31c002107b..ac31a8c616 100644
--- a/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/grouping/test.rs
@@ -404,6 +404,95 @@ async fn tagged_calendar_event_participates_in_grouped_property_soup(
Ok(())
}
+/// A fired reminder counts as the event's latest activity: the grouped
+/// recency sort must place the event at its delivery time, not at the older
+/// Google last-modified time that made reminder rows surface in the past.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn grouped_recency_sort_uses_reminder_delivery_time(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ const OWNER_ID: &str = "macro|[email protected]";
+ let link_id = uuid::Uuid::now_v7();
+ let reminded_id = uuid::Uuid::now_v7();
+ let edited_id = uuid::Uuid::now_v7();
+ sqlx::query!(
+ r#"
+ INSERT INTO email_links (
+ id, macro_id, fusionauth_user_id, email_address, provider
+ )
+ VALUES ($1, $2, $2, '[email protected]', 'GMAIL')
+ "#,
+ link_id,
+ OWNER_ID,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO calendar_events (
+ id, owner_id, source_link_id, ical_uid, title,
+ starts_at, ends_at, canonical_source_kind,
+ canonical_source_updated_at, updated_at, last_reminder_fired_at
+ )
+ VALUES (
+ $1, $2, $3, '[email protected]', 'Reminded event',
+ now(), now() + interval '1 hour', 'google', now(),
+ now() - interval '10 days', now()
+ )
+ "#,
+ reminded_id,
+ OWNER_ID,
+ link_id,
+ )
+ .execute(&pool)
+ .await?;
+ sqlx::query!(
+ r#"
+ INSERT INTO calendar_events (
+ id, owner_id, source_link_id, ical_uid, title,
+ starts_at, ends_at, canonical_source_kind,
+ canonical_source_updated_at, updated_at
+ )
+ VALUES (
+ $1, $2, $3, '[email protected]', 'Edited event',
+ now(), now() + interval '1 hour', 'google', now(),
+ now() - interval '1 day'
+ )
+ "#,
+ edited_id,
+ OWNER_ID,
+ link_id,
+ )
+ .execute(&pool)
+ .await?;
+
+ let user_id = MacroUserIdStr::parse_from_str(OWNER_ID).unwrap();
+ let ids: Vec<uuid::Uuid> = expanded_dynamic_cursor_soup_grouped(
+ &pool,
+ GroupedDynamicCursorArgs {
+ user_id: user_id.copied(),
+ limit: 50,
+ cursor: Query::Sort(
+ SimpleSortMethod::ViewedUpdated,
+ EntityFilterAst::mock_empty(),
+ ),
+ exclude_frecency: false,
+ grouping: GroupingConfig {
+ field: GroupByField::EntityType,
+ group_key: None,
+ per_group_limit: None,
+ },
+ },
+ )
+ .await?
+ .filter(|item| matches!(item.item, models_soup::item::SoupItem::CalendarEvent(_)))
+ .map(|item| item.item.id())
+ .collect();
+
+ assert_eq!(ids, vec![reminded_id, edited_id]);
+ Ok(())
+}
+
/// Regression: when a filter makes an arm of the Combined UNION impossible,
/// the remaining arms must still type-align. Postgres resolves UNION column
/// types pairwise left-to-right, and untyped `NULL`s across two arms resolve
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 56e04a30d9..1de474072d 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -7020,6 +7020,10 @@ export type SoupCalendarEventSoupPropertiesField = {
* Whether the selected canonical source is read-only.
*/
isReadOnly: boolean;
+ /**
+ * When this event's most recent reminder notification was delivered.
+ */
+ lastReminderFiredAt?: string | null;
/**
* Optional location label.
*/
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 12d504ca64..90e9d25dce 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -22915,6 +22915,11 @@
"type": "boolean",
"description": "Whether the selected canonical source is read-only."
},
+ "lastReminderFiredAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When this event's most recent reminder notification was delivered."
+ },
"location": {
"type": ["string", "null"],
"description": "Optional location label."