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.

feat(search): add documents_v2 parent/child index and join-shape upsert (#3345)

gbirmanbee5ab9a8b94
diff --git a/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts b/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts
new file mode 100644
index 0000000000..c42d3f3854
--- /dev/null
+++ b/infra/stacks/opensearch/helpers/scripts/create_documents_v2.ts
@@ -0,0 +1,77 @@
+/**
+ * Creates `documents_v2` with the parent/child join mapping used for the
+ * multi-term AND search migration. Does NOT touch the `documents` alias —
+ * `documents_v2` is created idle so the search_processing_service backfill
+ * can populate it (with `index_override: "documents_v2"`) while production
+ * reads/writes continue to flow through `documents` -> `documents_v1`.
+ *
+ * Swap the alias separately, once backfill is caught up and the new search
+ * query path is deployed.
+ *
+ * Usage:
+ * bun scripts/create_documents_v2.ts
+ *
+ * Idempotent — safe to re-run; if `documents_v2` already exists nothing
+ * happens.
+ */
+require('dotenv').config();
+
+import { client } from '../client';
+import { SHARD_SETTINGS } from '../constants';
+
+const INDEX = 'documents_v2';
+const RELATION_PARENT = 'document';
+const RELATION_CHILD = 'chunk';
+
+const BODY = {
+ settings: {
+ ...SHARD_SETTINGS,
+ refresh_interval: '1s',
+ },
+ mappings: {
+ dynamic: 'false',
+ properties: {
+ entity_id: { type: 'keyword' },
+ // Parent-only metadata
+ document_name: {
+ type: 'text',
+ fields: { keyword: { type: 'keyword', ignore_above: 128 } },
+ },
+ owner_id: { type: 'keyword', index: true, doc_values: true },
+ file_type: { type: 'keyword', index: false, doc_values: true },
+ sub_type: { type: 'keyword', index: true, doc_values: true },
+ updated_at_seconds: {
+ type: 'date',
+ format: 'epoch_second',
+ index: false,
+ doc_values: true,
+ },
+ // Child-only fields
+ node_id: { type: 'keyword', index: false, doc_values: true },
+ content: { type: 'text', analyzer: 'standard' },
+ raw_content: { type: 'text' },
+ // Join relationship
+ document_relation: {
+ type: 'join',
+ relations: { [RELATION_PARENT]: RELATION_CHILD },
+ },
+ },
+ },
+};
+
+async function run() {
+ const c = client();
+ const exists = (await c.indices.exists({ index: INDEX })).body;
+ if (exists) {
+ console.log(`${INDEX} already exists; nothing to do.`);
+ return;
+ }
+ console.log(`Creating ${INDEX} (no alias)`);
+ await c.indices.create({ index: INDEX, body: BODY });
+ console.log(`${INDEX} created`);
+}
+
+run().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/rust/cloud-storage/opensearch_client/src/documents_shape.rs b/rust/cloud-storage/opensearch_client/src/documents_shape.rs
new file mode 100644
index 0000000000..7dbc8648da
--- /dev/null
+++ b/rust/cloud-storage/opensearch_client/src/documents_shape.rs
@@ -0,0 +1,18 @@
+//! Dispatch helper for the documents index migration from a flat-chunk
+//! shape (`documents_v1`) to a parent/child join shape (`documents_v2`).
+//!
+//! 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.
+
+/// Physical index name of the join-shape documents index.
+pub const DOCUMENTS_V2: &str = "documents_v2";
+
+/// 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.
+pub fn destination_uses_join_shape(destination: &str) -> bool {
+ destination == DOCUMENTS_V2
+}
diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rs
index 516617dc29..1bb018ee9f 100644
--- a/rust/cloud-storage/opensearch_client/src/lib.rs
+++ b/rust/cloud-storage/opensearch_client/src/lib.rs
@@ -1,5 +1,6 @@
pub mod date_format;
pub mod delete;
+pub mod documents_shape;
pub mod error;
pub mod search;
pub mod unified;
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document.rs b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
index 7fe5e357f0..8726ba82f0 100644
--- a/rust/cloud-storage/opensearch_client/src/upsert/document.rs
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document.rs
@@ -1,7 +1,18 @@
+use std::collections::HashSet;
+
use models_opensearch::SearchIndex;
use super::BulkUpsertResult;
-use crate::{Result, date_format::EpochSeconds, error::OpensearchClientError};
+use crate::{
+ Result, date_format::EpochSeconds, documents_shape::destination_uses_join_shape,
+ error::OpensearchClientError,
+};
+
+/// Relation name for parent docs in the join field.
+const PARENT_RELATION: &str = "document";
+
+/// Relation name for child (chunk) docs in the join field.
+const CHILD_RELATION: &str = "chunk";
/// The arguments for upserting a document into the opensearch index
#[derive(Debug, serde::Serialize)]
@@ -35,11 +46,20 @@ pub struct UpsertDocumentArgs {
pub sub_type: Option<String>,
}
-/// Process a single chunk of documents
-async fn bulk_upsert_single_chunk(
+/// Resolve `index_override` to the physical/alias name we'll write to.
+fn resolve_destination(index_override: Option<&str>) -> &str {
+ index_override.unwrap_or(SearchIndex::Documents.as_ref())
+}
+
+// ---------------------------------------------------------------------------
+// Flat-shape (legacy) path
+// ---------------------------------------------------------------------------
+
+/// Process a single chunk of documents in the legacy flat shape.
+async fn bulk_upsert_single_chunk_flat(
client: &opensearch::OpenSearch,
documents: &[UpsertDocumentArgs],
- index_override: Option<&str>,
+ index: &str,
) -> Result<BulkUpsertResult> {
let mut bulk_body = Vec::new();
@@ -56,26 +76,134 @@ async fn bulk_upsert_single_chunk(
bulk_body.push(serde_json::to_string(doc).map_err(|e| {
OpensearchClientError::DeserializationFailed {
details: e.to_string(),
- method: Some("bulk_upsert_single_chunk".to_string()),
+ method: Some("bulk_upsert_single_chunk_flat".to_string()),
}
})?);
}
- let index = index_override.unwrap_or(SearchIndex::Documents.as_ref());
let result =
- super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk").await?;
+ super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk_flat")
+ .await?;
+
+ tracing::trace!(
+ chunk_total = documents.len(),
+ successful = result.successful,
+ failed = result.failed,
+ version_conflicts = result.version_conflicts,
+ "bulk upsert chunk completed (flat)"
+ );
+
+ Ok(result)
+}
+
+// ---------------------------------------------------------------------------
+// Join-shape path
+// ---------------------------------------------------------------------------
+
+/// Builds the JSON document body for a parent doc, given any one
+/// `UpsertDocumentArgs` belonging to that parent (parent metadata is
+/// denormalized identically across all chunks of the same document, so any
+/// chunk's metadata is authoritative).
+fn parent_doc_body(any_chunk: &UpsertDocumentArgs) -> serde_json::Value {
+ let mut doc = serde_json::json!({
+ "entity_id": &any_chunk.document_id,
+ "document_name": &any_chunk.document_name,
+ "owner_id": &any_chunk.owner_id,
+ "file_type": &any_chunk.file_type,
+ "updated_at_seconds": any_chunk.updated_at_seconds,
+ "document_relation": PARENT_RELATION,
+ });
+ if let Some(sub_type) = &any_chunk.sub_type {
+ doc["sub_type"] = serde_json::Value::String(sub_type.clone());
+ }
+ doc
+}
+
+/// Builds the JSON document body for a child (chunk) doc.
+fn child_doc_body(chunk: &UpsertDocumentArgs) -> serde_json::Value {
+ let mut doc = serde_json::json!({
+ "entity_id": &chunk.document_id,
+ "node_id": &chunk.node_id,
+ "content": &chunk.content,
+ "document_relation": {
+ "name": CHILD_RELATION,
+ "parent": &chunk.document_id,
+ },
+ });
+ if let Some(raw) = &chunk.raw_content {
+ doc["raw_content"] = serde_json::Value::String(raw.clone());
+ }
+ doc
+}
+
+/// 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`
+///
+/// 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.
+async fn bulk_upsert_single_chunk_join(
+ client: &opensearch::OpenSearch,
+ documents: &[UpsertDocumentArgs],
+ index: &str,
+) -> Result<BulkUpsertResult> {
+ let mut bulk_body = Vec::new();
+ let mut seen_parents: HashSet<&str> = HashSet::new();
+
+ for doc in documents {
+ let parent_id = doc.document_id.as_str();
+ let routing = parent_id;
+
+ if seen_parents.insert(parent_id) {
+ let parent_action = serde_json::json!({
+ "update": {
+ "_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());
+ }
+
+ let child_id = format!("{}:{}", doc.document_id, doc.node_id);
+ let child_action = serde_json::json!({
+ "index": {
+ "_id": child_id,
+ "routing": routing,
+ }
+ });
+ bulk_body.push(child_action.to_string());
+ bulk_body.push(child_doc_body(doc).to_string());
+ }
+
+ let result =
+ super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_single_chunk_join")
+ .await?;
tracing::trace!(
chunk_total = documents.len(),
+ parent_count = seen_parents.len(),
successful = result.successful,
failed = result.failed,
version_conflicts = result.version_conflicts,
- "bulk upsert chunk completed"
+ "bulk upsert chunk completed (join)"
);
Ok(result)
}
+// ---------------------------------------------------------------------------
+// Public entry points (dispatch)
+// ---------------------------------------------------------------------------
+
/// Bulk upsert documents to reduce version conflicts with automatic chunking
#[tracing::instrument(skip(client, documents))]
pub(crate) async fn bulk_upsert_documents(
@@ -90,13 +218,17 @@ pub(crate) async fn bulk_upsert_documents(
const CHUNK_SIZE: usize = 100;
let mut overall_result = BulkUpsertResult::default();
- // Process documents in chunks
+ let index = resolve_destination(index_override);
+ let join_shape = destination_uses_join_shape(index);
+
let chunks: Vec<_> = documents.chunks(CHUNK_SIZE).collect();
tracing::info!(
total_documents = documents.len(),
total_chunks = chunks.len(),
chunk_size = CHUNK_SIZE,
+ index = %index,
+ shape = if join_shape { "join" } else { "flat" },
"starting chunked bulk upsert"
);
@@ -107,12 +239,18 @@ pub(crate) async fn bulk_upsert_documents(
"processing chunk"
);
- match bulk_upsert_single_chunk(client, chunk, index_override).await {
- Ok(chunk_result) => {
- overall_result.successful += chunk_result.successful;
- overall_result.failed += chunk_result.failed;
- overall_result.version_conflicts += chunk_result.version_conflicts;
- overall_result.errors.extend(chunk_result.errors);
+ let chunk_result = if join_shape {
+ bulk_upsert_single_chunk_join(client, chunk, index).await
+ } else {
+ bulk_upsert_single_chunk_flat(client, chunk, index).await
+ };
+
+ match chunk_result {
+ Ok(r) => {
+ overall_result.successful += r.successful;
+ overall_result.failed += r.failed;
+ overall_result.version_conflicts += r.version_conflicts;
+ overall_result.errors.extend(r.errors);
}
Err(e) => {
tracing::error!(
@@ -145,9 +283,20 @@ pub(crate) async fn upsert_document(
client: &opensearch::OpenSearch,
args: &UpsertDocumentArgs,
index_override: Option<&str>,
+) -> Result<()> {
+ let index = resolve_destination(index_override);
+ if destination_uses_join_shape(index) {
+ return upsert_document_join(client, args, index).await;
+ }
+ upsert_document_flat(client, args, index).await
+}
+
+async fn upsert_document_flat(
+ client: &opensearch::OpenSearch,
+ args: &UpsertDocumentArgs,
+ index: &str,
) -> Result<()> {
let id = format!("{}:{}", args.document_id, args.node_id);
- let index = index_override.unwrap_or(SearchIndex::Documents.as_ref());
let response = client
.index(opensearch::IndexParts::IndexId(index, &id))
.body(args)
@@ -155,33 +304,86 @@ pub(crate) async fn upsert_document(
.await
.map_err(|err| OpensearchClientError::DeserializationFailed {
details: err.to_string(),
- method: Some("upsert_document".to_string()),
+ method: Some("upsert_document_flat".to_string()),
})?;
let status_code = response.status_code();
if status_code.is_success() {
tracing::trace!(id=%id, "document upserted successfully");
- } else {
- let body =
- response
- .text()
- .await
- .map_err(|err| OpensearchClientError::DeserializationFailed {
- details: err.to_string(),
- method: Some("upsert_document".to_string()),
- })?;
+ return Ok(());
+ }
- tracing::error!(
- status_code=?status_code,
- body=?body,
- "error upserting document",
- );
+ let body =
+ response
+ .text()
+ .await
+ .map_err(|err| OpensearchClientError::DeserializationFailed {
+ details: err.to_string(),
+ method: Some("upsert_document_flat".to_string()),
+ })?;
+ tracing::error!(
+ status_code = ?status_code,
+ body = ?body,
+ "error upserting document",
+ );
+
+ Err(OpensearchClientError::Unknown {
+ details: body,
+ method: Some("upsert_document_flat".to_string()),
+ })
+}
+
+/// 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.
+async fn upsert_document_join(
+ client: &opensearch::OpenSearch,
+ args: &UpsertDocumentArgs,
+ index: &str,
+) -> Result<()> {
+ let parent_id = args.document_id.as_str();
+ let routing = parent_id;
+
+ let parent_action = serde_json::json!({
+ "update": {
+ "_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!({
+ "index": {
+ "_id": child_id,
+ "routing": routing,
+ }
+ });
+
+ let bulk_body = vec![
+ parent_action.to_string(),
+ parent_body.to_string(),
+ child_action.to_string(),
+ child_doc_body(args).to_string(),
+ ];
+
+ let result =
+ super::bulk_upsert_to_index(client, index, bulk_body, "upsert_document_join").await?;
+
+ if result.failed > 0 {
return Err(OpensearchClientError::Unknown {
- details: body,
- method: Some("upsert_document".to_string()),
+ details: format!(
+ "upsert_document_join had {} failures: {:?}",
+ result.failed, result.errors
+ ),
+ method: Some("upsert_document_join".to_string()),
});
}
+
+ tracing::trace!(id=%child_id, parent=%parent_id, "document upserted successfully (join)");
Ok(())
}
@@ -262,3 +464,6 @@ pub(crate) async fn update_document_metadata(
Ok(())
}
+
+#[cfg(test)]
+mod test;
diff --git a/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
new file mode 100644
index 0000000000..894419c14a
--- /dev/null
+++ b/rust/cloud-storage/opensearch_client/src/upsert/document/test.rs
@@ -0,0 +1,132 @@
+use super::*;
+use crate::date_format::EpochSeconds;
+
+fn args(doc_id: &str, node_id: &str) -> UpsertDocumentArgs {
+ UpsertDocumentArgs {
+ document_id: doc_id.to_string(),
+ node_id: node_id.to_string(),
+ document_name: format!("name-{doc_id}"),
+ file_type: "md".to_string(),
+ owner_id: format!("owner-{doc_id}"),
+ raw_content: None,
+ content: format!("content {doc_id} {node_id}"),
+ updated_at_seconds: EpochSeconds::new(1_700_000_000).unwrap(),
+ sub_type: None,
+ }
+}
+
+#[test]
+fn parent_doc_body_has_metadata_no_chunk_fields() {
+ let doc = parent_doc_body(&args("doc1", "n1"));
+
+ assert_eq!(doc["entity_id"], "doc1");
+ assert_eq!(doc["document_name"], "name-doc1");
+ assert_eq!(doc["owner_id"], "owner-doc1");
+ assert_eq!(doc["file_type"], "md");
+ assert_eq!(doc["document_relation"], "document");
+ // Child-only fields must not be present on the parent.
+ assert!(doc.get("content").is_none());
+ assert!(doc.get("node_id").is_none());
+ assert!(doc.get("raw_content").is_none());
+}
+
+#[test]
+fn parent_doc_body_includes_optional_sub_type() {
+ let mut a = args("doc1", "n1");
+ a.sub_type = Some("task".to_string());
+ let doc = parent_doc_body(&a);
+ assert_eq!(doc["sub_type"], "task");
+}
+
+#[test]
+fn child_doc_body_has_chunk_fields_and_join_pointer() {
+ let mut a = args("doc1", "n1");
+ a.raw_content = Some("raw".to_string());
+ let doc = child_doc_body(&a);
+
+ assert_eq!(doc["entity_id"], "doc1");
+ assert_eq!(doc["node_id"], "n1");
+ assert_eq!(doc["content"], "content doc1 n1");
+ assert_eq!(doc["raw_content"], "raw");
+ assert_eq!(doc["document_relation"]["name"], "chunk");
+ assert_eq!(doc["document_relation"]["parent"], "doc1");
+ // Parent-only metadata must not be redundantly written to children.
+ assert!(doc.get("document_name").is_none());
+ assert!(doc.get("owner_id").is_none());
+ assert!(doc.get("file_type").is_none());
+ assert!(doc.get("sub_type").is_none());
+}
+
+#[test]
+fn child_doc_body_omits_raw_content_when_none() {
+ let doc = child_doc_body(&args("doc1", "n1"));
+ assert!(doc.get("raw_content").is_none());
+}
+
+#[test]
+fn destination_uses_join_shape_for_v2() {
+ use crate::documents_shape::{DOCUMENTS_V2, destination_uses_join_shape};
+ assert!(destination_uses_join_shape(DOCUMENTS_V2));
+ assert!(!destination_uses_join_shape("documents_v1"));
+ assert!(!destination_uses_join_shape("documents_join_test"));
+}
+
+#[test]
+fn resolve_destination_defaults_to_documents_alias() {
+ assert_eq!(resolve_destination(None), SearchIndex::Documents.as_ref());
+ assert_eq!(resolve_destination(Some("documents_v2")), "documents_v2");
+}
+
+/// Builds the same bulk body the join-shape upsert would send, so we can
+/// assert the exact OpenSearch wire format without standing up a cluster.
+fn build_join_bulk_body(documents: &[UpsertDocumentArgs]) -> Vec<serde_json::Value> {
+ let mut bulk: Vec<serde_json::Value> = Vec::new();
+ let mut seen_parents: std::collections::HashSet<&str> = std::collections::HashSet::new();
+ for doc in documents {
+ let 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,
+ }));
+ }
+ let child_id = format!("{}:{}", doc.document_id, doc.node_id);
+ bulk.push(serde_json::json!({
+ "index": { "_id": child_id, "routing": parent_id }
+ }));
+ bulk.push(child_doc_body(doc));
+ }
+ bulk
+}
+
+#[test]
+fn join_bulk_body_dedupes_parent_within_batch() {
+ let body = build_join_bulk_body(&[args("doc1", "n1"), args("doc1", "n2"), args("doc2", "n1")]);
+
+ // 2 parents × 2 ops + 3 children × 2 ops = 10 entries
+ assert_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");
+
+ // 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.
+ 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");
+ assert_eq!(body[8]["index"]["_id"], "doc2:n1");
+ assert_eq!(body[8]["index"]["routing"], "doc2");
+}