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.

perf(calendar): read the team out-of-office overlay through teammates (#8689)

gbirman0f0124bcfa61
diff --git a/.sqlx/query-78cc9d60c67aab67e3084408015e543b9abc4ee8716ab68991e4d3561b983fe2.json b/.sqlx/query-78cc9d60c67aab67e3084408015e543b9abc4ee8716ab68991e4d3561b983fe2.json
new file mode 100644
index 0000000000..8e4e680e23
--- /dev/null
+++ b/.sqlx/query-78cc9d60c67aab67e3084408015e543b9abc4ee8716ab68991e4d3561b983fe2.json
@@ -0,0 +1,57 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH teammates AS MATERIALIZED (\n SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id\n WHERE viewer.user_id=$1 AND teammate.user_id<>$1\n )\n SELECT owner_id AS \"owner_id!\", event_id AS \"event_id!\", ical_uid AS \"ical_uid!\",\n occurrence_key AS \"occurrence_key!\", title AS \"title?\", time AS \"time!\"\n FROM (\n SELECT DISTINCT ON (event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey')\n event.owner_id, event.id AS event_id, event.ical_uid,\n occurrence.value->>'occurrenceKey' AS occurrence_key,\n CASE WHEN sharing.sharing='all'\n THEN COALESCE(exception.value->>'title',source.normalized_payload->'event'->>'title')\n END AS title,\n occurrence.value->'time' AS time\n FROM teammates\n JOIN calendar_accounts account ON account.owner_id=teammates.user_id\n AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n JOIN calendar_event_sources source ON source.account_id=account.id\n AND source.event_type='out_of_office'\n AND source.normalized_payload->'event'->>'eventType'='out_of_office'\n JOIN calendar_events event ON event.id=source.event_id AND event.owner_id=account.owner_id\n JOIN calendars calendar ON calendar.id=source.calendar_id AND calendar.is_primary\n AND NOT calendar.is_deleted AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n LEFT JOIN calendar_team_sharing sharing ON sharing.user_id=event.owner_id\n CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') occurrence(value)\n LEFT JOIN LATERAL (\n SELECT candidate.value FROM jsonb_array_elements(source.normalized_payload->'overrides') candidate(value)\n WHERE candidate.value->>'recurrenceId'=occurrence.value->>'recurrenceId'\n LIMIT 1\n ) exception ON true\n WHERE COALESCE(sharing.sharing,'busy_only')<>'none'\n AND source.provider_access_role = calendar.access_role\n AND source.normalized_payload->'event'->>'visibility' IN ('default','public')\n AND COALESCE(exception.value->>'visibility','default') IN ('default','public')\n AND source.normalized_payload->'event'->>'status'<>'cancelled'\n AND COALESCE(exception.value->>'status','confirmed')<>'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean,false)\n AND (\n (occurrence.value->'time'->>'kind'='timed'\n AND (occurrence.value->'time'->>'endsAt')::timestamptz>(occurrence.value->'time'->>'startsAt')::timestamptz\n AND (occurrence.value->'time'->>'startsAt')::timestamptz<$3\n AND (occurrence.value->'time'->>'endsAt')::timestamptz>$2)\n OR (occurrence.value->'time'->>'kind'='allDay'\n AND (occurrence.value->'time'->>'startDate')::date<$5\n AND (occurrence.value->'time'->>'endDate')::date>$4)\n )\n ORDER BY event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey',source.source_updated_at DESC,source.id DESC\n ) sources\n ORDER BY COALESCE((time->>'startsAt')::timestamptz,(time->>'startDate')::date::timestamp AT TIME ZONE 'UTC'),event_id,occurrence_key\n LIMIT $6\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_id!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "event_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "ical_uid!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "occurrence_key!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "title?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "time!",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Timestamptz",
+ "Timestamptz",
+ "Date",
+ "Date",
+ "Int8"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ null,
+ null,
+ null
+ ]
+ },
+ "hash": "78cc9d60c67aab67e3084408015e543b9abc4ee8716ab68991e4d3561b983fe2"
+}
diff --git a/.sqlx/query-9e1ae17b9304f7cfd5e102fafde29a567e00c33e110104de975d847ba207e483.json b/.sqlx/query-9e1ae17b9304f7cfd5e102fafde29a567e00c33e110104de975d847ba207e483.json
deleted file mode 100644
index 47328322ce..0000000000
--- a/.sqlx/query-9e1ae17b9304f7cfd5e102fafde29a567e00c33e110104de975d847ba207e483.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT owner_id AS \"owner_id!\", event_id AS \"event_id!\", ical_uid AS \"ical_uid!\",\n occurrence_key AS \"occurrence_key!\", title AS \"title?\", time AS \"time!\"\n FROM (\n SELECT DISTINCT ON (event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey')\n event.owner_id, event.id AS event_id, event.ical_uid,\n occurrence.value->>'occurrenceKey' AS occurrence_key,\n CASE WHEN sharing.sharing='all'\n THEN COALESCE(exception.value->>'title',source.normalized_payload->'event'->>'title')\n END AS title,\n occurrence.value->'time' AS time\n FROM calendar_event_sources source\n JOIN calendar_events event ON event.id=source.event_id\n JOIN calendars calendar ON calendar.id=source.calendar_id AND calendar.is_primary\n AND NOT calendar.is_deleted AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL\n AND calendar.snapshot_normalization_version >= 1\n JOIN calendar_accounts account ON account.id=source.account_id\n AND account.owner_id=event.owner_id\n AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL\n AND account.last_synced_at > now() - interval '15 minutes'\n LEFT JOIN calendar_team_sharing sharing ON sharing.user_id=event.owner_id\n CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') occurrence(value)\n LEFT JOIN LATERAL (\n SELECT candidate.value FROM jsonb_array_elements(source.normalized_payload->'overrides') candidate(value)\n WHERE candidate.value->>'recurrenceId'=occurrence.value->>'recurrenceId'\n LIMIT 1\n ) exception ON true\n WHERE event.owner_id IN (\n SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id\n WHERE viewer.user_id=$1 AND teammate.user_id<>$1\n )\n AND COALESCE(sharing.sharing,'busy_only')<>'none'\n AND source.provider_access_role = calendar.access_role\n AND source.normalized_payload->'event'->>'eventType'='out_of_office'\n AND source.normalized_payload->'event'->>'visibility' IN ('default','public')\n AND COALESCE(exception.value->>'visibility','default') IN ('default','public')\n AND source.normalized_payload->'event'->>'status'<>'cancelled'\n AND COALESCE(exception.value->>'status','confirmed')<>'cancelled'\n AND NOT COALESCE((occurrence.value->>'isCancelled')::boolean,false)\n AND (\n (occurrence.value->'time'->>'kind'='timed'\n AND (occurrence.value->'time'->>'endsAt')::timestamptz>(occurrence.value->'time'->>'startsAt')::timestamptz\n AND (occurrence.value->'time'->>'startsAt')::timestamptz<$3\n AND (occurrence.value->'time'->>'endsAt')::timestamptz>$2)\n OR (occurrence.value->'time'->>'kind'='allDay'\n AND (occurrence.value->'time'->>'startDate')::date<$5\n AND (occurrence.value->'time'->>'endDate')::date>$4)\n )\n ORDER BY event.owner_id,event.ical_uid,occurrence.value->>'occurrenceKey',source.source_updated_at DESC,source.id DESC\n ) sources\n ORDER BY COALESCE((time->>'startsAt')::timestamptz,(time->>'startDate')::date::timestamp AT TIME ZONE 'UTC'),event_id,occurrence_key\n LIMIT $6\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "owner_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "event_id!",
- "type_info": "Uuid"
- },
- {
- "ordinal": 2,
- "name": "ical_uid!",
- "type_info": "Text"
- },
- {
- "ordinal": 3,
- "name": "occurrence_key!",
- "type_info": "Text"
- },
- {
- "ordinal": 4,
- "name": "title?",
- "type_info": "Text"
- },
- {
- "ordinal": 5,
- "name": "time!",
- "type_info": "Jsonb"
- }
- ],
- "parameters": {
- "Left": [
- "Text",
- "Timestamptz",
- "Timestamptz",
- "Date",
- "Date",
- "Int8"
- ]
- },
- "nullable": [
- false,
- false,
- false,
- null,
- null,
- null
- ]
- },
- "hash": "9e1ae17b9304f7cfd5e102fafde29a567e00c33e110104de975d847ba207e483"
-}
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index f2ed141911..53783140ca 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -144,6 +144,12 @@ reminder dispatch, team availability, and provider/Postgres persistence.
`myRole` there (`ToolEventRole::of`), so the agent can ask or pick by inbox.
- Preserve the conservative OOO refresh hint on write outcomes and sync reports;
its contract is in [team sharing](../../docs/design/calendar-team-sharing.md).
+- The team out-of-office overlay (`src/outbound/pg_team/ooo.rs`) starts from
+ the viewer's teammates and reaches sources through
+ `calendar_event_sources_out_of_office_idx` on the source's typed
+ `event_type`. Filtering on the payload's `eventType` alone makes Postgres
+ unpack every source on every primary calendar in the tenant (about 1.8 s per
+ call in production before October 2026).
## Related
diff --git a/crates/calendar_events/src/outbound/pg/test.rs b/crates/calendar_events/src/outbound/pg/test.rs
index 20e53dc776..c7ba5ea2dd 100644
--- a/crates/calendar_events/src/outbound/pg/test.rs
+++ b/crates/calendar_events/src/outbound/pg/test.rs
@@ -5359,6 +5359,47 @@ async fn team_out_of_office_shows_busy_only_status_without_its_title(pool: PgPoo
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn team_out_of_office_reads_each_sources_own_event_type(pool: PgPool) {
+ let viewer = "macro|[email protected]";
+ let teammate = "macro|[email protected]";
+ insert_team(&pool, viewer, &[viewer, teammate]).await;
+ let link = insert_link(&pool, teammate).await;
+ let repo = PgCalendarRepository::new(pool.clone());
+ let provider = provider_ids(&repo, link).await;
+ repo.upsert_event_fixture(ooo_upsert(
+ teammate,
+ link,
+ provider,
+ "Parental leave",
+ ))
+ .await
+ .unwrap();
+ // The entity's stored type follows its canonical source, which can be a
+ // non-out-of-office copy of the same event; the primary calendar's own
+ // source still says out of office.
+ sqlx::query!(
+ "UPDATE calendar_events SET event_type = 'default' WHERE owner_id = $1",
+ teammate,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ enable_team_details(&repo, &[teammate]).await;
+
+ let rows = repo
+ .list_team_out_of_office(viewer, july_2026_range(), 100)
+ .await
+ .unwrap();
+
+ assert_eq!(rows.len(), 2);
+ assert!(
+ rows.iter()
+ .all(|row| row.owner_id == teammate && row.title.as_deref() == Some("Parental leave"))
+ );
+}
+
fn shift_upsert_days(upsert: &mut CalendarEventUpsert, days: i64) {
let delta = Duration::days(days);
if let EventTime::Timed {
diff --git a/crates/calendar_events/src/outbound/pg_team/ooo.rs b/crates/calendar_events/src/outbound/pg_team/ooo.rs
index 48d4893849..aeece1ebeb 100644
--- a/crates/calendar_events/src/outbound/pg_team/ooo.rs
+++ b/crates/calendar_events/src/outbound/pg_team/ooo.rs
@@ -11,7 +11,16 @@ pub(in crate::outbound) async fn list_team_out_of_office(
range: OccurrenceRange,
limit: u16,
) -> Result<Vec<TeamOutOfOffice>, Report> {
+ // Teammates drive the plan: their fresh accounts, then only those
+ // accounts' out-of-office sources through the partial index on the
+ // source's typed event_type, which every write sets from the same value as
+ // the payload's eventType. Unpacking every primary calendar's payloads
+ // first made each call scan the whole tenant to return a handful of rows.
let rows = sqlx::query!(r#"
+ WITH teammates AS MATERIALIZED (
+ SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id
+ WHERE viewer.user_id=$1 AND teammate.user_id<>$1
+ )
SELECT owner_id AS "owner_id!", event_id AS "event_id!", ical_uid AS "ical_uid!",
occurrence_key AS "occurrence_key!", title AS "title?", time AS "time!"
FROM (
@@ -22,15 +31,17 @@ pub(in crate::outbound) async fn list_team_out_of_office(
THEN COALESCE(exception.value->>'title',source.normalized_payload->'event'->>'title')
END AS title,
occurrence.value->'time' AS time
- FROM calendar_event_sources source
- JOIN calendar_events event ON event.id=source.event_id
+ FROM teammates
+ JOIN calendar_accounts account ON account.owner_id=teammates.user_id
+ AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL
+ AND account.last_synced_at > now() - interval '15 minutes'
+ JOIN calendar_event_sources source ON source.account_id=account.id
+ AND source.event_type='out_of_office'
+ AND source.normalized_payload->'event'->>'eventType'='out_of_office'
+ JOIN calendar_events event ON event.id=source.event_id AND event.owner_id=account.owner_id
JOIN calendars calendar ON calendar.id=source.calendar_id AND calendar.is_primary
AND NOT calendar.is_deleted AND calendar.synced_at IS NOT NULL AND calendar.last_sync_error IS NULL
AND calendar.snapshot_normalization_version >= 1
- JOIN calendar_accounts account ON account.id=source.account_id
- AND account.owner_id=event.owner_id
- AND account.sync_status IN ('ready','syncing') AND account.last_sync_error IS NULL
- AND account.last_synced_at > now() - interval '15 minutes'
LEFT JOIN calendar_team_sharing sharing ON sharing.user_id=event.owner_id
CROSS JOIN LATERAL jsonb_array_elements(source.normalized_payload->'occurrences') occurrence(value)
LEFT JOIN LATERAL (
@@ -38,13 +49,8 @@ pub(in crate::outbound) async fn list_team_out_of_office(
WHERE candidate.value->>'recurrenceId'=occurrence.value->>'recurrenceId'
LIMIT 1
) exception ON true
- WHERE event.owner_id IN (
- SELECT teammate.user_id FROM team_user viewer JOIN team_user teammate ON teammate.team_id=viewer.team_id
- WHERE viewer.user_id=$1 AND teammate.user_id<>$1
- )
- AND COALESCE(sharing.sharing,'busy_only')<>'none'
+ WHERE COALESCE(sharing.sharing,'busy_only')<>'none'
AND source.provider_access_role = calendar.access_role
- AND source.normalized_payload->'event'->>'eventType'='out_of_office'
AND source.normalized_payload->'event'->>'visibility' IN ('default','public')
AND COALESCE(exception.value->>'visibility','default') IN ('default','public')
AND source.normalized_payload->'event'->>'status'<>'cancelled'
diff --git a/crates/macro_db_client/migrations/20261023222455_calendar_event_sources_out_of_office_idx.sql b/crates/macro_db_client/migrations/20261023222455_calendar_event_sources_out_of_office_idx.sql
new file mode 100644
index 0000000000..23c79afd55
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261023222455_calendar_event_sources_out_of_office_idx.sql
@@ -0,0 +1,11 @@
+-- no-transaction
+-- The team out-of-office overlay reads teammates' out-of-office sources by
+-- account. Without this index each call unpacked the payload of every source
+-- on every primary calendar in the tenant to find the few that qualify.
+-- Must stay a single statement: sqlx sends no-transaction migrations as one
+-- batch, and CONCURRENTLY cannot run inside a transaction. No IF NOT EXISTS:
+-- an interrupted concurrent build leaves an invalid index that a retry must
+-- not accept (see docs/design/outlook-email-support.md).
+CREATE INDEX CONCURRENTLY calendar_event_sources_out_of_office_idx
+ ON calendar_event_sources (account_id)
+ WHERE event_type = 'out_of_office';