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
perf(email): prune crm cleanup candidates with nothing to tear down (#5397)
Evan Hutnikf15b61c6b049
diff --git a/.sqlx/query-06e01322e08f6ddab836127adbea5a530a731db16923efc31ebc1cfc18894506.json b/.sqlx/query-06e01322e08f6ddab836127adbea5a530a731db16923efc31ebc1cfc18894506.jsonnew file mode 100644index 0000000000..a8a2a2c9ef--- /dev/null+++ b/.sqlx/query-06e01322e08f6ddab836127adbea5a530a731db16923efc31ebc1cfc18894506.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT cs.link_id AS \"link_id!\", LOWER(ct.email) AS \"email!\"\n FROM crm_contact_sources cs\n JOIN crm_contacts ct ON ct.id = cs.contact_id\n JOIN UNNEST($1::uuid[], $2::text[]) AS p(link_id, email)\n ON p.link_id = cs.link_id AND p.email = LOWER(ct.email)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "06e01322e08f6ddab836127adbea5a530a731db16923efc31ebc1cfc18894506"+}diff --git a/.sqlx/query-5da3501a72c81a825537d0b11a3f9c0d9c4c87e14febeab9fc5272b2ac582080.json b/.sqlx/query-368f362bd133f3dbea094757d24e04056011bc04e76c956e94b4badeec59edc5.jsonsimilarity index 65%rename from .sqlx/query-5da3501a72c81a825537d0b11a3f9c0d9c4c87e14febeab9fc5272b2ac582080.jsonrename to .sqlx/query-368f362bd133f3dbea094757d24e04056011bc04e76c956e94b4badeec59edc5.jsonindex 8d33d04c02..94a994d7cf 100644--- a/.sqlx/query-5da3501a72c81a825537d0b11a3f9c0d9c4c87e14febeab9fc5272b2ac582080.json+++ b/.sqlx/query-368f362bd133f3dbea094757d24e04056011bc04e76c956e94b4badeec59edc5.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO crm_cleanup_candidates (link_id, contact_email)\n SELECT $1, unnest($2::text[])\n ON CONFLICT (link_id, contact_email) DO NOTHING\n ",+ "query": "\n INSERT INTO crm_cleanup_candidates (link_id, contact_email)\n SELECT $1, unnest($2::text[])\n ON CONFLICT (link_id, contact_email) DO UPDATE SET created_at = now()\n ","describe": {"columns": [],"parameters": {@@ -11,5 +11,5 @@},"nullable": []},- "hash": "5da3501a72c81a825537d0b11a3f9c0d9c4c87e14febeab9fc5272b2ac582080"+ "hash": "368f362bd133f3dbea094757d24e04056011bc04e76c956e94b4badeec59edc5"}diff --git a/.sqlx/query-5798ed87ad7c9c785824ddf17697953054ea270b42c208adc07d187dce885997.json b/.sqlx/query-5798ed87ad7c9c785824ddf17697953054ea270b42c208adc07d187dce885997.jsonnew file mode 100644index 0000000000..155629b2e1--- /dev/null+++ b/.sqlx/query-5798ed87ad7c9c785824ddf17697953054ea270b42c208adc07d187dce885997.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM crm_cleanup_candidates c\n USING UNNEST($1::uuid[], $2::text[]) AS p(link_id, contact_email)\n WHERE c.link_id = p.link_id AND c.contact_email = p.contact_email\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "5798ed87ad7c9c785824ddf17697953054ea270b42c208adc07d187dce885997"+}diff --git a/.sqlx/query-4575cb6d19d4c0df01889d43a8e2426fb596e406c2fd316be1db6f0f2c769689.json b/.sqlx/query-b6c2dce065e0f4a872fd1158501cf56ef3f4a5730caa5fabd154ae9fdf1c96e6.jsonsimilarity index 57%rename from .sqlx/query-4575cb6d19d4c0df01889d43a8e2426fb596e406c2fd316be1db6f0f2c769689.jsonrename to .sqlx/query-b6c2dce065e0f4a872fd1158501cf56ef3f4a5730caa5fabd154ae9fdf1c96e6.jsonindex a415316796..91cd5b9b1b 100644--- a/.sqlx/query-4575cb6d19d4c0df01889d43a8e2426fb596e406c2fd316be1db6f0f2c769689.json+++ b/.sqlx/query-b6c2dce065e0f4a872fd1158501cf56ef3f4a5730caa5fabd154ae9fdf1c96e6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, link_id, contact_email\n FROM crm_cleanup_candidates\n WHERE id > $1 AND id <= $2\n ORDER BY id\n LIMIT $3\n ",+ "query": "\n SELECT id, link_id, contact_email, created_at\n FROM crm_cleanup_candidates\n WHERE id > $1 AND id <= $2\n ORDER BY id\n LIMIT $3\n ","describe": {"columns": [{@@ -17,6 +17,11 @@"ordinal": 2,"name": "contact_email","type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "created_at",+ "type_info": "Timestamptz"}],"parameters": {@@ -27,10 +32,11 @@]},"nullable": [+ false,false,false,false]},- "hash": "4575cb6d19d4c0df01889d43a8e2426fb596e406c2fd316be1db6f0f2c769689"+ "hash": "b6c2dce065e0f4a872fd1158501cf56ef3f4a5730caa5fabd154ae9fdf1c96e6"}diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rsindex 0edc6b358a..8b82964237 100644--- a/crates/crm/src/domain/companies_repo.rs+++ b/crates/crm/src/domain/companies_repo.rs@@ -292,6 +292,23 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {email: &str,) -> impl Future<Output = Result<DepopulateContactOutcome, CrmError>> + Send;+ /// Filters `(link_id, email)` pairs down to those that currently have a+ /// `crm_contact_sources` row — i.e. the pairs where this link actually+ /// contributed something [`depopulate_contact`] would tear down.+ ///+ /// Exists so the nightly cleanup job can drop never-tracked contacts+ /// before fanning out a message per candidate: the candidate table is fed+ /// by every message deletion, but CRM only tracks a small subset of+ /// correspondents, so most candidates have nothing to remove.+ ///+ /// `email` is matched case-insensitively against `crm_contacts.email`.+ /// Returns the surviving pairs with their emails lowercased; input order+ /// is not preserved and unmatched pairs are simply absent.+ fn link_contact_pairs_with_sources(+ &self,+ pairs: &[(uuid::Uuid, String)],+ ) -> impl Future<Output = Result<Vec<(uuid::Uuid, String)>, CrmError>> + Send;+/// Bulk counterpart to [`depopulate_contact`]: removes everything/// the link contributed to a single team's CRM rows. In one/// transaction:diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rsindex 26a0852523..283548ae63 100644--- a/crates/crm/src/domain/service.rs+++ b/crates/crm/src/domain/service.rs@@ -113,6 +113,18 @@ pub trait CrmService: Clone + Send + Sync + 'static {email: &str,) -> impl Future<Output = Result<DepopulateContactOutcome, CrmError>> + Send;+ /// Filters `(link_id, email)` pairs down to those with a live+ /// `crm_contact_sources` row — the pairs a teardown would actually touch.+ /// See+ /// [`crate::domain::companies_repo::CompaniesRepository::link_contact_pairs_with_sources`].+ ///+ /// Used by the nightly cleanup job to prune candidates for contacts CRM+ /// never tracked, before they become one SQS message each.+ fn link_contact_pairs_with_sources(+ &self,+ pairs: &[(uuid::Uuid, String)],+ ) -> impl Future<Output = Result<Vec<(uuid::Uuid, String)>, CrmError>> + Send;+/// Bulk teardown for one user's email link within one team: drops/// the team's `crm_contact_sources` rows owned by `link_id`, then/// cascades to `crm_contacts` and `crm_companies` for the rows@@ -644,6 +656,16 @@ where.await}+ #[tracing::instrument(skip(self, pairs), fields(pair_count = pairs.len()), err)]+ async fn link_contact_pairs_with_sources(+ &self,+ pairs: &[(uuid::Uuid, String)],+ ) -> Result<Vec<(uuid::Uuid, String)>, CrmError> {+ self.companies_repository+ .link_contact_pairs_with_sources(pairs)+ .await+ }+#[tracing::instrument(skip(self), err)]async fn depopulate_link_in_team(&self,@@ -1057,6 +1079,13 @@ impl CrmService for NoOpCrmService {unimplemented!("NoOpCrmService.depopulate_contact")}+ async fn link_contact_pairs_with_sources(+ &self,+ _pairs: &[(uuid::Uuid, String)],+ ) -> Result<Vec<(uuid::Uuid, String)>, CrmError> {+ unimplemented!("NoOpCrmService.link_contact_pairs_with_sources")+ }+async fn depopulate_link_in_team(&self,_team_id: &uuid::Uuid,diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rsindex 2f8aea8350..69f662bd01 100644--- a/crates/crm/src/domain/service/test.rs+++ b/crates/crm/src/domain/service/test.rs@@ -78,6 +78,13 @@ impl CompaniesRepository for StubRepo {unimplemented!()}+ async fn link_contact_pairs_with_sources(+ &self,+ _pairs: &[(uuid::Uuid, String)],+ ) -> Result<Vec<(uuid::Uuid, String)>, CrmError> {+ unimplemented!()+ }+async fn depopulate_link_in_team(&self,_team_id: &uuid::Uuid,diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rsindex 6332ab8c71..782f9f10cc 100644--- a/crates/crm/src/inbound/axum_extractors/test.rs+++ b/crates/crm/src/inbound/axum_extractors/test.rs@@ -283,6 +283,13 @@ impl CrmService for FakeCrmService {panic!("unexpected depopulate_contact call")}+ async fn link_contact_pairs_with_sources(+ &self,+ _pairs: &[(Uuid, String)],+ ) -> Result<Vec<(Uuid, String)>, CrmError> {+ panic!("unexpected link_contact_pairs_with_sources call")+ }+async fn depopulate_link_in_team(&self,_team_id: &Uuid,diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rsindex df33febde9..622d106310 100644--- a/crates/crm/src/outbound/companies_repo.rs+++ b/crates/crm/src/outbound/companies_repo.rs@@ -772,6 +772,41 @@ impl CompaniesRepository for CompaniesRepositoryImpl {Ok(outcome)}+ #[tracing::instrument(skip(self, pairs), fields(pair_count = pairs.len()), err)]+ async fn link_contact_pairs_with_sources(+ &self,+ pairs: &[(uuid::Uuid, String)],+ ) -> Result<Vec<(uuid::Uuid, String)>, CrmError> {+ if pairs.is_empty() {+ return Ok(Vec::new());+ }++ let (link_ids, emails): (Vec<uuid::Uuid>, Vec<String>) = pairs+ .iter()+ .map(|(link_id, email)| (*link_id, email.to_ascii_lowercase()))+ .unzip();++ let rows = sqlx::query!(+ r#"+ SELECT cs.link_id AS "link_id!", LOWER(ct.email) AS "email!"+ FROM crm_contact_sources cs+ JOIN crm_contacts ct ON ct.id = cs.contact_id+ JOIN UNNEST($1::uuid[], $2::text[]) AS p(link_id, email)+ ON p.link_id = cs.link_id AND p.email = LOWER(ct.email)+ "#,+ &link_ids,+ &emails,+ )+ .fetch_all(&self.pool)+ .await+ .map_err(|e| CrmError::StorageLayerError(e.into()))?;++ Ok(rows+ .into_iter()+ .map(|row| (row.link_id, row.email))+ .collect())+ }+#[tracing::instrument(skip(self), err)]async fn depopulate_link_in_team(&self,diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rsindex fe03f11bd4..333ab177fa 100644--- a/crates/crm/src/outbound/companies_repo/test.rs+++ b/crates/crm/src/outbound/companies_repo/test.rs@@ -11,6 +11,7 @@ mod create_company;mod create_contact;mod get_company_for_team;mod get_contact_for_team;+mod link_contact_pairs_with_sources;mod list_companies_for_soup;mod list_contacts_for_company;mod populate_contact;diff --git a/crates/crm/src/outbound/companies_repo/test/link_contact_pairs_with_sources.rs b/crates/crm/src/outbound/companies_repo/test/link_contact_pairs_with_sources.rsnew file mode 100644index 0000000000..95c650f8dc--- /dev/null+++ b/crates/crm/src/outbound/companies_repo/test/link_contact_pairs_with_sources.rs@@ -0,0 +1,98 @@+use super::helpers::*;+use crate::domain::companies_repo::*;+use crate::outbound::companies_repo::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use std::collections::HashSet;+use uuid::Uuid;++/// Sorted set form, so assertions don't depend on row order.+fn as_set(pairs: Vec<(Uuid, String)>) -> HashSet<(Uuid, String)> {+ pairs.into_iter().collect()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn keeps_only_pairs_backed_by_a_source_row(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ // Tracked by this link.+ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;+ // In CRM, but no source row for any link.+ insert_contact(&pool, company_id, "[email protected]").await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let got = repo+ .link_contact_pairs_with_sources(&[+ (link_id, "[email protected]".to_string()),+ (link_id, "[email protected]".to_string()),+ // Never in CRM at all — the common case the cleanup job prunes.+ (link_id, "[email protected]".to_string()),+ ])+ .await?;++ assert_eq!(+ as_set(got),+ HashSet::from([(link_id, "[email protected]".to_string())])+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn does_not_match_a_source_owned_by_a_different_link(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let link_a = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let link_b = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ insert_contact_with_source(&pool, company_id, "[email protected]", link_a).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let got = repo+ .link_contact_pairs_with_sources(&[+ (link_a, "[email protected]".to_string()),+ (link_b, "[email protected]".to_string()),+ ])+ .await?;++ // link_b contributed nothing for this contact, so it has nothing to tear down.+ assert_eq!(+ as_set(got),+ HashSet::from([(link_a, "[email protected]".to_string())])+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn matches_case_insensitively_and_returns_lowercased(pool: PgPool) -> anyhow::Result<()> {+ let team_id = Uuid::now_v7();+ let owner_id = "macro|[email protected]";+ seed_team(&pool, team_id, owner_id).await?;+ let link_id = insert_email_link(&pool, owner_id, "[email protected]").await?;+ let company_id = insert_company(&pool, team_id, true, &["acme.com"]).await?;++ insert_contact_with_source(&pool, company_id, "[email protected]", link_id).await?;++ let repo = CompaniesRepositoryImpl::new(pool.clone());+ let got = repo+ .link_contact_pairs_with_sources(&[(link_id, "[email protected]".to_string())])+ .await?;++ assert_eq!(+ as_set(got),+ HashSet::from([(link_id, "[email protected]".to_string())])+ );+ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn empty_input_is_a_no_op(pool: PgPool) -> anyhow::Result<()> {+ let repo = CompaniesRepositoryImpl::new(pool.clone());+ assert!(repo.link_contact_pairs_with_sources(&[]).await?.is_empty());+ Ok(())+}diff --git a/crates/email_db_client/src/crm_cleanup/candidates.rs b/crates/email_db_client/src/crm_cleanup/candidates.rsindex 836a35d932..12d1363486 100644--- a/crates/email_db_client/src/crm_cleanup/candidates.rs+++ b/crates/email_db_client/src/crm_cleanup/candidates.rs@@ -4,7 +4,14 @@ use sqlx::types::Uuid;/// Upserts one cleanup candidate per email for the link. The unique index on/// `(link_id, contact_email)` dedupes repeat deletes into a single pending row.-/// Returns the number of rows actually inserted.+///+/// A repeat delete refreshes `created_at` rather than being ignored: the+/// lister treats that timestamp as a settling clock for asynchronous CRM+/// populate, and each new deletion implies a new message that may have its own+/// populate still in flight. Keeping the original timestamp would let the+/// clock expire while that populate is pending.+///+/// Returns the number of rows recorded (inserted or refreshed).#[tracing::instrument(skip(pool, contact_emails), err)]pub async fn insert_candidates(pool: &PgPool,@@ -19,7 +26,7 @@ pub async fn insert_candidates(r#"INSERT INTO crm_cleanup_candidates (link_id, contact_email)SELECT $1, unnest($2::text[])- ON CONFLICT (link_id, contact_email) DO NOTHING+ ON CONFLICT (link_id, contact_email) DO UPDATE SET created_at = now()"#,link_id,contact_emails@@ -43,7 +50,7 @@ pub async fn list_candidates_page(let candidates = sqlx::query_as!(CrmCleanupCandidate,r#"- SELECT id, link_id, contact_email+ SELECT id, link_id, contact_email, created_atFROM crm_cleanup_candidatesWHERE id > $1 AND id <= $2ORDER BY id@@ -59,6 +66,36 @@ pub async fn list_candidates_page(Ok(candidates)}+/// Claims (deletes) a batch of candidate rows in one statement. Used by the+/// lister to retire pairs that have nothing to tear down, instead of spending+/// one `ProcessCandidate` message each to reach the same conclusion.+///+/// Same semantics as [`claim_candidate`], just set-based: a delete landing+/// concurrently re-inserts a fresh row that the next run picks up. Returns the+/// number of rows removed.+#[tracing::instrument(skip(pool, pairs), fields(pair_count = pairs.len()), err)]+pub async fn claim_candidates(pool: &PgPool, pairs: &[(Uuid, String)]) -> anyhow::Result<u64> {+ if pairs.is_empty() {+ return Ok(0);+ }++ let (link_ids, contact_emails): (Vec<Uuid>, Vec<String>) = pairs.iter().cloned().unzip();++ let result = sqlx::query!(+ r#"+ DELETE FROM crm_cleanup_candidates c+ USING UNNEST($1::uuid[], $2::text[]) AS p(link_id, contact_email)+ WHERE c.link_id = p.link_id AND c.contact_email = p.contact_email+ "#,+ &link_ids,+ &contact_emails,+ )+ .execute(pool)+ .await?;++ Ok(result.rows_affected())+}+/// Claims (deletes) the candidate row for a pair. Returns `true` when the row/// existed. Claiming happens before the depopulate check so a message delete/// that lands mid-processing re-inserts a fresh row for the next run insteaddiff --git a/crates/email_db_client/src/crm_cleanup/candidates/test.rs b/crates/email_db_client/src/crm_cleanup/candidates/test.rsindex 727c721866..3cab68c4f5 100644--- a/crates/email_db_client/src/crm_cleanup/candidates/test.rs+++ b/crates/email_db_client/src/crm_cleanup/candidates/test.rs@@ -24,14 +24,15 @@ async fn insert_candidates_dedupes_pairs(pool: Pool<Postgres>) -> anyhow::Resultlet inserted = insert_candidates(&pool, link_id, &emails).await?;assert_eq!(inserted, 2);- // Re-inserting the same pairs (plus one new) only adds the new row.+ // Re-recording the same pairs (plus one new) refreshes rather than+ // duplicating: three rows touched, but still only three rows total.let emails = vec!["[email protected]".to_string(),"[email protected]".to_string(),"[email protected]".to_string(),];- let inserted = insert_candidates(&pool, link_id, &emails).await?;- assert_eq!(inserted, 1);+ let recorded = insert_candidates(&pool, link_id, &emails).await?;+ assert_eq!(recorded, 3);let (_, count) = get_max_id_and_count(&pool).await?.unwrap();assert_eq!(count, 3);@@ -39,6 +40,34 @@ async fn insert_candidates_dedupes_pairs(pool: Pool<Postgres>) -> anyhow::ResultOk(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_candidates_refreshes_created_at_on_repeat(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let link_id = Uuid::new_v4();+ insert_link(&pool, link_id).await;++ let emails = vec!["[email protected]".to_string()];+ insert_candidates(&pool, link_id, &emails).await?;++ // Backdate so the refresh is unambiguous.+ sqlx::query!(r#"UPDATE crm_cleanup_candidates SET created_at = now() - INTERVAL '2 days'"#)+ .execute(&pool)+ .await?;+ let before = list_candidates_page(&pool, 0, i64::MAX, 10).await?[0].created_at;++ insert_candidates(&pool, link_id, &emails).await?;+ let after = list_candidates_page(&pool, 0, i64::MAX, 10).await?[0].created_at;++ // The pruning clock restarts on each new delete for the pair, so a+ // populate still in flight can't be outrun by a stale timestamp.+ assert!(+ after > before,+ "expected created_at to be refreshed: {before} -> {after}"+ );+ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn insert_candidates_empty_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {let link_id = Uuid::new_v4();diff --git a/crates/models_email/src/email/service/crm_cleanup.rs b/crates/models_email/src/email/service/crm_cleanup.rsindex 4885ef18e9..997b623c7d 100644--- a/crates/models_email/src/email/service/crm_cleanup.rs+++ b/crates/models_email/src/email/service/crm_cleanup.rs@@ -87,4 +87,10 @@ pub struct CrmCleanupCandidate {pub id: i64,pub link_id: Uuid,pub contact_email: String,+ /// When the pair was first recorded (the upsert keeps the original on+ /// repeat deletes). The lister uses this as a settling clock: populate for+ /// a contact is always enqueued before the deletion that records the+ /// candidate, so an old row means populate has had at least that long to+ /// land.+ pub created_at: DateTime<Utc>,}diff --git a/services/email_service/src/pubsub/crm_cleanup/list_candidates.rs b/services/email_service/src/pubsub/crm_cleanup/list_candidates.rsindex ff1db31697..64d1fb4d3f 100644--- a/services/email_service/src/pubsub/crm_cleanup/list_candidates.rs+++ b/services/email_service/src/pubsub/crm_cleanup/list_candidates.rs@@ -1,14 +1,26 @@use crate::pubsub::crm_cleanup::worker::CrmCleanupContext;+use crm::domain::service::CrmService;use email_db_client::crm_cleanup::{candidates, job};use models_email::email::service::crm_cleanup::{CrmCleanupJobStatus, CrmCleanupOperation, CrmCleanupPubsubMessage,};use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use std::collections::HashSet;use uuid::Uuid;/// Candidates dispatched per ListCandidates message.const CANDIDATE_PAGE_SIZE: i64 = 200;+/// A candidate younger than this is never pruned on a negative source lookup,+/// only dispatched. Populate is enqueued asynchronously and is always queued+/// *before* the deletion that records the candidate, so a row this old means+/// populate has had at least this long to commit its `crm_contact_sources`+/// row. Without the guard, a populate still in flight at 08:00 could land+/// right after the lookup missed, leaving a CRM row whose candidate we already+/// pruned. Candidates accumulate over 24h, so in practice this exempts almost+/// nothing.+const PRUNE_MIN_AGE: chrono::TimeDelta = chrono::TimeDelta::hours(6);+/// Dispatches one keyset page of cleanup candidates as `ProcessCandidate`/// messages, then re-enqueues itself with the new cursor. Mirrors the/// backfill `list_threads` pattern: each page is its own SQS message, so a@@ -16,9 +28,14 @@ const CANDIDATE_PAGE_SIZE: i64 = 200;/// the job's `max_candidate_id` snapshot has been dispatched — the job is/// marked `Complete`.///-/// A redelivered page re-publishes ProcessCandidate messages for pairs that-/// were already dispatched; that's harmless because the consumer's claim and-/// gate check are both idempotent.+/// Before fanning out, the page is filtered against `crm_contact_sources`:+/// candidates are written on every message deletion, but CRM only tracks a+/// small subset of correspondents, so most pairs have nothing to tear down.+/// Those are claimed in one batch instead of costing a message each. The+/// filter runs here rather than at insert time because populate is enqueued+/// asynchronously — at deletion the contact may not be in CRM *yet*, and+/// skipping it there would strand the row forever. By the nightly run,+/// populate has long since settled.#[tracing::instrument(skip(ctx), err)]pub async fn list_candidates(ctx: &CrmCleanupContext,@@ -62,12 +79,68 @@ pub async fn list_candidates(})})?;- for candidate in &page {+ let pairs: Vec<(Uuid, String)> = page+ .iter()+ .map(|c| (c.link_id, c.contact_email.clone()))+ .collect();++ // Pairs too young to prune safely — see PRUNE_MIN_AGE. Dispatched+ // unconditionally, which is exactly the pre-filter behaviour.+ let prune_cutoff = chrono::Utc::now() - PRUNE_MIN_AGE;+ let too_young: HashSet<(Uuid, String)> = page+ .iter()+ .filter(|c| c.created_at > prune_cutoff)+ .map(|c| (c.link_id, c.contact_email.clone()))+ .collect();++ let actionable: HashSet<(Uuid, String)> = ctx+ .crm_service+ .link_contact_pairs_with_sources(&pairs)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: anyhow::Error::from(e)+ .context("Failed to filter crm cleanup candidates by contact sources"),+ })+ })?+ .into_iter()+ .collect();++ // The repo lowercases the emails it echoes back, so compare on the same+ // footing — candidate rows are already normalized on insert, but a stray+ // mixed-case row must not silently fall out of the actionable set.+ let (to_dispatch, to_prune): (Vec<_>, Vec<_>) = pairs.into_iter().partition(|pair| {+ let (link_id, email) = pair;+ actionable.contains(&(*link_id, email.to_ascii_lowercase())) || too_young.contains(pair)+ });++ // Nothing to tear down for these: retire them here rather than spending a+ // ProcessCandidate message each to reach the same conclusion. Runs before+ // any dispatch, so a failure retries the whole page cleanly.+ if !to_prune.is_empty() {+ let pruned = candidates::claim_candidates(&ctx.db, &to_prune)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to prune crm cleanup candidates"),+ })+ })?;+ tracing::info!(+ job_id = %job_id,+ pruned,+ dispatching = to_dispatch.len(),+ "Pruned crm cleanup candidates with no contact sources"+ );+ }++ for (link_id, contact_email) in &to_dispatch {ctx.sqs_client.enqueue_email_crm_cleanup_message(CrmCleanupPubsubMessage {operation: CrmCleanupOperation::ProcessCandidate {- link_id: candidate.link_id,- contact_email: candidate.contact_email.clone(),+ link_id: *link_id,+ contact_email: contact_email.clone(),},}).await@@ -80,8 +153,8 @@ pub async fn list_candidates(}// Observability only; may over-count when a page is redelivered mid-dispatch.- if !page.is_empty() {- job::add_dispatched_count(&ctx.db, job_id, page.len() as i64)+ if !to_dispatch.is_empty() {+ job::add_dispatched_count(&ctx.db, job_id, to_dispatch.len() as i64).await.inspect_err(|e| tracing::error!(error = ?e, "Failed to bump dispatched_count")).ok();@@ -112,7 +185,7 @@ pub async fn list_candidates(source: e.context("Failed to mark crm cleanup job complete"),})})?;- tracing::info!(job_id = %job_id, dispatched = job.dispatched_count + page.len() as i64, "Crm cleanup job dispatch complete");+ tracing::info!(job_id = %job_id, dispatched = job.dispatched_count + to_dispatch.len() as i64, "Crm cleanup job dispatch complete");}Ok(())