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
feat(email_service): seed contacts from recent sent mail in backfill (#4382)
Evan Hutnikc9a0aab229b5
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex 94e6494f69..8b73a2d145 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -39,6 +39,8 @@ pub async fn handle_non_retryable_error(handle_message_failure(ctx, scope).await;}BackfillOperation::BackfillAttachment(_) => {}+ // Best-effort side seed — a failure must not fail the backfill job.+ BackfillOperation::SeedSentContact(_) => {}BackfillOperation::PopulateCrmContact(_) => {}BackfillOperation::DepopulateCrmContact(_) => {}BackfillOperation::PopulateCrmForUser(_) => {}@@ -138,6 +140,12 @@ pub async fn handle_retryable_error("Retryable error backfilling attachment")}+ BackfillOperation::SeedSentContact(scope) => {+ tracing::debug!(+ message_id = %scope.payload.message_provider_id,+ "Retryable error seeding contact from sent message"+ )+ }BackfillOperation::PopulateCrmContact(scope) => {tracing::debug!(contact_email = %scope.payload.contact_email,diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rsindex cd8a774c8c..3cd0b2401f 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs@@ -14,6 +14,15 @@ use std::cmp::min;// the max size allowed by the gmail apiconst BACKFILL_THREAD_BATCH_SIZE: u32 = 500;+// How many of the user's most important (CATEGORY_PERSONAL) threads the+// priority pass seeds first, before handing off to the normal sweep.+const PRIORITY_PASS_THREAD_LIMIT: u32 = 200;++// How many of the user's most recent sent messages we seed the contacts+// service from during the priority pass (the gmail api caps this at 500).+#[cfg(feature = "contacts_sync")]+const SENT_CONTACT_SEED_LIMIT: u32 = 200;+/// This step is invoked by Init./// Each ListThreads operation gets a batch of 500 thread_ids from the gmail api/// and sends a BackfillThread message for each thread_id in the batch. If there@@ -153,7 +162,7 @@ pub async fn list_threads(}/// The priority first pass (see [`ListThreadsPayload::priority_pass`]). Does a-/// single CATEGORY_PERSONAL-filtered listing of up to `BACKFILL_THREAD_BATCH_SIZE`+/// single CATEGORY_PERSONAL-filtered listing of up to `PRIORITY_PASS_THREAD_LIMIT`/// threads, enqueues a BackfillThread for each, bumps the job's redis total to/// account for the normal sweep re-covering these same threads, then hands off/// to the normal sweep. Unlike the normal pass it does not paginate and does@@ -168,7 +177,7 @@ async fn list_priority_threads() -> Result<(), ProcessingError> {// Never request more than the job's overall thread budget (which already// accounts for any requested limit set at job creation).- let num_threads_to_list = min(BACKFILL_THREAD_BATCH_SIZE as i32, job.total_threads);+ let num_threads_to_list = min(PRIORITY_PASS_THREAD_LIMIT as i32, job.total_threads);if num_threads_to_list > 0 {check_gmail_rate_limit(CheckGmailRateLimitArgs {@@ -248,6 +257,13 @@ async fn list_priority_threads(}}+ // Seed the contacts service from the user's recent sent mail so a new user+ // has contacts before full backfill completes. Best-effort: this runs after+ // the priority-pass total_threads bump, so it must never return a retryable+ // error (that would re-run the pass and double-bump the counter).+ #[cfg(feature = "contacts_sync")]+ enqueue_sent_contact_seeds(ctx, access_token, scope, link).await;+// Hand off to the normal most-recent-to-least sweep from the beginning. This// runs regardless of how many priority threads were found.let list_thread_msg = BackfillPubsubMessage {@@ -275,3 +291,67 @@ async fn list_priority_threads(Ok(())}++/// Lists the user's most recent sent messages and fans out one+/// [`BackfillOperation::SeedSentContact`] per message so the contacts service+/// gets seeded early in the backfill (see [`list_priority_threads`]).+///+/// Best-effort by design: it runs after the priority pass has already bumped+/// `total_threads`, so it must not propagate a retryable error (that would+/// re-run the whole pass and double-bump). On any failure it logs and returns —+/// `handle_contacts_sync` re-seeds the full contact set at job completion.+#[cfg(feature = "contacts_sync")]+async fn enqueue_sent_contact_seeds(+ ctx: &PubSubContext,+ access_token: &str,+ scope: &JobScopedPayload<ListThreadsPayload>,+ link: &link::Link,+) {+ use models_email::email::service::backfill::SeedSentContactPayload;++ if let Err(e) = check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::MessagesList,+ retryable: true,+ is_backfill: true,+ })+ .await+ {+ tracing::warn!(error = ?e, link_id = %link.id, "Skipping sent-contact seed: gmail rate limited");+ return;+ }++ let message_ids = match ctx+ .gmail_client+ .list_messages(+ access_token,+ SENT_CONTACT_SEED_LIMIT,+ &[SystemLabelID::Sent.as_str()],+ )+ .await+ {+ Ok(ids) => ids,+ Err(e) => {+ tracing::error!(error = ?e, link_id = %link.id, "Skipping sent-contact seed: failed to list sent messages");+ return;+ }+ };++ for message_provider_id in message_ids {+ let msg = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::SeedSentContact(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: SeedSentContactPayload {+ message_provider_id: message_provider_id.clone(),+ },+ }),+ };++ if let Err(e) = ctx.sqs_client.enqueue_email_backfill_message(msg).await {+ tracing::error!(error = ?e, link_id = %link.id, message_id = %message_provider_id, "Failed to enqueue sent-contact seed; skipping remaining");+ return;+ }+ }+}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rsindex 2023708253..d878985904 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/mod.rs@@ -10,5 +10,6 @@ mod list_threads;mod populate_crm_contact;mod populate_crm_for_user;mod process;+mod seed_sent_contact;mod update_metadata;pub mod worker;diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rsindex c6dbaa1e4b..c524963408 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/process.rs@@ -1,7 +1,7 @@use crate::pubsub::backfill::{backfill_attachment, backfill_message, backfill_thread, depopulate_crm_contact,depopulate_crm_for_user, error_handlers, init, list_threads, populate_crm_contact,- populate_crm_for_user, update_metadata,+ populate_crm_for_user, seed_sent_contact, update_metadata,};use crate::pubsub::context::PubSubContext;use crate::util::gmail::auth::fetch_token_or_mark_reauth;@@ -130,6 +130,15 @@ async fn inner_process_message(backfill_attachment::backfill_attachment(ctx, &access_token, &link, &scope.payload).await}+ BackfillOperation::SeedSentContact(scope) => {+ let Some(JobContext {+ link, access_token, ..+ }) = fetch_job_context(ctx, scope).await?+ else {+ return Ok(());+ };+ seed_sent_contact::seed_sent_contact(ctx, &access_token, scope, &link).await+ }BackfillOperation::PopulateCrmContact(scope) => {let link = fetch_link(ctx, scope.link_id).await?;populate_crm_contact::populate_crm_contact(ctx, &link, &scope.payload).awaitdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/seed_sent_contact.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/seed_sent_contact.rsnew file mode 100644index 0000000000..36d3628a51--- /dev/null+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/seed_sent_contact.rs@@ -0,0 +1,106 @@+use std::collections::HashSet;++use crate::convert::map_message_resource_to_service;+use crate::pubsub::context::PubSubContext;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};+use contacts::domain::ports::ContactsIngress;+use macro_user_id::user_id::MacroUserIdStr;+use models_email::email::service::backfill::{JobScopedPayload, SeedSentContactPayload};+use models_email::email::service::link;+use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};+use models_email::gmail::operations::GmailApiOperation;++/// Consumer for `BackfillOperation::SeedSentContact`. Fetches one recent sent+/// message and enqueues a sender<->recipient contact connection for every+/// non-generic To/Cc/Bcc address on it. Fanned out one-per-message by the+/// priority pass of `list_threads` so a new user has contacts before full+/// backfill completes.+///+/// Each connection is enqueued as a 2-element set (`{owner, recipient}`) rather+/// than the whole recipient list, so the contacts service connects the sender+/// to each recipient only — not the recipients to each other.+#[tracing::instrument(skip(ctx, access_token))]+pub async fn seed_sent_contact(+ ctx: &PubSubContext,+ access_token: &str,+ scope: &JobScopedPayload<SeedSentContactPayload>,+ link: &link::Link,+) -> Result<(), ProcessingError> {+ let p = &scope.payload;++ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::MessagesGet,+ retryable: true,+ is_backfill: true,+ })+ .await?;++ let message_resource = match ctx+ .gmail_client+ .get_message(access_token, &p.message_provider_id)+ .await+ {+ Ok(Some(message)) => message,+ // The message was deleted between listing and this fetch; nothing to seed.+ Ok(None) => return Ok(()),+ Err(e) => {+ return Err(ProcessingError::Retryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Gmail API failed to get sent message for contact seed"),+ }));+ }+ };++ let message = map_message_resource_to_service(message_resource, link.id).map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Failed to map message resource to service"),+ })+ })?;++ let self_email = link.email_address.0.as_ref().to_ascii_lowercase();++ // Recipients the user addressed on this sent message. Generic/automated+ // addresses are dropped, the user's own address is dropped, and we dedupe+ // so a recipient on both To and Cc only yields one connection.+ let mut seen: HashSet<String> = HashSet::new();+ for contact in message.to.iter().chain(&message.cc).chain(&message.bcc) {+ let email = contact.email.trim().to_ascii_lowercase();+ if email.is_empty()+ || email == self_email+ || email_utils::is_generic_email(&email)+ || !seen.insert(email.clone())+ {+ continue;+ }++ let recipient = match MacroUserIdStr::try_from_email(&email) {+ Ok(id) => id,+ // A single malformed address shouldn't fail the whole message.+ Err(e) => {+ tracing::warn!(error = ?e, "Skipping invalid recipient email for contact seed");+ continue;+ }+ };++ let users: HashSet<MacroUserIdStr<'static>> =+ HashSet::from([link.macro_id.clone(), recipient]);++ // Idempotent on the consumer side, so a retried seed message that+ // re-enqueues already-sent connections is harmless.+ ctx.contacts_ingress+ .enqueue_contacts(users)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: anyhow::anyhow!("{e:?}")+ .context("Failed to enqueue contact connection for sent-message seed"),+ })+ })?;+ }++ Ok(())+}diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rsindex 2f36b37e8e..062ba69e4d 100644--- a/rust/cloud-storage/gmail_client/src/lib.rs+++ b/rust/cloud-storage/gmail_client/src/lib.rs@@ -31,7 +31,7 @@ pub(crate) fn sanitize_error_body(body: &str) -> String {use crate::auth::{fetch_google_public_keys, verify_google_jwt};use crate::contacts::get_self_connection;-use crate::messages::{get_message, get_message_label_ids, get_message_thread_id};+use crate::messages::{get_message, get_message_label_ids, get_message_thread_id, list_messages};use crate::threads::get_thread;#[allow(unused_imports)]use mockall::automock;@@ -90,6 +90,19 @@ impl GmailClient {threads::list_threads(self, access_token, num_threads, next_page_token, label_ids).await}+ /// Lists the `num_messages` most recent message provider ids for the user,+ /// optionally filtered to messages carrying all of the given Gmail label+ /// ids (an empty slice applies no filter). Capped at 500 by the Gmail API.+ #[tracing::instrument(skip(self, access_token), err)]+ pub async fn list_messages(+ &self,+ access_token: &str,+ num_messages: u32,+ label_ids: &[&str],+ ) -> anyhow::Result<Vec<String>> {+ list_messages(self, access_token, num_messages, label_ids).await+ }+// Returns a list containing the message ids belonging to the thread.#[tracing::instrument(skip(self, access_token), err)]pub async fn get_message_ids_for_thread(diff --git a/rust/cloud-storage/gmail_client/src/messages.rs b/rust/cloud-storage/gmail_client/src/messages.rsindex ccbbe8b79a..d3dda633ea 100644--- a/rust/cloud-storage/gmail_client/src/messages.rs+++ b/rust/cloud-storage/gmail_client/src/messages.rs@@ -1,4 +1,4 @@-use crate::GmailClient;+use crate::{GmailClient, sanitize_error_body};use anyhow::Context;use base64::Engine;use base64::engine::general_purpose::URL_SAFE_NO_PAD;@@ -6,8 +6,73 @@ use mail_builder::headers::address::Address;use models_email::email::service::address::ContactInfo;use models_email::email::service::message;use models_email::gmail::{- MessageResource, MinimalMessageResource, SendMessagePayload, SentMessageResource,+ ListMessagesResponse, MessageResource, MinimalMessageResource, SendMessagePayload,+ SentMessageResource,};+use std::cmp::min;++// 500 is the max allowed by the gmail api+pub const LIST_MESSAGES_BATCH_SIZE: u32 = 500;++/// Lists message provider ids up to the requested number (capped at 500 by the+/// Gmail API), most recent first. `label_ids` restricts the result to messages+/// carrying all of the given Gmail label ids; an empty slice applies no filter.+#[tracing::instrument(skip(client, access_token), err)]+pub(crate) async fn list_messages(+ client: &GmailClient,+ access_token: &str,+ num_messages: u32,+ label_ids: &[&str],+) -> anyhow::Result<Vec<String>> {+ if num_messages == 0 {+ return Ok(Vec::new());+ }++ // The Gmail API's `maxResults` parameter is capped at 500.+ let batch_size = min(num_messages, LIST_MESSAGES_BATCH_SIZE);++ let http_client = client.inner.clone();+ let url = format!("{}/users/me/messages", client.base_url);++ let mut query_params = vec![("maxResults", batch_size.to_string())];++ // `labelIds` is a repeatable param; a message matches if it carries all of them.+ for label_id in label_ids {+ query_params.push(("labelIds", label_id.to_string()));+ }++ let response = http_client+ .get(&url)+ .bearer_auth(access_token)+ .query(&query_params)+ .send()+ .await+ .context("Failed to send request to Gmail API (list messages)")?;++ let status = response.status();+ if !status.is_success() {+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "Failed to read error body".to_string());+ let sanitized = sanitize_error_body(&error_body);+ anyhow::bail!("Gmail API error {} (list messages): {}", status, sanitized);+ }++ let gmail_response = response+ .json::<ListMessagesResponse>()+ .await+ .context("Failed to parse JSON response from Gmail API (list messages)")?;++ let message_ids = gmail_response+ .messages+ .unwrap_or_default()+ .into_iter()+ .map(|m| m.id)+ .collect();++ Ok(message_ids)+}#[tracing::instrument(skip(client, access_token), err)]pub(crate) async fn get_message(diff --git a/rust/cloud-storage/models_email/src/email/service/backfill.rs b/rust/cloud-storage/models_email/src/email/service/backfill.rsindex d88a9a5ee9..b46d2fe7c2 100644--- a/rust/cloud-storage/models_email/src/email/service/backfill.rs+++ b/rust/cloud-storage/models_email/src/email/service/backfill.rs@@ -74,6 +74,13 @@ pub enum BackfillOperation {UpdateThreadMetadata(JobScopedPayload<UpdateMetadataPayload>),// Uploads the message attachment as a Macro document.BackfillAttachment(JobScopedPayload<BackfillAttachmentPayload>),+ // Seeds the contacts service from one recent sent message. Fanned out+ // one-per-message by the priority pass of ListThreads (which lists the+ // user's last 200 sent messages). The consumer fetches the message and+ // enqueues a sender<->recipient connection for each non-generic To/Cc/Bcc+ // address, so a brand-new user has contacts before full backfill completes.+ // handle_contacts_sync re-seeds the full contact set at job completion.+ SeedSentContact(JobScopedPayload<SeedSentContactPayload>),// Idempotently records a contact the requesting user has emailed into the// CRM tables (crm_companies, crm_domains, crm_contacts, crm_contact_sources).// Fanned out one-per-recipient from BackfillMessage when the message was@@ -111,6 +118,7 @@ impl BackfillOperation {BackfillOperation::BackfillMessage(s) => Some(s.link_id),BackfillOperation::UpdateThreadMetadata(s) => Some(s.link_id),BackfillOperation::BackfillAttachment(s) => Some(s.link_id),+ BackfillOperation::SeedSentContact(s) => Some(s.link_id),BackfillOperation::PopulateCrmContact(s) => Some(s.link_id),BackfillOperation::DepopulateCrmContact(s) => Some(s.link_id),BackfillOperation::PopulateCrmForUser(_) => None,@@ -128,6 +136,7 @@ impl BackfillOperation {BackfillOperation::BackfillMessage(s) => Some(s.job_id),BackfillOperation::UpdateThreadMetadata(s) => Some(s.job_id),BackfillOperation::BackfillAttachment(s) => Some(s.job_id),+ BackfillOperation::SeedSentContact(s) => Some(s.job_id),BackfillOperation::PopulateCrmContact(_)| BackfillOperation::DepopulateCrmContact(_)| BackfillOperation::PopulateCrmForUser(_)@@ -269,6 +278,12 @@ pub struct BackfillAttachmentPayload {pub metadata: AttachmentUploadArgs,}+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]+pub struct SeedSentContactPayload {+ /// Gmail provider id of the sent message to seed contacts from.+ pub message_provider_id: String,+}+#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct PopulateCrmContactPayload {pub contact_email: String,diff --git a/rust/cloud-storage/models_email/src/gmail/mod.rs b/rust/cloud-storage/models_email/src/gmail/mod.rsindex fd0635da48..6bd573e527 100644--- a/rust/cloud-storage/models_email/src/gmail/mod.rs+++ b/rust/cloud-storage/models_email/src/gmail/mod.rs@@ -33,6 +33,21 @@ pub struct ThreadResource {// -- Messages objects --+// response from the messages.list endpoint - we just care about the ids+#[derive(Serialize, Deserialize, Debug, Clone)]+#[serde(rename_all = "camelCase")]+pub struct ListMessagesResponse {+ pub messages: Option<Vec<MessageSummary>>,+ pub next_page_token: Option<String>,+}++// a single message entry within a messages.list response+#[derive(Serialize, Deserialize, Debug, Clone)]+#[serde(rename_all = "camelCase")]+pub struct MessageSummary {+ pub id: String,+}+#[derive(Serialize, Deserialize, Debug, Clone)]#[serde(rename_all = "camelCase")]pub struct MessageResource {