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: improve SPS backfill performance (#1936)
gbirman349a24a63bb8
diff --git a/rust/cloud-storage/opensearch_client/src/document.rs b/rust/cloud-storage/opensearch_client/src/document.rsindex 88c15381c1..d1de8c9c59 100644--- a/rust/cloud-storage/opensearch_client/src/document.rs+++ b/rust/cloud-storage/opensearch_client/src/document.rs@@ -16,7 +16,7 @@ impl OpensearchClient {pub async fn bulk_upsert_documents(&self,documents: &[UpsertDocumentArgs],- ) -> Result<upsert::document::BulkUpsertResult> {+ ) -> Result<upsert::BulkUpsertResult> {upsert::document::bulk_upsert_documents(&self.inner, documents).await}diff --git a/rust/cloud-storage/opensearch_client/src/email.rs b/rust/cloud-storage/opensearch_client/src/email.rsindex 53a3142207..5a65dce8b4 100644--- a/rust/cloud-storage/opensearch_client/src/email.rs+++ b/rust/cloud-storage/opensearch_client/src/email.rs@@ -4,7 +4,7 @@ use crate::{emails::{EmailSearchArgs, search_emails},model::SearchHit,},- upsert::{self, email::UpsertEmailArgs},+ upsert::{self, BulkUpsertResult, email::UpsertEmailArgs},};impl OpensearchClient {@@ -14,6 +14,15 @@ impl OpensearchClient {upsert::email::upsert_email_message(&self.inner, upsert_email_args).await}+ /// Bulk upserts email messages into the opensearch index+ #[tracing::instrument(skip(self, messages))]+ pub async fn bulk_upsert_email_messages(+ &self,+ messages: &[UpsertEmailArgs],+ ) -> Result<BulkUpsertResult> {+ upsert::email::bulk_upsert_email_messages(&self.inner, messages).await+ }+pub async fn search_emails(&self, args: EmailSearchArgs) -> Result<Vec<SearchHit>> {search_emails(&self.inner, args).await}diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rsindex 9c4dbdc885..bdebb191bc 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs@@ -1,5 +1,6 @@use models_opensearch::SearchIndex;+use super::BulkUpsertResult;use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};/// The arguments for upserting a document into the opensearch index@@ -31,61 +32,16 @@ pub struct UpsertDocumentArgs {pub updated_at_seconds: EpochSeconds,}-#[derive(Debug, Default)]-pub struct BulkUpsertResult {- pub successful: usize,- pub failed: usize,- pub version_conflicts: usize,- pub errors: Vec<String>,-}--fn parse_bulk_response(response: &serde_json::Value) -> BulkUpsertResult {- let mut result = BulkUpsertResult::default();-- if let Some(items) = response["items"].as_array() {- for item in items {- if let Some(index_result) = item["index"].as_object()- && let Some(status) = index_result["status"].as_u64()- {- match status {- 200..=299 => result.successful += 1,- 409 => {- result.version_conflicts += 1;- result.failed += 1;- if let Some(error) = index_result["error"].as_object()- && let Some(reason) = error["reason"].as_str()- {- result.errors.push(reason.to_string());- }- }- _ => {- result.failed += 1;- if let Some(error) = index_result["error"].as_object()- && let Some(reason) = error["reason"].as_str()- {- result.errors.push(reason.to_string());- }- }- }- }- }- }-- result-}-/// Process a single chunk of documentsasync fn bulk_upsert_single_chunk(client: &opensearch::OpenSearch,documents: &[UpsertDocumentArgs],) -> Result<BulkUpsertResult> {- // Build bulk request bodylet mut bulk_body = Vec::new();for doc in documents {let id = format!("{}:{}", doc.document_id, doc.node_id);- // Index action (upsert)let action = serde_json::json!({"index": {"_id": id@@ -101,53 +57,13 @@ async fn bulk_upsert_single_chunk(})?);}- let response = client- .bulk(opensearch::BulkParts::Index(- SearchIndex::Documents.as_ref(),- ))- .body(bulk_body)- .refresh(opensearch::params::Refresh::WaitFor) // Ensure consistency- .send()- .await- .map_err(|err| OpensearchClientError::Unknown {- details: err.to_string(),- method: Some("bulk_upsert_single_chunk".to_string()),- })?;-- let status_code = response.status_code();- if !status_code.is_success() {- let body =- response- .text()- .await- .map_err(|err| OpensearchClientError::DeserializationFailed {- details: err.to_string(),- method: Some("bulk_upsert_single_chunk".to_string()),- })?;-- tracing::error!(- status_code = ?status_code,- body = ?body,- "bulk upsert chunk failed"- );-- return Err(OpensearchClientError::Unknown {- details: body,- method: Some("bulk_upsert_single_chunk".to_string()),- });- }-- // Parse response to check for individual errors- let response_body: serde_json::Value =- response- .json()- .await- .map_err(|err| OpensearchClientError::DeserializationFailed {- details: err.to_string(),- method: Some("bulk_upsert_single_chunk".to_string()),- })?;-- let result = parse_bulk_response(&response_body);+ let result = super::bulk_upsert_to_index(+ client,+ SearchIndex::Documents.as_ref(),+ bulk_body,+ "bulk_upsert_single_chunk",+ )+ .await?;tracing::trace!(chunk_total = documents.len(),diff --git a/rust/cloud-storage/opensearch_client/src/upsert/email.rs b/rust/cloud-storage/opensearch_client/src/upsert/email.rsindex 58d30257a0..1d2be8fe8c 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/email.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/email.rs@@ -1,5 +1,6 @@use models_opensearch::SearchIndex;+use super::BulkUpsertResult;use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};/// The arguments for upserting an email message into the opensearch index@@ -91,3 +92,41 @@ pub(crate) async fn upsert_email_message(}Ok(())}++#[tracing::instrument(skip(client, messages), err)]+pub(crate) async fn bulk_upsert_email_messages(+ client: &opensearch::OpenSearch,+ messages: &[UpsertEmailArgs],+) -> Result<BulkUpsertResult> {+ if messages.is_empty() {+ return Ok(BulkUpsertResult::default());+ }++ let mut bulk_body = Vec::new();++ for msg in messages {+ let id = format!("{}:{}", msg.thread_id, msg.message_id);++ let action = serde_json::json!({+ "index": {+ "_id": id+ }+ });++ bulk_body.push(action.to_string());+ bulk_body.push(serde_json::to_string(msg).map_err(|e| {+ OpensearchClientError::DeserializationFailed {+ details: e.to_string(),+ method: Some("bulk_upsert_email_messages".to_string()),+ }+ })?);+ }++ super::bulk_upsert_to_index(+ client,+ SearchIndex::Emails.as_ref(),+ bulk_body,+ "bulk_upsert_email_messages",+ )+ .await+}diff --git a/rust/cloud-storage/opensearch_client/src/upsert/mod.rs b/rust/cloud-storage/opensearch_client/src/upsert/mod.rsindex 313f5e18ee..3ba451666d 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/mod.rs@@ -3,3 +3,104 @@ pub mod chat_message;pub mod document;pub mod email;pub mod name;++use crate::error::OpensearchClientError;++/// Result of a bulk upsert operation+#[derive(Debug, Default)]+pub struct BulkUpsertResult {+ /// Number of successfully upserted documents+ pub successful: usize,+ /// Number of failed documents+ pub failed: usize,+ /// Number of version conflicts+ pub version_conflicts: usize,+ /// Error messages from failed documents+ pub errors: Vec<String>,+}++pub(crate) fn parse_bulk_response(response: &serde_json::Value) -> BulkUpsertResult {+ let mut result = BulkUpsertResult::default();++ if let Some(items) = response["items"].as_array() {+ for item in items {+ if let Some(index_result) = item["index"].as_object()+ && let Some(status) = index_result["status"].as_u64()+ {+ match status {+ 200..=299 => result.successful += 1,+ 409 => {+ result.version_conflicts += 1;+ result.failed += 1;+ if let Some(error) = index_result["error"].as_object()+ && let Some(reason) = error["reason"].as_str()+ {+ result.errors.push(reason.to_string());+ }+ }+ _ => {+ result.failed += 1;+ if let Some(error) = index_result["error"].as_object()+ && let Some(reason) = error["reason"].as_str()+ {+ result.errors.push(reason.to_string());+ }+ }+ }+ }+ }+ }++ result+}++pub(crate) async fn bulk_upsert_to_index(+ client: &opensearch::OpenSearch,+ index: &str,+ bulk_body: Vec<String>,+ method_name: &str,+) -> crate::Result<BulkUpsertResult> {+ let response = client+ .bulk(opensearch::BulkParts::Index(index))+ .body(bulk_body)+ .send()+ .await+ .map_err(|err| OpensearchClientError::Unknown {+ details: err.to_string(),+ method: Some(method_name.to_string()),+ })?;++ let status_code = response.status_code();+ if !status_code.is_success() {+ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some(method_name.to_string()),+ })?;++ tracing::error!(+ status_code = ?status_code,+ body = ?body,+ "bulk upsert failed"+ );++ return Err(OpensearchClientError::Unknown {+ details: body,+ method: Some(method_name.to_string()),+ });+ }++ let response_body: serde_json::Value =+ response+ .json()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some(method_name.to_string()),+ })?;++ Ok(parse_bulk_response(&response_body))+}diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rsindex 973cd616cd..644ef8f293 100644--- a/rust/cloud-storage/search_processing_service/src/config.rs+++ b/rust/cloud-storage/search_processing_service/src/config.rs@@ -55,7 +55,7 @@ impl Config {std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;let queue_max_messages: i32 = std::env::var("QUEUE_MAX_MESSAGES")- .unwrap_or("1".to_string())+ .unwrap_or("10".to_string()).parse::<i32>().unwrap();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.rsindex b7f49ee185..a1d128d79a 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@@ -223,9 +223,16 @@ pub async fn process_upsert_thread_message(}if !upsert_email_message_args.is_empty() {- // TODO: parllelize- for message in upsert_email_message_args {- opensearch_client.upsert_email_message(&message).await?;+ let result = opensearch_client+ .bulk_upsert_email_messages(&upsert_email_message_args)+ .await?;++ if result.failed > 0 {+ tracing::warn!(+ failed = result.failed,+ errors = ?result.errors,+ "some email messages failed to upsert"+ );}}diff --git a/rust/cloud-storage/search_processing_service/src/process/worker.rs b/rust/cloud-storage/search_processing_service/src/process/worker.rsindex a23baded7d..94fa410bb6 100644--- a/rust/cloud-storage/search_processing_service/src/process/worker.rs+++ b/rust/cloud-storage/search_processing_service/src/process/worker.rs@@ -31,13 +31,13 @@ pub async fn run_search_processing_worker_with_id(ctx: SearchProcessingContext,if messages.is_empty() {continue;}- let result = futures::stream::iter(messages.iter())- .then(|message| {+ let result = futures::stream::iter(messages.into_iter())+ .map(|message| {let ctx = ctx.clone();async move {let result = tokio::time::timeout(std::time::Duration::from_secs(300), // 5 minutes- process::process_message(&ctx, message)+ process::process_message(&ctx, &message)).await;match result {@@ -53,6 +53,7 @@ pub async fn run_search_processing_worker_with_id(ctx: SearchProcessingContext,}}})+ .buffer_unordered(10).collect::<Vec<Result<(), (String, anyhow::Error)>>>().await;