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(sps): speed up name index backfill script (#430)
Will Hutchinson992d3052d1c1
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 3558d755c8..627ea51f4a 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -8262,6 +8262,7 @@ dependencies = ["anyhow","aws-sdk-sqs","chrono",+ "futures","model","models_email","models_opensearch",diff --git a/rust/cloud-storage/deleted_item_poller/src/handler.rs b/rust/cloud-storage/deleted_item_poller/src/handler.rsindex 2085db794e..cfde6e1061 100644--- a/rust/cloud-storage/deleted_item_poller/src/handler.rs+++ b/rust/cloud-storage/deleted_item_poller/src/handler.rs@@ -1,7 +1,6 @@use crate::context::{self};use anyhow::Context;use aws_lambda_events::eventbridge::EventBridgeEvent;-use lambda_runtime::tracing::Instrument;use lambda_runtime::{Error, LambdaEvent,tracing::{self},@@ -10,45 +9,26 @@ use sqs_client::search::{SearchQueueMessage, chat::RemoveChatMessage, document::DocumentId, project,};-#[tracing::instrument(skip(ctx, _event))]+#[tracing::instrument(skip(ctx, _event), err)]pub async fn handler(ctx: context::Context,_event: LambdaEvent<EventBridgeEvent>,) -> Result<(), Error> {- let chat_handle = tokio::spawn({- let ctx = ctx.clone();- async move { handle_chats(&ctx).await }- });-- let document_handle = tokio::spawn({- let ctx = ctx.clone();- async move { handle_documents(&ctx).await }- });-- let project_handle = tokio::spawn({- let ctx = ctx.clone();- async move { handle_projects(&ctx).await }- });-- // Use tokio::try_join! macro- let (chat_result, document_result, project_result) =- tokio::try_join!(chat_handle, document_handle, project_handle)?;-- // Propagate any errors from the tasks- project_result.context("error handling projects")?;- chat_result.context("error handling chats")?;- document_result.context("error handling documents")?;+ let _ = tokio::try_join!(+ handle_chats(&ctx),+ handle_documents(&ctx),+ handle_projects(&ctx)+ )?;Ok(())}-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(skip(ctx), err)]async fn handle_projects(ctx: &context::Context) -> anyhow::Result<()> {let date = chrono::Utc::now().naive_utc() - chrono::Duration::days(30);- let projects_to_delete = macro_db_client::projects::get_projects_to_delete(&ctx.db, &date)- .await- .context("unable to get projects to delete")?;+ let projects_to_delete =+ macro_db_client::projects::get_projects_to_delete(&ctx.db, &date).await?;if projects_to_delete.is_empty() {tracing::info!("no projects to delete");@@ -63,34 +43,23 @@ async fn handle_projects(ctx: &context::Context) -> anyhow::Result<()> {.await.context("unable to delete projects")?;- // delete projects from search- tokio::spawn({- let sqs_client = ctx.sqs_client.clone();- let project_ids = projects_to_delete.clone();- async move {- tracing::trace!("sending message to search extractor queue");- let _ = sqs_client- .send_message_to_search_event_queue(SearchQueueMessage::BulkRemoveProjectMessage(- project::BulkRemoveProjectMessage { project_ids },- ))- .await- .inspect_err(|e| {- tracing::error!(error=?e, "SEARCH_QUEUE unable to enqueue message");- });- }- .in_current_span()- });+ let _ = ctx+ .sqs_client+ .send_message_to_search_event_queue(SearchQueueMessage::BulkRemoveProjectMessage(+ project::BulkRemoveProjectMessage {+ project_ids: projects_to_delete,+ },+ ))+ .await?;Ok(())}-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(skip(ctx), err)]async fn handle_chats(ctx: &context::Context) -> anyhow::Result<()> {let date = chrono::Utc::now().naive_utc() - chrono::Duration::days(30);- let chats_to_delete = macro_db_client::chat::get_chats_to_delete(&ctx.db, &date)- .await- .context("unable to get chats to delete")?;+ let chats_to_delete = macro_db_client::chat::get_chats_to_delete(&ctx.db, &date).await?;if chats_to_delete.is_empty() {tracing::info!("no chats to delete");@@ -111,25 +80,22 @@ async fn handle_chats(ctx: &context::Context) -> anyhow::Result<()> {}).collect(),)- .await- .context("unable to enqueue chat delete for search")?;+ .await?;ctx.sqs_client.bulk_enqueue_chat_delete(chats_to_delete)- .await- .context("unable to enqueue chat delete")?;+ .await?;Ok(())}-#[tracing::instrument(skip(ctx))]+#[tracing::instrument(skip(ctx), err)]async fn handle_documents(ctx: &context::Context) -> anyhow::Result<()> {let date = chrono::Utc::now().naive_utc() - chrono::Duration::days(30);let documents_to_delete =macro_db_client::document::get_all_documents::get_documents_to_delete(&ctx.db, &date)- .await- .context("unable to get documents to delete")?;+ .await?;if documents_to_delete.is_empty() {tracing::info!("no documents to delete");@@ -149,13 +115,11 @@ async fn handle_documents(ctx: &context::Context) -> anyhow::Result<()> {}).collect(),)- .await- .context("unable to enqueue chat delete for search")?;+ .await?;ctx.sqs_client.bulk_enqueue_document_delete(documents_to_delete)- .await- .context("unable to enqueue document delete")?;+ .await?;Ok(())}diff --git a/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs b/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rsindex cee16357bf..3cd4b480f5 100644--- a/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs+++ b/rust/cloud-storage/search_processing_service/src/bin/backfill_entity_names.rs@@ -8,12 +8,14 @@/// Example:/// cargo run backfill_entity_names.rs chats,documentsuse anyhow::Context;+use macro_entrypoint::MacroEntrypoint;use models_opensearch::SearchEntityType;use sqlx::postgres::PgPoolOptions;use sqs_client::search::name::EntityName;use std::future::Future;use std::str::FromStr;+use std::sync::Arc;use uuid::Uuid;#[tokio::main]@@ -60,12 +62,13 @@ async fn main() -> anyhow::Result<()> {println!("Starting backfill for indices: {:?}", target_indices);let database_url = std::env::var("DATABASE_URL").context("DATABASE_URL not set")?;- let db = PgPoolOptions::new()- .min_connections(10)- .max_connections(60)- .connect(&database_url)- .await- .context("could not connect to db")?;+ let db = Arc::new(+ PgPoolOptions::new()+ .min_connections(10)+ .max_connections(60)+ .connect(&database_url)+ .await?,+ );let search_event_queue =std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE not set")?;@@ -75,71 +78,125 @@ async fn main() -> anyhow::Result<()> {.load().await;- let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))- .search_event_queue(&search_event_queue);-- for index in target_indices {- match index {- SearchEntityType::Chats => {- backfill_entities(- &sqs_client,- "chats",- SearchEntityType::Chats,- |limit, offset| {- macro_db_client::chat::get::get_all_chat_ids_paginated(&db, limit, offset)- },- )- .await?;- }- SearchEntityType::Documents => {- backfill_entities(- &sqs_client,- "documents",- SearchEntityType::Documents,- |limit, offset| {- macro_db_client::document::get_all_documents::get_all_document_ids_paginated(- &db, limit, offset,+ let sqs_client = Arc::new(+ sqs_client::SQS::new(aws_sdk_sqs::Client::new(&queue_aws_config))+ .search_event_queue(&search_event_queue),+ );++ // Process all entity types in parallel+ let handles: Vec<_> = target_indices+ .into_iter()+ .map(|index| {+ let db = Arc::clone(&db);+ let sqs_client = Arc::clone(&sqs_client);++ tokio::spawn(async move {+ let result = match index {+ SearchEntityType::Chats => {+ backfill_entities(+ &sqs_client,+ "chats",+ SearchEntityType::Chats,+ |limit, offset| {+ let db = Arc::clone(&db);+ async move {+ macro_db_client::chat::get::get_all_chat_ids_paginated(+ &db, limit, offset,+ )+ .await+ }+ },)- },- )- .await?;- }- SearchEntityType::Channels => {- backfill_entities(- &sqs_client,- "channels",- SearchEntityType::Channels,- |limit, offset| {- comms_db_client::channels::get_channels::get_all_channel_ids_paginated(- &db, limit, offset,+ .await+ }+ SearchEntityType::Documents => {+ backfill_entities(+ &sqs_client,+ "documents",+ SearchEntityType::Documents,+ |limit, offset| {+ let db = Arc::clone(&db);+ async move {+ macro_db_client::document::get_all_documents::get_all_document_ids_paginated(+ &db, limit, offset,+ )+ .await+ }+ },)- },- )- .await?;- }- SearchEntityType::Emails => {- backfill_entities(- &sqs_client,- "email threads",- SearchEntityType::Emails,- |limit, offset| {- email_db_client::threads::get::get_all_thread_ids_paginated(- &db, limit, offset,+ .await+ }+ SearchEntityType::Channels => {+ backfill_entities(+ &sqs_client,+ "channels",+ SearchEntityType::Channels,+ |limit, offset| {+ let db = Arc::clone(&db);+ async move {+ comms_db_client::channels::get_channels::get_all_channel_ids_paginated(+ &db, limit, offset,+ )+ .await+ }+ },+ )+ .await+ }+ SearchEntityType::Emails => {+ backfill_entities(+ &sqs_client,+ "email threads",+ SearchEntityType::Emails,+ |limit, offset| {+ let db = Arc::clone(&db);+ async move {+ email_db_client::threads::get::get_all_thread_ids_paginated(+ &db, limit, offset,+ )+ .await+ }+ },)- },- )- .await?;+ .await+ }+ SearchEntityType::Projects => {+ unreachable!("Backfill logic for 'projects' is not implemented.");+ }+ };++ (index, result)+ })+ })+ .collect();++ // Wait for all tasks and report results+ let mut had_errors = false;+ for handle in handles {+ match handle.await {+ Ok((index, Ok(()))) => {+ println!("Successfully completed backfill for {:?}", index);}- SearchEntityType::Projects => {- unreachable!("Backfill logic for 'projects' is not implemented.");+ Ok((index, Err(e))) => {+ eprintln!("Error backfilling {:?}: {:?}", index, e);+ had_errors = true;+ }+ Err(e) => {+ eprintln!("Task panicked: {:?}", e);+ had_errors = true;}}}+ if had_errors {+ anyhow::bail!("One or more backfill tasks failed");+ }+Ok(())}/// Generic function to handle pagination, UUID parsing, and SQS queuing for any entity type+/// Uses concurrent batch processing for improved throughputasync fn backfill_entities<F, Fut>(sqs_client: &sqs_client::SQS,name: &str,@@ -147,18 +204,18 @@ async fn backfill_entities<F, Fut>(fetcher: F,) -> anyhow::Result<()>where- F: Fn(i64, i64) -> Fut, // Function taking (limit, offset)- Fut: Future<Output = anyhow::Result<Vec<String>>>,+ F: Fn(i64, i64) -> Fut + Send + Sync,+ Fut: Future<Output = anyhow::Result<Vec<String>>> + Send,{let limit = 5000;let mut offset = 0;let mut count = 0;loop {- println!("getting {name}");+ println!("[{}] fetching batch at offset {}", name, offset);let ids = fetcher(limit, offset).await?;- println!("got batch offset {offset}");+ println!("[{}] got {} ids at offset {}", name, ids.len(), offset);if ids.is_empty() {tracing::trace!("no more {name} found");@@ -167,29 +224,27 @@ wherecount += ids.len();- tracing::trace!(count = ids.len(), "ready to queue {name}");+ let messages: Vec<_> = ids+ .iter()+ .map(|id| {+ sqs_client::search::SearchQueueMessage::UpdateEntityName(EntityName {+ entity_id: Uuid::parse_str(id)+ .with_context(|| format!("Failed to parse UUID from {}: {}", name, id))+ .unwrap(),+ entity_type: entity_type.clone(),+ })+ })+ .collect();sqs_client- .bulk_send_message_to_search_event_queue(- ids.iter()- .map(|id| {- sqs_client::search::SearchQueueMessage::UpdateEntityName(EntityName {- entity_id: Uuid::parse_str(id)- .with_context(|| {- format!("Failed to parse UUID from {}: {}", name, id)- })- .unwrap(),- entity_type: entity_type.clone(),- })- })- .collect(),- )+ .bulk_send_message_to_search_event_queue(messages).await?;- println!("queued batch with offset {offset}");++ println!("[{}] queued batch at offset {}", name, offset);offset += limit;}- println!("Completed. Total {} processed: {}", name, count);+ println!("[{}] Completed. Total processed: {}", name, count);Ok(())}diff --git a/rust/cloud-storage/sqs_client/Cargo.toml b/rust/cloud-storage/sqs_client/Cargo.tomlindex 4ad2649ad6..0af06bae65 100644--- a/rust/cloud-storage/sqs_client/Cargo.toml+++ b/rust/cloud-storage/sqs_client/Cargo.toml@@ -28,7 +28,7 @@ email = ["model", "models_email"]gmail = ["model", "uuid"]insight_context = ["model"]organization_retention = []-search = ["chrono", "model", "models_opensearch", "uuid"]+search = ["chrono", "model", "models_opensearch", "uuid", "futures"]sfs_uploader = []upload_extractor = []@@ -44,3 +44,4 @@ strum = { workspace = true, features = ["derive"] }tracing = { workspace = true }uuid = { workspace = true, optional = true }models_opensearch = { path = "../models_opensearch", optional = true }+futures = { workspace = true, optional = true }diff --git a/rust/cloud-storage/sqs_client/src/search/mod.rs b/rust/cloud-storage/sqs_client/src/search/mod.rsindex 258bbd949d..21b32723a3 100644--- a/rust/cloud-storage/sqs_client/src/search/mod.rs+++ b/rust/cloud-storage/sqs_client/src/search/mod.rs@@ -11,6 +11,7 @@ use crate::{};use anyhow::Context;use aws_sdk_sqs::{self as sqs, types::SendMessageBatchRequestEntry};+use futures::StreamExt;use strum::Display;pub mod channel;@@ -189,6 +190,8 @@ pub async fn enqueue_search_text_extractor(.to_string())}+const MAX_CONCURRENT_BATCHES: usize = 20;+/// Bulk enqueues items to the search text extractor queue#[tracing::instrument(skip(sqs_client, items))]pub async fn bulk_enqueue_search_text_extractor(@@ -199,14 +202,12 @@ pub async fn bulk_enqueue_search_text_extractor(let mut entries: Vec<SendMessageBatchRequestEntry> = vec![];for item in items {tracing::trace!(item=?item, "enqueueing search text extractor");-let message_str = serde_json::to_string(&item)?;- let batch_requesst = SendMessageBatchRequestEntry::builder()+ let batch_request = SendMessageBatchRequestEntry::builder().id(item.id()).message_body(message_str).build()?;-- entries.push(batch_requesst);+ entries.push(batch_request);}if entries.is_empty() {@@ -214,17 +215,25 @@ pub async fn bulk_enqueue_search_text_extractor(return Ok(());}- // Batch the entries in chunks of 10 and send each batch separately- for chunk in entries.chunks(MAX_BATCH_SIZE) {- let chunk_to_send = chunk.to_vec();-- // Send the batch+ let results: Vec<_> = futures::stream::iter(+ entries+ .chunks(MAX_BATCH_SIZE)+ .map(|chunk| chunk.to_vec())+ .collect::<Vec<_>>(),+ )+ .map(|chunk| {sqs_client.send_message_batch()- .set_entries(Some(chunk_to_send))+ .set_entries(Some(chunk)).queue_url(queue_url).send()- .await?;+ })+ .buffer_unordered(MAX_CONCURRENT_BATCHES)+ .collect()+ .await;++ for result in results {+ result?;}Ok(())diff --git a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zipindex ca2151e7aa..8cebfe6805 100644Binary files a/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip and b/rust/cloud-storage/target/lambda/deleted_item_poller/bootstrap.zip differ