Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calendar): make calendar caches refetch events a writable calendar organizes (#8858)
gbirman75f60eecca59
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex 144e53341f..7c9ab3dcc7 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -184,7 +184,12 @@ reminder dispatch, team availability, and provider/Postgres persistence.has other guests, as Google's own client does, so a solo event is one block.- `viewer_can` is viewer-relative, like an attendee's `is_self`: resolve it with`ActorInboxes::mark_event` and the copy's source link wherever a read path- marks the viewer, and never store it. Each connected inbox gets its own copy+ marks the viewer, and never store it. Calendar caches refresh only the+ events the change log lists, so a change to how capabilities are resolved+ leaves cached events with the old ones until each changes; ship it with a+ migration that logs an upsert for every event it affects, as+ `20261026184741_log_events_organized_by_a_writable_calendar.sql` does for+ events a writable calendar organizes. Each connected inbox gets its own copy(entity) of an event, written through that inbox's grant, so the viewerorganizes or attends a copy only as its inbox: another of their inboxes on thesame event lends it nothing, and only that inbox's row is `is_self`. Mutationsdiff --git a/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rs b/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rsindex 7a0f685e5e..9a6c8659f7 100644--- a/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rs+++ b/crates/calendar_events/src/outbound/pg/test/organizer_calendar.rs@@ -208,3 +208,119 @@ async fn a_calendar_the_inbox_only_reads_lends_its_copy_nothing(pool: PgPool) {[false]);}++/// The migration that logs events organized by a calendar their inbox+/// writes, so caches holding their pre-October-2026 capabilities refetch them.+const LOG_ORGANIZED_EVENTS: &str = include_str!(+ "../../../../../macro_db_client/migrations/20261026184741_log_events_organized_by_a_writable_calendar.sql"+);++/// A copy of another meeting on `calendar_id`, organized by `organizer`.+fn other_meeting(+ owner_id: &str,+ link_id: Uuid,+ provider: (Uuid, Uuid),+ uid: &str,+ organizer: &str,+ inbox_email: &str,+) -> CalendarEventUpsert {+ let mut copy = copy_of(owner_id, link_id, provider, organizer, inbox_email);+ copy.event.ical_uid = uid.to_string();+ copy.source.details_mut().provider_event_id = format!("provider-{uid}");+ copy+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn the_capability_backfill_logs_only_events_a_writable_calendar_organizes(pool: PgPool) {+ let owner_id = "macro|[email protected]";+ let link_id = insert_link(&pool, owner_id).await;+ let inbox_email = link_email(&pool, link_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (account_id, primary_id) = grant_and_provider_ids(&repo, link_id).await;+ let secondary_id = repo+ .upsert_calendar_fixture(account_id, secondary_calendar(SECONDARY, "owner"))+ .await+ .unwrap();+ let shared = "[email protected]";+ let shared_id = repo+ .upsert_calendar_fixture(account_id, secondary_calendar(shared, "reader"))+ .await+ .unwrap();+ let organized = repo+ .upsert_event_fixture(copy_of(+ owner_id,+ link_id,+ (account_id, secondary_id),+ SECONDARY,+ &inbox_email,+ ))+ .await+ .unwrap();+ repo.upsert_event_fixture(copy_of(+ owner_id,+ link_id,+ (account_id, primary_id),+ SECONDARY,+ &inbox_email,+ ))+ .await+ .unwrap();+ for (uid, calendar_id, organizer) in [+ ("[email protected]", primary_id, inbox_email.as_str()),+ ("[email protected]", shared_id, shared),+ (+ "[email protected]",+ primary_id,+ "[email protected]",+ ),+ ] {+ repo.upsert_event_fixture(other_meeting(+ owner_id,+ link_id,+ (account_id, calendar_id),+ uid,+ organizer,+ &inbox_email,+ ))+ .await+ .unwrap();+ }+ let before = sqlx::query_scalar!(+ "SELECT seq FROM calendar_change_counters WHERE link_id = $1",+ link_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();++ sqlx::raw_sql(LOG_ORGANIZED_EVENTS)+ .execute(&pool)+ .await+ .unwrap();++ let logged = sqlx::query!(+ r#"+ SELECT seq, kind, event_id+ FROM calendar_change_log+ WHERE link_id = $1 AND seq > $2+ ORDER BY seq+ "#,+ link_id,+ before,+ )+ .fetch_all(&pool)+ .await+ .unwrap()+ .into_iter()+ .map(|row| (row.seq, row.kind, row.event_id))+ .collect::<Vec<_>>();+ assert_eq!(logged, [(before + 1, 1, Some(organized))]);+ let after = sqlx::query_scalar!(+ "SELECT seq FROM calendar_change_counters WHERE link_id = $1",+ link_id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(after, before + 1, "the counter covers the logged row");+}diff --git a/crates/macro_db_client/migrations/20261026184741_log_events_organized_by_a_writable_calendar.sql b/crates/macro_db_client/migrations/20261026184741_log_events_organized_by_a_writable_calendar.sqlnew file mode 100644index 0000000000..4d12e2bbe0--- /dev/null+++ b/crates/macro_db_client/migrations/20261026184741_log_events_organized_by_a_writable_calendar.sql@@ -0,0 +1,71 @@+-- no-transaction++-- Since October 2026 an inbox organizes an event whose organizer is a calendar+-- it can write, not only one whose organizer is its own address, so events+-- made on a secondary calendar gained organizer capabilities (viewerCan).+-- Clients holding a calendar cache refresh only the events the change log+-- lists, so log an upsert for each such event on its inbox's link and every+-- cache refetches it on its next sync. One read finds the events, then each+-- batch commits on its own with its counter locks taken in link order, as+-- every calendar write takes them, so no lock outlives a batch. A rerun after+-- a failure logs some events twice, which costs clients one more refetch.+-- Keep this file a single statement: COMMIT inside DO needs a top-level call.+DO $$+DECLARE+ batch_size CONSTANT integer := 1000;+ link_ids uuid[];+ event_ids uuid[];+ batch_start integer := 1;+ batch_end integer;+ link_batch record;+ last_seq bigint;+BEGIN+ SELECT COALESCE(array_agg(event.source_link_id ORDER BY event.source_link_id, event.id), '{}'),+ COALESCE(array_agg(event.id ORDER BY event.source_link_id, event.id), '{}')+ INTO link_ids, event_ids+ FROM calendar_events event+ JOIN email_links link ON link.id = event.source_link_id+ WHERE event.status <> 'cancelled'+ AND event.organizer_email IS NOT NULL+ AND lower(event.organizer_email) <> lower(link.email_address::text)+ AND EXISTS (+ SELECT 1+ FROM calendar_accounts account+ JOIN calendars calendar ON calendar.account_id = account.id+ WHERE account.email_link_id = link.id+ AND account.sync_status <> 'disabled'+ AND NOT calendar.is_deleted+ AND calendar.access_role IN ('owner', 'writer')+ AND lower(calendar.provider_calendar_id) = lower(event.organizer_email)+ );+ COMMIT;++ WHILE batch_start <= cardinality(event_ids) LOOP+ batch_end := least(batch_start + batch_size - 1, cardinality(event_ids));+ FOR link_batch IN+ SELECT batch.link_id, array_agg(batch.event_id ORDER BY batch.position) AS events+ FROM unnest(link_ids[batch_start:batch_end], event_ids[batch_start:batch_end])+ WITH ORDINALITY AS batch(link_id, event_id, position)+ GROUP BY batch.link_id+ ORDER BY batch.link_id+ LOOP+ INSERT INTO calendar_change_counters (link_id, seq)+ VALUES (link_batch.link_id, cardinality(link_batch.events))+ ON CONFLICT (link_id) DO UPDATE+ SET seq = calendar_change_counters.seq + EXCLUDED.seq,+ updated_at = now()+ RETURNING seq INTO last_seq;+ INSERT INTO calendar_change_log (link_id, seq, kind, event_id)+ SELECT link_batch.link_id,+ last_seq - cardinality(link_batch.events) + logged.position,+ 1,+ logged.event_id+ FROM unnest(link_batch.events) WITH ORDINALITY AS logged(event_id, position);+ END LOOP;+ COMMIT;+ batch_start := batch_end + 1;+ END LOOP;++ RAISE NOTICE 'logged % calendar events organized by a calendar their inbox writes',+ cardinality(event_ids);+END $$;