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.

feat(users): clean up sessions and scheduled actions before user deletion (#6838)

Will Hutchinson0416572c72da
diff --git a/crates/agent_harness/src/domain/service/lifecycle.rs b/crates/agent_harness/src/domain/service/lifecycle.rs
index a1842117ee..f3bacda82a 100644
--- a/crates/agent_harness/src/domain/service/lifecycle.rs
+++ b/crates/agent_harness/src/domain/service/lifecycle.rs
@@ -46,6 +46,33 @@ where
Mentions: PromptMentions,
Notifier: AgentSessionNotifier,
{
+ async fn delete_user_sessions(
+ &self,
+ owner: MacroUserIdStr<'static>,
+ ) -> agent_session::domain::error::Result<()> {
+ loop {
+ let sessions = self
+ .inner
+ .sessions
+ .sessions_for_user_cleanup(&owner)
+ .await?;
+ if sessions.is_empty() {
+ return Ok(());
+ }
+ for session in sessions {
+ // Fail closed if a repository ever returns another principal's row.
+ if !session.owner_id.is_user(&owner) {
+ return Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "account cleanup returned a session owned by another principal"
+ )));
+ }
+ // Includes replica forwarding and the per-session command queue.
+ // Teardown failure leaves the durable row available for a retry.
+ self.session_deleted(session.id).await?;
+ }
+ }
+ }
+
async fn session_deleted(
&self,
id: AgentSessionId,
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 08664f41c4..2c9103087a 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2,6 +2,8 @@
//! with in-memory persistence, mock containers, a fake agent, and a
//! recording announcer. Only the edges are doubles.
+mod user_cleanup;
+
use messages::domain::models::MessageParent;
use std::sync::{Arc, Mutex};
diff --git a/crates/agent_harness/src/domain/service/test/user_cleanup.rs b/crates/agent_harness/src/domain/service/test/user_cleanup.rs
new file mode 100644
index 0000000000..c17449966c
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/test/user_cleanup.rs
@@ -0,0 +1,44 @@
+use super::*;
+use model_owner::Owner;
+
+#[tokio::test]
+async fn delete_user_sessions_cleans_live_and_inactive_sessions_only_for_the_owner() {
+ let (service, repo, containers, _, _) = harness();
+ let live = AgentSessionId::new();
+ live_sandboxed_coder_session(&service, &containers, live).await;
+ // More than one cleanup batch, including disconnected sessions.
+ let mut owned = vec![live];
+ for _ in 0..101 {
+ owned.push(
+ disconnected_session_owned_by(&repo, &containers, Owner::User(staff_sender())).await,
+ );
+ }
+ let other = disconnected_session_owned_by(&repo, &containers, Owner::User(sender())).await;
+ let bot_owned =
+ disconnected_session_owned_by(&repo, &containers, Owner::Bot(BotId::TEST_A)).await;
+
+ service.delete_user_sessions(staff_sender()).await.unwrap();
+ assert_eq!(containers.torn_down(), owned.len());
+ for id in owned {
+ assert!(repo.get(id).await.is_err());
+ }
+ assert!(repo.get(other).await.is_ok());
+ assert!(repo.get(bot_owned).await.is_ok());
+ assert!(containers.container(other).is_some());
+ service.delete_user_sessions(staff_sender()).await.unwrap();
+ assert_eq!(containers.torn_down(), 102, "retry is a no-op");
+}
+
+#[tokio::test]
+async fn delete_user_sessions_preserves_the_row_on_teardown_failure_and_can_retry() {
+ let (service, repo, containers, _, _) = harness();
+ let id = disconnected_session_owned_by(&repo, &containers, Owner::User(sender())).await;
+ containers.fail_next_teardown();
+ assert!(service.delete_user_sessions(sender()).await.is_err());
+ assert!(repo.get(id).await.is_ok());
+ assert!(containers.container(id).is_some());
+
+ service.delete_user_sessions(sender()).await.unwrap();
+ assert!(repo.get(id).await.is_err());
+ assert_eq!(containers.torn_down(), 1);
+}
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index b9449bba91..d22db37a2d 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -204,6 +204,7 @@ pub struct MockContainerManager {
resize_unsupported: Arc<AtomicBool>,
resumes: Arc<AtomicUsize>,
teardowns: Arc<AtomicUsize>,
+ teardown_error: Arc<AtomicBool>,
/// Signalled on every spawn, so a test waits for a sandbox instead of
/// spinning on [`Self::spawned`].
spawned_signal: Arc<tokio::sync::Notify>,
@@ -271,6 +272,11 @@ impl MockContainerManager {
self.resumes.load(Ordering::Relaxed)
}
+ /// Fail the next teardown before removing its container.
+ pub fn fail_next_teardown(&self) {
+ self.teardown_error.store(true, Ordering::Relaxed);
+ }
+
/// How many sandboxes have been destroyed.
#[must_use]
pub fn torn_down(&self) -> usize {
@@ -401,6 +407,9 @@ impl ContainerManager for MockContainerManager {
}
async fn teardown(&self, session: AgentSessionId) -> Result<(), HarnessError> {
+ if self.teardown_error.swap(false, Ordering::Relaxed) {
+ return Err(HarnessError::Container("injected teardown failure".into()));
+ }
self.teardowns.fetch_add(1, Ordering::Relaxed);
self.lock().remove(&session);
Ok(())
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index a2506bcfa7..d3014bad2d 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -1003,6 +1003,13 @@ pub struct QueuedControl {
/// control routes can be mounted against it without knowing what a harness is.
#[cfg_attr(feature = "test-utils", mockall::automock)]
pub trait AgentSessionNotificationRecipient: Send + Sync + 'static {
+ /// Release and delete every session owned by a user before account deletion.
+ /// Internal account lifecycle only; shared sessions owned by others are untouched.
+ fn delete_user_sessions(
+ &self,
+ owner: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
/// The session is going away: release its live resources and delete it.
fn session_deleted(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 52e5065afc..a6cdd51c2b 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -75,6 +75,8 @@ use crate::domain::events::{AgentSessionLifecycleEvent, SessionRenamedMetadata};
/// Buffered not-yet-accepted commands per session actor.
const COMMAND_BUFFER: usize = 1028;
+/// Bound memory usage while draining all sessions during account cleanup.
+const USER_CLEANUP_BATCH_SIZE: std::num::NonZeroUsize = std::num::NonZeroUsize::new(100).unwrap();
/// Persistence may delay lifecycle teardown, but never indefinitely.
const SESSION_PERSIST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
/// How long a command may sit queued behind the ACP handshake
@@ -174,6 +176,13 @@ pub trait AgentSessionService: Send + Sync + 'static {
name: &str,
) -> impl Future<Output = Result<()>> + Send;
+ /// A bounded batch of sessions owned by this user, including inactive sessions.
+ /// Used by account cleanup, not access-based discovery.
+ fn sessions_for_user_cleanup(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<AgentSession>>> + Send;
+
/// Delete an agent session by id.
fn delete_session(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
@@ -751,6 +760,15 @@ where
self.repo.find_for_thread(thread_id, bot_id).await
}
+ async fn sessions_for_user_cleanup(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<AgentSession>> {
+ self.repo
+ .recent_for_owner(owner, USER_CLEANUP_BATCH_SIZE)
+ .await
+ }
+
async fn delete_session(&self, id: AgentSessionId) -> Result<()> {
let (stopped, marker) = self.begin_stop(id, true);
Self::wait_stopped(stopped).await;
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index e7371790c5..0f5a5d3aff 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -35,8 +35,8 @@ use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAcces
use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
use macro_authorization::{
- ActingUser, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
- UserBotOrHarness, UserBotOrHarnessAuthorization,
+ ActingUser, InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService,
+ MacroAuthorizationState, UserBotOrHarness, UserBotOrHarnessAuthorization,
};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -214,6 +214,10 @@ where
"/{session_id}",
delete(delete_agent_session_handler::<R, Access, Auth>),
)
+ .route(
+ "/user/{user_id}",
+ delete(delete_user_sessions_handler::<R, Access, Auth>),
+ )
.route(
"/{session_id}/control",
post(control_agent_session_handler::<R, Access, Auth>),
@@ -234,6 +238,21 @@ where
.with_state(state)
}
+/// Account lifecycle endpoint: never grants cleanup authority to a user or harness token.
+async fn delete_user_sessions_handler<R, Access, Auth>(
+ State(state): State<AgentSessionControlState<R, Access, Auth>>,
+ _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
+ Path(user_id): Path<MacroUserIdStr<'static>>,
+) -> Result<StatusCode, AgentSessionApiError>
+where
+ R: AgentSessionNotificationRecipient,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+{
+ state.recipient.delete_user_sessions(user_id).await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
/// Build the caller-default sandbox size router. Mount at `/agent-sandbox-size`.
pub fn agent_sandbox_size_router<T, Access, Auth, S>(
state: AgentSessionRouterState<T, Access, Auth>,
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 2dca4749b9..9cd5749088 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -821,6 +821,7 @@ async fn an_external_open_carries_its_instructions() {
}
mod read;
+mod user_cleanup;
/// The client speculates under an id it mints and sends it alongside the
/// action's own flattened fields, which are tagged under `type`.
diff --git a/crates/agent_session/src/inbound/axum_router/test/user_cleanup.rs b/crates/agent_session/src/inbound/axum_router/test/user_cleanup.rs
new file mode 100644
index 0000000000..6ca84f0b89
--- /dev/null
+++ b/crates/agent_session/src/inbound/axum_router/test/user_cleanup.rs
@@ -0,0 +1,110 @@
+use super::*;
+use crate::domain::error::Result as SessionResult;
+use crate::domain::ports::{AcceptedControl, QueuedControl};
+
+#[derive(Default)]
+struct Recipient(Mutex<Vec<MacroUserIdStr<'static>>>);
+
+impl AgentSessionNotificationRecipient for Recipient {
+ async fn delete_user_sessions(&self, owner: MacroUserIdStr<'static>) -> SessionResult<()> {
+ self.0.lock().unwrap().push(owner);
+ Ok(())
+ }
+ async fn session_deleted(&self, _: AgentSessionId) -> SessionResult<()> {
+ unreachable!()
+ }
+ async fn control_event(
+ &self,
+ _: AgentSessionId,
+ _: ControlEvent,
+ ) -> SessionResult<AcceptedControl> {
+ unreachable!()
+ }
+ async fn queued_controls(&self, _: AgentSessionId) -> SessionResult<Vec<QueuedControl>> {
+ unreachable!()
+ }
+ async fn edit_queued_control(
+ &self,
+ _: AgentSessionId,
+ _: AgentActionId,
+ _: String,
+ _: Option<MacroUserIdStr<'static>>,
+ ) -> SessionResult<()> {
+ unreachable!()
+ }
+ async fn remove_queued_control(
+ &self,
+ _: AgentSessionId,
+ _: AgentActionId,
+ _: Option<MacroUserIdStr<'static>>,
+ ) -> SessionResult<()> {
+ unreachable!()
+ }
+ async fn set_sandbox_size(&self, _: AgentSessionId, _: SandboxSize) -> SessionResult<()> {
+ unreachable!()
+ }
+ async fn session_harness(
+ &self,
+ _: AgentSessionId,
+ ) -> SessionResult<Option<harness_id::HarnessId>> {
+ unreachable!()
+ }
+}
+
+#[tokio::test]
+async fn cleanup_requires_internal_credentials_not_user_bot_or_harness_authority() {
+ let recipient = Arc::new(Recipient::default());
+ let auth = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: "test-internal-key".into(),
+ default_user_id: None,
+ },
+ SelfBotAuthorizer,
+ NoUserApiKeyAuthorizer,
+ )
+ .with_harness_authorizer(SelfHarnessAuthorizer);
+ let router: Router = agent_session_control_router(AgentSessionControlState::new(
+ recipient.clone(),
+ Arc::new(entity_access::domain::ports::NoOpEntityAccessService),
+ MacroAuthorizationState::new(Arc::new(auth)),
+ ));
+ let bearer = format!("Bearer {OWNER}");
+ for headers in [
+ vec![],
+ vec![("authorization", bearer.as_str())],
+ vec![(BOT_TOKEN_HEADER, BOT_TOKEN), (BOT_SCOPE_HEADER, "user")],
+ vec![(HARNESS_TOKEN_HEADER, HARNESS_TOKEN)],
+ vec![(macro_authorization::INTERNAL_API_KEY_HEADER, "bad-key")],
+ ] {
+ let mut request = Request::builder()
+ .method("DELETE")
+ .uri("/user/macro%7Cowner%40example.com");
+ for (key, value) in headers {
+ request = request.header(key, value);
+ }
+ let response = router
+ .clone()
+ .oneshot(request.body(Body::empty()).unwrap())
+ .await
+ .unwrap();
+ assert!(response.status().is_client_error());
+ assert!(recipient.0.lock().unwrap().is_empty());
+ }
+ let response = router
+ .oneshot(
+ Request::builder()
+ .method("DELETE")
+ .uri("/user/macro%7Cowner%40example.com")
+ .header(
+ macro_authorization::INTERNAL_API_KEY_HEADER,
+ "test-internal-key",
+ )
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::NO_CONTENT);
+ assert_eq!(recipient.0.lock().unwrap()[0].as_ref(), OWNER);
+}
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index a19145b04b..c199314d48 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -1,5 +1,6 @@
use super::*;
mod search;
+mod user_cleanup;
mod working_branch;
use crate::domain::model::{AgentMcpServer, DEFAULT_AGENT_SESSION_NAME};
use crate::domain::ports::AgentSessionRepo;
diff --git a/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs
new file mode 100644
index 0000000000..5e27fd85ef
--- /dev/null
+++ b/crates/agent_session/src/outbound/postgres/test/user_cleanup.rs
@@ -0,0 +1,62 @@
+use super::*;
+use crate::domain::ports::{
+ NoOpAgentSessionNameGenerator, NoOpRealtime, NoOpTurnObserver, NoopLifecyclePublisher,
+};
+use crate::domain::service::{AgentSessionService, AgentSessionServiceImpl};
+use agent_fold::domain::service::FoldedMessageService;
+use std::sync::Arc;
+
+/// The user is deliberately never deleted: no User cascade can make this pass.
+/// Harness tests separately prove every selected row goes through teardown first.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn cleanup_batches_remove_all_session_rows_without_a_user_cascade(pool: PgPool) {
+ const OTHER: &str = "macro|[email protected]";
+ let repo = PgAgentSessionRepo::new(pool.clone());
+ let bot = create_test_bot(&pool).await;
+ insert_user(&pool, OTHER).await;
+ for _ in 0..101 {
+ create_session(&repo, new_session(bot, None, None)).await;
+ }
+ let other = create_session(
+ &repo,
+ CreateAgentSessionParams {
+ owner_id: Owner::User(user_id(OTHER)),
+ ..new_session(bot, None, None)
+ },
+ )
+ .await;
+ let service = AgentSessionServiceImpl::new(
+ repo.clone(),
+ FoldedMessageService::new(repo.clone()),
+ NoOpRealtime,
+ NoOpAgentSessionNameGenerator,
+ Arc::new(NoOpTurnObserver),
+ Arc::new(NoopLifecyclePublisher),
+ ReplicaId::mint(),
+ );
+ let mut deleted = 0;
+ loop {
+ let batch = service
+ .sessions_for_user_cleanup(&user_id(OWNER))
+ .await
+ .unwrap();
+ if batch.is_empty() {
+ break;
+ }
+ assert!(batch.len() <= 100);
+ for session in batch {
+ service.delete_session(session.id).await.unwrap();
+ assert!(AgentSessionRepo::get(&repo, session.id).await.is_err());
+ deleted += 1;
+ }
+ }
+ assert_eq!(deleted, 101);
+ assert!(
+ service
+ .sessions_for_user_cleanup(&user_id(OWNER))
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(AgentSessionRepo::get(&repo, other.id).await.is_ok());
+}
diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rs
index ebc1f3a2ea..4e9a4847f2 100644
--- a/crates/macro_service_urls/src/lib.rs
+++ b/crates/macro_service_urls/src/lib.rs
@@ -561,6 +561,12 @@ service_url! {
dev: "https://dev-gateway.macro.com/agent-harness",
prod: "https://gateway.macro.com/agent-harness",
},
+ /// Scheduled action service API URL.
+ pub ScheduledActionServiceUrl {
+ local: "http://localhost:8099",
+ dev: "https://dev-gateway.macro.com/scheduled-action",
+ prod: "https://gateway.macro.com/scheduled-action",
+ },
/// Sandbox-facing agent harness egress proxy URL.
/// Override the local default when sandbox clients need a Docker-network
/// address or a public tunnel rather than the host's loopback address.
diff --git a/crates/macro_service_urls/src/test.rs b/crates/macro_service_urls/src/test.rs
index 15da7a1dbb..881c3c5ee4 100644
--- a/crates/macro_service_urls/src/test.rs
+++ b/crates/macro_service_urls/src/test.rs
@@ -149,6 +149,23 @@ fn agent_harness_service_url_parses() {
assert_parses_for_all_environments(AgentHarnessServiceUrl::default_for_environment);
}
+#[test]
+fn scheduled_action_service_url_parses() {
+ assert_parses_for_all_environments(ScheduledActionServiceUrl::default_for_environment);
+ assert_eq!(
+ ScheduledActionServiceUrl::local().as_ref(),
+ "http://localhost:8099"
+ );
+ assert_eq!(
+ ScheduledActionServiceUrl::dev().as_ref(),
+ "https://dev-gateway.macro.com/scheduled-action"
+ );
+ assert_eq!(
+ ScheduledActionServiceUrl::prod().as_ref(),
+ "https://gateway.macro.com/scheduled-action"
+ );
+}
+
#[test]
fn agent_harness_service_url_has_no_trailing_slash() {
for environment in ENVS {
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 3fafa4c018..7d51a69b6d 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -129,6 +129,7 @@ pub(crate) struct ApiContext {
pub stripe_client: Arc<stripe::Client>,
pub document_storage_service_client:
Arc<document_storage_service_client::DocumentStorageServiceClient>,
+ pub user_deletion: Arc<authentication_service::outbound::user_deletion::UserDeletionAdapter>,
pub email_service_client: Arc<email::outbound::EmailServiceHttpClient>,
pub ses_client: Arc<ses_client::Ses>,
pub notification_ingress_service: Arc<NotificationIngressType>,
diff --git a/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
index 944b9dd384..49e72a49de 100644
--- a/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
+++ b/services/authentication_service/src/api/webhooks/user/delete_user_webhook.rs
@@ -48,12 +48,23 @@ pub async fn handler(
return Ok(StatusCode::OK.into_response());
}
- let macro_user = macro_db_client::macro_user::get_macro_user(&ctx.db, &fusionauth_user_id)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to get macro user");
- (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
- })?;
+ let macro_user =
+ match macro_db_client::macro_user::get_macro_user(&ctx.db, &fusionauth_user_id).await {
+ Ok(user) => user,
+ // A retry after the final delete has nothing left to clean up.
+ Err(error)
+ if matches!(
+ error.downcast_ref::<sqlx::Error>(),
+ Some(sqlx::Error::RowNotFound)
+ ) =>
+ {
+ return Ok(StatusCode::OK.into_response());
+ }
+ Err(error) => {
+ tracing::error!(error=?error, "unable to get macro user");
+ return Err(StatusCode::INTERNAL_SERVER_ERROR.into_response());
+ }
+ };
let user_ids: Vec<String> =
macro_db_client::user::get::get_user_profiles_by_fusionauth_user_id(
@@ -66,9 +77,14 @@ pub async fn handler(
(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
})?;
- // TODO: should probably make this into an event so we can handle service restarts
- // Spawn a single tokio task to perform the user deletion
- tokio::spawn(delete_user(ctx, macro_user, fusionauth_user_id, user_ids).in_current_span());
+ // Await the durable cleanup so FusionAuth can retry failures. Acknowledging
+ // before cleanup would strand resources if a service is unavailable.
+ delete_user(ctx, macro_user, fusionauth_user_id, user_ids)
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error, "unable to complete user deletion");
+ StatusCode::INTERNAL_SERVER_ERROR.into_response()
+ })?;
Ok(StatusCode::OK.into_response())
}
@@ -240,34 +256,18 @@ async fn delete_user(
.in_current_span(),
);
- // MacroDB deletion
- tokio::spawn({
- let user_infos = user_infos.clone();
- let document_storage_service_client = ctx.document_storage_service_client.clone();
- let db = ctx.db.clone();
- let macro_user_id = macro_user.id;
- async move {
- for user_info in user_infos {
- let user_id = user_info.id.clone();
- tracing::trace!(user_id, "delete_document_storage_service_items");
- if let Err(e) = document_storage_service_client
- .delete_all_user_items(&user_id)
- .await
- {
- tracing::error!(error=?e, user_id, "unable to delete user items from document storage service");
- }
- tracing::trace!(user_id, "delete_document_storage_service_items complete");
-
- tracing::trace!(user_id, "delete_user_macro_db");
- if let Err(e) = macro_db_client::user::delete_user::delete_user(&db, &user_id, &macro_user_id).await {
- tracing::error!(error=?e, user_id, "delete_user_macro_db unable to delete user");
- }
- tracing::trace!(user_id, "delete_user_macro_db complete");
-
- }
- let _ = macro_db_client::macro_user::delete_macro_user(&db, &macro_user_id).await.inspect_err(|e| tracing::error!(error=?e, "unable to delete macro user"));
- }
- }.in_current_span());
+ // Use the authoritative profile ids, not the best-effort user-info lookups.
+ let users = user_ids
+ .iter()
+ .map(|id| MacroUserIdStr::try_from(id.clone()))
+ .collect::<Result<Vec<_>, _>>()?;
+ authentication_service::service::user::delete_user::delete_user_data(
+ ctx.user_deletion.as_ref(),
+ &macro_user.id,
+ &users,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!("{error:?}"))?;
Ok(())
}
diff --git a/services/authentication_service/src/lib.rs b/services/authentication_service/src/lib.rs
index 1f278a4d51..d83bf12274 100644
--- a/services/authentication_service/src/lib.rs
+++ b/services/authentication_service/src/lib.rs
@@ -1 +1,2 @@
+pub mod outbound;
pub mod service;
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index e313c54472..872fbd2f61 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -497,6 +497,18 @@ async fn main() -> anyhow::Result<()> {
None
};
+ let document_storage_service_client = Arc::new(document_storage_service_client);
+ let user_deletion = Arc::new(
+ authentication_service::outbound::user_deletion::UserDeletionAdapter::new(
+ db.clone(),
+ document_storage_service_client.clone(),
+ internal_api_key.to_string(),
+ macro_service_urls::AgentHarnessServiceUrl::new()?.to_string(),
+ macro_service_urls::ScheduledActionServiceUrl::new()?.to_string(),
+ )
+ .map_err(|error| anyhow::anyhow!("{error:?}"))?,
+ );
+
let server_result = api::setup_and_serve(
ApiContext {
db,
@@ -507,7 +519,8 @@ async fn main() -> anyhow::Result<()> {
codex_connection,
macro_cache_client: Arc::new(macro_cache_client),
stripe_client: Arc::new(stripe_client),
- document_storage_service_client: Arc::new(document_storage_service_client),
+ document_storage_service_client,
+ user_deletion,
email_service_client: Arc::new(email_service_client),
ses_client: Arc::new(ses_client),
notification_ingress_service,
diff --git a/services/authentication_service/src/outbound.rs b/services/authentication_service/src/outbound.rs
new file mode 100644
index 0000000000..00007625a4
--- /dev/null
+++ b/services/authentication_service/src/outbound.rs
@@ -0,0 +1,3 @@
+//! Adapters for authentication service use cases.
+
+pub mod user_deletion;
diff --git a/services/authentication_service/src/outbound/user_deletion.rs b/services/authentication_service/src/outbound/user_deletion.rs
new file mode 100644
index 0000000000..c93bd3cdd8
--- /dev/null
+++ b/services/authentication_service/src/outbound/user_deletion.rs
@@ -0,0 +1,114 @@
+//! Account deletion through the owning services, followed by MacroDB cleanup.
+
+use std::{sync::Arc, time::Duration};
+
+use document_storage_service_client::DocumentStorageServiceClient;
+use macro_authorization::INTERNAL_API_KEY_HEADER;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::{
+ Report,
+ prelude::{IntoRootcause, ResultExt},
+};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::service::user::delete_user::UserDeletionGateway;
+
+/// HTTP and database adapter composed at authentication-service startup.
+pub struct UserDeletionAdapter {
+ db: PgPool,
+ documents: Arc<DocumentStorageServiceClient>,
+ client: reqwest::Client,
+ internal_key: String,
+ harness_url: String,
+ scheduled_action_url: String,
+}
+
+impl UserDeletionAdapter {
+ /// Construct a bounded HTTP client. Redirects must not turn a failed
+ /// internal DELETE into an unrelated successful response.
+ pub fn new(
+ db: PgPool,
+ documents: Arc<DocumentStorageServiceClient>,
+ internal_key: String,
+ harness_url: String,
+ scheduled_action_url: String,
+ ) -> Result<Self, Report> {
+ Ok(Self {
+ db,
+ documents,
+ client: reqwest::Client::builder()
+ .timeout(Duration::from_secs(300))
+ .redirect(reqwest::redirect::Policy::none())
+ .build()?,
+ internal_key,
+ harness_url,
+ scheduled_action_url,
+ })
+ }
+
+ async fn delete_owned(
+ &self,
+ base: &str,
+ resource: &str,
+ user: &MacroUserIdStr<'static>,
+ ) -> Result<(), Report> {
+ let url = format!(
+ "{}/{resource}/user/{}",
+ base.trim_end_matches('/'),
+ urlencoding::encode(user.as_ref())
+ );
+ let response = self
+ .client
+ .delete(url)
+ .header(INTERNAL_API_KEY_HEADER, &self.internal_key)
+ .send()
+ .await
+ .context_with(|| format!("failed to delete user's {resource}"))?;
+ if response.status() != reqwest::StatusCode::NO_CONTENT {
+ return Err(rootcause::report!("user cleanup did not complete")
+ .attach(format!("{resource}: {}", response.status())));
+ }
+ Ok(())
+ }
+}
+
+impl UserDeletionGateway for UserDeletionAdapter {
+ async fn delete_scheduled_actions(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.delete_owned(&self.scheduled_action_url, "scheduled-actions", user)
+ .await
+ }
+
+ async fn delete_agent_sessions(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.delete_owned(&self.harness_url, "agent-sessions", user)
+ .await
+ }
+
+ async fn delete_items(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.documents
+ .delete_all_user_items(user.as_ref())
+ .await
+ .into_rootcause()
+ .context("failed to delete user items")?;
+ Ok(())
+ }
+
+ async fn delete_profile(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ account: &Uuid,
+ ) -> Result<(), Report> {
+ macro_db_client::user::delete_user::delete_user(&self.db, user.as_ref(), account)
+ .await
+ .context("failed to delete user profile")?;
+ Ok(())
+ }
+
+ async fn delete_account(&self, account: &Uuid) -> Result<(), Report> {
+ macro_db_client::macro_user::delete_macro_user(&self.db, account)
+ .await
+ .into_rootcause()
+ .context("failed to delete macro user")?;
+ Ok(())
+ }
+}
diff --git a/services/authentication_service/src/service/user/delete_user.rs b/services/authentication_service/src/service/user/delete_user.rs
new file mode 100644
index 0000000000..499e9ca069
--- /dev/null
+++ b/services/authentication_service/src/service/user/delete_user.rs
@@ -0,0 +1,51 @@
+//! Fail-closed ordering for the durable part of account deletion.
+
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Owning services and persistence needed to remove an account.
+pub trait UserDeletionGateway: Send + Sync {
+ /// Stop future scheduled work before tearing down sessions.
+ fn delete_scheduled_actions(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Delete sessions through the harness so live resources are released first.
+ fn delete_agent_sessions(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Delete documents, chats, and projects through their owning service.
+ fn delete_items(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Delete the profile only after all owning services have succeeded.
+ fn delete_profile(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ account: &Uuid,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+ /// Delete the account only after all profiles have been cleaned up.
+ fn delete_account(&self, account: &Uuid) -> impl Future<Output = Result<(), Report>> + Send;
+}
+
+/// Cleanup is retryable: failures preserve the profile/account and never fall
+/// through to a cascading delete. Callers must await this and report failure.
+pub async fn delete_user_data(
+ gateway: &impl UserDeletionGateway,
+ account: &Uuid,
+ users: &[MacroUserIdStr<'static>],
+) -> Result<(), Report> {
+ for user in users {
+ gateway.delete_scheduled_actions(user).await?;
+ gateway.delete_agent_sessions(user).await?;
+ gateway.delete_items(user).await?;
+ gateway.delete_profile(user, account).await?;
+ }
+ gateway.delete_account(account).await
+}
diff --git a/services/authentication_service/src/service/user/delete_user/test.rs b/services/authentication_service/src/service/user/delete_user/test.rs
new file mode 100644
index 0000000000..de09f40942
--- /dev/null
+++ b/services/authentication_service/src/service/user/delete_user/test.rs
@@ -0,0 +1,90 @@
+use super::*;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct FakeGateway {
+ calls: Mutex<Vec<String>>,
+ fail_at: Option<usize>,
+}
+
+impl FakeGateway {
+ fn call(&self, name: &str, user: &str) -> Result<(), Report> {
+ let mut calls = self.calls.lock().unwrap();
+ calls.push(format!("{name}:{user}"));
+ if self.fail_at == Some(calls.len()) {
+ return Err(rootcause::report!("injected cleanup failure"));
+ }
+ Ok(())
+ }
+}
+
+impl UserDeletionGateway for FakeGateway {
+ async fn delete_scheduled_actions(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.call("actions", user.as_ref())
+ }
+ async fn delete_agent_sessions(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.call("sessions", user.as_ref())
+ }
+ async fn delete_items(&self, user: &MacroUserIdStr<'static>) -> Result<(), Report> {
+ self.call("items", user.as_ref())
+ }
+ async fn delete_profile(&self, user: &MacroUserIdStr<'static>, _: &Uuid) -> Result<(), Report> {
+ self.call("profile", user.as_ref())
+ }
+ async fn delete_account(&self, _: &Uuid) -> Result<(), Report> {
+ self.call("account", "")
+ }
+}
+
+fn users() -> Vec<MacroUserIdStr<'static>> {
+ .into_iter()
+ .map(|email| MacroUserIdStr::try_from_email(email).unwrap())
+ .collect()
+}
+
+fn expected_calls() -> Vec<String> {
+ let mut expected = Vec::new();
+ for user in users() {
+ for step in ["actions", "sessions", "items", "profile"] {
+ expected.push(format!("{step}:{user}"));
+ }
+ }
+ expected.push("account:".into());
+ expected
+}
+
+#[tokio::test]
+async fn all_profiles_are_cleaned_before_the_account_is_deleted() {
+ let gateway = FakeGateway::default();
+ delete_user_data(&gateway, &Uuid::now_v7(), &users())
+ .await
+ .unwrap();
+ assert_eq!(*gateway.calls.lock().unwrap(), expected_calls());
+}
+
+#[tokio::test]
+async fn every_failure_stops_deletion_without_erasing_retry_state() {
+ let expected = expected_calls();
+ for fail_at in 1..=expected.len() {
+ let gateway = FakeGateway {
+ fail_at: Some(fail_at),
+ ..Default::default()
+ };
+ assert!(
+ delete_user_data(&gateway, &Uuid::now_v7(), &users())
+ .await
+ .is_err()
+ );
+ assert_eq!(*gateway.calls.lock().unwrap(), expected[..fail_at]);
+ }
+}
+
+#[tokio::test]
+async fn retry_after_profiles_are_gone_still_deletes_the_account() {
+ let gateway = FakeGateway::default();
+ delete_user_data(&gateway, &Uuid::now_v7(), &[])
+ .await
+ .unwrap();
+ assert_eq!(*gateway.calls.lock().unwrap(), ["account:"]);
+}
diff --git a/services/authentication_service/src/service/user/mod.rs b/services/authentication_service/src/service/user/mod.rs
index ca714dfe67..a517a959fd 100644
--- a/services/authentication_service/src/service/user/mod.rs
+++ b/services/authentication_service/src/service/user/mod.rs
@@ -1,2 +1,3 @@
pub mod create_user;
+pub mod delete_user;
pub mod support_channel_welcome;
diff --git a/services/scheduled_action/src/domain/ports.rs b/services/scheduled_action/src/domain/ports.rs
index 3f34a76295..0138fd975d 100644
--- a/services/scheduled_action/src/domain/ports.rs
+++ b/services/scheduled_action/src/domain/ports.rs
@@ -81,6 +81,13 @@ pub trait ScheduledActionRepo: Send + Sync + 'static {
}
pub trait ScheduledActionService: Send + Sync + 'static {
+ /// Delete all of a user's actions before account deletion, including disabled
+ /// and claimed actions. Repeating a completed cleanup succeeds.
+ fn delete_user_actions(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<()>> + Send;
+
fn create_action(
&self,
input: CreateScheduledAction,
diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rs
index 8750a818ca..8d0686abcd 100644
--- a/services/scheduled_action/src/domain/service.rs
+++ b/services/scheduled_action/src/domain/service.rs
@@ -1,6 +1,6 @@
use std::sync::Arc;
-use anyhow::Result;
+use anyhow::{Result, bail};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
@@ -94,6 +94,25 @@ where
Rpo: ScheduledActionRepo,
Exe: ScheduledActionExecutor + Send + Sync + 'static,
{
+ async fn delete_user_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<()> {
+ // Use the repository list, not the legacy cron-only service list, so
+ // event-triggered actions are also removed regardless of rollout gates.
+ for action in self.repo.get_actions(user_id.clone()).await? {
+ if !action.owner.is_user(&user_id) {
+ bail!("account cleanup returned an action owned by another principal");
+ }
+ let Some(id) = action.id else {
+ bail!("cannot delete action without id");
+ };
+ // Reserve before deleting: a stopped dispatcher must not leave us
+ // reporting failure after losing the row needed to retry its event.
+ let permit = self.dispatcher_tx.reserve().await?;
+ self.repo.delete_action(&id, user_id.clone()).await?;
+ permit.send(DispatchEvent::Delete(action));
+ }
+ Ok(())
+ }
+
async fn create_action(
&self,
input: CreateScheduledAction,
diff --git a/services/scheduled_action/src/domain/service/test.rs b/services/scheduled_action/src/domain/service/test.rs
index 160f07b4e3..39a8347b87 100644
--- a/services/scheduled_action/src/domain/service/test.rs
+++ b/services/scheduled_action/src/domain/service/test.rs
@@ -1,3 +1,5 @@
+mod user_cleanup;
+
use super::*;
use crate::domain::event_runs::ClaimToken;
use crate::domain::models::ActionKind;
diff --git a/services/scheduled_action/src/domain/service/test/user_cleanup.rs b/services/scheduled_action/src/domain/service/test/user_cleanup.rs
new file mode 100644
index 0000000000..b6096a45bd
--- /dev/null
+++ b/services/scheduled_action/src/domain/service/test/user_cleanup.rs
@@ -0,0 +1,156 @@
+use super::super::*;
+use super::{configuration, user};
+use crate::domain::event_runs::ClaimToken;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct FakeRepo {
+ actions: Mutex<Vec<ScheduledAction>>,
+ fail_delete: Mutex<bool>,
+}
+
+impl ScheduledActionRepo for FakeRepo {
+ async fn get_actions(&self, user: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {
+ Ok(self
+ .actions
+ .lock()
+ .unwrap()
+ .iter()
+ .filter(|a| a.owner.is_user(&user))
+ .cloned()
+ .collect())
+ }
+ async fn delete_action(&self, id: &Uuid, _: MacroUserIdStr<'static>) -> Result<()> {
+ if *self.fail_delete.lock().unwrap() {
+ bail!("injected deletion failure");
+ }
+ self.actions.lock().unwrap().retain(|a| a.id != Some(*id));
+ Ok(())
+ }
+ async fn create_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
+ unreachable!()
+ }
+ async fn get_action(
+ &self,
+ _: &Uuid,
+ _: MacroUserIdStr<'static>,
+ ) -> Result<Option<ScheduledAction>> {
+ unreachable!()
+ }
+ async fn get_next_unclaimed_actions(&self, _: i64) -> Result<Vec<ScheduledAction>> {
+ unreachable!()
+ }
+ async fn update_action(&self, _: ScheduledAction) -> Result<ScheduledAction> {
+ unreachable!()
+ }
+ async fn claim_action(&self, _: &Uuid) -> Result<ClaimToken> {
+ unreachable!()
+ }
+ async fn release_action(&self, _: &Uuid, _: ClaimToken) -> Result<()> {
+ unreachable!()
+ }
+ async fn create_execution_record(&self, _: ActionExecutionRecord) -> Result<()> {
+ unreachable!()
+ }
+ async fn get_execution_records(&self, _: &Uuid) -> Result<Vec<ActionExecutionRecord>> {
+ unreachable!()
+ }
+ async fn update_next_run_at(&self, _: &Uuid) -> Result<()> {
+ unreachable!()
+ }
+ async fn update_last_executed(&self, _: &Uuid, _: DateTime<Utc>) -> Result<()> {
+ unreachable!()
+ }
+}
+
+struct NeverExecutor;
+impl ScheduledActionExecutor for NeverExecutor {
+ async fn execute_action(&self, _: ScheduledAction) -> Result<InProgressExecution> {
+ panic!("cleanup must not execute actions")
+ }
+}
+
+fn action(owner: Owner, events: bool) -> ScheduledAction {
+ let now = Utc::now();
+ let config = configuration(events);
+ ScheduledAction {
+ id: Some(macro_uuid::generate_uuid_v7()),
+ owner,
+ name: config.name,
+ next_run_at: next_run(&config.trigger).unwrap(),
+ trigger: config.trigger,
+ kind: config.kind,
+ created_at: now,
+ updated_at: now,
+ configuration_revision: ConfigurationRevision::INITIAL,
+ event_activated_at: events.then_some(now),
+ task: config.task,
+ claimed: None,
+ enabled: true,
+ }
+}
+
+#[tokio::test]
+async fn deletes_disabled_and_claimed_actions_not_other_owners_and_retries_empty() {
+ let repo = Arc::new(FakeRepo::default());
+ let mut disabled = action(Owner::User(user()), false);
+ disabled.enabled = false;
+ let mut claimed = action(Owner::User(user()), false);
+ claimed.claimed = Some(Utc::now());
+ let event = action(Owner::User(user()), true);
+ let other = action(
+ Owner::User(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ false,
+ );
+ *repo.actions.lock().unwrap() = vec![
+ disabled.clone(),
+ claimed.clone(),
+ event.clone(),
+ other.clone(),
+ ];
+ let (tx, mut rx) = tokio::sync::mpsc::channel(10);
+ // Event management is disabled by default, but cleanup must still remove events.
+ let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+
+ service.delete_user_actions(user()).await.unwrap();
+ service.delete_user_actions(user()).await.unwrap();
+ let remaining = repo.actions.lock().unwrap();
+ assert_eq!(remaining.len(), 1);
+ assert_eq!(remaining[0].id, other.id);
+ for expected in [disabled.id, claimed.id, event.id] {
+ assert!(matches!(rx.try_recv().unwrap(), DispatchEvent::Delete(a) if a.id == expected));
+ }
+ assert!(rx.try_recv().is_err());
+}
+
+#[tokio::test]
+async fn repository_failure_keeps_retry_state_and_emits_no_delete() {
+ let repo = Arc::new(FakeRepo::default());
+ repo.actions
+ .lock()
+ .unwrap()
+ .push(action(Owner::User(user()), false));
+ *repo.fail_delete.lock().unwrap() = true;
+ let (tx, mut rx) = tokio::sync::mpsc::channel(10);
+ let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ assert!(service.delete_user_actions(user()).await.is_err());
+ assert_eq!(repo.actions.lock().unwrap().len(), 1);
+ assert!(rx.try_recv().is_err());
+ *repo.fail_delete.lock().unwrap() = false;
+ service.delete_user_actions(user()).await.unwrap();
+ assert!(repo.actions.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn closed_dispatcher_fails_before_deleting_rows() {
+ let repo = Arc::new(FakeRepo::default());
+ repo.actions
+ .lock()
+ .unwrap()
+ .push(action(Owner::User(user()), false));
+ let (tx, rx) = tokio::sync::mpsc::channel(10);
+ drop(rx);
+ let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+ assert!(service.delete_user_actions(user()).await.is_err());
+ assert_eq!(repo.actions.lock().unwrap().len(), 1);
+}
diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rs
index 9df44766ca..2361b9eb7b 100644
--- a/services/scheduled_action/src/inbound/axum_router.rs
+++ b/services/scheduled_action/src/inbound/axum_router.rs
@@ -9,12 +9,14 @@ use crate::domain::ports::ScheduledActionService;
use axum::extract::{FromRef, Path, Query, State, rejection::JsonRejection};
use axum::http::StatusCode;
use axum::response::IntoResponse;
-use axum::routing::{get, post, put};
+use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use chrono_tz::Tz;
use macro_authorization::{
- MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+ InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+ UserOrInternal,
};
+use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use model::response::EmptyResponse;
use serde::{Deserialize, Serialize};
@@ -92,6 +94,10 @@ where
St: Send + Sync,
{
Router::new()
+ .route(
+ "/scheduled-actions/user/{user_id}",
+ delete(delete_user_actions::<S, Auth>),
+ )
.route(
"/scheduled-actions",
get(list_actions::<S, Auth>).post(create_action::<S, Auth>),
@@ -111,6 +117,15 @@ where
.with_state(state)
}
+async fn delete_user_actions<S: ScheduledActionService, Auth: MacroAuthorizationService>(
+ State(state): State<ScheduledActionRouterState<S, Auth>>,
+ _internal: MacroAuthorizationExtractor<Auth, InternalOnly>,
+ Path(user_id): Path<MacroUserIdStr<'static>>,
+) -> Result<StatusCode, ScheduledActionApiError> {
+ state.service.delete_user_actions(user_id).await?;
+ Ok(StatusCode::NO_CONTENT)
+}
+
#[utoipa::path(
get,
path = "/health",
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
index d369312145..f9fb98c23f 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
@@ -1,3 +1,5 @@
+mod user_cleanup;
+
use chrono::Utc;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs
new file mode 100644
index 0000000000..dc222c34af
--- /dev/null
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test/user_cleanup.rs
@@ -0,0 +1,51 @@
+use super::*;
+use crate::domain::models::InProgressExecution;
+use crate::domain::ports::{ScheduledActionExecutor, ScheduledActionService};
+use crate::domain::service::ScheduledActionServiceImpl;
+use std::sync::Arc;
+
+struct NeverExecutor;
+impl ScheduledActionExecutor for NeverExecutor {
+ async fn execute_action(&self, _: ScheduledAction) -> Result<InProgressExecution> {
+ panic!("cleanup must not execute actions")
+ }
+}
+
+/// Both User rows remain throughout, ruling out ON DELETE CASCADE entirely.
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn deletes_user_actions_without_cascade_and_preserves_other_users(pool: PgPool) {
+ insert_user(&pool, USER_A).await;
+ insert_user(&pool, USER_B).await;
+ let repo = Arc::new(PgScheduledActionRepo::new(pool.clone()));
+ let enabled = repo
+ .create_action(sample_action(user_owner(USER_A), "enabled"))
+ .await
+ .unwrap();
+ let disabled = repo
+ .create_action(ScheduledAction {
+ enabled: false,
+ ..sample_action(user_owner(USER_A), "disabled")
+ })
+ .await
+ .unwrap();
+ repo.claim_action(&enabled.id.unwrap()).await.unwrap();
+ let event = repo.create_action(event_action()).await.unwrap();
+ let other = repo
+ .create_action(sample_action(user_owner(USER_B), "other"))
+ .await
+ .unwrap();
+ let (tx, _rx) = tokio::sync::mpsc::channel(10);
+ let service = ScheduledActionServiceImpl::new(repo.clone(), Arc::new(NeverExecutor), tx);
+
+ service.delete_user_actions(user(USER_A)).await.unwrap();
+ service.delete_user_actions(user(USER_A)).await.unwrap();
+ assert!(repo.get_actions(user(USER_A)).await.unwrap().is_empty());
+ for id in [enabled.id.unwrap(), disabled.id.unwrap(), event.id.unwrap()] {
+ assert_eq!(scheduled_action_row_count(&pool, id).await, 0);
+ assert_eq!(entity_row_count(&pool, id).await, 0);
+ }
+ assert_eq!(
+ scheduled_action_row_count(&pool, other.id.unwrap()).await,
+ 1
+ );
+}
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 48af6bb842..c1985d4a54 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -195,6 +195,15 @@ impl InfraEnv {
"OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL".into(),
"http://document-storage-service:8080".into(),
);
+ // Account deletion awaits both owning services from the auth container.
+ env.insert(
+ "OVERRIDE_AGENT_HARNESS_SERVICE_URL".into(),
+ "http://agent-harness-service:8101".into(),
+ );
+ env.insert(
+ "OVERRIDE_SCHEDULED_ACTION_SERVICE_URL".into(),
+ "http://scheduled-action-service:8080".into(),
+ );
// Lexical has the same host-vs-container split. The plain
// `LEXICAL_SERVICE_URL` value does not affect `LexicalServiceUrl`,
// which only reads the `OVERRIDE_` form.
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index a6dfe890b5..ce13efc45d 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -206,6 +206,14 @@ fn emits_in_network_service_url_overrides() {
"OVERRIDE_DOCUMENT_STORAGE_SERVICE_URL",
"http://document-storage-service:8080",
),
+ (
+ "OVERRIDE_AGENT_HARNESS_SERVICE_URL",
+ "http://agent-harness-service:8101",
+ ),
+ (
+ "OVERRIDE_SCHEDULED_ACTION_SERVICE_URL",
+ "http://scheduled-action-service:8080",
+ ),
(
"OVERRIDE_STATIC_FILE_SERVICE_URL",
"http://static-file-service:8080",