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): retire a join request's notification when it is answered (#9256)
gbirman28ef4f26e778
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.mdindex dfc91bbb6c..72152f8a5f 100644--- a/crates/calendar_events/AGENTS.md+++ b/crates/calendar_events/AGENTS.md@@ -187,16 +187,21 @@ reminder dispatch, team availability, and provider/Postgres persistence.invitation under the meeting's UID, which a snapshot imported meanwhilewould take in. A declined requester may still add a copy. Nothing in thedomain retires the sharer's notification: opening the event marks it seen,- and two triggers on `calendar_events` running+ a trigger on `calendar_event_join_requests` running+ `delete_answered_join_request_notification` deletes it when anyone answers+ the request, and two triggers on `calendar_events` running`delete_calendar_event_join_request_notifications` delete it with the eventrow, or when the row turns `cancelled` (Outlook can keep a cancelledmeeting). That covers the ways a copy goes away listed for channel grants- above, and the delete reaches open clients through- `trg_notify_user_notification_deletes`. The notifier only queues, so a backlog- can deliver a notification after that cleanup; a `notification` insert trigger- skips it while the event is gone or cancelled, locking the row to decide in- order with a change in flight. The cancelled row keeps its requests, as it- keeps its grants, and a cancelled occurrence changes neither.+ above, and each delete reaches open clients through+ `trg_notify_user_notification_deletes`. An event can hold several open+ requests, so the answer's trigger matches the `requestId` in the notification's+ metadata, not the event alone. The notifier only queues, so a backlog can+ deliver a notification after that cleanup; a `notification` insert trigger+ skips it while the event is gone or cancelled or the request is no longer+ pending, locking the event and then the request to decide in order with a+ change in flight. The cancelled row keeps its requests, as it keeps its+ grants, and a cancelled occurrence changes neither.- Calendar mentions reach the agent as document mentions (`blockName``calendar`), but `ReadContent` and `ReadMetadata` need document access, whicha channel-shared event never grants. The agent reads a mentioned event withdiff --git a/crates/calendar_events/src/outbound/pg/test/join_requests.rs b/crates/calendar_events/src/outbound/pg/test/join_requests.rsindex 4f5a9a21d8..ab82db7f50 100644--- a/crates/calendar_events/src/outbound/pg/test/join_requests.rs+++ b/crates/calendar_events/src/outbound/pg/test/join_requests.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::join_requests::CalendarJoinRequestStatus;+use crate::domain::join_requests::{CalendarJoinRequest, CalendarJoinRequestStatus};use sqlx::postgres::PgListener;#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -127,47 +127,76 @@ async fn join_requests_open_once_and_resolve_once(pool: PgPool) {assert_eq!(repo.get_join_request(first.id).await.unwrap(), None);}-pub(super) const JOIN_REQUEST_NOTIFICATION: &str = "calendar_event_join_request";+const JOIN_REQUEST_NOTIFICATION: &str = "calendar_event_join_request";/// Store an unseen notification about `event_id`, as notification ingress does.-pub(super) async fn insert_notification(+async fn store_notification(pool: &PgPool,notification_event_type: &str,event_id: Uuid,- user_id: &str,+ metadata: serde_json::Value,+ recipients: &[&str],) -> Uuid {let id = Uuid::now_v7();let event_item_id = event_id.to_string();sqlx::query!(r#"INSERT INTO notification (- id, notification_event_type, event_item_id, event_item_type, service_sender+ id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)- VALUES ($1, $2, $3, 'calendar_event', 'document_storage_service')+ VALUES ($1, $2, $3, 'calendar_event', 'document_storage_service', $4)"#,id,notification_event_type,event_item_id,+ metadata,).execute(pool).await.unwrap();- sqlx::query!(- r#"- INSERT INTO user_notification (- user_id, notification_id, event_item_type, event_item_id, notification_event_type+ for user_id in recipients {+ sqlx::query!(+ r#"+ INSERT INTO user_notification (+ user_id, notification_id, event_item_type, event_item_id, notification_event_type+ )+ VALUES ($1, $2, 'calendar_event', $3, $4)+ "#,+ user_id,+ id,+ event_item_id,+ notification_event_type,)- VALUES ($1, $2, 'calendar_event', $3, $4)- "#,- user_id,- id,- event_item_id,- notification_event_type,+ .execute(pool)+ .await+ .unwrap();+ }+ id+}++/// The metadata `CalendarEventJoinRequestMetadata` stores for `request`.+fn join_request_metadata(request: &CalendarJoinRequest) -> serde_json::Value {+ serde_json::json!({+ "requestId": request.id,+ "eventId": request.event_id,+ "title": "Offsite",+ })+}++/// Store the notification about `request`, as notification ingress does.+pub(super) async fn insert_join_request_notification(+ pool: &PgPool,+ request: &CalendarJoinRequest,+ recipients: &[&str],+) -> Uuid {+ store_notification(+ pool,+ JOIN_REQUEST_NOTIFICATION,+ request.event_id,+ join_request_metadata(request),+ recipients,)- .execute(pool).await- .unwrap();- id}/// Whether the notification's recipient still has it.@@ -224,13 +253,25 @@ async fn a_join_request_notification_goes_with_the_last_copy_of_its_event(pool:)).await.unwrap();- repo.open_join_request(event_id, member_id, "[email protected]")+ let (request, _) = repo+ .open_join_request(event_id, member_id, "[email protected]")+ .await+ .unwrap();+ let (other_request, _) = repo+ .open_join_request(other_event_id, member_id, "[email protected]").await.unwrap();- let asked = insert_notification(&pool, JOIN_REQUEST_NOTIFICATION, event_id, sharer_id).await;- let reminder = insert_notification(&pool, "calendar_event_reminder", event_id, sharer_id).await;+ let asked = insert_join_request_notification(&pool, &request, &[sharer_id]).await;+ let reminder = store_notification(+ &pool,+ "calendar_event_reminder",+ event_id,+ serde_json::json!({}),+ &[sharer_id],+ )+ .await;let asked_elsewhere =- insert_notification(&pool, JOIN_REQUEST_NOTIFICATION, other_event_id, sharer_id).await;+ insert_join_request_notification(&pool, &other_request, &[sharer_id]).await;let mut listener = PgListener::connect_with(&pool).await.unwrap();listener.listen("notification_events").await.unwrap();@@ -245,12 +286,8 @@ async fn a_join_request_notification_goes_with_the_last_copy_of_its_event(pool:.await.unwrap();assert!(!recipient_holds(&pool, asked).await);- let delivered = tokio::time::timeout(std::time::Duration::from_secs(5), listener.recv())- .await- .expect("the notification's delete should be published")- .unwrap();assert_eq!(- serde_json::from_str::<serde_json::Value>(delivered.payload()).unwrap(),+ published_delete(&mut listener).await,serde_json::json!({"type": "user_notification_deletes","notificationId": asked,@@ -293,7 +330,7 @@ async fn a_cancelled_occurrence_keeps_the_join_request_notification_and_a_cancel.open_join_request(event_id, member_id, "[email protected]").await.unwrap();- let asked = insert_notification(&pool, JOIN_REQUEST_NOTIFICATION, event_id, sharer_id).await;+ let asked = insert_join_request_notification(&pool, &request, &[sharer_id]).await;// Deleting one occurrence refreshes the series without it: the sharer can// still add the guest to the rest.@@ -363,20 +400,18 @@ async fn removing_the_calendar_or_the_inbox_removes_join_request_notifications(p)).await.unwrap();- let on_disconnected_calendar = insert_notification(- &pool,- JOIN_REQUEST_NOTIFICATION,- disconnected_event_id,- sharer_id,- )- .await;- let on_removed_inbox = insert_notification(- &pool,- JOIN_REQUEST_NOTIFICATION,- removed_event_id,- sharer_id,- )- .await;+ let (disconnected_request, _) = repo+ .open_join_request(disconnected_event_id, member_id, "[email protected]")+ .await+ .unwrap();+ let (removed_request, _) = repo+ .open_join_request(removed_event_id, member_id, "[email protected]")+ .await+ .unwrap();+ let on_disconnected_calendar =+ insert_join_request_notification(&pool, &disconnected_request, &[sharer_id]).await;+ let on_removed_inbox =+ insert_join_request_notification(&pool, &removed_request, &[sharer_id]).await;repo.disconnect_provider_calendar(sharer_id, disconnected_link).await@@ -395,42 +430,71 @@ async fn removing_the_calendar_or_the_inbox_removes_join_request_notifications(p/// Notification ingress's insert, reporting whether the row was stored.async fn ingress_insert(executor: impl sqlx::PgExecutor<'_>,- event_id: Uuid,+ request: &CalendarJoinRequest,) -> Result<bool, sqlx::Error> {sqlx::query!(r#"INSERT INTO notification (- id, notification_event_type, event_item_id, event_item_type, service_sender+ id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)VALUES (- $1, 'calendar_event_join_request', $2, 'calendar_event', 'notification_service'+ $1, 'calendar_event_join_request', $2, 'calendar_event', 'notification_service', $3)ON CONFLICT (id) DO NOTHING"#,Uuid::now_v7(),- event_id.to_string(),+ request.event_id.to_string(),+ join_request_metadata(request),).execute(executor).await.map(|result| result.rows_affected() == 1)}-/// An event a sharer could be asked to join.-async fn shared_event(pool: &PgPool) -> Uuid {- let sharer_id = "macro|[email protected]";- let sharer_link = insert_link(pool, sharer_id).await;+const SHARER_ID: &str = "macro|[email protected]";+const MEMBER_ID: &str = "macro|[email protected]";+const OTHER_MEMBER_ID: &str = "macro|[email protected]";++/// A pending request to join an event a sharer shared.+async fn open_request(pool: &PgPool) -> CalendarJoinRequest {+ insert_user(pool, MEMBER_ID).await;+ let sharer_link = insert_link(pool, SHARER_ID).await;let repo = PgCalendarRepository::new(pool.clone());let provider = provider_ids(&repo, sharer_link).await;- repo.upsert_event_fixture(timed_upsert(- sharer_id,- sharer_link,- provider,- "[email protected]",- "Offsite",- 1,- ))- .await- .unwrap()+ let event_id = repo+ .upsert_event_fixture(timed_upsert(+ SHARER_ID,+ sharer_link,+ provider,+ "[email protected]",+ "Offsite",+ 1,+ ))+ .await+ .unwrap();+ repo.open_join_request(event_id, MEMBER_ID, "[email protected]")+ .await+ .unwrap()+ .0+}++/// A second member's pending request to join the event of `request`.+async fn another_open_request(pool: &PgPool, request: &CalendarJoinRequest) -> CalendarJoinRequest {+ insert_user(pool, OTHER_MEMBER_ID).await;+ PgCalendarRepository::new(pool.clone())+ .open_join_request(request.event_id, OTHER_MEMBER_ID, "[email protected]")+ .await+ .unwrap()+ .0+}++/// The next delete `trg_notify_user_notification_deletes` published.+async fn published_delete(listener: &mut PgListener) -> serde_json::Value {+ let delivered = tokio::time::timeout(std::time::Duration::from_secs(5), listener.recv())+ .await+ .expect("the notification's delete should be published")+ .unwrap();+ serde_json::from_str(delivered.payload()).unwrap()}async fn backend_pid(transaction: &mut Transaction<'_, Postgres>) -> i32 {@@ -474,8 +538,9 @@ async fn stored_notifications(pool: &PgPool) -> i64 {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_queued_join_request_notification_is_not_stored_after_its_event_went(pool: PgPool) {- let event_id = shared_event(&pool).await;- assert!(ingress_insert(&pool, event_id).await.unwrap());+ let request = open_request(&pool).await;+ let event_id = request.event_id;+ assert!(ingress_insert(&pool, &request).await.unwrap());sqlx::query!("UPDATE calendar_events SET status = 'cancelled' WHERE id = $1",@@ -484,19 +549,20 @@ async fn a_queued_join_request_notification_is_not_stored_after_its_event_went(p.execute(&pool).await.unwrap();- assert!(!ingress_insert(&pool, event_id).await.unwrap());+ assert!(!ingress_insert(&pool, &request).await.unwrap());sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id).execute(&pool).await.unwrap();- assert!(!ingress_insert(&pool, event_id).await.unwrap());+ assert!(!ingress_insert(&pool, &request).await.unwrap());assert_eq!(stored_notifications(&pool).await, 0);}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_queued_insert_waits_for_a_cancellation_then_stores_nothing(pool: PgPool) {- let event_id = shared_event(&pool).await;+ let request = open_request(&pool).await;+ let event_id = request.event_id;let mut cancelling = pool.begin().await.unwrap();let blocker = backend_pid(&mut cancelling).await;sqlx::query!(@@ -509,7 +575,8 @@ async fn a_queued_insert_waits_for_a_cancellation_then_stores_nothing(pool: PgPolet arriving = tokio::spawn({let pool = pool.clone();- async move { ingress_insert(&pool, event_id).await }+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }});wait_for_blocked_transaction(&pool, blocker).await;cancelling.commit().await.unwrap();@@ -520,7 +587,8 @@ async fn a_queued_insert_waits_for_a_cancellation_then_stores_nothing(pool: PgPo#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_queued_insert_waits_for_a_delete_then_stores_nothing(pool: PgPool) {- let event_id = shared_event(&pool).await;+ let request = open_request(&pool).await;+ let event_id = request.event_id;let mut deleting = pool.begin().await.unwrap();let blocker = backend_pid(&mut deleting).await;sqlx::query!("DELETE FROM calendar_events WHERE id = $1", event_id)@@ -530,7 +598,8 @@ async fn a_queued_insert_waits_for_a_delete_then_stores_nothing(pool: PgPool) {let arriving = tokio::spawn({let pool = pool.clone();- async move { ingress_insert(&pool, event_id).await }+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }});wait_for_blocked_transaction(&pool, blocker).await;deleting.commit().await.unwrap();@@ -541,10 +610,11 @@ async fn a_queued_insert_waits_for_a_delete_then_stores_nothing(pool: PgPool) {#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn a_delete_waits_for_a_queued_insert_then_retires_it(pool: PgPool) {- let event_id = shared_event(&pool).await;+ let request = open_request(&pool).await;+ let event_id = request.event_id;let mut arriving = pool.begin().await.unwrap();let blocker = backend_pid(&mut arriving).await;- assert!(ingress_insert(&mut *arriving, event_id).await.unwrap());+ assert!(ingress_insert(&mut *arriving, &request).await.unwrap());let deleting = tokio::spawn({let pool = pool.clone();@@ -560,3 +630,188 @@ async fn a_delete_waits_for_a_queued_insert_then_retires_it(pool: PgPool) {deleting.await.unwrap().unwrap();assert_eq!(stored_notifications(&pool).await, 0);}++/// Answers `request` inside `transaction`, as `resolve_join_request` does.+async fn answer_within(transaction: &mut Transaction<'_, Postgres>, request: &CalendarJoinRequest) {+ sqlx::query!(+ "UPDATE calendar_event_join_requests SET status = 'declined' WHERE id = $1",+ request.id,+ )+ .execute(&mut **transaction)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn answering_a_join_request_retires_its_notification_for_every_recipient(pool: PgPool) {+ let accepted = open_request(&pool).await;+ let declined = another_open_request(&pool, &accepted).await;+ let delegate_id = "macro|[email protected]";+ insert_user(&pool, delegate_id).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let reminder = store_notification(+ &pool,+ "calendar_event_reminder",+ accepted.event_id,+ serde_json::json!({}),+ &[SHARER_ID],+ )+ .await;+ let mut listener = PgListener::connect_with(&pool).await.unwrap();+ listener.listen("notification_events").await.unwrap();++ for (request, status) in [+ (&accepted, CalendarJoinRequestStatus::Accepted),+ (&declined, CalendarJoinRequestStatus::Declined),+ ] {+ let asked =+ insert_join_request_notification(&pool, request, &[SHARER_ID, delegate_id]).await;+ repo.resolve_join_request(request.id, status)+ .await+ .unwrap()+ .expect("the request was open");+ assert!(!recipient_holds(&pool, asked).await);++ let mut published = published_delete(&mut listener).await;+ assert_eq!(published["notificationId"], serde_json::json!(asked));+ let recipients = published["userIds"].as_array_mut().unwrap();+ recipients.sort_by_key(ToString::to_string);+ assert_eq!(+ *recipients,+ vec![serde_json::json!(delegate_id), serde_json::json!(SHARER_ID)]+ );+ }++ assert!(recipient_holds(&pool, reminder).await);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn answering_one_join_request_keeps_the_notification_of_another_still_open(pool: PgPool) {+ let answered = open_request(&pool).await;+ let still_open = another_open_request(&pool, &answered).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let about_answered = insert_join_request_notification(&pool, &answered, &[SHARER_ID]).await;+ let about_still_open = insert_join_request_notification(&pool, &still_open, &[SHARER_ID]).await;++ repo.resolve_join_request(answered.id, CalendarJoinRequestStatus::Declined)+ .await+ .unwrap()+ .expect("the request was open");+ assert!(!recipient_holds(&pool, about_answered).await);+ assert!(recipient_holds(&pool, about_still_open).await);+ assert_eq!(+ repo.list_pending_join_requests(answered.event_id)+ .await+ .unwrap(),+ std::slice::from_ref(&still_open)+ );++ repo.resolve_join_request(still_open.id, CalendarJoinRequestStatus::Accepted)+ .await+ .unwrap()+ .expect("the request was open");+ assert!(!recipient_holds(&pool, about_still_open).await);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_join_request_notification_is_not_stored_after_its_request_was_answered(+ pool: PgPool,+) {+ let accepted = open_request(&pool).await;+ let declined = another_open_request(&pool, &accepted).await;+ let third_member = "macro|[email protected]";+ insert_user(&pool, third_member).await;+ let repo = PgCalendarRepository::new(pool.clone());+ let (still_open, _) = repo+ .open_join_request(accepted.event_id, third_member, "[email protected]")+ .await+ .unwrap();+ repo.resolve_join_request(accepted.id, CalendarJoinRequestStatus::Accepted)+ .await+ .unwrap();+ repo.resolve_join_request(declined.id, CalendarJoinRequestStatus::Declined)+ .await+ .unwrap();++ assert!(!ingress_insert(&pool, &accepted).await.unwrap());+ assert!(!ingress_insert(&pool, &declined).await.unwrap());+ assert_eq!(stored_notifications(&pool).await, 0);++ assert!(ingress_insert(&pool, &still_open).await.unwrap());+ assert_eq!(stored_notifications(&pool).await, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_join_request_notification_is_not_stored_without_its_request(pool: PgPool) {+ let request = open_request(&pool).await;+ sqlx::query!(+ "DELETE FROM calendar_event_join_requests WHERE id = $1",+ request.id,+ )+ .execute(&pool)+ .await+ .unwrap();++ assert!(!ingress_insert(&pool, &request).await.unwrap());+ assert_eq!(stored_notifications(&pool).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_insert_waits_for_an_answer_then_stores_nothing(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut answering = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut answering).await;+ answer_within(&mut answering, &request).await;++ let arriving = tokio::spawn({+ let pool = pool.clone();+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ answering.commit().await.unwrap();++ assert!(!arriving.await.unwrap().unwrap());+ assert_eq!(stored_notifications(&pool).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn a_queued_insert_is_stored_when_the_answer_it_waited_for_rolls_back(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut answering = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut answering).await;+ answer_within(&mut answering, &request).await;++ let arriving = tokio::spawn({+ let pool = pool.clone();+ let request = request.clone();+ async move { ingress_insert(&pool, &request).await }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ answering.rollback().await.unwrap();++ assert!(arriving.await.unwrap().unwrap());+ assert_eq!(stored_notifications(&pool).await, 1);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn an_answer_waits_for_a_queued_insert_then_retires_it(pool: PgPool) {+ let request = open_request(&pool).await;+ let mut arriving = pool.begin().await.unwrap();+ let blocker = backend_pid(&mut arriving).await;+ assert!(ingress_insert(&mut *arriving, &request).await.unwrap());++ let answering = tokio::spawn({+ let repo = PgCalendarRepository::new(pool.clone());+ let request_id = request.id;+ async move {+ repo.resolve_join_request(request_id, CalendarJoinRequestStatus::Declined)+ .await+ }+ });+ wait_for_blocked_transaction(&pool, blocker).await;+ arriving.commit().await.unwrap();++ assert!(answering.await.unwrap().unwrap().is_some());+ assert_eq!(stored_notifications(&pool).await, 0);+}diff --git a/crates/calendar_events/src/outbound/pg/test/outlook.rs b/crates/calendar_events/src/outbound/pg/test/outlook.rsindex 21fd92d72c..530c19742a 100644--- a/crates/calendar_events/src/outbound/pg/test/outlook.rs+++ b/crates/calendar_events/src/outbound/pg/test/outlook.rs@@ -1,4 +1,4 @@-use super::join_requests::{JOIN_REQUEST_NOTIFICATION, insert_notification, recipient_holds};+use super::join_requests::{insert_join_request_notification, recipient_holds};use super::*;use crate::domain::models::{AutomaticDeclinePolicy, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties,@@ -1423,10 +1423,12 @@ async fn an_outlook_cancellation_or_removal_retires_join_request_notifications(p.open_join_request(cancelled_id, member, "[email protected]").await.unwrap();- let on_cancelled =- insert_notification(&pool, JOIN_REQUEST_NOTIFICATION, cancelled_id, &owner).await;- let on_removed =- insert_notification(&pool, JOIN_REQUEST_NOTIFICATION, removed_id, &owner).await;+ let (removed_request, _) = repo+ .open_join_request(removed_id, member, "[email protected]")+ .await+ .unwrap();+ let on_cancelled = insert_join_request_notification(&pool, &request, &[&owner]).await;+ let on_removed = insert_join_request_notification(&pool, &removed_request, &[&owner]).await;// Outlook can keep a cancelled meeting: the row stays, with its request.let mut cancelled = upsert(&event, "cancelled");diff --git a/crates/macro_db_client/migrations/20261031013525_calendar_event_join_request_answer_notification_cleanup.sql b/crates/macro_db_client/migrations/20261031013525_calendar_event_join_request_answer_notification_cleanup.sqlnew file mode 100644index 0000000000..5915f0ce5c--- /dev/null+++ b/crates/macro_db_client/migrations/20261031013525_calendar_event_join_request_answer_notification_cleanup.sql@@ -0,0 +1,70 @@+-- Answering a request to join a calendar event retires its notification.+--+-- Only opening the event marked the notification seen, so an answer from a+-- delegate, through the API or by an agent left it listed and eligible for the+-- digest email, for a request already settled. As in+-- calendar_event_join_request_notification_cleanup, the notification is deleted+-- rather than marked, which reaches every recipient's open clients and takes it+-- out of a pending digest, and the cleanup lives on the row, where it commits+-- with the answer whichever path gave it.+--+-- The notification is keyed to the event, and an event can hold several open+-- requests, each with its own notification. The event and type find its+-- notifications by index; the request id in the metadata, which+-- CalendarEventJoinRequestMetadata writes as requestId, picks the answered one.+--+-- These notifications are queued, so one can arrive after the answer, past the+-- cleanup above, and the insert checks the request too. The lookup locks the+-- request FOR SHARE, which conflicts with the update that answers it, so it+-- waits for an answer in flight: whichever commits first, the notification does+-- not outlive the open request. The event is locked first, in the order a delete+-- reaches the two rows, so the guard cannot deadlock with the cascade. A request+-- that is gone has nothing to answer either. The trigger on notification keeps+-- its function, replaced in place, so this takes no lock on that table.++SET LOCAL lock_timeout = '5s';++CREATE FUNCTION delete_answered_join_request_notification()+ RETURNS TRIGGER+ LANGUAGE PLPGSQL+ AS+$$+ BEGIN+ DELETE FROM notification+ WHERE event_item_type = 'calendar_event'+ AND event_item_id = NEW.event_id::text+ AND notification_event_type = 'calendar_event_join_request'+ AND metadata->>'requestId' = NEW.id::text;+ RETURN NULL;+ END;+$$;++CREATE TRIGGER calendar_event_join_request_answered_notification_cleanup+ AFTER UPDATE OF status ON calendar_event_join_requests+ FOR EACH ROW+ WHEN (OLD.status = 'pending' AND NEW.status <> 'pending')+ EXECUTE FUNCTION delete_answered_join_request_notification();++CREATE OR REPLACE FUNCTION skip_join_request_notification_without_live_event()+ RETURNS TRIGGER+ LANGUAGE PLPGSQL+ AS+$$+ BEGIN+ PERFORM 1 FROM calendar_events+ WHERE id = NEW.event_item_id::uuid+ AND status <> 'cancelled'+ FOR SHARE;+ IF NOT FOUND THEN+ RETURN NULL;+ END IF;+ PERFORM 1 FROM calendar_event_join_requests+ WHERE id = (NEW.metadata->>'requestId')::uuid+ AND status = 'pending'+ FOR SHARE;+ IF FOUND THEN+ RETURN NEW;+ END IF;+ RETURN NULL;+ END;+$$;diff --git a/crates/model_notifications/src/metadata/calendar_join_request.rs b/crates/model_notifications/src/metadata/calendar_join_request.rsindex f170fc9d3f..29b232734f 100644--- a/crates/model_notifications/src/metadata/calendar_join_request.rs+++ b/crates/model_notifications/src/metadata/calendar_join_request.rs@@ -8,6 +8,8 @@ use super::*;#[serde(rename_all = "camelCase")]pub struct CalendarEventJoinRequestMetadata {/// Stable request identity, answered from the event's details.+ // Database triggers read this from the stored metadata as `requestId`, to+ // retire the notification when the request is answered.pub request_id: Uuid,/// The shared calendar event entity the request is for.pub event_id: Uuid,diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rsindex d08c72cb25..30e59b884f 100644--- a/crates/model_notifications/src/metadata/test.rs+++ b/crates/model_notifications/src/metadata/test.rs@@ -40,6 +40,18 @@ fn calendar_join_requests_name_the_requester_and_the_event() {assert_eq!(untitled.format_body(None).unwrap(), "(No title)");}+#[test]+fn calendar_join_requests_store_the_key_their_retirement_reads() {+ let request_id = Uuid::now_v7();+ let stored = serde_json::to_value(CalendarEventJoinRequestMetadata {+ request_id,+ event_id: Uuid::nil(),+ title: "Design review".into(),+ })+ .unwrap();+ assert_eq!(stored["requestId"], request_id.to_string());+}+#[test]fn view_access_notifications_preserve_permission_and_format_copy() {let request = EntityAccessRequestedMetadata {diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.mdindex 7692249fd1..d1b8ec3aac 100644--- a/crates/notification/AGENTS.md+++ b/crates/notification/AGENTS.md@@ -83,9 +83,11 @@ through the same service.- Access-request withdrawals suppress delayed ingress and queued push/realtimedelivery; keep tombstone checks when changing either delivery boundary.- A `calendar_event_join_request` insert is skipped by a `notification` trigger- when its event has gone or been cancelled, since queued ingress can run after- the event's cleanup. `create_notification` reads the skipped insert as nothing- to deliver, so keep that `rows_affected` check.+ when its event has gone or been cancelled or its request is no longer pending,+ since queued ingress can run after that cleanup. `create_notification` reads+ the skipped insert as nothing to deliver, so keep that `rows_affected` check.+ The triggers read `requestId` from the stored metadata, so renaming that field+ needs a migration.- Crates on `macrod`'s dependency path (`teams`, `model_notifications`,`invite_email`) take this crate with `default-features = false`, which keepslibrdkafka out of the self-hosted daemon; keep it that way.diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.mdindex a239ba6d40..1995d087e1 100644--- a/docs/agent-guide/calendar.md+++ b/docs/agent-guide/calendar.md@@ -885,9 +885,11 @@ Outlook sends the invitation and the mention then opens the viewer's own copy. Dthe requester nothing, but their card then reads `Declined` and `The person who shared this eventdeclined your request to join.` with no `Ask to join`, and offers `Add to calendar` again. Adeclined request stands: the server refuses another ask with 409 `request_declined`, so the-sharer is asked only once. The notification goes when the event does (deleted in Macro, deleted-or cancelled in Google or Outlook, its calendar or inbox removed); deleting one occurrence of a-series leaves it, since the sharer can still add the guest. A classic `@Macro` reply that+sharer is asked only once. The notification goes when the request is answered, by whoever answers+it and however they do, leaving the notifications of other requests on the event, and when the+event goes (deleted in Macro, deleted or cancelled in Google or Outlook, its calendar or inbox+removed); deleting one occurrence of a series leaves it, since the sharer can still add the guest.+A classic `@Macro` reply thatmentions an event does not shareit by posting the chip. It asks whether to share with the channel, and a yes in that threadwrites the same channel grant. Private and confidential events are never shared this way.