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): stop a deleted split Google series from coming back (#9417)

gbirmanc9f671c0ce1d
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
index 00571a1d8a..c4e6a8b3cb 100644
--- a/crates/calendar_events/AGENTS.md
+++ b/crates/calendar_events/AGENTS.md
@@ -335,6 +335,16 @@ reminder dispatch, team availability, and provider/Postgres persistence.
plain sentence for an event that is not the user's: `ReadCalendarEvent` and
`NameSearch` both give it, because models follow it more reliably than the
fields behind it.
+- A series Google split off another without moving it in time has the id
+ `<parent>_R<first start>`, a UID of its own and the parent's `created`; a
+ split that moved it gets an unrelated id. A change to a `_R` series' recurrence
+ answers with a new event, new id and UID at `sequence` + 1, and leaves the old
+ id, and every later `_R` slice of that parent, a cancelled tombstone Google
+ refuses to patch (`badRequest`). The entity follows the UID, so the echo lands
+ on a new entity: `delete_copy` retires the old id's source in the same request,
+ or the old entity keeps every occurrence until the tombstone syncs, and
+ `truncate_recurring_event` reads a tombstone as gone, so a delete from a copy
+ or later slice that has not synced yet retires it too.
- Copies of one meeting pair by `calendar_meeting_uid(ical_uid)`, not the raw
UID: Exchange gives a meeting it imports from an invitation its own UID that
wraps the original after `vCal-Uid`, and the SQL function unwraps it, so an
diff --git a/crates/calendar_events/src/domain/mutations/copy_writes.rs b/crates/calendar_events/src/domain/mutations/copy_writes.rs
index 4bf1ce6ec2..ba47130f3e 100644
--- a/crates/calendar_events/src/domain/mutations/copy_writes.rs
+++ b/crates/calendar_events/src/domain/mutations/copy_writes.rs
@@ -182,29 +182,52 @@ where
.map_err(provider_error)?,
};
match outcome {
- ProviderSeriesMutationOutcome::Applied(upsert) => self
- .persist_echo(target.actor.as_ref(), *upsert)
- .await
- .map(|_| ()),
+ ProviderSeriesMutationOutcome::Applied(upsert) => {
+ // Google answers a recurrence change to a series split off
+ // another (an `_R…` id) with a new event under a new id and
+ // UID. The echo lands on a new entity, so the source of the
+ // id that no longer exists has to go with it, or the old
+ // entity stays on the calendar until its tombstone syncs.
+ let replacement = upsert.source.details().provider_event_id.clone();
+ self.persist_echo(target.actor.as_ref(), *upsert).await?;
+ if replacement == target.master_provider_event_id() {
+ return Ok(());
+ }
+ tracing::info!(
+ event_id = %target.event_id,
+ provider_event_id = target.master_provider_event_id(),
+ replacement,
+ "the provider replaced the series, retiring its old source"
+ );
+ self.retire_deleted_series(target).await
+ }
// Either the deletion removed the series or it was already
// gone; retiring the local source converges both.
ProviderSeriesMutationOutcome::SeriesDeleted | ProviderSeriesMutationOutcome::Gone => {
- // Retiring a recurring master's source also retires its
- // expanded instances, so this reports several events; each
- // announces its own fate.
- let retired = self
- .repository
- .remove_provider_source(
- target.account_id,
- target.calendar_id,
- target.master_provider_event_id(),
- )
- .await
- .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;
- self.announce_retirements(&target.owner_id, target.email_link_id, retired)
- .await;
- Ok(())
+ self.retire_deleted_series(target).await
}
}
}
+
+ /// Retire the source of a series the provider no longer has under the id
+ /// `target` addresses. Retiring a recurring master's source also retires
+ /// its expanded instances, so this reports several events; each announces
+ /// its own fate.
+ async fn retire_deleted_series(
+ &self,
+ target: &CalendarEventMutationTarget,
+ ) -> Result<(), CalendarMutationError> {
+ let retired = self
+ .repository
+ .remove_provider_source(
+ target.account_id,
+ target.calendar_id,
+ target.master_provider_event_id(),
+ )
+ .await
+ .map_err(|error| CalendarMutationError::PersistFailed(format!("{error:?}")))?;
+ self.announce_retirements(&target.owner_id, target.email_link_id, retired)
+ .await;
+ Ok(())
+ }
}
diff --git a/crates/calendar_events/src/domain/mutations/test.rs b/crates/calendar_events/src/domain/mutations/test.rs
index acafe305aa..db4dd4edde 100644
--- a/crates/calendar_events/src/domain/mutations/test.rs
+++ b/crates/calendar_events/src/domain/mutations/test.rs
@@ -188,6 +188,7 @@ struct FakeRepo {
visible_calendars: Vec<VisibleCalendar>,
fail_list_visible: bool,
fail_owned_inboxes: bool,
+ fail_remove_source: bool,
/// Guest policies recorded after the provider refused an invite.
recorded_guest_policies: Arc<Mutex<Vec<(Uuid, GuestPolicy)>>>,
/// Stored details a guest's update is compared against.
@@ -226,6 +227,7 @@ impl Default for FakeRepo {
visible_calendars: Vec::new(),
fail_list_visible: false,
fail_owned_inboxes: false,
+ fail_remove_source: false,
recorded_guest_policies: Default::default(),
event_details: None,
details_requests: Default::default(),
@@ -618,6 +620,9 @@ impl CalendarRepository for FakeRepo {
calendar_id: Uuid,
provider_event_id: &str,
) -> Result<Vec<RetiredCalendarEvent>, rootcause::Report> {
+ if self.fail_remove_source {
+ return Err(rootcause::report!("the source could not be removed"));
+ }
self.removed_sources.lock().unwrap().push((
account_id,
calendar_id,
@@ -653,6 +658,8 @@ struct FakeProvider {
invited_as: Arc<Mutex<Vec<Vec<String>>>>,
/// Whether reading a copy back finds it gone.
refresh_gone: bool,
+ /// The id Google answers a change to a split series' recurrence with.
+ series_replaced_by: Option<&'static str>,
/// The title a copy read back still has because Google has yet to carry
/// the write to it, with a provider stamp older than the write's.
refresh_stale: Option<&'static str>,
@@ -673,10 +680,22 @@ impl FakeProvider {
imported: Arc::new(Mutex::new(Vec::new())),
invited_as: Arc::new(Mutex::new(Vec::new())),
refresh_gone: false,
+ series_replaced_by: None,
refresh_stale: None,
}
}
+ /// A series echo, which names the master it was read from.
+ fn series_echo(
+ &self,
+ target: &ProviderCalendarTarget,
+ master_provider_event_id: &str,
+ ) -> CalendarEventUpsert {
+ let mut upsert = self.echo(target);
+ upsert.source.details_mut().provider_event_id = master_provider_event_id.to_string();
+ upsert
+ }
+
fn echo(&self, target: &ProviderCalendarTarget) -> CalendarEventUpsert {
let mut upsert = echo_upsert(&target.owner_id);
upsert.source.details_mut().email_link_id = target.email_link_id;
@@ -900,7 +919,9 @@ impl CalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderSeriesMutationOutcome::Gone,
- _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(target))),
+ _ => ProviderSeriesMutationOutcome::Applied(Box::new(
+ self.series_echo(target, master_provider_event_id),
+ )),
})
}
@@ -919,7 +940,10 @@ impl CalendarMutationProvider for FakeProvider {
}
Ok(match self.behavior {
FakeProviderBehavior::Gone => ProviderSeriesMutationOutcome::SeriesDeleted,
- _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.echo(target))),
+ _ => ProviderSeriesMutationOutcome::Applied(Box::new(self.series_echo(
+ target,
+ self.series_replaced_by.unwrap_or(master_provider_event_id),
+ ))),
})
}
@@ -2829,6 +2853,105 @@ async fn scoped_deletions_reshape_or_retire_the_series() {
.await
.unwrap();
assert_eq!(upserts.lock().unwrap().len(), 2);
+ assert!(
+ removed.lock().unwrap().is_empty(),
+ "a series that keeps its id keeps its source"
+ );
+}
+
+/// Google answers a change to the recurrence of a series split off another
+/// with a new event under a new id and UID, so the echo lands on a new entity.
+/// The old id's source goes with it, or its entity stays on the calendar,
+/// future occurrences included, until the tombstone syncs.
+#[tokio::test]
+async fn truncation_google_answers_with_a_new_series_retires_the_old_source() {
+ let target = mutation_target(false);
+ let (account_id, calendar_id) = (target.account_id, target.calendar_id);
+ let event_id = target.event_id;
+ let repo = FakeRepo {
+ mutation_target: Some(target),
+ retired_events: vec![RetiredCalendarEvent {
+ event_id,
+ owner_id: "macro|[email protected]".to_string(),
+ deleted: true,
+ team_ooo_changed: false,
+ }],
+ ..FakeRepo::default()
+ };
+ let upserts = repo.upserts.clone();
+ let removed = repo.removed_sources.clone();
+ let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ provider.series_replaced_by = Some("replacement-id");
+ let broker = RecordingEventBroker::default();
+ let svc = service_with_broker(repo, provider, FakeTokens::ok(), broker.clone());
+
+ svc.delete_event(
+ "macro|user",
+ event_id,
+ None,
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: "2026-08-12T09:00:00+00:00".to_string(),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ upserts.lock().unwrap()[0]
+ .source
+ .details()
+ .provider_event_id,
+ "replacement-id",
+ "what is left of the series is stored under Google's new id"
+ );
+ assert_eq!(
+ removed.lock().unwrap().as_slice(),
+ [(account_id, calendar_id, "master-id".to_string())],
+ "the id that no longer exists loses its source"
+ );
+ assert!(
+ broker
+ .published()
+ .iter()
+ .any(|event| event.key == event_id.to_string()
+ && event.payload.get("calendar_event.deleted").is_some()),
+ "the old entity's retirement is announced"
+ );
+}
+
+/// The series changed at the provider, so the caller hears that the stale row
+/// is still there, as for any other write that reached the provider.
+#[tokio::test]
+async fn a_replaced_series_whose_old_source_stays_reports_the_failure() {
+ let repo = FakeRepo {
+ mutation_target: Some(mutation_target(false)),
+ fail_remove_source: true,
+ ..FakeRepo::default()
+ };
+ let upserts = repo.upserts.clone();
+ let mut provider = FakeProvider::new(FakeProviderBehavior::Echo);
+ provider.series_replaced_by = Some("replacement-id");
+
+ let result = service(repo, provider, FakeTokens::ok())
+ .delete_event(
+ "macro|user",
+ Uuid::now_v7(),
+ None,
+ CalendarDeletionScope::ThisAndFollowing {
+ recurrence_id: "2026-08-12T09:00:00+00:00".to_string(),
+ },
+ )
+ .await;
+
+ assert!(matches!(
+ result,
+ Err(CalendarMutationError::PersistFailed(_))
+ ));
+ assert_eq!(
+ upserts.lock().unwrap().len(),
+ 1,
+ "what is left of the series is stored first"
+ );
}
#[tokio::test]
diff --git a/crates/calendar_events/src/outbound/google.rs b/crates/calendar_events/src/outbound/google.rs
index 53e8d81e82..300c0c3b17 100644
--- a/crates/calendar_events/src/outbound/google.rs
+++ b/crates/calendar_events/src/outbound/google.rs
@@ -1356,6 +1356,16 @@ impl<G: GoogleRequestGate> CalendarMutationProvider for GoogleCalendarClient<G>
else {
return Ok(ProviderSeriesMutationOutcome::Gone);
};
+ // Google answers a read of a deleted or replaced series with its
+ // tombstone and refuses any change to it, so there is nothing left to
+ // truncate. The caller retires the source, as for a missing series.
+ if master.status.as_deref() == Some("cancelled") {
+ tracing::info!(
+ master_provider_event_id,
+ "the series is a tombstone, nothing to truncate"
+ );
+ return Ok(ProviderSeriesMutationOutcome::Gone);
+ }
// Removing everything from the first occurrence onward is a series
// deletion, matching Google Calendar's own behavior.
let master_start = google_time(&master).ok().map(|time| event_start_of(&time));
diff --git a/crates/calendar_events/src/outbound/google/test.rs b/crates/calendar_events/src/outbound/google/test.rs
index fcc372e2d7..93b9c6bf76 100644
--- a/crates/calendar_events/src/outbound/google/test.rs
+++ b/crates/calendar_events/src/outbound/google/test.rs
@@ -3,6 +3,7 @@ use super::*;
mod all_day;
mod import;
mod points;
+mod truncate;
#[test]
fn calendar_access_role_is_reflected_on_mapped_events() {
diff --git a/crates/calendar_events/src/outbound/google/test/truncate.rs b/crates/calendar_events/src/outbound/google/test/truncate.rs
new file mode 100644
index 0000000000..b00f8f0c22
--- /dev/null
+++ b/crates/calendar_events/src/outbound/google/test/truncate.rs
@@ -0,0 +1,210 @@
+#![cfg(feature = "inbound")]
+
+use super::*;
+use axum::{
+ Json, Router,
+ extract::{Path, State},
+ http::StatusCode as AxumStatus,
+ routing::get,
+};
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+};
+
+/// An id Google gives a series split off another without moving it in time.
+const SPLIT_SERIES: &str = "base_R20260921T140000";
+/// The id Google moves that series to when its recurrence changes.
+const REPLACEMENT: &str = "freshid";
+const CUTOFF: &str = "2026-11-02T15:00:00+00:00";
+
+fn series(id: &str, status: &str, sequence: u32, recurrence: &str) -> serde_json::Value {
+ serde_json::json!({
+ "id": id,
+ "iCalUID": format!("{id}@google.com"),
+ "status": status,
+ "eventType": "default",
+ "summary": "Weekly sync",
+ "sequence": sequence,
+ "start": {"dateTime": "2026-09-21T10:00:00-04:00", "timeZone": "America/New_York"},
+ "end": {"dateTime": "2026-09-21T11:00:00-04:00", "timeZone": "America/New_York"},
+ "recurrence": [recurrence],
+ "created": "2026-09-04T19:13:09.000Z",
+ "updated": "2026-11-02T14:52:50.000Z"
+ })
+}
+
+/// Google's calendar, holding each event by id, with what each patch sent.
+#[derive(Clone, Default)]
+struct Remote {
+ events: Arc<Mutex<HashMap<String, serde_json::Value>>>,
+ patches: Arc<Mutex<Vec<(String, serde_json::Value)>>>,
+}
+
+impl Remote {
+ fn holding(events: Vec<serde_json::Value>) -> Self {
+ let remote = Self::default();
+ for event in events {
+ remote
+ .events
+ .lock()
+ .unwrap()
+ .insert(event["id"].as_str().unwrap().to_string(), event);
+ }
+ remote
+ }
+}
+
+async fn read(
+ State(remote): State<Remote>,
+ Path(id): Path<String>,
+) -> (AxumStatus, Json<serde_json::Value>) {
+ match remote.events.lock().unwrap().get(&id) {
+ Some(event) => (AxumStatus::OK, Json(event.clone())),
+ None => (AxumStatus::NOT_FOUND, Json(serde_json::json!({}))),
+ }
+}
+
+/// As Google does: a change to a tombstone is refused, and a change to the
+/// recurrence of a split series moves it to a new id and UID, leaving a
+/// tombstone behind. Any other series takes the change in place.
+async fn patch(
+ State(remote): State<Remote>,
+ Path(id): Path<String>,
+ Json(body): Json<serde_json::Value>,
+) -> (AxumStatus, Json<serde_json::Value>) {
+ remote
+ .patches
+ .lock()
+ .unwrap()
+ .push((id.clone(), body.clone()));
+ let mut events = remote.events.lock().unwrap();
+ let Some(event) = events.get_mut(&id) else {
+ return (AxumStatus::NOT_FOUND, Json(serde_json::json!({})));
+ };
+ if event["status"] == "cancelled" {
+ return (
+ AxumStatus::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": {
+ "code": 400,
+ "message": "Bad Request",
+ "errors": [{ "reason": "badRequest" }]
+ }
+ })),
+ );
+ }
+ event["recurrence"] = body["recurrence"].clone();
+ if !id.contains("_R") {
+ return (AxumStatus::OK, Json(event.clone()));
+ }
+ let recurrence = body["recurrence"][0].as_str().unwrap().to_string();
+ event["status"] = serde_json::json!("cancelled");
+ let replacement = series(REPLACEMENT, "confirmed", 1, &recurrence);
+ events.insert(REPLACEMENT.to_string(), replacement.clone());
+ (AxumStatus::OK, Json(replacement))
+}
+
+async fn list() -> Json<serde_json::Value> {
+ Json(serde_json::json!({ "items": [] }))
+}
+
+async fn serve(remote: Remote) -> (GoogleCalendarClient<UnmeteredGate>, ProviderCalendarTarget) {
+ let app = Router::new()
+ .route("/calendars/primary/events", get(list))
+ .route("/calendars/primary/events/{id}", get(read).patch(patch))
+ .route("/calendars/primary/events/{id}/instances", get(list))
+ .with_state(remote);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let endpoint = format!("http://{}", listener.local_addr().unwrap());
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.unwrap();
+ });
+ let client = GoogleCalendarClient {
+ client: Client::new(),
+ gate: UnmeteredGate,
+ api_base: endpoint,
+ };
+ let range_start = DateTime::parse_from_rfc3339("2026-09-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ let target = ProviderCalendarTarget {
+ binding: None,
+ provider: crate::domain::models::CalendarProvider::Google,
+ observed_access_role: Some("owner".to_owned()),
+ owner_id: "macro|[email protected]".to_owned(),
+ email_link_id: Uuid::now_v7(),
+ account_id: Uuid::now_v7(),
+ calendar_id: Uuid::now_v7(),
+ provider_calendar_id: "primary".to_owned(),
+ is_read_only: false,
+ range: OccurrenceRange {
+ starts_at: range_start,
+ ends_at: range_start + chrono::Duration::days(180),
+ start_date: range_start.date_naive(),
+ end_date: range_start.date_naive() + chrono::Duration::days(180),
+ },
+ };
+ (client, target)
+}
+
+/// The prod sequence: the first truncation of a split series comes back as a
+/// new event, and the same delete again reaches the tombstone it left.
+#[tokio::test]
+async fn a_replaced_series_echoes_its_new_id_and_a_repeat_finds_it_gone() {
+ let remote = Remote::holding(vec![series(
+ SPLIT_SERIES,
+ "confirmed",
+ 0,
+ "RRULE:FREQ=WEEKLY;BYDAY=MO",
+ )]);
+ let (client, target) = serve(remote.clone()).await;
+
+ let first = client
+ .truncate_recurring_event("token", &target, SPLIT_SERIES, CUTOFF)
+ .await
+ .unwrap();
+ let ProviderSeriesMutationOutcome::Applied(echo) = first else {
+ panic!("the truncation should echo what is left of the series");
+ };
+ assert_eq!(echo.source.details().provider_event_id, REPLACEMENT);
+ assert_eq!(echo.event.ical_uid, format!("{REPLACEMENT}@google.com"));
+ assert_eq!(
+ echo.event.recurrence_lines,
+ ["RRULE:FREQ=WEEKLY;BYDAY=MO;UNTIL=20261102T145959Z"]
+ );
+
+ let repeat = client
+ .truncate_recurring_event("token", &target, SPLIT_SERIES, CUTOFF)
+ .await
+ .unwrap();
+ assert!(matches!(repeat, ProviderSeriesMutationOutcome::Gone));
+ assert_eq!(
+ remote.patches.lock().unwrap().len(),
+ 1,
+ "a tombstone is not patched: Google refuses it"
+ );
+}
+
+#[tokio::test]
+async fn a_plain_series_keeps_its_id_and_takes_a_repeat() {
+ let remote = Remote::holding(vec![series(
+ "plain",
+ "confirmed",
+ 0,
+ "RRULE:FREQ=WEEKLY;BYDAY=MO",
+ )]);
+ let (client, target) = serve(remote.clone()).await;
+
+ for _ in 0..2 {
+ let outcome = client
+ .truncate_recurring_event("token", &target, "plain", CUTOFF)
+ .await
+ .unwrap();
+ let ProviderSeriesMutationOutcome::Applied(echo) = outcome else {
+ panic!("a plain series survives truncation");
+ };
+ assert_eq!(echo.source.details().provider_event_id, "plain");
+ }
+ assert_eq!(remote.patches.lock().unwrap().len(), 2);
+}