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.

perf(search): reduce backend response payload (#1734)

gbirmana4ce73747a72
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder.rs b/rust/cloud-storage/opensearch_client/src/search/builder.rs
index cb29f3b29e..9cb3ddbd5d 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder.rs
@@ -336,7 +336,7 @@ impl<T: SearchQueryConfig> SearchQueryBuilder<T> {
.highlight_type("plain")
.pre_tags(vec![MacroEm::Open.to_string()])
.post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(0),
+ .number_of_fragments(1),
),
};
diff --git a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
index a4a8279a4a..cae80e2714 100644
--- a/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/builder/test.rs
@@ -144,7 +144,7 @@ fn test_build_search_request() -> anyhow::Result<()> {
"fields": {
"content": {
"type": "plain",
- "number_of_fragments": 0,
+ "number_of_fragments": 1,
"pre_tags": ["<macro_em>"],
"post_tags": ["</macro_em>"],
},
@@ -212,7 +212,7 @@ fn test_build_search_request() -> anyhow::Result<()> {
"fields": {
"content": {
"type": "plain",
- "number_of_fragments": 0,
+ "number_of_fragments": 1,
"pre_tags": ["<macro_em>"],
"post_tags": ["</macro_em>"],
},
diff --git a/rust/cloud-storage/opensearch_client/src/search/channels.rs b/rust/cloud-storage/opensearch_client/src/search/channels.rs
index bcb1c3c87b..08d12e3fdd 100644
--- a/rust/cloud-storage/opensearch_client/src/search/channels.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/channels.rs
@@ -5,7 +5,7 @@ use crate::{
builder::{SearchQueryBuilder, SearchQueryConfig, create_highlight_field},
model::{
DefaultSearchResponse, NameIndex, SearchGotoChannel, SearchGotoContent, SearchHit,
- parse_highlight_hit,
+ exclude_source_content, inject_fragment_size, parse_highlight_hit,
},
query::Keys,
},
@@ -25,7 +25,6 @@ pub(crate) struct ChannelMessageIndex {
pub thread_id: Option<uuid::Uuid>,
pub sender_id: String,
pub mentions: Vec<String>,
- pub content: String,
pub created_at_seconds: i64,
pub updated_at_seconds: i64,
}
@@ -170,8 +169,10 @@ impl From<ChannelMessageSearchArgs> for ChannelMessageQueryBuilder {
impl ChannelMessageSearchArgs {
pub fn build(self) -> Result<Value> {
let builder: ChannelMessageQueryBuilder = self.into();
-
- Ok(builder.build_search_request()?.to_json())
+ let mut json = builder.build_search_request()?.to_json();
+ inject_fragment_size(&mut json, 1000);
+ exclude_source_content(&mut json);
+ Ok(json)
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/chats.rs b/rust/cloud-storage/opensearch_client/src/search/chats.rs
index e72c3c7dea..dd03068c4a 100644
--- a/rust/cloud-storage/opensearch_client/src/search/chats.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/chats.rs
@@ -5,7 +5,7 @@ use crate::{
builder::{SearchQueryBuilder, SearchQueryConfig},
model::{
DefaultSearchResponse, NameIndex, SearchGotoChat, SearchGotoContent, SearchHit,
- parse_highlight_hit,
+ exclude_source_content, inject_fragment_size, parse_highlight_hit,
},
query::Keys,
utils::should_wildcard_field_query_builder,
@@ -24,7 +24,6 @@ pub(crate) struct ChatIndex {
pub user_id: String,
pub role: String,
pub title: String,
- pub content: String,
pub updated_at_seconds: Option<i64>,
}
@@ -135,7 +134,10 @@ impl From<ChatSearchArgs> for ChatQueryBuilder {
impl ChatSearchArgs {
pub fn build(self) -> Result<Value> {
let builder: ChatQueryBuilder = self.into();
- Ok(builder.build_search_request()?.to_json())
+ let mut json = builder.build_search_request()?.to_json();
+ inject_fragment_size(&mut json, 1000);
+ exclude_source_content(&mut json);
+ Ok(json)
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index 929c051407..1e98ee5bad 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -5,7 +5,7 @@ use crate::{
builder::{SearchQueryBuilder, SearchQueryConfig, create_highlight_field},
model::{
DefaultSearchResponse, NameIndex, SearchGotoContent, SearchGotoDocument, SearchHit,
- parse_highlight_hit,
+ exclude_source_content, inject_fragment_size, parse_highlight_hit,
},
query::Keys,
},
@@ -77,7 +77,6 @@ pub(crate) struct DocumentIndex {
pub document_name: String,
pub node_id: String,
pub raw_content: Option<String>,
- pub content: String,
pub owner_id: String,
pub file_type: String,
pub updated_at_seconds: Option<i64>,
@@ -122,7 +121,10 @@ impl From<DocumentSearchArgs> for DocumentQueryBuilder {
impl DocumentSearchArgs {
pub fn build(self) -> Result<Value> {
let builder: DocumentQueryBuilder = self.into();
- Ok(builder.build_search_request()?.to_json())
+ let mut json = builder.build_search_request()?.to_json();
+ inject_fragment_size(&mut json, 1000);
+ exclude_source_content(&mut json);
+ Ok(json)
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/emails.rs b/rust/cloud-storage/opensearch_client/src/search/emails.rs
index c2f1db1296..268b9272ba 100644
--- a/rust/cloud-storage/opensearch_client/src/search/emails.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/emails.rs
@@ -3,7 +3,10 @@ use crate::{
error::{OpensearchClientError, ResponseExt},
search::{
builder::{SearchQueryBuilder, SearchQueryConfig},
- model::{NameIndex, SearchGotoContent, SearchGotoEmail, SearchHit, parse_highlight_hit},
+ model::{
+ NameIndex, SearchGotoContent, SearchGotoEmail, SearchHit, exclude_source_content,
+ inject_fragment_size, parse_highlight_hit,
+ },
query::Keys,
utils::should_wildcard_field_query_builder,
},
@@ -239,8 +242,6 @@ pub(crate) struct EmailIndex {
pub subject: Option<String>,
/// The sent at time of the email message
pub sent_at_seconds: Option<i64>,
- /// The content of the email message
- pub content: String,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -297,7 +298,10 @@ impl From<EmailSearchArgs> for EmailQueryBuilder {
impl EmailSearchArgs {
pub fn build(self) -> Result<Value> {
let builder: EmailQueryBuilder = self.into();
- Ok(builder.build_search_request()?.to_json())
+ let mut json = builder.build_search_request()?.to_json();
+ inject_fragment_size(&mut json, 1000);
+ exclude_source_content(&mut json);
+ Ok(json)
}
}
diff --git a/rust/cloud-storage/opensearch_client/src/search/model.rs b/rust/cloud-storage/opensearch_client/src/search/model.rs
index 567c923585..590c426a30 100644
--- a/rust/cloud-storage/opensearch_client/src/search/model.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/model.rs
@@ -5,6 +5,120 @@ use models_opensearch::SearchEntityType;
use crate::search::query::Keys;
+/// Injects `fragment_size` into every highlight field config in the query JSON.
+/// The `opensearch_query_builder` crate doesn't support `fragment_size` natively,
+/// so we patch the serialized JSON after building.
+pub(crate) fn inject_fragment_size(query: &mut serde_json::Value, fragment_size: u32) {
+ if let Some(fields) = query
+ .pointer_mut("/highlight/fields")
+ .and_then(|v| v.as_object_mut())
+ {
+ for (_name, config) in fields.iter_mut() {
+ if let Some(obj) = config.as_object_mut() {
+ obj.insert(
+ "fragment_size".to_string(),
+ serde_json::json!(fragment_size),
+ );
+ }
+ }
+ }
+}
+
+/// Excludes `content` from `_source` in the query JSON. The content field is
+/// only needed in highlights, not in the raw source — excluding it cuts ~40%
+/// of the OpenSearch response payload.
+pub(crate) fn exclude_source_content(query: &mut serde_json::Value) {
+ if let Some(obj) = query.as_object_mut() {
+ obj.insert(
+ "_source".to_string(),
+ serde_json::json!({"excludes": ["content"]}),
+ );
+ }
+}
+
+const MAX_VISIBLE_FRAGMENT_CHARS: usize = 500;
+const OPEN_TAG: &str = "<macro_em>";
+const CLOSE_TAG: &str = "</macro_em>";
+
+fn normalize_highlight_fragment(fragment: &str) -> String {
+ let stripped: String = fragment
+ .chars()
+ .filter(|&c| {
+ !matches!(c,
+ '\u{2800}'..='\u{28FF}' | '\u{200B}'..='\u{200F}' |
+ '\u{2028}'..='\u{202F}' | '\u{2060}'..='\u{206F}' |
+ '\u{FEFF}' | '\u{00AD}' | '\u{034F}'
+ )
+ })
+ .collect();
+
+ let mut prev_space = false;
+ let normalized: String = stripped
+ .chars()
+ .filter_map(|c| {
+ if c == '\n' || c == '\r' || c.is_whitespace() {
+ if prev_space {
+ return None;
+ }
+ prev_space = true;
+ Some(' ')
+ } else {
+ prev_space = false;
+ Some(c)
+ }
+ })
+ .collect();
+
+ let trimmed = normalized.trim();
+ truncate_preserving_tags(trimmed, MAX_VISIBLE_FRAGMENT_CHARS)
+}
+
+/// Truncates a highlight fragment to `max_chars` visible characters (excluding
+/// `<macro_em>`/`</macro_em>` tags from the count). If truncation lands inside
+/// an open tag, the closing tag is appended. Adds "..." when truncated.
+fn truncate_preserving_tags(s: &str, max_chars: usize) -> String {
+ let mut result = String::new();
+ let mut visible_count = 0;
+ let mut inside_tag = false;
+ let mut chars = s.chars().peekable();
+
+ while let Some(&c) = chars.peek() {
+ if visible_count >= max_chars {
+ break;
+ }
+
+ if c == '<' {
+ let rest: String = chars.clone().collect();
+ if rest.starts_with(OPEN_TAG) {
+ for _ in 0..OPEN_TAG.len() {
+ result.push(chars.next().unwrap());
+ }
+ inside_tag = true;
+ continue;
+ } else if rest.starts_with(CLOSE_TAG) {
+ for _ in 0..CLOSE_TAG.len() {
+ result.push(chars.next().unwrap());
+ }
+ inside_tag = false;
+ continue;
+ }
+ }
+
+ result.push(c);
+ visible_count += 1;
+ chars.next();
+ }
+
+ if visible_count >= max_chars && chars.peek().is_some() {
+ if inside_tag {
+ result.push_str(CLOSE_TAG);
+ }
+ result.push_str("...");
+ }
+
+ result
+}
+
/// macro open/close tags for highlight matches
#[derive(Debug, PartialEq)]
pub(crate) enum MacroEm {
@@ -90,7 +204,7 @@ pub(crate) fn parse_highlight_hit(
.map(|v| v.to_string()),
content: highlight
.get(keys.content_key)
- .map(|v| v.to_vec())
+ .map(|v| v.iter().map(|f| normalize_highlight_fragment(f)).collect())
.unwrap_or_default(),
sender: highlight
.get("sender")
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index 090c08e48c..0d5bad1cee 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -16,7 +16,8 @@ use crate::{
emails::{EmailIndex, EmailQueryBuilder, EmailSearchArgs, EmailSearchConfig},
model::{
DefaultSearchResponse, Hit, MacroEm, SearchGotoChannel, SearchGotoChat,
- SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit, parse_highlight_hit,
+ SearchGotoContent, SearchGotoDocument, SearchGotoEmail, SearchHit,
+ exclude_source_content, inject_fragment_size, parse_highlight_hit,
},
query::Keys,
},
@@ -424,7 +425,7 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
.highlight_type("plain")
.pre_tags(vec![MacroEm::Open.to_string()])
.post_tags(vec![MacroEm::Close.to_string()])
- .number_of_fragments(0),
+ .number_of_fragments(1),
);
search_request_builder.highlight(highlight);
@@ -443,7 +444,9 @@ pub(crate) async fn search_unified(
client: &opensearch::OpenSearch,
args: UnifiedSearchArgs,
) -> Result<(Vec<SearchHit>, SearchCursorOption)> {
- let search_request = build_unified_search_request(&args)?.to_json();
+ let mut search_request = build_unified_search_request(&args)?.to_json();
+ inject_fragment_size(&mut search_request, 1000);
+ exclude_source_content(&mut search_request);
tracing::trace!("search request {:?}", search_request);
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
index 93eb54b33c..c8aac11151 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -474,7 +474,7 @@ fn test_build_unified_search_request_content() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": {
- "number_of_fragments": 0,
+ "number_of_fragments": 1,
"post_tags": ["</macro_em>"],
"pre_tags": ["<macro_em>"],
"type": "plain"
@@ -870,7 +870,7 @@ fn test_build_unified_search_request_single_index() -> anyhow::Result<()> {
"highlight": {
"fields": {
"content": {
- "number_of_fragments": 0,
+ "number_of_fragments": 1,
"post_tags": ["</macro_em>"],
"pre_tags": ["<macro_em>"],
"type": "plain"
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
index 4a562a2056..44ecaea64a 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified.rs
@@ -84,7 +84,7 @@ fn compute_next_cursor(
/// Creates a unified search request and performs the search
/// by calling individual simple search endpoints for each entity type
-#[tracing::instrument(skip(ctx, user_context, query_params, req), err)]
+#[tracing::instrument(skip(ctx, user_context, query_params), fields(user_id = %user_context.user_id), err)]
pub(in crate::api::search) async fn perform_unified_search(
ctx: &SearchHandlerState,
user_context: &UserContext,