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): backfill CATEGORY_PERSONAL threads first (#4243)
Evan Hutnik1ea1067b96dd
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rsindex 2467a65b0a..022136a0c3 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs@@ -116,6 +116,13 @@ pub async fn init_backfill(job_id: scope.job_id,payload: ListThreadsPayload {next_page_token: None, // a value of None tells the process to start from the beginning+ // Seed the user's most important threads first; this pass then+ // hands off to the normal most-recent-to-least sweep. Only for+ // full backfills: a bounded backfill (threads_requested_limit set)+ // must process an exact count, but the priority pass and the+ // newest-first sweep can each enqueue up to the limit, so their+ // non-overlapping threads would push the unique total past it.+ priority_pass: threads_requested_limit.is_none(),},}),};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 fd9295e122..cd8a774c8c 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@@ -7,6 +7,7 @@ use models_email::email::service::backfill::{use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::email::service::thread::ListThreadsPayload;+use models_email::gmail::labels::SystemLabelID;use models_email::gmail::operations::GmailApiOperation;use std::cmp::min;@@ -18,6 +19,10 @@ const BACKFILL_THREAD_BATCH_SIZE: u32 = 500;/// and sends a BackfillThread message for each thread_id in the batch. If there/// are still threads left to fetch, it will trigger another ListThreads message/// to be created, looping until all threads requiring population have been listed.+///+/// The very first ListThreads (enqueued by Init) is a `priority_pass`: it lists+/// only the user's most important threads first, then hands off to this normal+/// most-recent-to-least sweep.pub async fn list_threads(ctx: &PubSubContext,access_token: &str,@@ -25,6 +30,10 @@ pub async fn list_threads(link: &link::Link,job: &BackfillJob,) -> Result<(), ProcessingError> {+ if scope.payload.priority_pass {+ return list_priority_threads(ctx, access_token, scope, link, job).await;+ }+let p = &scope.payload;let total_threads = job.total_threads;let threads_retrieved_count = job.threads_retrieved_count;@@ -49,6 +58,7 @@ pub async fn list_threads(access_token,num_threads_to_list as u32,p.next_page_token.as_deref(),+ &[],).await{@@ -109,7 +119,10 @@ pub async fn list_threads(backfill_operation: BackfillOperation::ListThreads(JobScopedPayload {link_id: scope.link_id,job_id: scope.job_id,- payload: ListThreadsPayload { next_page_token },+ payload: ListThreadsPayload {+ next_page_token,+ priority_pass: false,+ },}),};@@ -138,3 +151,127 @@ pub async fn list_threads(Ok(())}++/// The priority first pass (see [`ListThreadsPayload::priority_pass`]). Does a+/// single CATEGORY_PERSONAL-filtered listing of up to `BACKFILL_THREAD_BATCH_SIZE`+/// 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+/// not touch `threads_retrieved_count` (that counter drives the normal sweep's+/// batch math and must stay equal to the real mailbox count).+async fn list_priority_threads(+ ctx: &PubSubContext,+ access_token: &str,+ scope: &JobScopedPayload<ListThreadsPayload>,+ link: &link::Link,+ job: &BackfillJob,+) -> 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);++ if num_threads_to_list > 0 {+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::ThreadsList,+ retryable: true,+ is_backfill: true,+ })+ .await?;++ // CATEGORY_PERSONAL is Gmail's "important to a human" bucket; seeding+ // these first means a brand-new user sees signal immediately.+ let thread_list = match ctx+ .gmail_client+ .list_threads(+ access_token,+ num_threads_to_list as u32,+ None,+ &[SystemLabelID::CategoryPersonal.as_str()],+ )+ .await+ {+ Ok(list) => list,+ Err(e) => {+ return Err(ProcessingError::Retryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Failed to list priority threads from Gmail API"),+ }));+ }+ };++ let threads = thread_list.threads;++ // Bump the job total to cover these extra BackfillThread messages: the+ // normal sweep re-covers the same threads and re-increments the+ // completed counter via the skip path, so without this the+ // `completed >= total` check would finalize the job early. Bump before+ // enqueuing so no priority thread can complete against a stale total;+ // after this only non-retryable enqueues remain, so a retry can't+ // double-bump.+ if !threads.is_empty() {+ ctx.redis_client+ .add_to_total_threads(scope.job_id, threads.len() as i32)+ .await+ .map_err(|e| {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::RedisQueryFailed,+ source: e.context("Failed to bump total_threads for priority pass"),+ })+ })?;+ }++ for thread in &threads {+ let thread_sqs_msg = BackfillPubsubMessage {+ backfill_operation: BackfillOperation::BackfillThread(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: BackfillThreadPayload {+ thread_provider_id: thread.provider_id.clone(),+ },+ }),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(thread_sqs_msg)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context(format!(+ "Failed to enqueue priority thread {}",+ thread.provider_id+ )),+ })+ })?;+ }+ }++ // 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 {+ backfill_operation: BackfillOperation::ListThreads(JobScopedPayload {+ link_id: scope.link_id,+ job_id: scope.job_id,+ payload: ListThreadsPayload {+ next_page_token: None,+ priority_pass: false,+ },+ }),+ };++ ctx.sqs_client+ .enqueue_email_backfill_message(list_thread_msg)+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::SqsEnqueueFailed,+ source: e.context(+ "Failed to enqueue normal ListThreads after priority pass".to_string(),+ ),+ })+ })?;++ Ok(())+}diff --git a/rust/cloud-storage/email_service/src/util/redis/backfill.rs b/rust/cloud-storage/email_service/src/util/redis/backfill.rsindex eb1a5031ca..7a71d8cab0 100644--- a/rust/cloud-storage/email_service/src/util/redis/backfill.rs+++ b/rust/cloud-storage/email_service/src/util/redis/backfill.rs@@ -44,6 +44,27 @@ impl RedisClient {Ok(())}+ /// Atomically add `delta` to a job's `total_threads`. Used by the priority+ /// first pass to account for the extra BackfillThread messages it enqueues:+ /// the normal sweep re-covers those same threads and re-increments the+ /// completed counter via the already-exists skip path, so the total must+ /// grow to match or the `completed >= total` check would complete the job early.+ pub async fn add_to_total_threads(&self, job_id: Uuid, delta: i32) -> anyhow::Result<()> {+ let key = Self::job_status_key(job_id);++ let mut redis_connection = self+ .inner+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;++ redis_connection+ .hincr::<&str, &str, i32, i32>(&key, "total_threads", delta)+ .await?;++ Ok(())+ }+/// Increment completed threads count and return the resulting progress, deleting redis entry for job if completepub async fn incr_completed_threads(&self,diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rsindex 82e129aa8b..8f2f197391 100644--- a/rust/cloud-storage/gmail_client/src/lib.rs+++ b/rust/cloud-storage/gmail_client/src/lib.rs@@ -77,15 +77,18 @@ impl GmailClient {}}- /// Lists the num_threads most recent threads for the user+ /// Lists the num_threads most recent threads for the user, optionally+ /// filtered to threads carrying all of the given Gmail label ids+ /// (an empty slice applies no filter).#[tracing::instrument(skip(self, access_token), err)]pub async fn list_threads(&self,access_token: &str,num_threads: u32,next_page_token: Option<&str>,+ label_ids: &[&str],) -> anyhow::Result<ServiceThreadList> {- threads::list_threads(self, access_token, num_threads, next_page_token).await+ threads::list_threads(self, access_token, num_threads, next_page_token, label_ids).await}// Returns a list containing the message ids belonging to the thread.diff --git a/rust/cloud-storage/gmail_client/src/threads.rs b/rust/cloud-storage/gmail_client/src/threads.rsindex 2a5d6d468c..b1bbcb1dc9 100644--- a/rust/cloud-storage/gmail_client/src/threads.rs+++ b/rust/cloud-storage/gmail_client/src/threads.rs@@ -8,13 +8,16 @@ use std::cmp::min;// 500 is max allowed by gmail apipub const LIST_THREADS_BATCH_SIZE: u32 = 500;-/// lists thread provider ids up to the requested number, or all if none specified+/// lists thread provider ids up to the requested number, or all if none specified.+/// `label_ids` restricts the result to threads carrying all of the given Gmail+/// label ids; an empty slice applies no label filter.#[tracing::instrument(skip(client, access_token, next_page_token), err)]pub(crate) async fn list_threads(client: &GmailClient,access_token: &str,num_threads: u32,next_page_token: Option<&str>,+ label_ids: &[&str],) -> anyhow::Result<ThreadList> {if num_threads == 0 {return Ok(ThreadList {@@ -36,6 +39,11 @@ pub(crate) async fn list_threads(query_params.push(("pageToken", token.to_string()));}+ // `labelIds` is a repeatable param; a thread 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)diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rsindex db4bdb0dba..4be0d327ea 100644--- a/rust/cloud-storage/models_email/src/email/service/thread.rs+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs@@ -181,6 +181,11 @@ pub struct ThreadUserInfo {#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]pub struct ListThreadsPayload {pub next_page_token: Option<String>,+ /// When true, this is the priority first pass: list only the user's most+ /// important threads (CATEGORY_PERSONAL) so they backfill first, then hand+ /// off to the normal most-recent-to-least sweep.+ #[serde(default)]+ pub priority_pass: bool,}/// A mapping from provider IDs to thread IDs