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): call records v2 parent/child join + keyset backfill (#3499)
gbirmanfec36d4fb2b8
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 95b8ff86fd..07686fe716 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -470,6 +470,13 @@ const cloudStorageService = new CloudStorageService(name: 'CHATS_INDEX_USES_JOIN',value: config.get('chats_index_uses_join') ?? 'false',},+ {+ // Same as DOCUMENTS_INDEX_USES_JOIN, but for the call_records+ // alias (`call_records_v1` flat -> `call_records_v2`+ // parent/child).+ name: 'CALL_RECORDS_INDEX_USES_JOIN',+ value: config.get('call_records_index_uses_join') ?? 'false',+ },{name: 'DATABASE_URL',value: pulumi.interpolate`${DATABASE_URL}`,diff --git a/infra/stacks/opensearch/helpers/scripts/create_call_records_v2.ts b/infra/stacks/opensearch/helpers/scripts/create_call_records_v2.tsnew file mode 100644index 0000000000..5a9109cc3c--- /dev/null+++ b/infra/stacks/opensearch/helpers/scripts/create_call_records_v2.ts@@ -0,0 +1,88 @@+/**+ * Creates `call_records_v2` with the parent/child join mapping used for+ * the multi-term AND search migration. Does NOT touch the `call_records`+ * alias — `call_records_v2` is created idle so the+ * search_processing_service backfill can populate it (with+ * `index_override: "call_records_v2"`) while production reads/writes+ * continue to flow through `call_records` -> `call_records_v1`.+ *+ * Swap the alias separately, once backfill is caught up and the new+ * search query path is deployed.+ *+ * Usage:+ * bun scripts/create_call_records_v2.ts+ *+ * Idempotent — safe to re-run; if `call_records_v2` already exists+ * nothing happens.+ */+require('dotenv').config();++import { client } from '../client';+import { SHARD_SETTINGS } from '../constants';++const INDEX = 'call_records_v2';+const RELATION_PARENT = 'call';+const RELATION_CHILD = 'segment';++const BODY = {+ settings: {+ ...SHARD_SETTINGS,+ refresh_interval: '2s',+ },+ mappings: {+ dynamic: 'false',+ properties: {+ entity_id: { type: 'keyword' },+ // Parent-only metadata+ channel_id: { type: 'keyword', index: true, doc_values: true },+ channel_name: {+ type: 'text',+ fields: { keyword: { type: 'keyword', ignore_above: 128 } },+ },+ participant_ids: { type: 'keyword', index: true, doc_values: true },+ started_at_seconds: {+ type: 'date',+ format: 'epoch_second',+ index: false,+ doc_values: true,+ },+ ended_at_seconds: {+ type: 'date',+ format: 'epoch_second',+ index: false,+ doc_values: true,+ },+ // Child-only fields+ transcript_id: { type: 'keyword', index: false, doc_values: true },+ speaker_id: { type: 'keyword', index: true, doc_values: true },+ sequence_num: { type: 'integer', index: false, doc_values: true },+ content: { type: 'text', analyzer: 'standard' },+ // Aliases preserved for any reader that still expects them; both map+ // to the parent's call-start timestamp.+ created_at_seconds: { type: 'alias', path: 'started_at_seconds' },+ updated_at_seconds: { type: 'alias', path: 'started_at_seconds' },+ // Join relationship+ call_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/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex 5f7fccd8b0..3db208a7c4 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -156,6 +156,13 @@ const searchProcessingService = new SearchProcessingService(name: 'CHATS_INDEX_USES_JOIN',value: config.get('chats_index_uses_join') ?? 'false',},+ {+ // Same as DOCUMENTS_INDEX_USES_JOIN, but for the call_records+ // alias (`call_records_v1` flat -> `call_records_v2`+ // parent/child).+ name: 'CALL_RECORDS_INDEX_USES_JOIN',+ value: config.get('call_records_index_uses_join') ?? 'false',+ },{name: 'DOCUMENT_STORAGE_BUCKET',value: pulumi.interpolate`${documentStorageBucketId}`,diff --git a/rust/cloud-storage/.sqlx/query-28baf072b97758fba3e18900b97176766a0cd023d6730538b6e5c936ae7bdb48.json b/rust/cloud-storage/.sqlx/query-28baf072b97758fba3e18900b97176766a0cd023d6730538b6e5c936ae7bdb48.jsonnew file mode 100644index 0000000000..d1cec003c4--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-28baf072b97758fba3e18900b97176766a0cd023d6730538b6e5c936ae7bdb48.json@@ -0,0 +1,32 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id AS \"call_id!\",\n started_at AS \"started_at!\"\n FROM call_records\n WHERE\n ($2::timestamptz IS NULL OR started_at >= $2)\n AND ($3::timestamptz IS NULL OR started_at < $3)\n AND (\n $4::timestamptz IS NULL\n OR (started_at, id) > ($4, $5::uuid)\n )\n ORDER BY started_at ASC, id ASC\n LIMIT $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "call_id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "started_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Int8",+ "Timestamptz",+ "Timestamptz",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "28baf072b97758fba3e18900b97176766a0cd023d6730538b6e5c936ae7bdb48"+}diff --git a/rust/cloud-storage/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.json b/rust/cloud-storage/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.jsondeleted file mode 100644index 453c91ef24..0000000000--- a/rust/cloud-storage/.sqlx/query-74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "SELECT id AS \"call_id!\" FROM call_records ORDER BY started_at DESC LIMIT $1 OFFSET $2",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "call_id!",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Int8",- "Int8"- ]- },- "nullable": [- false- ]- },- "hash": "74e76c125eb6beb0ade0d0aa8882199445908c8a1990d01d5526a2717a33d39f"-}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260522183506_call_records_started_at_id_keyset_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260522183506_call_records_started_at_id_keyset_index.sqlnew file mode 100644index 0000000000..33512dcb65--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260522183506_call_records_started_at_id_keyset_index.sql@@ -0,0 +1,8 @@+-- no-transaction+-- Supports keyset pagination over call_records for the search backfill+-- orchestrator, which sorts by (started_at ASC, id ASC). call_records+-- doesn't have an updated_at column so the cursor uses started_at —+-- functionally equivalent for these calls since they're immutable+-- after creation.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_call_records_started_at_id+ ON call_records (started_at, id);diff --git a/rust/cloud-storage/macro_db_client/src/call_record/get.rs b/rust/cloud-storage/macro_db_client/src/call_record/get.rsindex 51ab0d2389..d90a5be13c 100644--- a/rust/cloud-storage/macro_db_client/src/call_record/get.rs+++ b/rust/cloud-storage/macro_db_client/src/call_record/get.rs@@ -4,6 +4,7 @@ use uuid::Uuid;#[derive(Debug, Clone)]pub struct CallRecordSearchBackfill {pub call_id: Uuid,+ pub started_at: DateTime<Utc>,}#[derive(Debug, Clone)]@@ -87,17 +88,49 @@ pub async fn get_accessible_call_ids(.map_err(Into::into)}+/// Gets call records for search backfill.+///+/// Pagination is **keyset (seek-method)**: pass `cursor` as the last+/// row's `(started_at, id)` pair from the previous page (or `None` for+/// the first page). call_records doesn't have an updated_at column so+/// the cursor and `started_after` / `started_before` filters use+/// started_at — functionally equivalent because calls are immutable+/// after creation.#[tracing::instrument(skip(db))]pub async fn get_call_records_for_search_backfill(db: &sqlx::Pool<sqlx::Postgres>,limit: i64,- offset: i64,+ cursor: Option<(DateTime<Utc>, Uuid)>,+ started_after: Option<DateTime<Utc>>,+ started_before: Option<DateTime<Utc>>,) -> anyhow::Result<Vec<CallRecordSearchBackfill>> {+ let (cursor_started_at, cursor_id) = match cursor {+ Some((t, id)) => (Some(t), Some(id)),+ None => (None, None),+ };+sqlx::query_as!(CallRecordSearchBackfill,- r#"SELECT id AS "call_id!" FROM call_records ORDER BY started_at DESC LIMIT $1 OFFSET $2"#,+ r#"+ SELECT+ id AS "call_id!",+ started_at AS "started_at!"+ FROM call_records+ WHERE+ ($2::timestamptz IS NULL OR started_at >= $2)+ AND ($3::timestamptz IS NULL OR started_at < $3)+ AND (+ $4::timestamptz IS NULL+ OR (started_at, id) > ($4, $5::uuid)+ )+ ORDER BY started_at ASC, id ASC+ LIMIT $1+ "#,limit,- offset,+ started_after as Option<DateTime<Utc>>,+ started_before as Option<DateTime<Utc>>,+ cursor_started_at as Option<DateTime<Utc>>,+ cursor_id as Option<Uuid>,).fetch_all(db).awaitdiff --git a/rust/cloud-storage/opensearch_client/src/call_records_shape.rs b/rust/cloud-storage/opensearch_client/src/call_records_shape.rsnew file mode 100644index 0000000000..03faf46e21--- /dev/null+++ b/rust/cloud-storage/opensearch_client/src/call_records_shape.rs@@ -0,0 +1,54 @@+//! Dispatch helpers for the call_records index migration from a flat+//! one-doc-per-segment shape to a parent/child join shape.+//!+//! Mirrors [`crate::documents_shape`] and [`crate::chats_shape`].++use std::sync::OnceLock;++/// Physical name of the join-shape call_records 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 CALL_RECORDS_V2: &str = "call_records_v2";++/// Default alias name reads target. Production code always uses this.+const DEFAULT_CALL_RECORDS_ALIAS: &str = "call_records";++/// Whether writes targeting this destination should use the parent/child+/// join shape.+pub fn destination_uses_join_shape(destination: &str) -> bool {+ if destination == CALL_RECORDS_V2 {+ return true;+ }+ if destination == DEFAULT_CALL_RECORDS_ALIAS {+ return alias_uses_join_shape();+ }+ false+}++/// Whether the `call_records` alias currently resolves to a join-shape+/// index.+///+/// Controlled by the `CALL_RECORDS_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("CALL_RECORDS_INDEX_USES_JOIN")+ .map(|v| v == "true")+ .unwrap_or(false)+ })+}++/// Alias name that search reads target for call records. Returns+/// `call_records` by default; the `CALL_RECORDS_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+/// `call_records` alias.+pub fn call_records_search_alias() -> &'static str {+ static NAME: OnceLock<&'static str> = OnceLock::new();+ NAME.get_or_init(|| match std::env::var("CALL_RECORDS_INDEX_NAME") {+ Ok(s) if !s.is_empty() => Box::leak(s.into_boxed_str()) as &'static str,+ _ => DEFAULT_CALL_RECORDS_ALIAS,+ })+}diff --git a/rust/cloud-storage/opensearch_client/src/lib.rs b/rust/cloud-storage/opensearch_client/src/lib.rsindex 18928d8ea7..966b699fe8 100644--- a/rust/cloud-storage/opensearch_client/src/lib.rs+++ b/rust/cloud-storage/opensearch_client/src/lib.rs@@ -1,3 +1,4 @@+pub mod call_records_shape;pub mod chats_shape;pub mod date_format;pub mod delete;diff --git a/rust/cloud-storage/opensearch_client/src/search/call_records.rs b/rust/cloud-storage/opensearch_client/src/search/call_records.rsindex 4efa91c469..ac556203f2 100644--- a/rust/cloud-storage/opensearch_client/src/search/call_records.rs+++ b/rust/cloud-storage/opensearch_client/src/search/call_records.rs@@ -1,22 +1,58 @@+use std::collections::HashMap;+use crate::{- Result, delegate_methods,- search::builder::{SearchQueryBuilder, SearchQueryConfig},+ Result,+ call_records_shape::{alias_uses_join_shape, call_records_search_alias},+ delegate_methods,+ search::{+ builder::{SearchQueryBuilder, SearchQueryConfig},+ model::{+ Highlight, SearchGotoCallRecord, SearchGotoContent, SearchHit, parse_highlight_hit,+ },+ query::Keys,+ },+};++use chrono::DateTime;+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::call_record`.+const PARENT_RELATION: &str = "call";+const CHILD_RELATION: &str = "segment";++/// Minimum prefix length before we emit a `match_phrase_prefix`. Mirrors+/// the documents/chats threshold.+const MIN_PREFIX_LEN: usize = 3;++/// Cap on segments returned per `has_child` clause inside `inner_hits`.+/// OpenSearch's default is 3 which would silently drop matches on calls+/// with many matching segments.+const INNER_HITS_PER_TERM: u32 = 100;++const MATCH_PHRASE_PREFIX_MAX_EXPANSIONS: u32 = 256;#[derive(Debug, serde::Serialize, serde::Deserialize)]pub(crate) struct CallRecordIndex {pub entity_id: uuid::Uuid,pub channel_id: uuid::Uuid,- pub transcript_id: uuid::Uuid,+ /// Present on flat-shape (legacy) segment docs. Absent on join-shape+ /// parent docs — the matching segments come via `inner_hits`.+ #[serde(default)]+ pub transcript_id: Option<uuid::Uuid>,#[serde(default)]pub participant_ids: Vec<String>,#[serde(default)]pub channel_name: Option<String>,- pub speaker_id: String,- pub sequence_num: i32,+ /// Present on flat-shape segment docs. Absent on join-shape parents.+ #[serde(default)]+ pub speaker_id: Option<String>,+ #[serde(default)]+ pub sequence_num: Option<i32>,pub started_at_seconds: i64,#[serde(default)]pub ended_at_seconds: Option<i64>,@@ -65,6 +101,16 @@ impl CallRecordQueryBuilder {}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 one-doc-per-segment path: the whole user query becomes a+ /// single phrase[-prefix] match on `content` and the channel /+ /// speaker filters sit on the same doc as the content.+ fn build_bool_query_flat<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {// Access comes from `ids_only` + accessible call_ids; these just narrow.let mut content_bool_query = self.inner.build_content_bool_query()?;@@ -78,6 +124,131 @@ impl CallRecordQueryBuilder {Ok(content_bool_query)}++ /// Parent/child join path: one `has_child` clause per term, ANDed+ /// inside `bool.must` so every search term must match some segment+ /// in the same call. channel_id lives on the parent so it sits on+ /// `bool.filter` directly; speaker_id is child-side so it's a+ /// has_child filter clause.+ 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(+ CallRecordSearchConfig::ENTITY_INDEX,+ ));+ }+ if self.inner.terms.is_empty() {+ return Err(crate::error::OpensearchClientError::NoTermsProvided);+ }++ let mut bool_query = BoolQueryBuilder::new();++ // Restrict to parent calls in the call_records alias (overridable+ // via CALL_RECORDS_INDEX_NAME for local end-to-end testing).+ bool_query.filter(QueryType::term(+ "_index",+ call_records_search_alias().to_string(),+ ));+ bool_query.filter(QueryType::term(+ "call_relation",+ PARENT_RELATION.to_string(),+ ));++ // Access is via accessible call ids only — no user_id field.+ if self.inner.ids_only {+ bool_query.filter(QueryType::terms("entity_id", self.inner.ids.clone()));+ } else if !self.inner.ids.is_empty() {+ // ids list narrows even when not ids_only.+ bool_query.filter(QueryType::terms("entity_id", self.inner.ids.clone()));+ }++ // channel_id is denormalized onto the parent in v2.+ if !self.channel_ids.is_empty() {+ bool_query.filter(QueryType::terms("channel_id", self.channel_ids.clone()));+ }++ // One has_child clause per term, ANDed via bool.must. Each+ // carries its own inner_hits; the shared highlight_query tags+ // every search term on a returned segment regardless of which+ // clause produced it.+ //+ // speaker_id is a child-side field — it lives inside each+ // has_child clause alongside the term query so the same segment+ // that matches the term must also be from one of the requested+ // speakers. Filtering speaker_id at the bool level instead+ // would only require *some* segment in the call to have the+ // speaker, not necessarily the segment matching the term.+ 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 term_query = build_child_content_query(term, &self.inner.match_type);+ let inner_query = if self.speaker_ids.is_empty() {+ term_query+ } else {+ let mut combined = BoolQueryBuilder::new();+ combined.must(term_query);+ combined.must(QueryType::terms("speaker_id", self.speaker_ids.clone()));+ combined.build().into()+ };+ 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)+ }+}++/// Highlight config attached to each `has_child` inner_hits block.+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,+ }+ }+ })+}++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,+ }+ })+}++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, Default)]@@ -108,3 +279,101 @@ impl From<CallRecordSearchArgs> for CallRecordQueryBuilder {.ids_only(args.ids_only)}}++// ---------------------------------------------------------------------------+// inner_hits → segment-level SearchHits+// ---------------------------------------------------------------------------++#[derive(Debug, serde::Deserialize)]+struct SegmentInnerHit {+ #[serde(rename = "_id")]+ id: String,+ #[serde(rename = "_score")]+ score: Option<f64>,+ #[serde(rename = "_source")]+ source: SegmentSource,+ #[serde(default)]+ highlight: Option<HashMap<String, Vec<String>>>,+}++#[derive(Debug, serde::Deserialize)]+struct SegmentSource {+ transcript_id: uuid::Uuid,+ #[serde(default)]+ speaker_id: Option<String>,+ #[serde(default)]+ sequence_num: Option<i32>,+ started_at_seconds: i64,+ #[serde(default)]+ ended_at_seconds: Option<i64>,+}++#[derive(Debug, serde::Deserialize)]+struct InnerHitsGroup {+ #[serde(default)]+ hits: InnerHitsList,+}++#[derive(Debug, Default, serde::Deserialize)]+struct InnerHitsList {+ #[serde(default)]+ hits: Vec<SegmentInnerHit>,+}++/// Walk the `inner_hits` block from a join-shape parent hit and emit+/// one `SearchHit` per matching child segment, carrying that segment's+/// `transcript_id`, `speaker_id`, `sequence_num`, timestamps, and+/// highlight — plus the parent's `channel_id` and `participant_ids`+/// threaded through for goto-navigation.+pub(crate) fn expand_inner_hits_to_search_hits(+ parent: &CallRecordIndex,+ 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 seg in group.hits.hits {+ if !seen.insert(seg.id) {+ continue;+ }+ let highlight: Highlight = seg+ .highlight+ .map(|h| {+ parse_highlight_hit(+ h,+ Keys {+ title_key: CallRecordSearchConfig::TITLE_KEY,+ content_key: CallRecordSearchConfig::CONTENT_KEY,+ },+ )+ })+ .unwrap_or_default();+ out.push(SearchHit {+ entity_id: parent.entity_id,+ entity_type: SearchEntityType::CallRecords,+ score: seg.score,+ highlight,+ goto: Some(SearchGotoContent::CallRecords(SearchGotoCallRecord {+ channel_id: parent.channel_id,+ transcript_id: seg.source.transcript_id,+ speaker_id: seg.source.speaker_id.unwrap_or_default(),+ sequence_num: seg.source.sequence_num.unwrap_or_default(),+ started_at: DateTime::from_timestamp(seg.source.started_at_seconds, 0)+ .unwrap_or_default(),+ ended_at: seg+ .source+ .ended_at_seconds+ .and_then(|s| DateTime::from_timestamp(s, 0)),+ participant_ids: parent.participant_ids.clone(),+ })),+ updated_at: DateTime::from_timestamp(parent.started_at_seconds, 0),+ });+ }+ }+ out+}diff --git a/rust/cloud-storage/opensearch_client/src/search/unified.rs b/rust/cloud-storage/opensearch_client/src/search/unified.rsindex 42e5bd6a1f..92537d3925 100644--- a/rust/cloud-storage/opensearch_client/src/search/unified.rs+++ b/rust/cloud-storage/opensearch_client/src/search/unified.rs@@ -321,6 +321,17 @@ fn expand_hit_into_search_hits(hit: Hit<UnifiedSearchIndex>) -> Vec<SearchHit> {}expanded}+ UnifiedSearchIndex::CallRecord(parent) => {+ let Some(inner) = hit.inner_hits.as_ref() else {+ return vec![hit.into()];+ };+ let expanded =+ crate::search::call_records::expand_inner_hits_to_search_hits(parent, inner);+ if expanded.is_empty() {+ return vec![hit.into()];+ }+ expanded+ }_ => vec![hit.into()],}}@@ -465,9 +476,13 @@ impl From<Hit<UnifiedSearchIndex>> for SearchHit {.unwrap_or_default(),goto: Some(SearchGotoContent::CallRecords(SearchGotoCallRecord {channel_id: a.channel_id,- transcript_id: a.transcript_id,- speaker_id: a.speaker_id,- sequence_num: a.sequence_num,+ // Flat-shape docs always carry transcript/speaker/sequence;+ // the join-shape parent fallback path only arrives here+ // when inner_hits was empty, in which case we have no+ // segment-level identifier to navigate to.+ transcript_id: a.transcript_id.unwrap_or_default(),+ speaker_id: a.speaker_id.unwrap_or_default(),+ sequence_num: a.sequence_num.unwrap_or_default(),started_at: DateTime::from_timestamp(a.started_at_seconds, 0).unwrap_or_default(),ended_at: a@@ -606,15 +621,19 @@ pub(crate) async fn search_unified(tracing::trace!("search request {:?}", search_request);- // Documents and chats reads can be redirected to a side alias via- // DOCUMENTS_INDEX_NAME / CHATS_INDEX_NAME for local end-to-end- // testing; every other entity type keeps its default alias.+ // Documents, chats, and call records reads can be redirected to a+ // side alias via DOCUMENTS_INDEX_NAME / CHATS_INDEX_NAME /+ // CALL_RECORDS_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(),OpenSearchEntityType::Chats => crate::chats_shape::chats_search_alias(),+ OpenSearchEntityType::CallRecords => {+ crate::call_records_shape::call_records_search_alias()+ }other => other.index_name(),}).collect();diff --git a/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs b/rust/cloud-storage/opensearch_client/src/upsert/call_record.rsindex bbceff9e92..89a7e95be5 100644--- a/rust/cloud-storage/opensearch_client/src/upsert/call_record.rs+++ b/rust/cloud-storage/opensearch_client/src/upsert/call_record.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, call_records_shape::destination_uses_join_shape, date_format::EpochSeconds,+ error::OpensearchClientError,+};++/// Relation name for parent docs in the call_records join field.+const PARENT_RELATION: &str = "call";++/// Relation name for child (segment) docs in the call_records join field.+const CHILD_RELATION: &str = "segment";#[derive(Debug, serde::Serialize)]pub struct UpsertCallRecordSegmentArgs {@@ -20,14 +31,35 @@ pub struct UpsertCallRecordSegmentArgs {pub ended_at_seconds: Option<EpochSeconds>,}+fn resolve_destination(index_override: Option<&str>) -> &str {+ index_override.unwrap_or(SearchIndex::CallRecords.as_ref())+}+#[tracing::instrument(skip(client), err)]pub(crate) async fn upsert_call_record_segment(client: &opensearch::OpenSearch,args: &UpsertCallRecordSegmentArgs,index_override: Option<&str>,+) -> Result<()> {+ let destination = resolve_destination(index_override);+ if destination_uses_join_shape(destination) {+ return bulk_upsert_call_record_segments_join(+ client,+ std::slice::from_ref(args),+ destination,+ )+ .await+ .map(|_| ());+ }+ upsert_call_record_segment_flat(client, args, destination).await+}++async fn upsert_call_record_segment_flat(+ client: &opensearch::OpenSearch,+ args: &UpsertCallRecordSegmentArgs,+ index: &str,) -> Result<()> {let id = &args.transcript_id;- let index = index_override.unwrap_or(SearchIndex::CallRecords.as_ref());let response = client.index(opensearch::IndexParts::IndexId(index, id)).body(args)@@ -41,24 +73,24 @@ pub(crate) async fn upsert_call_record_segment(let status_code = response.status_code();if status_code.is_success() {tracing::trace!(id=%id, "call record segment upserted");- } else {- let body =- response- .text()- .await- .map_err(|err| OpensearchClientError::DeserializationFailed {- details: err.to_string(),- method: Some("upsert_call_record_segment".to_string()),- })?;-- tracing::error!(status_code=%status_code, body=%body, "error upserting call record segment");-- return Err(OpensearchClientError::Unknown {- details: body,- method: Some("upsert_call_record_segment".to_string()),- });+ return Ok(());}- Ok(())++ let body =+ response+ .text()+ .await+ .map_err(|err| OpensearchClientError::DeserializationFailed {+ details: err.to_string(),+ method: Some("upsert_call_record_segment".to_string()),+ })?;++ tracing::error!(status_code=%status_code, body=%body, "error upserting call record segment");++ Err(OpensearchClientError::Unknown {+ details: body,+ method: Some("upsert_call_record_segment".to_string()),+ })}#[tracing::instrument(skip(client, segments), err)]@@ -71,6 +103,19 @@ pub(crate) async fn bulk_upsert_call_record_segments(return Ok(BulkUpsertResult::default());}+ let index = resolve_destination(index_override);+ if destination_uses_join_shape(index) {+ bulk_upsert_call_record_segments_join(client, segments, index).await+ } else {+ bulk_upsert_call_record_segments_flat(client, segments, index).await+ }+}++async fn bulk_upsert_call_record_segments_flat(+ client: &opensearch::OpenSearch,+ segments: &[UpsertCallRecordSegmentArgs],+ index: &str,+) -> Result<BulkUpsertResult> {let mut bulk_body = Vec::with_capacity(segments.len() * 2);for seg in segments {@@ -84,6 +129,79 @@ pub(crate) async fn bulk_upsert_call_record_segments(})?);}- let index = index_override.unwrap_or(SearchIndex::CallRecords.as_ref());super::bulk_upsert_to_index(client, index, bulk_body, "bulk_upsert_call_record_segments").await}++/// Builds the JSON document body for the parent call doc.+fn parent_doc_body(any_segment: &UpsertCallRecordSegmentArgs) -> serde_json::Value {+ let mut doc = serde_json::json!({+ "entity_id": &any_segment.call_id,+ "channel_id": &any_segment.channel_id,+ "participant_ids": &any_segment.participant_ids,+ "started_at_seconds": any_segment.started_at_seconds,+ "call_relation": PARENT_RELATION,+ });+ if let Some(name) = &any_segment.channel_name {+ doc["channel_name"] = serde_json::Value::String(name.clone());+ }+ if let Some(ended) = &any_segment.ended_at_seconds {+ doc["ended_at_seconds"] = serde_json::to_value(ended).unwrap_or(serde_json::Value::Null);+ }+ doc+}++/// Builds the JSON document body for a child (segment) doc.+fn child_doc_body(seg: &UpsertCallRecordSegmentArgs) -> serde_json::Value {+ serde_json::json!({+ "entity_id": &seg.transcript_id,+ "transcript_id": &seg.transcript_id,+ "speaker_id": &seg.speaker_id,+ "sequence_num": seg.sequence_num,+ "content": &seg.content,+ "started_at_seconds": seg.started_at_seconds,+ "ended_at_seconds": &seg.ended_at_seconds,+ "call_relation": {+ "name": CHILD_RELATION,+ "parent": &seg.call_id,+ },+ })+}++/// Writes one parent call doc per unique call_id and one child segment+/// doc per row, all rooted at the call_id via `_routing` so the parent+/// and all its segments live on the same shard.+async fn bulk_upsert_call_record_segments_join(+ client: &opensearch::OpenSearch,+ segments: &[UpsertCallRecordSegmentArgs],+ index: &str,+) -> Result<BulkUpsertResult> {+ let mut bulk_body = Vec::with_capacity(segments.len() * 2 + 2);+ let mut seen_parents: HashSet<&str> = HashSet::new();++ for seg in segments {+ let parent_id = seg.call_id.as_str();+ let routing = parent_id;++ if seen_parents.insert(parent_id) {+ let parent_action = serde_json::json!({+ "index": { "_id": parent_id, "routing": routing }+ });+ bulk_body.push(parent_action.to_string());+ bulk_body.push(parent_doc_body(seg).to_string());+ }++ let child_action = serde_json::json!({+ "index": { "_id": &seg.transcript_id, "routing": routing }+ });+ bulk_body.push(child_action.to_string());+ bulk_body.push(child_doc_body(seg).to_string());+ }++ super::bulk_upsert_to_index(+ client,+ index,+ bulk_body,+ "bulk_upsert_call_record_segments_join",+ )+ .await+}diff --git a/rust/cloud-storage/search_processing_service/src/domain/models.rs b/rust/cloud-storage/search_processing_service/src/domain/models.rsindex 9c0ade07ab..6ce294041c 100644--- a/rust/cloud-storage/search_processing_service/src/domain/models.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/models.rs@@ -59,14 +59,32 @@ impl DeletionFilter {}/// Call-record backfill filter. Empty `call_ids` means "all archived calls".+///+/// `started_after` / `started_before` filter on `call_records.started_at`+/// because the table doesn't carry an updated_at — calls are immutable+/// after creation, so this gives the equivalent "since X" semantics.#[derive(Debug, Clone, Default, Deserialize)]#[serde(default)]pub struct CallBackfillRequest {pub call_ids: Vec<String>,+ pub started_after: Option<DateTime<Utc>>,+ pub started_before: Option<DateTime<Utc>>,/// Override the OpenSearch target index for upserts (e.g. blue/green swap).pub index_override: Option<String>,}+/// Keyset (seek-method) pagination cursor for call backfills.+///+/// `get_call_records_for_search_backfill` walks `call_records` in+/// `(started_at ASC, id ASC)` order; the cursor carries the last row's+/// pair so the next page resumes with `WHERE (started_at, id) > cursor`.+/// `None` starts at the beginning.+#[derive(Debug, Clone)]+pub struct CallBackfillCursor {+ pub started_at: DateTime<Utc>,+ pub call_id: uuid::Uuid,+}+/// Chat-message backfill filter. Empty vectors mean "all messages for every/// chat / every user".///diff --git a/rust/cloud-storage/search_processing_service/src/domain/ports.rs b/rust/cloud-storage/search_processing_service/src/domain/ports.rsindex 1c113bea8b..d32496ba48 100644--- a/rust/cloud-storage/search_processing_service/src/domain/ports.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/ports.rs@@ -17,9 +17,9 @@ use std::future::Future;use sqs_client::search::SearchQueueMessage;use super::models::{- BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillCursor,- ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest,- SourcePage,+ BackfillError, CallBackfillCursor, CallBackfillRequest, ChannelBackfillRequest,+ ChatBackfillCursor, ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest,+ EmailBackfillRequest, SourcePage,};/// Publishes batches of search-event messages.@@ -39,11 +39,17 @@ pub trait SearchEventPublisher: Send + Sync + 'static {/// per user) must report the row count separately so the loop offsets/// correctly.pub trait BackfillSource: Send + Sync + 'static {+ /// Calls paginate by keyset cursor (mirroring documents/chats): the+ /// implementation returns the page plus the cursor of the last row+ /// to feed back into the next call. An empty page signals+ /// end-of-source. When `req.call_ids` is non-empty, the+ /// implementation paginates the explicit list with the cursor+ /// instead of scanning the table.fn fetch_calls(&self,req: &CallBackfillRequest,- offset: usize,- ) -> impl Future<Output = Result<SourcePage, BackfillError>> + Send;+ cursor: Option<CallBackfillCursor>,+ ) -> impl Future<Output = Result<(SourcePage, Option<CallBackfillCursor>), BackfillError>> + Send;/// Chats paginate by keyset cursor (mirroring documents): each call/// passes the cursor of the last row from the previous page (ordiff --git a/rust/cloud-storage/search_processing_service/src/domain/service.rs b/rust/cloud-storage/search_processing_service/src/domain/service.rsindex 5397e306ab..4aca6e7b16 100644--- a/rust/cloud-storage/search_processing_service/src/domain/service.rs+++ b/rust/cloud-storage/search_processing_service/src/domain/service.rs@@ -165,8 +165,8 @@ whereprogress: Arc<JobProgress>,cancel: CancellationToken,) -> Result<BackfillReceipt, BackfillError> {- drain_source(&self.publisher, &progress, &cancel, |offset| {- self.source.fetch_calls(&req, offset)+ drain_source_with_cursor(&self.publisher, &progress, &cancel, |cursor| {+ self.source.fetch_calls(&req, cursor)}).await}diff --git a/rust/cloud-storage/search_processing_service/src/outbound/source.rs b/rust/cloud-storage/search_processing_service/src/outbound/source.rsindex 6baa31b25f..18ce9aeefa 100644--- a/rust/cloud-storage/search_processing_service/src/outbound/source.rs+++ b/rust/cloud-storage/search_processing_service/src/outbound/source.rs@@ -9,9 +9,9 @@ use sqs_client::search::{use crate::config::BackfillPageSizes;use crate::domain::models::{- BackfillError, CallBackfillRequest, ChannelBackfillRequest, ChatBackfillCursor,- ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest, EmailBackfillRequest,- SourcePage,+ BackfillError, CallBackfillCursor, CallBackfillRequest, ChannelBackfillRequest,+ ChatBackfillCursor, ChatBackfillRequest, DocumentBackfillCursor, DocumentBackfillRequest,+ EmailBackfillRequest, SourcePage,};use crate::domain::ports::BackfillSource;@@ -35,20 +35,30 @@ impl BackfillSource for PgBackfillSource {async fn fetch_calls(&self,req: &CallBackfillRequest,- offset: usize,- ) -> Result<SourcePage, BackfillError> {- // Caller passed an explicit set of ids: page through them at the- // configured page size so this branch and the full-scan branch share- // the same loop shape and failure semantics.+ cursor: Option<CallBackfillCursor>,+ ) -> Result<(SourcePage, Option<CallBackfillCursor>), BackfillError> {+ // Caller passed an explicit set of ids: walk them in order,+ // using the cursor's call_id as the "where to resume" anchor.+ // The cursor's started_at is irrelevant for this branch since+ // the ids list isn't ordered by it; we just position by id.if !req.call_ids.is_empty() {- let start = offset;- if start >= req.call_ids.len() {- return Ok(SourcePage::empty());+ let resume_from = cursor+ .as_ref()+ .and_then(|c| {+ req.call_ids+ .iter()+ .position(|id| id.parse::<uuid::Uuid>().ok() == Some(c.call_id))+ })+ .map(|i| i + 1)+ .unwrap_or(0);+ if resume_from >= req.call_ids.len() {+ return Ok((SourcePage::empty(), None));}- let end = start+ let end = resume_from.saturating_add(self.page_sizes.calls).min(req.call_ids.len());- let messages: Vec<SearchQueueMessage> = req.call_ids[start..end]+ let slice = &req.call_ids[resume_from..end];+ let messages: Vec<SearchQueueMessage> = slice.iter().map(|id| {SearchQueueMessage::CallRecord(CallRecordMessage {@@ -58,20 +68,43 @@ impl BackfillSource for PgBackfillSource {}).collect();let rows_consumed = messages.len();- return Ok(SourcePage {- messages,- rows_consumed,+ // started_at is a placeholder for this branch (epoch) because+ // the explicit-id list isn't sorted by it; we navigate by+ // call_id position. Using Utc::now is also fine; either way+ // the only thing the loop uses next time is call_id.+ let next_cursor = slice.last().and_then(|last_id| {+ last_id+ .parse::<uuid::Uuid>()+ .ok()+ .map(|call_id| CallBackfillCursor {+ started_at: chrono::Utc::now(),+ call_id,+ })});+ return Ok((+ SourcePage {+ messages,+ rows_consumed,+ },+ next_cursor,+ ));}+ let db_cursor = cursor.map(|c| (c.started_at, c.call_id));let batch = macro_db_client::call_record::get::get_call_records_for_search_backfill(&self.db,self.page_sizes.calls as i64,- offset as i64,+ db_cursor,+ req.started_after,+ req.started_before,).await.map_err(BackfillError::Source)?;+ let next_cursor = batch.last().map(|r| CallBackfillCursor {+ started_at: r.started_at,+ call_id: r.call_id,+ });let rows_consumed = batch.len();let messages: Vec<SearchQueueMessage> = batch.into_iter()@@ -83,10 +116,13 @@ impl BackfillSource for PgBackfillSource {}).collect();- Ok(SourcePage {- messages,- rows_consumed,- })+ Ok((+ SourcePage {+ messages,+ rows_consumed,+ },+ next_cursor,+ ))}async fn fetch_chats(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 a1e02b9222..aad511dba5 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@@ -213,12 +213,17 @@ pub(in crate::api::search) async fn perform_unified_search(} else {terms.clone()};+ let call_record_terms = if opensearch_client::call_records_shape::alias_uses_join_shape() {+ split_search_terms(&terms)+ } else {+ terms.clone()+ };let channel_terms = split_search_terms(&terms);filter_document_response.terms = document_terms;filter_channel_response.terms = channel_terms;filter_chat_response.terms = chat_terms;filter_email_response.terms = email_terms.clone();- filter_call_record_response.terms = terms.clone();+ filter_call_record_response.terms = call_record_terms;// Clone terms for use in name searcheslet name_search_term = terms[0].clone();