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(search): has_child read path + write fixes for documents join shape (#3402)
gbirman95dcee39a817
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 32abb29434..ac0ca773a1 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -455,6 +455,15 @@ const cloudStorageService = new CloudStorageService(name: 'OPENSEARCH_PASSWORD',value: OPENSEARCH_PASSWORD,},+ {+ // Flips the documents alias dispatch in opensearch_client between+ // the flat-chunk shape (`documents_v1`) and the parent/child join+ // shape (`documents_v2`). Set via Pulumi config and flipped at+ // cutover; defaults to `false` so the existing flat-shape paths+ // stay active until the alias is swapped.+ name: 'DOCUMENTS_INDEX_USES_JOIN',+ value: config.get('documents_index_uses_join') ?? 'false',+ },{name: 'DATABASE_URL',value: pulumi.interpolate`${DATABASE_URL}`,diff --git a/infra/stacks/opensearch/helpers/constants.ts b/infra/stacks/opensearch/helpers/constants.tsindex 88bab9e623..22dc3a2a7f 100644--- a/infra/stacks/opensearch/helpers/constants.ts+++ b/infra/stacks/opensearch/helpers/constants.ts@@ -11,7 +11,7 @@ export const CALL_RECORDS_ALIAS = 'call_records';// version, then swap the alias atomically.export const CHANNELS_INDEX = 'channels_v1';export const CHATS_INDEX = 'chats_v1';-export const DOCUMENTS_INDEX = 'documents_v1';+export const DOCUMENTS_INDEX = 'documents_v2';export const EMAILS_INDEX = 'emails_v1';export const CALL_RECORDS_INDEX = 'call_records_v1';diff --git a/infra/stacks/opensearch/helpers/scripts/create_indices.ts b/infra/stacks/opensearch/helpers/scripts/create_indices.tsindex 7e2edb1a76..4d77399dc7 100644--- a/infra/stacks/opensearch/helpers/scripts/create_indices.ts+++ b/infra/stacks/opensearch/helpers/scripts/create_indices.ts@@ -224,6 +224,11 @@ const CHANNEL_BODY = {},};+// `documents_v2` uses an OpenSearch parent/child `join` field so we can+// AND multi-term searches across chunks of the same document via+// `has_child` queries. Parents carry the document's metadata; children+// carry per-chunk content. All children must be written with+// `routing = parent _id` so the pair lands on the same shard.const DOCUMENT_BODY = {settings: {...SHARD_SETTINGS,@@ -235,9 +240,19 @@ const DOCUMENT_BODY = {entity_id: {type: 'keyword',},- node_id: {+ // Parent-only metadata+ document_name: {+ type: 'text',+ fields: {+ keyword: {+ type: 'keyword',+ ignore_above: 128,+ },+ },+ },+ owner_id: {type: 'keyword',- index: false,+ index: true,doc_values: true,},file_type: {@@ -245,38 +260,35 @@ const DOCUMENT_BODY = {index: false,doc_values: true,},- owner_id: {+ sub_type: {type: 'keyword',index: true,doc_values: true,},- document_name: {- type: 'text',- fields: {- keyword: {- type: 'keyword',- ignore_above: 128,- },- },- },- raw_content: {- type: 'text',- },- content: {- type: 'text',- analyzer: 'standard',- },updated_at_seconds: {type: 'date',format: 'epoch_second',index: false,doc_values: true,},- sub_type: {+ // Child-only fields+ node_id: {type: 'keyword',- index: true,+ index: false,doc_values: true,},+ content: {+ type: 'text',+ analyzer: 'standard',+ },+ raw_content: {+ type: 'text',+ },+ // Join relationship+ document_relation: {+ type: 'join',+ relations: { document: 'chunk' },+ },},},};diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex 73cbb7980e..5efbdad746 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -141,6 +141,15 @@ const searchProcessingService = new SearchProcessingService(name: 'OPENSEARCH_PASSWORD',value: OPENSEARCH_PASSWORD,},+ {+ // Flips the documents alias dispatch in opensearch_client between+ // the flat-chunk shape (`documents_v1`) and the parent/child join+ // shape (`documents_v2`). Set via Pulumi config and flipped at+ // cutover; defaults to `false` so the existing flat-shape paths+ // stay active until the alias is swapped.+ name: 'DOCUMENTS_INDEX_USES_JOIN',+ value: config.get('documents_index_uses_join') ?? 'false',+ },{name: 'DOCUMENT_STORAGE_BUCKET',value: pulumi.interpolate`${documentStorageBucketId}`,diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.tsindex 6d8b00b7a1..cde61de82b 100644--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts@@ -730,7 +730,7 @@ export interface MarkdownNode {type: string;}/**- * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. For emails, whitespace-separated terms are ANDed and each term is matched independently across the text fields and the local-part of address fields, with the two groups OR'd. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `"deal review"` or `"[email protected]"`) to force exact-token matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.+ * Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `"deal review"` or `"[email protected]"`) to force exact-token / exact-phrase matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.*/export interface ContentSearch {/**@@ -738,7 +738,7 @@ export interface ContentSearch {*/entityTypes?: UnifiedSearchIndex[];/**- * The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched across subject/body/sender/recipient. Wrap a term in double quotes to force exact-token (or full-email-address) matching.+ * The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a term in double quotes to force exact-token (or full-email-address) matching.*/query: string;}diff --git a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs b/rust/cloud-storage/ai_tools/src/search/search_service/content.rsindex 295bd75338..524e373820 100644--- a/rust/cloud-storage/ai_tools/src/search/search_service/content.rs+++ b/rust/cloud-storage/ai_tools/src/search/search_service/content.rs@@ -14,12 +14,12 @@ use std::sync::Arc;#[derive(Debug, JsonSchema, Deserialize, Clone)]#[serde(rename_all = "camelCase")]#[schemars(- description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. For emails, whitespace-separated terms are ANDed and each term is matched independently across the text fields and the local-part of address fields, with the two groups OR'd. For all other types the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `\"deal review\"` or `\"[email protected]\"`) to force exact-token matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",+ description = "Search items by their content: document body text; email subject/body/sender/recipient/cc/bcc and the display names on those addresses; chat messages; call transcripts. Whitespace-separated terms are ANDed. For documents and emails, every term must match somewhere in the document — different terms can appear in different chunks/pages or different fields. For documents and emails specifically, each single-word term is matched as a prefix (so `scri` matches `script`); for emails the prefix expansion also runs against the local-part of address fields. For chats, channels, and call transcripts the whole query is matched as a single adjacent phrase prefix — so pass 1-3 targeted keywords drawn from words that would literally appear in the content, not the user's natural-language description; long phrases will not match. Wrap a term in double quotes (e.g. `\"deal review\"` or `\"[email protected]\"`) to force exact-token / exact-phrase matching instead of prefix. If the user's request combines a person with a topic, run separate searches rather than one combined query. Leave entityTypes empty by default; only filter when the user explicitly scopes to a type.",title = "ContentSearch")]pub struct ContentSearch {#[schemars(- description = "The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For non-email types the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. For emails each term is matched across subject/body/sender/recipient. Wrap a term in double quotes to force exact-token (or full-email-address) matching."+ description = "The text to search. Pass 1-3 keywords drawn from words that would literally appear in the content, not the user's natural-language description. Whitespace-separated terms are ANDed. For documents, every term must appear somewhere in the document (different chunks/pages are fine). For emails each term is matched across subject/body/sender/recipient. For chats/channels/calls the whole query is matched as a single adjacent phrase prefix, so long phrases will not match. Wrap a term in double quotes to force exact-token (or full-email-address) matching.")]pub query: String,diff --git a/rust/cloud-storage/opensearch_client/src/delete/document.rs b/rust/cloud-storage/opensearch_client/src/delete/document.rsindex a23e789632..677c5ee5c1 100644--- a/rust/cloud-storage/opensearch_client/src/delete/document.rs+++ b/rust/cloud-storage/opensearch_client/src/delete/document.rs@@ -1,6 +1,6 @@use models_opensearch::SearchIndex;-use crate::{Result, error::OpensearchClientError};+use crate::{Result, documents_shape::alias_uses_join_shape, error::OpensearchClientError};/// Deletes all document nodes with the specified document_id#[tracing::instrument(skip(client))]@@ -58,19 +58,42 @@ pub async fn delete_document_by_id(Ok(())}-/// Deletes all documents with the specified owner_id+/// Deletes every document owned by `owner_id`.+///+/// Flat shape: every chunk carries `owner_id`, so a simple term match+/// catches them all. Join shape: only parents carry `owner_id`, so the+/// query also matches children of those parents via `has_parent`.#[tracing::instrument(skip(client))]pub async fn delete_document_by_owner_id(client: &opensearch::OpenSearch,owner_id: &str,) -> Result<()> {- let query = serde_json::json!({- "query": {- "term": {- "owner_id": owner_id+ let query = if alias_uses_join_shape() {+ serde_json::json!({+ "query": {+ "bool": {+ "minimum_should_match": 1,+ "should": [+ { "term": { "owner_id": owner_id } },+ {+ "has_parent": {+ "parent_type": "document",+ "query": { "term": { "owner_id": owner_id } }+ }+ }+ ]+ }}- },- });+ })+ } else {+ serde_json::json!({+ "query": {+ "term": {+ "owner_id": owner_id+ }+ }+ })+ };let response = client.delete_by_query(opensearch::DeleteByQueryParts::Index(&[diff --git a/rust/cloud-storage/opensearch_client/src/documents_shape.rs b/rust/cloud-storage/opensearch_client/src/documents_shape.rsindex 7dbc8648da..0e00229b4f 100644--- a/rust/cloud-storage/opensearch_client/src/documents_shape.rs+++ b/rust/cloud-storage/opensearch_client/src/documents_shape.rs@@ -1,18 +1,76 @@-//! Dispatch helper for the documents index migration from a flat-chunk-//! shape (`documents_v1`) to a parent/child join shape (`documents_v2`).+//! Dispatch helpers for the documents index migration from a flat-chunk+//! shape to a parent/child join shape.//!-//! For now, only writes targeted explicitly at `documents_v2` (via the-//! backfill's `index_override`) take the join-shape code path. Reads, the-//! default-destination write path, and the eventual alias-swap dispatch-//! will come in follow-up changes.+//! Three dispatch points:+//!+//! * `destination_uses_join_shape(dest)` — used by writers that take an+//! explicit `index_override`. Returns `true` when the override names+//! the join-shape physical index so the backfill can target it in+//! join-shape mode while normal traffic continues writing flat docs+//! through the alias.+//!+//! * `alias_uses_join_shape()` — used by callers that always target the+//! `documents` alias (search reads, owner-id deletes, metadata+//! updates). Driven by the `DOCUMENTS_INDEX_USES_JOIN` env var so we+//! can flip the alias contract atomically with the alias swap without+//! per-call introspection.+//!+//! * `documents_search_alias()` — the alias name search reads target.+//! Defaults to `documents`. The `DOCUMENTS_INDEX_NAME` env var+//! overrides this so local end-to-end tests can read from a side+//! alias pointing only at the join-shape index, without disturbing+//! the shared `documents` alias on dev/prod.-/// Physical index name of the join-shape documents index.+use std::sync::OnceLock;++/// Physical name of the join-shape documents index. Used as the+/// `index_override` value for backfills that should write in the join+/// shape and as the trigger for `destination_uses_join_shape`.pub const DOCUMENTS_V2: &str = "documents_v2";+/// Default alias name reads target. Production code always uses this.+const DEFAULT_DOCUMENTS_ALIAS: &str = "documents";+/// Whether writes targeting this destination should use the parent/child-/// join shape. True only for the explicit `documents_v2` name today;-/// writes via the `documents` alias keep the flat-chunk shape until we-/// also switch the read path.+/// join shape. True when the destination is the explicit join-shape+/// index name and, when configured via env var, when it's the+/// `documents` alias too.pub fn destination_uses_join_shape(destination: &str) -> bool {- destination == DOCUMENTS_V2+ if destination == DOCUMENTS_V2 {+ return true;+ }+ if destination == "documents" {+ return alias_uses_join_shape();+ }+ false+}++/// Whether the `documents` alias currently resolves to a join-shape index.+///+/// Controlled by the `DOCUMENTS_INDEX_USES_JOIN` env var, cached once per+/// process. Operators set it `true` at the alias swap; before then it+/// defaults to `false` so the existing flat-shape paths stay active.+pub fn alias_uses_join_shape() -> bool {+ static ALIAS_USES_JOIN: OnceLock<bool> = OnceLock::new();+ *ALIAS_USES_JOIN.get_or_init(|| {+ std::env::var("DOCUMENTS_INDEX_USES_JOIN")+ .map(|v| v == "true")+ .unwrap_or(false)+ })+}++/// Alias name that search reads target for documents. Returns `documents`+/// by default; the `DOCUMENTS_INDEX_NAME` env var overrides this so local+/// tests can point at a side alias pointing only at the join-shape index+/// without disturbing the shared `documents` alias.+///+/// Only the read path consults this — writes still resolve through+/// `OpenSearchEntityType::Documents.index_name()` so the alias contract+/// for ingestion stays unchanged.+pub fn documents_search_alias() -> &'static str {+ static NAME: OnceLock<&'static str> = OnceLock::new();+ NAME.get_or_init(|| match std::env::var("DOCUMENTS_INDEX_NAME") {+ Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,+ _ => DEFAULT_DOCUMENTS_ALIAS,+ })}diff --git a/rust/cloud-storage/opensearch_client/src/search/documents.rs b/rust/cloud-storage/opensearch_client/src/search/documents.rsindex 3cb9d49ff4..8433b69060 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents.rs@@ -1,10 +1,43 @@+use std::collections::HashMap;+use crate::{Result, delegate_methods,- search::builder::{SearchQueryBuilder, SearchQueryConfig},+ documents_shape::{alias_uses_join_shape, documents_search_alias},+ search::{+ builder::{SearchQueryBuilder, SearchQueryConfig},+ model::{Highlight, SearchGotoContent, SearchGotoDocument, SearchHit, parse_highlight_hit},+ query::Keys,+ },+};++use chrono::{DateTime, Utc};+use models_opensearch::{OpenSearchEntityType, SearchEntityType};+use opensearch_query_builder::{+ BoolQueryBuilder, HasChildQuery, InnerHits, MatchPhrasePrefixQuery, MatchPhraseQuery,+ QueryType, ToOpenSearchJson,};-use models_opensearch::OpenSearchEntityType;-use opensearch_query_builder::{BoolQueryBuilder, QueryType};+/// Relation names for the join field. Kept in sync with the upsert path+/// in `upsert::document`.+const PARENT_RELATION: &str = "document";+const CHILD_RELATION: &str = "chunk";++/// Minimum prefix length before we emit a `match_phrase_prefix`. Matches+/// the email keyword-field threshold — shorter prefixes explode the term+/// set on the analyzer and risk hitting `max_clause_count`.+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;++/// 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`+/// can expand to far more real tokens. Picking a fixed ceiling keeps+/// query cost bounded without truncating common cases.+const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;#[derive(Clone)]pub(crate) struct DocumentSearchConfig;@@ -45,6 +78,16 @@ impl DocumentQueryBuilder {}pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ if alias_uses_join_shape() {+ return self.build_bool_query_join();+ }+ self.build_bool_query_flat()+ }++ /// Flat-chunk path: every chunk is its own top-level OpenSearch doc+ /// and the whole user query becomes a single phrase[-prefix] match+ /// on `content`.+ fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {let mut query = self.inner.build_content_bool_query()?;if !self.sub_types.is_empty() {@@ -56,13 +99,161 @@ impl DocumentQueryBuilder {Ok(query)}++ /// Parent/child join path: one `has_child` clause per term, ANDed+ /// inside `bool.must`. Parent metadata filters (owner, ids,+ /// sub_type) sit on `bool.filter` directly because they live on+ /// the parent doc.+ fn build_bool_query_join<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {+ if self.inner.ids_only && self.inner.ids.is_empty() {+ return Err(crate::error::OpensearchClientError::EmptyIdsWithIdsOnly(+ DocumentSearchConfig::ENTITY_INDEX,+ ));+ }+ if self.inner.terms.is_empty() {+ return Err(crate::error::OpensearchClientError::NoTermsProvided);+ }++ let mut bool_query = BoolQueryBuilder::new();++ // Restrict to parent documents in the documents alias (overridable+ // via DOCUMENTS_INDEX_NAME for local end-to-end testing against a+ // side alias).+ bool_query.filter(QueryType::term(+ "_index",+ documents_search_alias().to_string(),+ ));+ bool_query.filter(QueryType::term(+ "document_relation",+ PARENT_RELATION.to_string(),+ ));++ // Access control: filter on parent fields (owner_id and/or entity_id).+ bool_query.filter(self.build_parent_filter()?);++ // Optional sub_type filter (parent field).+ if !self.sub_types.is_empty() {+ bool_query.filter(QueryType::terms("sub_type", self.sub_types.clone()));+ }++ // One has_child clause per term, ANDed via bool.must. Each carries+ // its own inner_hits so highlights and chunk-nav data come back+ // alongside the parent. `size` is bumped well above the OpenSearch+ // default of 3 so a doc with many matching chunks returns all of+ // them (the flat shape had no per-doc cap; this preserves parity).+ //+ // The inner_hits highlight uses a shared `highlight_query` that+ // ORs every search term, so a chunk returned by any one+ // has_child clause gets tags around *every* term it contains —+ // not just the term whose clause produced it.+ let highlight_query =+ build_all_terms_highlight_query(&self.inner.terms, &self.inner.match_type);+ for (idx, term) in self.inner.terms.iter().enumerate() {+ let inner_query = build_child_content_query(term, &self.inner.match_type);+ let inner_hits = InnerHits::new()+ .name(format!("term_{idx}"))+ .size(INNER_HITS_PER_TERM)+ .highlight(inner_hits_content_highlight(&highlight_query));+ let has_child = HasChildQuery::new(CHILD_RELATION, inner_query).inner_hits(inner_hits);+ bool_query.must(has_child.into());+ }++ Ok(bool_query)+ }++ /// Build the access-control filter using parent-side fields: either+ /// `entity_id ∈ ids` (ids_only), `owner_id` alone, or a should-bool of+ /// both when ids are provided alongside the owner.+ fn build_parent_filter<'a>(&'a self) -> Result<QueryType<'a>> {+ let owner_key =+ DocumentSearchConfig::USER_ID_KEY.expect("documents config has owner_id key");++ if self.inner.ids_only {+ return Ok(QueryType::terms("entity_id", self.inner.ids.clone()));+ }+ let owner_query = QueryType::term(owner_key.to_string(), self.inner.user_id.clone());+ if self.inner.ids.is_empty() {+ return Ok(owner_query);+ }+ let mut filter = BoolQueryBuilder::new();+ filter.minimum_should_match(1);+ filter.should(QueryType::terms("entity_id", self.inner.ids.clone()));+ filter.should(owner_query);+ Ok(filter.build().into())+ }+}++/// Highlight config attached to each `has_child` inner_hits block.+/// Matches the top-level documents highlight (plain highlighter,+/// `<macro_em>` tags, single fragment) so chunk hits come back with+/// the same shape downstream consumers already handle.+///+/// `highlight_query` lets each clause tag every search term in the+/// returned chunk content, not just the term its own has_child matched.+fn inner_hits_content_highlight(highlight_query: &serde_json::Value) -> serde_json::Value {+ serde_json::json!({+ "require_field_match": true,+ "pre_tags": ["<macro_em>"],+ "post_tags": ["</macro_em>"],+ "fields": {+ "content": {+ "type": "plain",+ "number_of_fragments": 1,+ "fragment_size": 1000,+ "highlight_query": highlight_query,+ }+ }+ })+}++/// Combined OR-of-all-terms query used as the inner_hits highlight_query.+/// Single-term queries return that one term's query directly; multi-term+/// builds a `bool.should` so the highlighter tags every search term it+/// finds in the chunk's content.+fn build_all_terms_highlight_query(terms: &[String], match_type: &str) -> serde_json::Value {+ let term_queries: Vec<serde_json::Value> = terms+ .iter()+ .map(|t| build_child_content_query(t, match_type).to_json())+ .collect();+ if term_queries.len() == 1 {+ return term_queries.into_iter().next().unwrap();+ }+ serde_json::json!({+ "bool": {+ "should": term_queries,+ "minimum_should_match": 1,+ }+ })+}++/// Build the per-term query that runs inside `has_child` against `content`.+///+/// - Quoted phrases (term contains whitespace) → `match_phrase` (exact).+/// - Short terms (< `MIN_PREFIX_LEN`) → `match_phrase` (no prefix expansion).+/// - `match_type` = "exact" → `match_phrase` always.+/// - Otherwise → `match_phrase_prefix`.+fn build_child_content_query<'a>(term: &str, match_type: &str) -> QueryType<'a> {+ let exact = match_type == "exact"+ || term.chars().any(|c| c.is_whitespace())+ || term.chars().count() < MIN_PREFIX_LEN;+ if exact {+ QueryType::MatchPhrase(MatchPhraseQuery::new(+ "content".to_string(),+ term.to_string(),+ ))+ } else {+ QueryType::MatchPhrasePrefix(+ MatchPhrasePrefixQuery::new("content".to_string(), term.to_string())+ .max_expansions(MATCH_PHRASE_PREFIX_MAX_EXPANSIONS),+ )+ }}#[derive(Debug, serde::Serialize, serde::Deserialize)]pub(crate) struct DocumentIndex {pub entity_id: uuid::Uuid,pub document_name: String,- pub node_id: String,+ pub node_id: Option<String>,pub raw_content: Option<String>,pub owner_id: String,pub file_type: String,@@ -96,5 +287,103 @@ impl From<DocumentSearchArgs> for DocumentQueryBuilder {}}+// ---------------------------------------------------------------------------+// inner_hits → chunk-level SearchHits+// ---------------------------------------------------------------------------++/// One child chunk as it appears under `inner_hits.<term_name>.hits.hits[]`.+/// The fields we deserialize are exactly what we need to build a+/// `SearchHit` — anything else OpenSearch sends back is dropped.+#[derive(Debug, serde::Deserialize)]+struct ChunkInnerHit {+ #[serde(rename = "_id")]+ id: String,+ #[serde(rename = "_score")]+ score: Option<f64>,+ #[serde(rename = "_source")]+ source: ChunkSource,+ #[serde(default)]+ highlight: Option<HashMap<String, Vec<String>>>,+}++/// The chunk-only `_source` fields we surface in a `SearchHit.goto`.+#[derive(Debug, serde::Deserialize)]+struct ChunkSource {+ #[serde(default)]+ node_id: String,+ #[serde(default)]+ raw_content: Option<String>,+}++/// The shape of one entry under `inner_hits` — keyed by the+/// `has_child` clause name (e.g. `term_0`).+#[derive(Debug, serde::Deserialize)]+struct InnerHitsGroup {+ #[serde(default)]+ hits: InnerHitsList,+}++#[derive(Debug, Default, serde::Deserialize)]+struct InnerHitsList {+ #[serde(default)]+ hits: Vec<ChunkInnerHit>,+}++/// Walk the `inner_hits` block from a join-shape parent hit and emit+/// one `SearchHit` per matching chunk, carrying that chunk's+/// `node_id`, `raw_content`, score, and highlight.+///+/// A chunk matched by multiple `has_child` clauses (multi-term queries)+/// appears once per term in the response; we dedup by chunk `_id` so a+/// single chunk maps to a single `SearchHit` downstream.+///+/// Returns an empty vec if `inner_hits` is malformed or carries no+/// chunks — callers fall back to emitting a single parent hit so the+/// document still surfaces in results.+pub(crate) fn expand_inner_hits_to_search_hits(+ entity_id: uuid::Uuid,+ updated_at: Option<DateTime<Utc>>,+ inner_hits: &serde_json::Value,+) -> Vec<SearchHit> {+ let groups: HashMap<String, InnerHitsGroup> = match serde_json::from_value(inner_hits.clone()) {+ Ok(g) => g,+ Err(_) => return Vec::new(),+ };++ let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();+ let mut out: Vec<SearchHit> = Vec::new();+ for group in groups.into_values() {+ for chunk in group.hits.hits {+ if !seen.insert(chunk.id) {+ continue;+ }+ let highlight: Highlight = chunk+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: DocumentSearchConfig::TITLE_KEY,+ content_key: DocumentSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default();+ out.push(SearchHit {+ entity_id,+ entity_type: SearchEntityType::Documents,+ score: chunk.score,+ highlight,+ goto: Some(SearchGotoContent::Documents(SearchGotoDocument {+ node_id: chunk.source.node_id,+ raw_content: chunk.source.raw_content,+ })),+ updated_at,+ });+ }+ }+ out+}+#[cfg(test)]mod test;diff --git a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs b/rust/cloud-storage/opensearch_client/src/search/documents/test.rsindex 3d41565a89..00000d9c53 100644--- a/rust/cloud-storage/opensearch_client/src/search/documents/test.rs+++ b/rust/cloud-storage/opensearch_client/src/search/documents/test.rs@@ -1,8 +1,13 @@use super::*;use opensearch_query_builder::ToOpenSearchJson;+// `build_bool_query` dispatches on `alias_uses_join_shape()`, which is+// cached via OnceLock for the process lifetime — so tests call the+// explicit flat/join variants directly to stay deterministic regardless+// of env state.+#[test]-fn test_build_bool_query() -> anyhow::Result<()> {+fn test_build_bool_query_flat_shape() -> anyhow::Result<()> {let builder = DocumentQueryBuilder::new(vec!["test".to_string()]).match_type("exact").page_size(20)@@ -11,7 +16,7 @@ fn test_build_bool_query() -> anyhow::Result<()> {.collapse(true).ids(vec!["doc1".to_string(), "doc2".to_string()]);- let result = builder.build_bool_query()?;+ let result = builder.build_bool_query_flat()?;let expected = serde_json::json!({"bool": {@@ -44,3 +49,199 @@ fn test_build_bool_query() -> anyhow::Result<()> {Ok(())}++#[test]+fn test_build_bool_query_join_shape_multi_term_and() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string(), "bar".to_string()])+ .match_type("partial")+ .page_size(20)+ .page(0)+ .user_id("alice");++ let json = builder.build_bool_query_join()?.build().to_json();++ let filter = json["bool"]["filter"].as_array().expect("filter array");+ assert!(+ filter.contains(&serde_json::json!({"term": {"_index": "documents"}})),+ "filter must constrain to documents index: {filter:?}"+ );+ assert!(+ filter.contains(&serde_json::json!({"term": {"document_relation": "document"}})),+ "filter must constrain to parent docs: {filter:?}"+ );+ assert!(+ filter.contains(&serde_json::json!({"term": {"owner_id": "alice"}})),+ "filter must constrain to owner: {filter:?}"+ );++ let must = json["bool"]["must"].as_array().expect("must array");+ assert_eq!(must.len(), 2, "expected one has_child per term: {must:?}");++ let term_match = |val: &serde_json::Value, expected_term: &str, expected_type: &str| {+ let has_child = &val["has_child"];+ assert_eq!(has_child["type"], "chunk");+ assert_eq!(+ has_child["query"][expected_type]["content"]["query"],+ expected_term+ );+ };+ term_match(&must[0], "foo", "match_phrase_prefix");+ term_match(&must[1], "bar", "match_phrase_prefix");++ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_quoted_phrase_uses_match_phrase() -> anyhow::Result<()> {+ // A term that came from a quoted phrase has internal whitespace and+ // should fall back to match_phrase (no prefix expansion).+ let builder = DocumentQueryBuilder::new(vec!["deal review".to_string()])+ .match_type("partial")+ .user_id("alice");++ let json = builder.build_bool_query_join()?.build().to_json();+ let must = &json["bool"]["must"][0]["has_child"]["query"];+ assert!(+ must.get("match_phrase").is_some(),+ "quoted phrase should use match_phrase, got {must:?}"+ );+ assert_eq!(must["match_phrase"]["content"], "deal review");+ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_short_term_no_prefix() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["ab".to_string()])+ .match_type("partial")+ .user_id("alice");++ let json = builder.build_bool_query_join()?.build().to_json();+ let must = &json["bool"]["must"][0]["has_child"]["query"];+ assert!(+ must.get("match_phrase").is_some(),+ "short term should use match_phrase, got {must:?}"+ );+ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_exact_match_type_uses_match_phrase() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["release".to_string()])+ .match_type("exact")+ .user_id("alice");++ let json = builder.build_bool_query_join()?.build().to_json();+ let must = &json["bool"]["must"][0]["has_child"]["query"];+ assert!(+ must.get("match_phrase").is_some(),+ "match_type=exact should use match_phrase, got {must:?}"+ );+ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_ids_only_filter() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])+ .match_type("partial")+ .user_id("alice")+ .ids(vec!["doc1".to_string(), "doc2".to_string()])+ .ids_only(true);++ let json = builder.build_bool_query_join()?.build().to_json();+ let filter = json["bool"]["filter"].as_array().expect("filter array");+ assert!(+ filter.contains(&serde_json::json!({+ "terms": { "entity_id": ["doc1", "doc2"] }+ })),+ "ids_only should restrict to entity_id terms: {filter:?}"+ );+ assert!(+ !filter+ .iter()+ .any(|f| f.get("term").and_then(|t| t.get("owner_id")).is_some()),+ "ids_only should not include owner filter: {filter:?}"+ );+ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_sub_type_filter() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string()])+ .match_type("partial")+ .user_id("alice")+ .sub_types(vec!["task".to_string()]);++ let json = builder.build_bool_query_join()?.build().to_json();+ let filter = json["bool"]["filter"].as_array().expect("filter array");+ assert!(+ filter.contains(&serde_json::json!({"terms": {"sub_type": ["task"]}})),+ "sub_type filter should be on the parent: {filter:?}"+ );+ Ok(())+}++#[test]+fn test_build_bool_query_join_shape_has_inner_hits() -> anyhow::Result<()> {+ let builder = DocumentQueryBuilder::new(vec!["foo".to_string(), "bar".to_string()])+ .match_type("partial")+ .user_id("alice");++ let json = builder.build_bool_query_join()?.build().to_json();+ let must = json["bool"]["must"].as_array().expect("must array");+ for (idx, clause) in must.iter().enumerate() {+ let inner = &clause["has_child"]["inner_hits"];+ assert!(+ inner.is_object(),+ "expected inner_hits on has_child clause {idx}: {clause:?}"+ );+ assert_eq!(+ inner["name"],+ format!("term_{idx}"),+ "inner_hits name should be term_<idx>"+ );+ }+ Ok(())+}++#[test]+fn document_index_deserializes_parent_shape_with_no_node_id_or_raw_content() {+ // Join-shape parent docs only carry parent metadata in `_source`;+ // `node_id` and `raw_content` are child-only fields and are+ // absent. Deserialization has to succeed (otherwise the unified+ // search response 500s on any v2 hit) and produce None for both.+ let parent = serde_json::json!({+ "entity_id": "00000000-0000-0000-0000-000000000001",+ "document_name": "Q3 Planning",+ "owner_id": "macro|[email protected]",+ "file_type": "pdf",+ "updated_at_seconds": 1779000000_i64,+ "document_relation": "document",+ });++ let doc: DocumentIndex =+ serde_json::from_value(parent).expect("parent _source should deserialize");+ assert!(doc.node_id.is_none(), "parent shape should have no node_id");+ assert!(+ doc.raw_content.is_none(),+ "parent shape should have no raw_content"+ );+}++#[test]+fn document_index_deserializes_flat_chunk_shape_with_node_id() {+ // Flat-shape chunk docs carry node_id (and optionally raw_content)+ // directly. Make sure they keep deserializing after the move to+ // Option<String>.+ let chunk = serde_json::json!({+ "entity_id": "00000000-0000-0000-0000-000000000001",+ "document_name": "Q3 Planning",+ "node_id": "0",+ "owner_id": "macro|[email protected]",+ "file_type": "pdf",+ "content": "Page text",+ "updated_at_seconds": 1779000000_i64,+ });++ let doc: DocumentIndex = serde_json::from_value(chunk).expect("flat chunk should deserialize");+ assert_eq!(doc.node_id.as_deref(), Some("0"));+}diff --git a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs b/rust/cloud-storage/opensearch_client/src/search/model/mod.rsindex a0f2867b1e..9ec21f0dc9 100644--- a/rust/cloud-storage/opensearch_client/src/search/model/mod.rs+++ b/rust/cloud-storage/opensearch_client/src/search/model/mod.rs@@ -227,6 +227,12 @@ pub(crate) struct Hit<T> {/// Highlights may or may not be present since we could match/// purely on the title of the itempub highlight: Option<HashMap<String, Vec<String>>>,+ /// `inner_hits` come back attached to a parent hit when the query+ /// used `has_child` (the documents join shape). Kept as raw JSON+ /// because the structure is per-has_child-clause and only the+ /// documents branch consumes it today.+ #[serde(default)]+ pub inner_hits: Option<serde_json::Value>,}#[derive(Debug, serde::Serialize, serde::Deserialize, Default, Clone)]diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex c082945f88..6d2d6b4470 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -280,6 +280,36 @@ where}}+/// Expand one OpenSearch hit into one or more `SearchHit`s.+///+/// For the documents join shape, OpenSearch returns one parent hit per+/// matching document with the matching chunks nested under+/// `inner_hits`. The documents module knows how to unpack that into+/// chunk-level hits; everything else (flat indices, non-document hits)+/// takes the 1:1 conversion.+fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {+ let UnifiedSearchIndex::Document(parent) = &hit.source else {+ return vec![hit.into()];+ };+ let Some(inner) = hit.inner_hits.as_ref() else {+ return vec![hit.into()];+ };++ let entity_id = parent.entity_id;+ let updated_at = parent+ .updated_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0));++ let expanded =+ crate::search::documents::expand_inner_hits_to_search_hits(entity_id, updated_at, inner);+ if expanded.is_empty() {+ // Malformed or empty inner_hits — fall back to the parent so+ // the document still surfaces, just without per-chunk drill-down.+ return vec![hit.into()];+ }+ expanded+}+impl From<Hit<UnifiedSearchIndex>> for SearchHit {fn from(index: Hit<UnifiedSearchIndex>) -> Self {match index.source {@@ -327,7 +357,12 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {}).unwrap_or_default(),goto: Some(SearchGotoContent::Documents(SearchGotoDocument {- node_id: a.node_id,+ // Parent hits in the join shape have no node_id on+ // `_source` (it lives on the matching chunk in+ // inner_hits). Fall back to empty for now; piping+ // the chunk's node_id through inner_hits is a+ // follow-up.+ node_id: a.node_id.unwrap_or_default(),raw_content: a.raw_content,})),updated_at: a@@ -551,7 +586,17 @@ pub(crate) async fn search_unified(tracing::trace!("search request {:?}", search_request);- let search_indices: Vec<&str> = args.search_indices.iter().map(|i| i.index_name()).collect();+ // Documents reads can be redirected to a side alias via+ // DOCUMENTS_INDEX_NAME for local end-to-end testing; every other+ // entity type keeps its default alias.+ let search_indices: Vec<&str> = args+ .search_indices+ .iter()+ .map(|i| match i {+ OpenSearchEntityType::Documents => crate::documents_shape::documents_search_alias(),+ other => other.index_name(),+ })+ .collect();let response = async {client@@ -594,7 +639,12 @@ pub(crate) async fn search_unified("opensearch response");- let mut results: Vec<SearchHit> = result.hits.hits.into_iter().map(|h| h.into()).collect();+ 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;diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rsindex 8726ba82f0..8f461b9ddd 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs@@ -4,7 +4,9 @@ use models_opensearch::SearchIndex;use super::BulkUpsertResult;use crate::{- Result, date_format::EpochSeconds, documents_shape::destination_uses_join_shape,+ Result,+ date_format::EpochSeconds,+ documents_shape::{alias_uses_join_shape, destination_uses_join_shape},error::OpensearchClientError,};@@ -139,13 +141,15 @@ fn child_doc_body(chunk: &UpsertDocumentArgs) -> serde_json::Value {/// Process a single chunk of documents in the join shape.////// Emits, for each chunk:-/// - one parent upsert (deduped within this batch; the first time we see-/// a parent_id in this batch we emit `update` with `doc_as_upsert: true`)-/// - one child index op with `routing = parent_id`+/// - one parent `index` op with `routing = parent_id` (deduped within+/// this batch). We use full-overwrite `index` semantics rather than+/// `update + doc_as_upsert` so omitted optional fields like `sub_type`+/// get cleared when a document transitions from having them to not.+/// - one child `index` op with `routing = parent_id`.///-/// Cross-batch duplicate parent upserts are accepted as cheap idempotent-/// no-ops; deduping across batches would require either a pre-pass or-/// shared state, and isn't worth the complexity at the per-call scale.+/// Cross-batch duplicate parent writes are accepted as cheap last-writer-+/// wins overwrites; all writers should agree on parent metadata since it's+/// denormalized from the same source.async fn bulk_upsert_single_chunk_join(client: &opensearch::OpenSearch,documents: &[UpsertDocumentArgs],@@ -160,17 +164,13 @@ async fn bulk_upsert_single_chunk_join(if seen_parents.insert(parent_id) {let parent_action = serde_json::json!({- "update": {+ "index": {"_id": parent_id,"routing": routing,}});- let parent_body = serde_json::json!({- "doc": parent_doc_body(doc),- "doc_as_upsert": true,- });bulk_body.push(parent_action.to_string());- bulk_body.push(parent_body.to_string());+ bulk_body.push(parent_doc_body(doc).to_string());}let child_id = format!("{}:{}", doc.document_id, doc.node_id);@@ -334,8 +334,10 @@ async fn upsert_document_flat(})}-/// Upsert a single chunk in the join shape: parent upsert (idempotent)-/// followed by child index. Uses a 2-op bulk so both land in one request.+/// Upsert a single chunk in the join shape: parent index followed by+/// child index. Uses a 2-op bulk so both land in one request. Full-+/// overwrite `index` semantics on the parent ensure omitted optional+/// fields (e.g. `sub_type`) get cleared on Some→None transitions.async fn upsert_document_join(client: &opensearch::OpenSearch,args: &UpsertDocumentArgs,@@ -345,15 +347,11 @@ async fn upsert_document_join(let routing = parent_id;let parent_action = serde_json::json!({- "update": {+ "index": {"_id": parent_id,"routing": routing,}});- let parent_body = serde_json::json!({- "doc": parent_doc_body(args),- "doc_as_upsert": true,- });let child_id = format!("{}:{}", args.document_id, args.node_id);let child_action = serde_json::json!({@@ -365,7 +363,7 @@ async fn upsert_document_join(let bulk_body = vec![parent_action.to_string(),- parent_body.to_string(),+ parent_doc_body(args).to_string(),child_action.to_string(),child_doc_body(args).to_string(),];@@ -387,10 +385,27 @@ async fn upsert_document_join(Ok(())}+/// Update the denormalized `document_name` for an existing document.+///+/// Flat shape: `update_by_query` fans the new name across every chunk+/// doc. Join shape: a single partial-update on the parent (children+/// don't carry `document_name`).pub(crate) async fn update_document_metadata(client: &opensearch::OpenSearch,document_id: &str,document_name: &str,+) -> Result<()> {+ if alias_uses_join_shape() {+ update_document_metadata_join(client, document_id, document_name).await+ } else {+ update_document_metadata_flat(client, document_id, document_name).await+ }+}++async fn update_document_metadata_flat(+ client: &opensearch::OpenSearch,+ document_id: &str,+ document_name: &str,) -> Result<()> {use opensearch::UpdateByQueryParts;use serde_json::json;@@ -418,7 +433,7 @@ pub(crate) async fn update_document_metadata(.await.map_err(|err| OpensearchClientError::DeserializationFailed {details: err.to_string(),- method: Some("update_document_metadata".to_string()),+ method: Some("update_document_metadata_flat".to_string()),})?;let status_code = response.status_code();@@ -429,7 +444,7 @@ pub(crate) async fn update_document_metadata(.await.map_err(|err| OpensearchClientError::DeserializationFailed {details: err.to_string(),- method: Some("update_document_metadata".to_string()),+ method: Some("update_document_metadata_flat".to_string()),})?;let updated_count = response_body["updated"].as_u64().unwrap_or(0);@@ -437,32 +452,92 @@ pub(crate) async fn update_document_metadata(document_id=%document_id,document_name=%document_name,updated_count=%updated_count,- "document metadata updated successfully"+ "document metadata updated successfully (flat)");- } else {- let body =- response- .text()- .await- .map_err(|err| OpensearchClientError::DeserializationFailed {- details: err.to_string(),- method: Some("update_document_metadata".to_string()),- })?;+ return Ok(());+ }++ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("update_document_metadata_flat".to_string()),+ })?;++ tracing::error!(+ status_code=?status_code,+ body=?body,+ document_id=%document_id,+ "error updating document metadata (flat)",+ );++ Err(OpensearchClientError::Unknown {+ details: body,+ method: Some("update_document_metadata_flat".to_string()),+ })+}++/// Partial update on the parent doc. Routing must match the parent's+/// routing (= parent _id = document_id).+async fn update_document_metadata_join(+ client: &opensearch::OpenSearch,+ document_id: &str,+ document_name: &str,+) -> Result<()> {+ use serde_json::json;++ let body = json!({+ "doc": {+ "document_name": document_name,+ }+ });- tracing::error!(- status_code=?status_code,- body=?body,+ let response = client+ .update(opensearch::UpdateParts::IndexId(+ SearchIndex::Documents.as_ref(),+ document_id,+ ))+ .routing(document_id)+ .body(body)+ .send()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("update_document_metadata_join".to_string()),+ })?;++ let status_code = response.status_code();+ if status_code.is_success() {+ tracing::info!(document_id=%document_id,- "error updating document metadata",+ document_name=%document_name,+ "document metadata updated successfully (join)");-- return Err(OpensearchClientError::Unknown {- details: body,- method: Some("update_document_metadata".to_string()),- });+ return Ok(());}- Ok(())+ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("update_document_metadata_join".to_string()),+ })?;++ tracing::error!(+ status_code=?status_code,+ body=?body,+ document_id=%document_id,+ "error updating document metadata (join)",+ );++ Err(OpensearchClientError::Unknown {+ details: body,+ method: Some("update_document_metadata_join".to_string()),+ })}#[cfg(test)]diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rsindex 894419c14a..04982ed23b 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs@@ -86,12 +86,9 @@ fn build_join_bulk_body(documents: &[UpsertDocumentArgs]) -> Vec<serde_json::Vallet parent_id = doc.document_id.as_str();if seen_parents.insert(parent_id) {bulk.push(serde_json::json!({- "update": { "_id": parent_id, "routing": parent_id }- }));- bulk.push(serde_json::json!({- "doc": parent_doc_body(doc),- "doc_as_upsert": true,+ "index": { "_id": parent_id, "routing": parent_id }}));+ bulk.push(parent_doc_body(doc));}let child_id = format!("{}:{}", doc.document_id, doc.node_id);bulk.push(serde_json::json!({@@ -109,24 +106,34 @@ fn join_bulk_body_dedupes_parent_within_batch() {// 2 parents × 2 ops + 3 children × 2 ops = 10 entriesassert_eq!(body.len(), 10);- // First op is doc1's parent update.- assert_eq!(body[0]["update"]["_id"], "doc1");- assert_eq!(body[0]["update"]["routing"], "doc1");- assert_eq!(body[1]["doc_as_upsert"], true);- assert_eq!(body[1]["doc"]["entity_id"], "doc1");+ // First op is doc1's parent index.+ assert_eq!(body[0]["index"]["_id"], "doc1");+ assert_eq!(body[0]["index"]["routing"], "doc1");+ assert_eq!(body[1]["entity_id"], "doc1");+ assert_eq!(body[1]["document_relation"], "document");// Then doc1's first child.assert_eq!(body[2]["index"]["_id"], "doc1:n1");assert_eq!(body[2]["index"]["routing"], "doc1");assert_eq!(body[3]["document_relation"]["parent"], "doc1");- // Doc1's second child — note no second parent update for doc1.+ // Doc1's second child — note no second parent index for doc1.assert_eq!(body[4]["index"]["_id"], "doc1:n2");assert_eq!(body[4]["index"]["routing"], "doc1");- // Now doc2 — new parent so we get an upsert again.- assert_eq!(body[6]["update"]["_id"], "doc2");- assert_eq!(body[6]["update"]["routing"], "doc2");+ // Now doc2 — new parent so we get an index op again.+ assert_eq!(body[6]["index"]["_id"], "doc2");+ assert_eq!(body[6]["index"]["routing"], "doc2");assert_eq!(body[8]["index"]["_id"], "doc2:n1");assert_eq!(body[8]["index"]["routing"], "doc2");}++#[test]+fn parent_body_omits_sub_type_when_none_so_index_clears_it() {+ // The whole point of switching from update+doc_as_upsert to full index+ // writes: when sub_type becomes None, the new parent body must NOT+ // include sub_type, so an `index` op will drop any previously-stored+ // value rather than leaving it stale.+ let doc = parent_doc_body(&args("doc1", "n1"));+ assert!(doc.get("sub_type").is_none());+}diff --git a/rust/cloud-storage/opensearch_query_builder/src/lib.rs b/rust/cloud-storage/opensearch_query_builder/src/lib.rsindex ab208183d9..c3c22d73d5 100644--- a/rust/cloud-storage/opensearch_query_builder/src/lib.rs+++ b/rust/cloud-storage/opensearch_query_builder/src/lib.rs@@ -13,10 +13,10 @@ mod util;pub use query::{BoolQuery, BoolQueryBuilder, BoostMode, DecayFunction, FieldValueFactor, FunctionScoreQuery,- FunctionScoreQueryBuilder, MatchPhrasePrefixQuery, MatchPhraseQuery, MatchQuery, QueryType,- RandomScore, RangeQuery, RangeQueryBuilder, RegexpQuery, RegexpQueryFlags, ScoreFunction,- ScoreFunctionType, ScoreMode, ScriptScore, SimpleQueryStringQuery, TermQuery, TermsQuery,- WildcardQuery,+ FunctionScoreQueryBuilder, HasChildQuery, InnerHits, MatchPhrasePrefixQuery, MatchPhraseQuery,+ MatchQuery, QueryType, RandomScore, RangeQuery, RangeQueryBuilder, RegexpQuery,+ RegexpQueryFlags, ScoreFunction, ScoreFunctionType, ScoreMode, ScriptScore,+ SimpleQueryStringQuery, TermQuery, TermsQuery, WildcardQuery,};pub use request::{AggregationType, CardinalityAggregation, Collapse, FieldSort, Highlight, HighlightField, Lang,diff --git a/rust/cloud-storage/opensearch_query_builder/src/query.rs b/rust/cloud-storage/opensearch_query_builder/src/query.rsindex 0db461a415..1fb6b50d36 100644--- a/rust/cloud-storage/opensearch_query_builder/src/query.rs+++ b/rust/cloud-storage/opensearch_query_builder/src/query.rs@@ -4,6 +4,7 @@ use serde::Serialize;mod bool;mod function_score;+mod has_child;mod match_phrase;mod match_phrase_prefix;mod match_query;@@ -20,6 +21,7 @@ pub use function_score::{BoostMode, DecayFunction, FieldValueFactor, FunctionScoreQuery, FunctionScoreQueryBuilder,RandomScore, ScoreFunction, ScoreFunctionType, ScoreMode, ScriptScore,};+pub use has_child::{HasChildQuery, InnerHits};pub use match_phrase::MatchPhraseQuery;pub use match_phrase_prefix::MatchPhrasePrefixQuery;pub use match_query::MatchQuery;@@ -57,6 +59,8 @@ pub enum QueryType<'a> {WildCard(WildcardQuery<'a>),/// Simple query string querySimpleQueryString(SimpleQueryStringQuery<'a>),+ /// has_child join query (returns parents whose children match)+ HasChild(HasChildQuery<'a>),}impl<'a> ToOpenSearchJson for QueryType<'a> {@@ -73,6 +77,7 @@ impl<'a> ToOpenSearchJson for QueryType<'a> {QueryType::WildCard(wildcard_query) => wildcard_query.to_json(),QueryType::Regexp(regexp_query) => regexp_query.to_json(),QueryType::SimpleQueryString(simple_query_string) => simple_query_string.to_json(),+ QueryType::HasChild(has_child) => has_child.to_json(),}}}@@ -159,6 +164,7 @@ impl<'a> QueryType<'a> {QueryType::Terms(terms) => QueryType::Terms(terms.to_owned()),QueryType::WildCard(wildcard) => QueryType::WildCard(wildcard.to_owned()),QueryType::SimpleQueryString(sqs) => QueryType::SimpleQueryString(sqs.to_owned()),+ QueryType::HasChild(has_child) => QueryType::HasChild(has_child.to_owned()),}}}diff --git a/rust/cloud-storage/opensearch_query_builder/src/query/has_child.rs b/rust/cloud-storage/opensearch_query_builder/src/query/has_child.rsnew file mode 100644index 0000000000..c22bcc2053--- /dev/null+++ b/rust/cloud-storage/opensearch_query_builder/src/query/has_child.rs@@ -0,0 +1,205 @@+use std::borrow::Cow;++use serde::Serialize;+use serde_json::{Map, Value};++use crate::{QueryType, ToOpenSearchJson};++/// `has_child` join query. Returns parent documents that have at least one+/// child of `child_type` matching `query`.+///+/// Combine multiple `has_child` clauses inside a `bool.must` to require that+/// *every* term matches in *some* child (not necessarily the same one) —+/// the multi-term-AND-across-chunks semantics.+#[derive(Debug, Clone, Serialize)]+pub struct HasChildQuery<'a> {+ /// Name of the child relation defined in the join field mapping.+ #[serde(borrow)]+ pub child_type: Cow<'a, str>,+ /// Inner query to run against children. A parent matches if any one of+ /// its children matches this inner query.+ pub query: Box<QueryType<'a>>,+ /// If set, returns matching children alongside the parent. Each+ /// has_child clause's `inner_hits` is independent — name them to+ /// disambiguate when multiple has_child clauses appear in the same bool.+ pub inner_hits: Option<InnerHits<'a>>,+ /// Minimum number of distinct matching children required (default 1).+ pub min_children: Option<u32>,+ /// Maximum number of matching children (parents with more are excluded).+ pub max_children: Option<u32>,+ /// How child scores aggregate into the parent score. Default `none`.+ /// One of: `none`, `avg`, `max`, `min`, `sum`.+ pub score_mode: Option<Cow<'a, str>>,+ /// If true, suppress errors when `child_type` is not mapped in the+ /// target index. Useful for unified queries that span heterogeneous+ /// indices, only some of which use the join shape.+ pub ignore_unmapped: Option<bool>,+}++/// `inner_hits` clause attached to a parent/child join query. Returns the+/// underlying matching child docs inside the parent hit.+#[derive(Debug, Clone, Serialize)]+pub struct InnerHits<'a> {+ /// Optional name used to disambiguate this clause in the response.+ pub name: Option<Cow<'a, str>>,+ /// Optional highlight config to apply to the matching children.+ pub highlight: Option<Value>,+ /// Optional size override (default 3 in OpenSearch).+ pub size: Option<u32>,+}++impl<'a> InnerHits<'a> {+ /// Create a new InnerHits with no overrides.+ pub fn new() -> Self {+ Self {+ name: None,+ highlight: None,+ size: None,+ }+ }++ /// Set the inner_hits name (used to key the inner hits in the response).+ pub fn name(mut self, name: impl Into<Cow<'a, str>>) -> Self {+ self.name = Some(name.into());+ self+ }++ /// Set the highlight config (raw JSON value, since the existing+ /// Highlight builder type isn't visible from this crate).+ pub fn highlight(mut self, highlight: Value) -> Self {+ self.highlight = Some(highlight);+ self+ }++ /// Set the maximum number of inner hits to return.+ pub fn size(mut self, size: u32) -> Self {+ self.size = Some(size);+ self+ }++ /// Convert to an owned version with 'static lifetime.+ pub fn to_owned(&self) -> InnerHits<'static> {+ InnerHits {+ name: self.name.as_ref().map(|n| Cow::Owned(n.to_string())),+ highlight: self.highlight.clone(),+ size: self.size,+ }+ }+}++impl<'a> Default for InnerHits<'a> {+ fn default() -> Self {+ Self::new()+ }+}++impl<'a> ToOpenSearchJson for InnerHits<'a> {+ fn to_json(&self) -> Value {+ let mut obj = Map::new();+ if let Some(name) = &self.name {+ obj.insert("name".to_string(), Value::String(name.to_string()));+ }+ if let Some(highlight) = &self.highlight {+ obj.insert("highlight".to_string(), highlight.clone());+ }+ if let Some(size) = self.size {+ obj.insert("size".to_string(), Value::Number(size.into()));+ }+ Value::Object(obj)+ }+}++impl<'a> HasChildQuery<'a> {+ /// Create a new has_child query against `child_type` running `query`.+ pub fn new(child_type: impl Into<Cow<'a, str>>, query: QueryType<'a>) -> Self {+ Self {+ child_type: child_type.into(),+ query: Box::new(query),+ inner_hits: None,+ min_children: None,+ max_children: None,+ score_mode: None,+ ignore_unmapped: None,+ }+ }++ /// Attach an inner_hits clause so the matching children come back with+ /// the parent.+ pub fn inner_hits(mut self, inner_hits: InnerHits<'a>) -> Self {+ self.inner_hits = Some(inner_hits);+ self+ }++ /// Set the minimum number of matching children required.+ pub fn min_children(mut self, min: u32) -> Self {+ self.min_children = Some(min);+ self+ }++ /// Set the maximum number of matching children allowed.+ pub fn max_children(mut self, max: u32) -> Self {+ self.max_children = Some(max);+ self+ }++ /// Configure how child scores aggregate into the parent.+ pub fn score_mode(mut self, mode: impl Into<Cow<'a, str>>) -> Self {+ self.score_mode = Some(mode.into());+ self+ }++ /// Ignore mapping errors when the child relation is missing on the+ /// target index.+ pub fn ignore_unmapped(mut self, ignore: bool) -> Self {+ self.ignore_unmapped = Some(ignore);+ self+ }++ /// Convert to an owned version with 'static lifetime.+ pub fn to_owned(&self) -> HasChildQuery<'static> {+ HasChildQuery {+ child_type: Cow::Owned(self.child_type.to_string()),+ query: Box::new((*self.query).to_owned()),+ inner_hits: self.inner_hits.as_ref().map(|h| h.to_owned()),+ min_children: self.min_children,+ max_children: self.max_children,+ score_mode: self.score_mode.as_ref().map(|m| Cow::Owned(m.to_string())),+ ignore_unmapped: self.ignore_unmapped,+ }+ }+}++impl<'a> From<HasChildQuery<'a>> for QueryType<'a> {+ fn from(q: HasChildQuery<'a>) -> Self {+ QueryType::HasChild(q)+ }+}++impl<'a> ToOpenSearchJson for HasChildQuery<'a> {+ fn to_json(&self) -> Value {+ let mut inner = Map::new();+ inner.insert(+ "type".to_string(),+ Value::String(self.child_type.to_string()),+ );+ inner.insert("query".to_string(), self.query.to_json());+ if let Some(inner_hits) = &self.inner_hits {+ inner.insert("inner_hits".to_string(), inner_hits.to_json());+ }+ if let Some(min) = self.min_children {+ inner.insert("min_children".to_string(), Value::Number(min.into()));+ }+ if let Some(max) = self.max_children {+ inner.insert("max_children".to_string(), Value::Number(max.into()));+ }+ if let Some(mode) = &self.score_mode {+ inner.insert("score_mode".to_string(), Value::String(mode.to_string()));+ }+ if let Some(ignore) = self.ignore_unmapped {+ inner.insert("ignore_unmapped".to_string(), Value::Bool(ignore));+ }+ let mut outer = Map::new();+ outer.insert("has_child".to_string(), Value::Object(inner));+ Value::Object(outer)+ }+}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.rsindex d37dca690c..ef3510b142 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@@ -222,9 +222,21 @@ pub(in crate::api::search) async fn perform_unified_search().map_err(|e| SearchError::InternalError(anyhow::anyhow!("tokio error: {:?}", e)))?;- // Set terms on each index's search args- // Email gets split terms for multi-field search; other indices get the original query- filter_document_response.terms = terms.clone();+ // Set terms on each index's search args.+ //+ // Emails always get whitespace-split terms (each term matched+ // independently across many fields, ANDed inside OpenSearch).+ // Documents get split terms only once the alias points at a+ // join-shape index, where each term becomes a separate has_child+ // clause ANDed via bool.must. While the alias still points at the+ // flat-shape index, the documents branch keeps the single adjacent+ // phrase-prefix behavior.+ let document_terms = if opensearch_client::documents_shape::alias_uses_join_shape() {+ split_search_terms(&terms)+ } else {+ terms.clone()+ };+ filter_document_response.terms = document_terms;filter_channel_response.terms = terms.clone();filter_chat_response.terms = terms.clone();filter_email_response.terms = email_terms.clone();