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(search): reduce DB pressure during email search backfills (#2007)

gbirmancce91c568f53
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index bea2d2bfa9..e9acafd1fc 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3515,6 +3515,7 @@ dependencies = [
"models_properties",
"notification",
"once_cell",
+ "openssl",
"redis",
"regex",
"reqwest",
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-7f8601bd8c738ab2e656f22c009f7c6599dd2dd0de63c92a772d6638bec6ef77.json b/rust/cloud-storage/email_db_client/.sqlx/query-7f8601bd8c738ab2e656f22c009f7c6599dd2dd0de63c92a772d6638bec6ef77.json
new file mode 100644
index 0000000000..1c2c59c1b8
--- /dev/null
+++ b/rust/cloud-storage/email_db_client/.sqlx/query-7f8601bd8c738ab2e656f22c009f7c6599dd2dd0de63c92a772d6638bec6ef77.json
@@ -0,0 +1,172 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id,\n provider_id,\n global_id,\n thread_id,\n provider_thread_id,\n replying_to_id,\n link_id,\n provider_history_id,\n internal_date_ts,\n snippet,\n size_estimate,\n subject,\n from_name,\n from_contact_id,\n sent_at,\n has_attachments,\n is_read,\n is_starred,\n is_sent,\n is_draft,\n headers_jsonb,\n created_at,\n updated_at,\n body_text as body_text,\n body_html_sanitized as body_html_sanitized,\n NULL::TEXT as body_macro\n FROM email_messages\n WHERE thread_id = ANY($1)\n ORDER BY internal_date_ts DESC NULLS LAST\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "provider_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "global_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "thread_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider_thread_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "replying_to_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 6,
+ "name": "link_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 7,
+ "name": "provider_history_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 8,
+ "name": "internal_date_ts",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "snippet",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "size_estimate",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 11,
+ "name": "subject",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
+ "name": "from_name",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 13,
+ "name": "from_contact_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 14,
+ "name": "sent_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 15,
+ "name": "has_attachments",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 16,
+ "name": "is_read",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 17,
+ "name": "is_starred",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 18,
+ "name": "is_sent",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 19,
+ "name": "is_draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 20,
+ "name": "headers_jsonb",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 21,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 22,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 23,
+ "name": "body_text",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 24,
+ "name": "body_html_sanitized",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 25,
+ "name": "body_macro",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ true,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false,
+ true,
+ true,
+ null
+ ]
+ },
+ "hash": "7f8601bd8c738ab2e656f22c009f7c6599dd2dd0de63c92a772d6638bec6ef77"
+}
diff --git a/rust/cloud-storage/email_db_client/src/messages/get_parsed_search.rs b/rust/cloud-storage/email_db_client/src/messages/get_parsed_search.rs
index 24fc446149..9cc87d379b 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get_parsed_search.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get_parsed_search.rs
@@ -71,6 +71,92 @@ pub async fn get_parsed_search_message_by_id(
)))
}
+/// Get parsed search messages for multiple threads at once.
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_parsed_search_messages_by_thread_ids(
+ pool: &PgPool,
+ thread_ids: &[Uuid],
+) -> anyhow::Result<Vec<message::ParsedSearchMessage>> {
+ let mut conn = pool.acquire().await?;
+
+ let db_messages: Vec<db::message::Message> = sqlx::query_as!(
+ db::message::Message,
+ r#"
+ SELECT
+ id,
+ provider_id,
+ global_id,
+ thread_id,
+ provider_thread_id,
+ replying_to_id,
+ link_id,
+ provider_history_id,
+ internal_date_ts,
+ snippet,
+ size_estimate,
+ subject,
+ from_name,
+ from_contact_id,
+ sent_at,
+ has_attachments,
+ is_read,
+ is_starred,
+ is_sent,
+ is_draft,
+ headers_jsonb,
+ created_at,
+ updated_at,
+ body_text as body_text,
+ body_html_sanitized as body_html_sanitized,
+ NULL::TEXT as body_macro
+ FROM email_messages
+ WHERE thread_id = ANY($1)
+ ORDER BY internal_date_ts DESC NULLS LAST
+ "#,
+ thread_ids
+ )
+ .fetch_all(&mut *conn)
+ .await?;
+
+ if db_messages.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ let message_ids: Vec<Uuid> = db_messages.iter().map(|m| m.id).collect();
+
+ let senders_map = contacts::get::get_senders_contacts_map(&mut *conn, &message_ids).await?;
+ let recipients_map =
+ contacts::get::fetch_db_recipients_in_bulk(&mut *conn, &message_ids).await?;
+ let labels_map = labels::get::fetch_message_labels_in_bulk(&mut *conn, &message_ids).await?;
+
+ let tasks: Vec<_> = db_messages
+ .into_iter()
+ .map(|message| {
+ let senders_map = &senders_map;
+ let recipients_map = &recipients_map;
+ let labels_map = &labels_map;
+
+ async move {
+ let sender = message
+ .from_contact_id
+ .and_then(|id| senders_map.get(&id).cloned());
+ let recipients = recipients_map.get(&message.id).cloned().unwrap_or_default();
+ let labels = labels_map.get(&message.id).cloned().unwrap_or_default();
+
+ let service_message = db_to_service::map_attachmentless_db_message_to_service(
+ message, sender, recipients, None, labels,
+ );
+
+ ParsedSearchMessage::from(MessageWithBodyReplyless::from(service_message))
+ }
+ })
+ .collect();
+
+ let result = join_all(tasks).await;
+
+ Ok(result)
+}
+
/// get a paginated number of messages for a given thread.
#[tracing::instrument(skip(pool), err)]
pub async fn get_paginated_parsed_search_messages_by_thread_id(
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 047f8a521f..04390fa90a 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -69,6 +69,7 @@ sfs_delete = []
[dependencies]
ammonia = "4.1.0"
+openssl = { workspace = true }
anyhow = { workspace = true }
authentication_service_client = { path = "../authentication_service_client" }
macro_aws_config = { path = "../macro_aws_config", features = ["s3", "sqs"] }
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs b/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs
index 60227c526a..28a5de524b 100644
--- a/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs
+++ b/rust/cloud-storage/email_service/src/bin/backfill_search/backfill_search.rs
@@ -9,10 +9,12 @@
/// e.g. SINCE=2026-03-16T00:00:00Z
/// - EMAIL_INDEX_OVERRIDE: Override the target OpenSearch index for email upserts
/// e.g. EMAIL_INDEX_OVERRIDE=emails_v2
+/// - BATCH_SIZE: Number of threads per SQS batch message (default: 50)
+/// e.g. BATCH_SIZE=100
use anyhow::Context;
use macro_entrypoint::MacroEntrypoint;
use sqlx::postgres::PgPoolOptions;
-use sqs_client::search::{SearchQueueMessage, email::EmailThreadMessage};
+use sqs_client::search::{SearchQueueMessage, email::EmailThreadBatchMessage};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
@@ -39,6 +41,11 @@ async fn main() -> anyhow::Result<()> {
let index_override = std::env::var("EMAIL_INDEX_OVERRIDE").ok();
+ let batch_size: usize = std::env::var("BATCH_SIZE")
+ .unwrap_or("50".to_string())
+ .parse()
+ .context("BATCH_SIZE must be a valid number")?;
+
if let Some(ref index) = index_override {
println!("Index override: {}", index);
}
@@ -81,14 +88,28 @@ async fn main() -> anyhow::Result<()> {
total += thread_and_macro_user_ids.len();
- let search_messages: Vec<SearchQueueMessage> = thread_and_macro_user_ids
+ let mut user_threads: std::collections::HashMap<String, Vec<String>> =
+ std::collections::HashMap::new();
+ for (thread_id, macro_user_id) in thread_and_macro_user_ids {
+ user_threads
+ .entry(macro_user_id)
+ .or_default()
+ .push(thread_id.to_string());
+ }
+
+ let search_messages: Vec<SearchQueueMessage> = user_threads
.into_iter()
- .map(|(thread_id, macro_user_id)| {
- SearchQueueMessage::ExtractEmailThreadMessage(EmailThreadMessage {
- thread_id: thread_id.to_string(),
- macro_user_id,
- index_override: index_override.clone(),
- })
+ .flat_map(|(macro_user_id, thread_ids)| {
+ thread_ids
+ .chunks(batch_size)
+ .map(|chunk| {
+ SearchQueueMessage::ExtractEmailThreadBatch(EmailThreadBatchMessage {
+ thread_ids: chunk.to_vec(),
+ macro_user_id: macro_user_id.clone(),
+ index_override: index_override.clone(),
+ })
+ })
+ .collect::<Vec<_>>()
})
.collect();
diff --git a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs
index 1f0449423b..c7256eb83a 100644
--- a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs
@@ -5,7 +5,7 @@ use opensearch_client::{
OpensearchClient, date_format::EpochSeconds, upsert::email::UpsertEmailArgs,
};
use sqlx::PgPool;
-use sqs_client::search::email::{EmailMessage, EmailThreadMessage};
+use sqs_client::search::email::{EmailMessage, EmailThreadBatchMessage, EmailThreadMessage};
use uuid::Uuid;
pub async fn process_upsert_message(
@@ -125,7 +125,7 @@ pub async fn process_upsert_thread_message(
) -> anyhow::Result<()> {
let mut message_offset = 0;
// Max is 100
- let message_limit = 10;
+ let message_limit = 100;
let thread_id: Uuid = upsert_email_thread_message
.thread_id
@@ -245,3 +245,114 @@ pub async fn process_upsert_thread_message(
Ok(())
}
+
+pub async fn process_upsert_thread_batch_message(
+ opensearch_client: &OpensearchClient,
+ db: &PgPool,
+ batch_message: &EmailThreadBatchMessage,
+) -> anyhow::Result<()> {
+ let thread_ids: Vec<Uuid> = batch_message
+ .thread_ids
+ .iter()
+ .map(|id| id.parse().context("failed to parse thread_id as UUID"))
+ .collect::<anyhow::Result<Vec<_>>>()?;
+
+ let now = EpochSeconds::new(Utc::now().timestamp())?;
+
+ let messages =
+ email_db_client::messages::get_parsed_search::get_parsed_search_messages_by_thread_ids(
+ db,
+ &thread_ids,
+ )
+ .await
+ .context("failed to get batch thread messages")?;
+
+ let mut upsert_email_message_args = Vec::new();
+
+ for message in messages {
+ if message.labels.iter().any(|label| {
+ label.provider_id == system_labels::SPAM || label.provider_id == system_labels::TRASH
+ }) {
+ continue;
+ }
+
+ if let Some(content) = message.body_parsed_linkless {
+ let sent_at = message
+ .internal_date_ts
+ .map(|date| EpochSeconds::new(date.timestamp()))
+ .transpose()?;
+
+ let updated_at = message
+ .internal_date_ts
+ .map(|date| EpochSeconds::new(date.timestamp()))
+ .transpose()?
+ .unwrap_or(now);
+
+ upsert_email_message_args.push(UpsertEmailArgs {
+ message_id: message.db_id.to_string(),
+ link_id: message.link_id.to_string(),
+ user_id: batch_message.macro_user_id.clone(),
+ thread_id: message.thread_db_id.to_string(),
+ subject: message.subject,
+ sender: message
+ .from
+ .as_ref()
+ .map(|f| f.email.to_lowercase())
+ .unwrap_or_default(),
+ sender_name: message.from.as_ref().and_then(|f| f.name.clone()),
+ reply_to: message.reply_to.map(|r| r.to_lowercase()),
+ recipients: message
+ .to
+ .iter()
+ .map(|to| to.email.to_lowercase())
+ .collect(),
+ recipient_names: message.to.iter().filter_map(|to| to.name.clone()).collect(),
+ cc: message
+ .cc
+ .iter()
+ .map(|cc| cc.email.to_lowercase())
+ .collect(),
+ cc_names: message.cc.iter().filter_map(|cc| cc.name.clone()).collect(),
+ bcc: message
+ .bcc
+ .iter()
+ .map(|bcc| bcc.email.to_lowercase())
+ .collect(),
+ bcc_names: message
+ .bcc
+ .iter()
+ .filter_map(|bcc| bcc.name.clone())
+ .collect(),
+ labels: message
+ .labels
+ .iter()
+ .map(|label| label.name.clone())
+ .collect(),
+ content,
+ updated_at_seconds: updated_at,
+ sent_at_seconds: sent_at,
+ });
+ } else {
+ tracing::warn!("no content found for email message");
+ }
+ }
+
+ if !upsert_email_message_args.is_empty() {
+ let result = opensearch_client
+ .bulk_upsert_email_messages(
+ &upsert_email_message_args,
+ batch_message.index_override.as_deref(),
+ )
+ .await?;
+
+ if result.failed > 0 {
+ tracing::warn!(
+ failed = result.failed,
+ errors = ?result.errors,
+ "some email messages failed to upsert"
+ );
+ }
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/search_processing_service/src/process/mod.rs b/rust/cloud-storage/search_processing_service/src/process/mod.rs
index 21d34132e4..8ffba222a9 100644
--- a/rust/cloud-storage/search_processing_service/src/process/mod.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/mod.rs
@@ -50,6 +50,14 @@ pub async fn process_message(
email::upsert::process_upsert_thread_message(&ctx.opensearch_client, &ctx.db, &message)
.await?;
}
+ SearchQueueMessage::ExtractEmailThreadBatch(message) => {
+ email::upsert::process_upsert_thread_batch_message(
+ &ctx.opensearch_client,
+ &ctx.db,
+ &message,
+ )
+ .await?;
+ }
SearchQueueMessage::RemoveEmailMessage(message) => {
email::remove::process_remove_message(&ctx.opensearch_client, &message).await?;
}
diff --git a/rust/cloud-storage/sqs_client/src/search/email.rs b/rust/cloud-storage/sqs_client/src/search/email.rs
index 59da8a82f9..2982d928f1 100644
--- a/rust/cloud-storage/sqs_client/src/search/email.rs
+++ b/rust/cloud-storage/sqs_client/src/search/email.rs
@@ -17,6 +17,17 @@ pub struct EmailThreadMessage {
pub index_override: Option<String>,
}
+#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]
+pub struct EmailThreadBatchMessage {
+ /// The thread ids to process
+ pub thread_ids: Vec<String>,
+ /// The macro user id of the user who the messages are for
+ pub macro_user_id: String,
+ /// Optional override for the target OpenSearch index
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub index_override: Option<String>,
+}
+
#[derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Debug)]
pub struct EmailLinkMessage {
/// The link id
diff --git a/rust/cloud-storage/sqs_client/src/search/mod.rs b/rust/cloud-storage/sqs_client/src/search/mod.rs
index 3e02498168..ba3473240d 100644
--- a/rust/cloud-storage/sqs_client/src/search/mod.rs
+++ b/rust/cloud-storage/sqs_client/src/search/mod.rs
@@ -4,7 +4,7 @@ use crate::{
channel::{ChannelMessageUpdate, RemoveChannelMessage},
chat::{ChatMessage, RemoveChatMessage},
document::{DocumentId, SearchExtractorMessage},
- email::{EmailLinkMessage, EmailMessage, EmailThreadMessage},
+ email::{EmailLinkMessage, EmailMessage, EmailThreadBatchMessage, EmailThreadMessage},
},
};
use anyhow::Context;
@@ -76,6 +76,7 @@ pub enum SearchQueueMessage {
RemoveEmailMessage(EmailMessage),
ExtractEmailThreadMessage(EmailThreadMessage),
RemoveEmailLink(EmailLinkMessage),
+ ExtractEmailThreadBatch(EmailThreadBatchMessage),
// Channel
ChannelMessageUpdate(ChannelMessageUpdate),
RemoveChannelMessage(RemoveChannelMessage),
@@ -96,6 +97,9 @@ impl PrimaryId for SearchQueueMessage {
SearchQueueMessage::ExtractEmailMessage(message)
| SearchQueueMessage::RemoveEmailMessage(message) => message.message_id.clone(),
SearchQueueMessage::ExtractEmailThreadMessage(message) => message.thread_id.clone(),
+ SearchQueueMessage::ExtractEmailThreadBatch(message) => {
+ message.thread_ids.first().cloned().unwrap_or_default()
+ }
SearchQueueMessage::RemoveEmailLink(message) => message.link_id.clone(),
SearchQueueMessage::ChannelMessageUpdate(message) => message.message_id.clone(),
SearchQueueMessage::RemoveChannelMessage(message) => {
@@ -125,6 +129,7 @@ impl SearchQueueMessage {
SearchQueueMessage::ExtractEmailMessage(_) => Operation::ExtractText,
SearchQueueMessage::RemoveEmailMessage(_) => Operation::Remove,
SearchQueueMessage::ExtractEmailThreadMessage(_) => Operation::ExtractText,
+ SearchQueueMessage::ExtractEmailThreadBatch(_) => Operation::ExtractText,
SearchQueueMessage::RemoveEmailLink(_) => Operation::Remove,
// Channels
SearchQueueMessage::ChannelMessageUpdate(_) => Operation::ExtractText,