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.

fix(search): paginate unified search by distinct entity, not inner hit (#4346)

gbirman521d0f0aa43a
diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rs
index 7e489b6f28..e912cded6a 100644
--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs
@@ -27,10 +27,11 @@ const CHILD_RELATION: &str = "chunk";
const MIN_PREFIX_LEN: usize = 3;
/// Cap on chunks returned per `has_child` clause inside `inner_hits`.
-/// OpenSearch's default is 3 which would silently drop matches on docs
-/// with many hits; pick a number well above any reasonable document's
-/// matching-chunk count for a single search.
-const INNER_HITS_PER_TERM: u32 = 100;
+/// Applied per term, so an N-term query can surface up to N times this many
+/// chunks per document. Highlight cost and response size scale with it (and
+/// with the term count), so it stays small. A grouped result row only previews
+/// a handful of matching passages per document.
+const INNER_HITS_PER_TERM: u32 = 10;
/// Cap on terms a `match_phrase_prefix` may expand the last word to.
/// OpenSearch's default of 50 is too aggressive — a prefix like `wo`
diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rs
index 4cbee1ab8d..32a85bface 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs
@@ -645,6 +645,48 @@ fn build_unified_search_request(args: &UnifiedSearchArgs) -> Result<SearchReques
Ok(search_request_builder.build())
}
+/// Trim a page of top-level OpenSearch hits and derive the next cursor.
+///
+/// The query fetches `page_size + 1` *top-level* hits — one per parent entity
+/// for the join-shape indices (documents, chats, call records), one per message
+/// for the flat indices. Pagination is measured in those top-level hits, never
+/// in the child inner-hits a single parent expands into: a document matched on
+/// many content chunks is still one entity against the page budget. Counting the
+/// expanded children instead lets a couple of chunk-heavy documents exhaust the
+/// budget and short the page while minting a spurious "more results" cursor.
+///
+/// The extra (`page_size + 1`th) hit only signals "more exist"; it is dropped
+/// before expansion. The cursor anchors on the last *included* entity — every
+/// child a parent expands into carries that parent's `entity_id`/`updated_at`,
+/// so the last expanded hit yields the correct `search_after` for the next page.
+fn paginate_unified_hits(
+ hits: Vec<Hit<UnifiedSearchIndex>>,
+ page_size: usize,
+) -> (Vec<SearchHit>, SearchCursorOption) {
+ let has_more = hits.len() > page_size;
+
+ let results: Vec<SearchHit> = hits
+ .into_iter()
+ .take(page_size)
+ .flat_map(expand_hit_into_search_hits)
+ .collect();
+
+ // Continue only with a real anchor to resume from. A page_size of 0 yields
+ // an empty page (nothing to anchor on), so emitting NotDone there would loop
+ // the caller on identical empty pages. Return a terminal cursor instead.
+ let cursor = match results.last() {
+ Some(last) if has_more && page_size > 0 => {
+ SearchCursorOption::NotDone(Some(SearchMethodCursor::UpdatedAt {
+ entity_id: last.entity_id,
+ updated_at: last.updated_at.unwrap_or_else(Utc::now),
+ }))
+ }
+ _ => SearchCursorOption::Done,
+ };
+
+ (results, cursor)
+}
+
#[tracing::instrument(skip(client, args), err)]
pub(crate) async fn search_unified(
client: &opensearch::OpenSearch,
@@ -699,27 +741,7 @@ pub(crate) async fn search_unified(
"opensearch response"
);
- let mut results: Vec<SearchHit> = result
- .hits
- .hits
- .into_iter()
- .flat_map(expand_hit_into_search_hits)
- .collect();
-
- let has_more = results.len() > args.page_size as usize;
-
- if has_more {
- results.pop(); // Remove the extra item
- }
-
- let cursor = if has_more {
- SearchCursorOption::NotDone(results.last().map(|last| SearchMethodCursor::UpdatedAt {
- entity_id: last.entity_id,
- updated_at: last.updated_at.unwrap_or_else(Utc::now),
- }))
- } else {
- SearchCursorOption::Done
- };
+ let (results, cursor) = paginate_unified_hits(result.hits.hits, args.page_size as usize);
Ok((results, cursor))
}
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 fe33d88eee..97e196e373 100644
--- a/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
+++ b/rust/cloud-storage/opensearch_client/src/search/unified/test.rs
@@ -894,3 +894,125 @@ fn test_thread_sort_is_thread_id_then_message_id_field_sorts() {
assert_eq!(json[1]["message_id"]["order"], "desc");
assert_eq!(json[1]["message_id"]["unmapped_type"], "keyword");
}
+
+/// A join-shape parent document whose content matched on `chunk_count` chunks,
+/// shaped like the `inner_hits` block OpenSearch returns for a `has_child`
+/// content query.
+fn doc_hit_with_chunks(
+ entity_id: uuid::Uuid,
+ updated_at_seconds: i64,
+ chunk_count: usize,
+) -> Hit<UnifiedSearchIndex> {
+ let chunks: Vec<serde_json::Value> = (0..chunk_count)
+ .map(|i| {
+ serde_json::json!({
+ "_id": format!("{entity_id}-chunk-{i}"),
+ "_score": 1.0,
+ "_source": { "node_id": format!("node-{i}"), "raw_content": "match" },
+ "highlight": { "content": ["<macro_em>match</macro_em>"] },
+ })
+ })
+ .collect();
+
+ Hit {
+ score: Some(1.0),
+ source: UnifiedSearchIndex::Document(DocumentIndex {
+ entity_id,
+ document_name: "Doc".to_string(),
+ owner_id: "alice".to_string(),
+ file_type: "md".to_string(),
+ updated_at_seconds: Some(updated_at_seconds),
+ }),
+ highlight: None,
+ inner_hits: Some(serde_json::json!({ "term_0": { "hits": { "hits": chunks } } })),
+ }
+}
+
+#[test]
+fn paginate_counts_parent_entities_not_inner_hits() {
+ // Two documents, each matched on many content chunks. The expanded hit count
+ // far exceeds page_size, but there are only two entities — the page is not
+ // full, so no spurious "more" cursor is minted and every chunk is returned.
+ let d1 = "00000000-0000-0000-0000-000000000001"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let d2 = "00000000-0000-0000-0000-000000000002"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let hits = vec![
+ doc_hit_with_chunks(d1, 1_779_000_100, 30),
+ doc_hit_with_chunks(d2, 1_779_000_050, 30),
+ ];
+
+ let (results, cursor) = paginate_unified_hits(hits, 10);
+
+ assert_eq!(
+ results.len(),
+ 60,
+ "all chunks of both documents are returned"
+ );
+ assert!(
+ cursor.is_done(),
+ "two entities under a page_size of 10 must not report more results, got {cursor:?}"
+ );
+}
+
+#[test]
+fn paginate_has_more_when_parent_count_exceeds_page_size() {
+ // page_size + 1 distinct documents: the extra one signals more, is dropped
+ // before expansion, and the cursor anchors on the last *included* document.
+ let d1 = "00000000-0000-0000-0000-000000000001"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let d2 = "00000000-0000-0000-0000-000000000002"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let d3 = "00000000-0000-0000-0000-000000000003"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let hits = vec![
+ doc_hit_with_chunks(d1, 1_779_000_300, 5),
+ doc_hit_with_chunks(d2, 1_779_000_200, 5),
+ doc_hit_with_chunks(d3, 1_779_000_100, 5),
+ ];
+
+ let (results, cursor) = paginate_unified_hits(hits, 2);
+
+ assert_eq!(
+ results.len(),
+ 10,
+ "only the two included docs' chunks remain"
+ );
+ assert!(
+ results
+ .iter()
+ .all(|h| h.entity_id == d1 || h.entity_id == d2),
+ "the third document must be dropped entirely, not partially"
+ );
+ match cursor {
+ SearchCursorOption::NotDone(Some(c)) => {
+ let (id, _) = c.as_updated_at().expect("UpdatedAt cursor");
+ assert_eq!(id, d2, "cursor anchors on the last included entity");
+ }
+ _ => panic!("expected NotDone cursor, got {cursor:?}"),
+ }
+}
+
+#[test]
+fn paginate_page_size_zero_terminates() {
+ // page_size 0 passes request validation, and the query fetches size(1) so a
+ // hit can return. The page is empty (take(0)) with no anchor, so the cursor
+ // must be Done — a NotDone here would loop the caller on empty pages.
+ let d1 = "00000000-0000-0000-0000-000000000001"
+ .parse::<uuid::Uuid>()
+ .unwrap();
+ let hits = vec![doc_hit_with_chunks(d1, 1_779_000_100, 5)];
+
+ let (results, cursor) = paginate_unified_hits(hits, 0);
+
+ assert!(results.is_empty(), "page_size 0 yields no results");
+ assert!(
+ cursor.is_done(),
+ "no anchor to resume from must terminate, not loop, got {cursor:?}"
+ );
+}
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 2affa74b37..c1787b7cda 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
@@ -59,7 +59,41 @@ fn cursor_from_tagged(tagged: &TaggedSearchHit) -> Option<SearchMethodCursor> {
})
}
+/// Trim the merged, sorted hit list to the first `page_size` distinct entities,
+/// keeping every hit of an included entity. The page budget is entities, not
+/// hits: a content document expands to one hit per matching chunk and an email
+/// thread to one per matching message, so counting hits here lets a single
+/// chunk-heavy entity exhaust the budget and short the page.
+fn take_first_n_entities(combined: Vec<TaggedSearchHit>, page_size: usize) -> Vec<TaggedSearchHit> {
+ let mut page_entities = std::collections::HashSet::new();
+ combined
+ .into_iter()
+ .filter(|tagged| {
+ if page_entities.contains(&tagged.hit.entity_id) {
+ true
+ } else if page_entities.len() < page_size {
+ page_entities.insert(tagged.hit.entity_id);
+ true
+ } else {
+ false
+ }
+ })
+ .collect()
+}
+
+/// Count distinct entities among `hits` (multiple hits can share one entity_id —
+/// content chunks of a document, messages of an email thread).
+fn distinct_entity_count<'a>(hits: impl IntoIterator<Item = &'a SearchHit>) -> usize {
+ hits.into_iter()
+ .map(|h| h.entity_id)
+ .collect::<std::collections::HashSet<_>>()
+ .len()
+}
+
/// Computes the next cursor for a search source based on pagination state.
+///
+/// `included_count`/`original_count` are measured in distinct entities, not hits,
+/// so a chunk-heavy source is not falsely judged truncated.
fn compute_next_cursor(
next_cursor_from_search: &SearchCursorOption,
included_count: usize,
@@ -67,9 +101,15 @@ fn compute_next_cursor(
last_included_hit: Option<&TaggedSearchHit>,
original_cursor: &SearchCursorOption,
) -> SearchCursorOption {
- if next_cursor_from_search.is_done() {
+ // `included_count < original_count` means the cross-source merge dropped some
+ // of this source's entities to stay within the page budget — they must be
+ // re-surfaced next page even when the sub-search itself reported Done, so the
+ // sub-search reporting Done is not on its own enough to end this source.
+ let truncated_in_merge = included_count < original_count;
+
+ if !truncated_in_merge && next_cursor_from_search.is_done() {
SearchCursorOption::Done
- } else if included_count < original_count || next_cursor_from_search.has_more() {
+ } else if truncated_in_merge || next_cursor_from_search.has_more() {
if included_count > 0 {
SearchCursorOption::NotDone(last_included_hit.and_then(cursor_from_tagged))
} else {
@@ -473,7 +513,10 @@ pub(in crate::api::search) async fn perform_unified_search(
// Track original counts before combining
let chat_name_count = chat_hits.len();
let project_name_count = project_hits.len();
- let content_count = content_hits.len();
+ // Content hits are chunk-level (many per document), so the page budget counts
+ // distinct documents. Name/crm sub-searches return one row per entity, so
+ // their hit count already equals their entity count.
+ let content_count = distinct_entity_count(&content_hits);
let crm_count = crm_hits.len();
let final_tagged = {
@@ -516,10 +559,10 @@ pub(in crate::api::search) async fn perform_unified_search(
(None, None) => b.hit.entity_id.cmp(&a.hit.entity_id),
});
- // Take only page_size results
+ // Take the first page_size distinct entities (keeping all of each
+ // entity's hits), not the first page_size hits.
let page_size_usize = page_size as usize;
- let final_tagged: Vec<TaggedSearchHit> =
- combined.into_iter().take(page_size_usize).collect();
+ let final_tagged: Vec<TaggedSearchHit> = take_first_n_entities(combined, page_size_usize);
tracing::debug!(
final_count = final_tagged.len(),
@@ -541,10 +584,12 @@ pub(in crate::api::search) async fn perform_unified_search(
.iter()
.filter(|h| h.source == SearchSource::ProjectName)
.count();
- let included_content = final_tagged
- .iter()
- .filter(|h| h.source == SearchSource::Content)
- .count();
+ let included_content = distinct_entity_count(
+ final_tagged
+ .iter()
+ .filter(|h| h.source == SearchSource::Content)
+ .map(|h| &h.hit),
+ );
let included_crm = final_tagged
.iter()
.filter(|h| h.source == SearchSource::CrmCompany)
diff --git a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
index 666d29eae6..9b16488381 100644
--- a/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
+++ b/rust/cloud-storage/search_service/src/api/search/simple/simple_unified/test.rs
@@ -31,21 +31,31 @@ fn ts(secs: i64) -> chrono::DateTime<Utc> {
// ==================== Tests for compute_next_cursor ====================
#[test]
-fn test_compute_next_cursor_search_is_done_returns_done() {
- // When search returned Done, always return Done regardless of other params
+fn test_compute_next_cursor_search_done_but_truncated_in_merge_continues() {
+ // The sub-search reported Done, but the cross-source merge dropped some of
+ // this source's entities (included < original). Those must resurface next
+ // page, so the cursor continues from the last included hit rather than ending
+ // — returning Done here would silently lose the bumped entities.
+ let entity_id = Uuid::new_v4();
+ let timestamp = ts(1000);
+ let last_hit = make_tagged_hit(entity_id, Some(timestamp), SearchSource::ProjectName);
+
let result = compute_next_cursor(
&SearchCursorOption::Done,
5, // included_count
- 10, // original_count (more than included)
- Some(&make_tagged_hit(
- Uuid::new_v4(),
- Some(ts(1000)),
- SearchSource::ProjectName,
- )),
+ 10, // original_count (more than included — truncated in merge)
+ Some(&last_hit),
&SearchCursorOption::NotDone(None),
);
- assert!(result.is_done());
+ match result {
+ SearchCursorOption::NotDone(Some(cursor)) => {
+ let (id, got_ts) = cursor.as_updated_at().expect("expected UpdatedAt cursor");
+ assert_eq!(id, entity_id);
+ assert_eq!(got_ts, timestamp);
+ }
+ _ => panic!("Expected NotDone with cursor, got {:?}", result),
+ }
}
#[test]
@@ -198,6 +208,55 @@ fn test_compute_next_cursor_hit_without_timestamp_returns_none_cursor() {
}
}
+// ==================== Tests for take_first_n_entities ====================
+
+#[test]
+fn take_first_n_entities_budgets_distinct_entities_keeping_all_hits() {
+ let e1 = Uuid::new_v4();
+ let e2 = Uuid::new_v4();
+ let e3 = Uuid::new_v4();
+ // e1 contributes 3 hits (e.g. three matching content chunks), e2 and e3 one
+ // each. The budget is 2 entities.
+ let combined = vec![
+ make_tagged_hit(e1, Some(ts(3000)), SearchSource::Content),
+ make_tagged_hit(e1, Some(ts(3000)), SearchSource::Content),
+ make_tagged_hit(e1, Some(ts(3000)), SearchSource::Content),
+ make_tagged_hit(e2, Some(ts(2000)), SearchSource::Content),
+ make_tagged_hit(e3, Some(ts(1000)), SearchSource::Content),
+ ];
+
+ let result = take_first_n_entities(combined, 2);
+
+ // All three of e1's hits plus e2's single hit; e3 dropped entirely.
+ assert_eq!(result.len(), 4);
+ assert_eq!(
+ result.iter().filter(|t| t.hit.entity_id == e1).count(),
+ 3,
+ "every hit of an included entity is kept together"
+ );
+ assert!(
+ result
+ .iter()
+ .all(|t| t.hit.entity_id == e1 || t.hit.entity_id == e2),
+ "the third entity must not appear once the budget is full"
+ );
+}
+
+#[test]
+fn take_first_n_entities_keeps_all_when_under_budget() {
+ let e1 = Uuid::new_v4();
+ let e2 = Uuid::new_v4();
+ let combined = vec![
+ make_tagged_hit(e1, Some(ts(2000)), SearchSource::Content),
+ make_tagged_hit(e1, Some(ts(2000)), SearchSource::Content),
+ make_tagged_hit(e2, Some(ts(1000)), SearchSource::ChatName),
+ ];
+
+ let result = take_first_n_entities(combined, 10);
+
+ assert_eq!(result.len(), 3, "nothing is dropped when under the budget");
+}
+
// ==================== Tests for find_last_of_source ====================
#[test]