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_processing_service): Kafka consumer for calls (#5273)
Will Hutchinson247311498f6c
diff --git a/Cargo.lock b/Cargo.lockindex 2b9aacb995..252f7e6087 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12821,6 +12821,7 @@ dependencies = ["aws-sdk-s3","aws-sdk-sqs","axum",+ "call","chrono","comms_db_client","document_sub_type",@@ -12829,6 +12830,7 @@ dependencies = ["ensure_exists","futures","http-body-util",+ "kafka_util","lexical_client","macro_auth","macro_authorization",@@ -12839,6 +12841,8 @@ dependencies = ["macro_entrypoint","macro_env","macro_env_var",+ "macro_event_broker",+ "macro_event_topics","macro_middleware","macro_queues","macro_service_urls",@@ -12855,6 +12859,8 @@ dependencies = ["opensearch_client","pdfium-render","properties",+ "rdkafka",+ "rootcause","rust-embed","s3_client","s3_key",@@ -12866,6 +12872,7 @@ dependencies = ["strum 0.27.2","thiserror 2.0.18","tokio",+ "tokio-retry","tokio-util","tower 0.5.3","tower-http",diff --git a/crates/call/src/domain/entity_mutation.rs b/crates/call/src/domain/entity_mutation.rsindex bc7b2bf6b8..072d1f9bf2 100644--- a/crates/call/src/domain/entity_mutation.rs+++ b/crates/call/src/domain/entity_mutation.rs@@ -20,8 +20,7 @@ use connection::domain::ports::ConnectionService;use notification::domain::{ports::VoipPushSender, service::NotificationIngress};use crate::domain::ports::{- CallRepository, CallRtcClient, CallSearchIndexer, CallSummarizer, RecordingStorage,- VoiceRepository,+ CallRepository, CallRtcClient, CallSummarizer, RecordingStorage, VoiceRepository,};impl From<CallError> for EntityMutationErrorCode {@@ -74,8 +73,8 @@ async fn require_archived_call<S: CallService>(Ok(())}-impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> RenameEntity- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+impl<R, C, Cn, E, N, S, Sm, V, Vr, B> RenameEntity+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>whereR: CallRepository,C: CallRtcClient,@@ -84,7 +83,6 @@ whereN: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository,B: MacroEventBroker,@@ -112,8 +110,8 @@ where}}-impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> UpdateEntitySharePolicy- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+impl<R, C, Cn, E, N, S, Sm, V, Vr, B> UpdateEntitySharePolicy+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>whereR: CallRepository,C: CallRtcClient,@@ -122,7 +120,6 @@ whereN: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository,B: MacroEventBroker,@@ -150,8 +147,8 @@ where}}-impl<R, C, Cn, E, N, S, Sm, I, V, Vr, B> DeleteEntityPermanently- for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+impl<R, C, Cn, E, N, S, Sm, V, Vr, B> DeleteEntityPermanently+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>whereR: CallRepository,C: CallRtcClient,@@ -160,7 +157,6 @@ whereN: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository,B: MacroEventBroker,diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rsindex 9af7564da5..035beabd05 100644--- a/crates/call/src/domain/ports.rs+++ b/crates/call/src/domain/ports.rs@@ -690,19 +690,6 @@ impl CallRecordQueryService for NoOpCallRecordQueryService {}}-/// Propagates call record lifecycle events to the search index.-pub trait CallSearchIndexer: Send + Sync + 'static {- /// Enqueue an upsert.- fn enqueue_upsert(&self, call_id: &Uuid) -> impl Future<Output = anyhow::Result<()>> + Send;-- /// Enqueue a removal.- fn enqueue_remove(- &self,- channel_id: &Uuid,- call_id: &Uuid,- ) -> impl Future<Output = anyhow::Result<()>> + Send;-}-/// Repository port for persisting speaker voice embeddings and their/// association with macro users.///@@ -810,16 +797,3 @@ impl VoiceRepository for NoOpVoiceRepository {Ok(None)}}--/// No-op for services without search.-pub struct NoOpCallSearchIndexer;--impl CallSearchIndexer for NoOpCallSearchIndexer {- async fn enqueue_upsert(&self, _call_id: &Uuid) -> anyhow::Result<()> {- Ok(())- }-- async fn enqueue_remove(&self, _channel_id: &Uuid, _call_id: &Uuid) -> anyhow::Result<()> {- Ok(())- }-}diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rsindex aed5a13aab..3350466d96 100644--- a/crates/call/src/domain/service.rs+++ b/crates/call/src/domain/service.rs@@ -43,8 +43,8 @@ use super::models::{RingStatusResponse, TranscriptSegmentRequest,};use super::ports::{- CallRecordQueryService, CallRepository, CallRtcClient, CallSearchIndexer, CallService,- CallSummarizer, NoOpCallSearchIndexer, NoOpVoiceRepository, RecordingStorage, VoiceRepository,+ CallRecordQueryService, CallRepository, CallRtcClient, CallService, CallSummarizer,+ NoOpVoiceRepository, RecordingStorage, VoiceRepository,};/// The concrete call service implementation.@@ -56,7 +56,6 @@ pub struct CallServiceImpl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer = NoopCallSummarizer,- I: CallSearchIndexer = NoOpCallSearchIndexer,V: VoipPushSender = (),Vr: VoiceRepository = NoOpVoiceRepository,B: MacroEventBroker = NoopMacroEventBroker,@@ -67,7 +66,6 @@ pub struct CallServiceImpl<entity_access_service: E,notification_ingress: N,recording_storage: S,- search_indexer: I,server_url: String,egress_s3_config: Option<EgressS3Config>,internal_call_secret: Option<String>,@@ -86,7 +84,7 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer, (), NoOpVoiceRepository>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, (), NoOpVoiceRepository>{/// Create a new call service.pub fn new(@@ -105,7 +103,6 @@ impl<entity_access_service,notification_ingress,recording_storage,- search_indexer: NoOpCallSearchIndexer,server_url: server_url.into(),egress_s3_config: None,internal_call_secret: None,@@ -126,11 +123,10 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository,B: MacroEventBroker,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>{/// Enable auto-recording with the given S3 configuration.pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {@@ -164,7 +160,7 @@ impl<pub fn with_voip_push_sender<V2: VoipPushSender>(self,sender: V2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2, Vr, B> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V2, Vr, B> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -172,7 +168,6 @@ impl<entity_access_service: self.entity_access_service,notification_ingress: self.notification_ingress,recording_storage: self.recording_storage,- search_indexer: self.search_indexer,server_url: self.server_url,egress_s3_config: self.egress_s3_config,internal_call_secret: self.internal_call_secret,@@ -184,35 +179,11 @@ impl<}}- /// Swap the search indexer.- pub fn with_search_indexer<I2: CallSearchIndexer>(- self,- indexer: I2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V, Vr, B> {- CallServiceImpl {- repo: self.repo,- rtc_client: self.rtc_client,- connection_service: self.connection_service,- entity_access_service: self.entity_access_service,- notification_ingress: self.notification_ingress,- recording_storage: self.recording_storage,- search_indexer: indexer,- server_url: self.server_url,- egress_s3_config: self.egress_s3_config,- internal_call_secret: self.internal_call_secret,- summarizer: self.summarizer,- voip_push_sender: self.voip_push_sender,- voice_repo: self.voice_repo,- ring_status_base_url: self.ring_status_base_url,- event_broker: self.event_broker,- }- }-/// Swap the voice repository.pub fn with_voice_repo<Vr2: VoiceRepository>(self,voice_repo: Vr2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr2, B> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr2, B> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -220,7 +191,6 @@ impl<entity_access_service: self.entity_access_service,notification_ingress: self.notification_ingress,recording_storage: self.recording_storage,- search_indexer: self.search_indexer,server_url: self.server_url,egress_s3_config: self.egress_s3_config,internal_call_secret: self.internal_call_secret,@@ -236,7 +206,7 @@ impl<pub fn with_event_broker<B2: MacroEventBroker>(self,event_broker: B2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B2> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B2> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -244,7 +214,6 @@ impl<entity_access_service: self.entity_access_service,notification_ingress: self.notification_ingress,recording_storage: self.recording_storage,- search_indexer: self.search_indexer,server_url: self.server_url,egress_s3_config: self.egress_s3_config,internal_call_secret: self.internal_call_secret,@@ -501,11 +470,10 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer + Clone,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository + Clone,B: MacroEventBroker + Clone,-> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>{fn validate_internal_call(&self, token: &str) -> bool {self.internal_call_secret@@ -951,10 +919,6 @@ impl<self.spawn_summarize_call(archived.call_id);self.spawn_process_voices_for_call(archived.call_id);- if let Err(e) = self.search_indexer.enqueue_upsert(&archived.call_id).await {- tracing::error!(error=?e, call_id=%archived.call_id, "failed to enqueue call record for search indexing");- }-self.send_call_event(&archived.channel_id,"call_ended",@@ -1075,10 +1039,6 @@ impl<self.spawn_summarize_call(archived.call_id);self.spawn_process_voices_for_call(archived.call_id);- if let Err(e) = self.search_indexer.enqueue_upsert(&archived.call_id).await {- tracing::error!(error=?e, call_id=%archived.call_id, "failed to enqueue call record for search indexing");- }-// Stop egress explicitly before deleting the room. DeleteRoom// is expected to cascade-stop egress, but a failed or slow// DeleteRoom can leave egress running and billing. Doing it@@ -1270,7 +1230,7 @@ impl<.map_err(|_| CallError::Internal(anyhow::anyhow!("invalid call_id in receipt")))?;let actor_user_id = event_actor_user_id(receipt.auth());- // Look up channel_id before deletion to keep the search-remove message id unique.+ // Look up channel_id before deletion so the deleted event includes channel context.let channel_id = self.repo.get_call_record_by_call_id(&call_id)@@ -1294,15 +1254,6 @@ impl<}));}- if let Some(channel_id) = channel_id- && let Err(e) = self- .search_indexer- .enqueue_remove(&channel_id, &call_id)- .await- {- tracing::error!(error=?e, call_id=%call_id, "failed to enqueue call record removal from search");- }-if let Some(storage_keys) = storage_keys {if let Some(key) = storage_keys.recording_key.as_deref() {self.recording_storage@@ -1635,11 +1586,10 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer + Clone,- I: CallSearchIndexer,V: VoipPushSender,Vr: VoiceRepository + Clone,B: MacroEventBroker + Clone,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr, B>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>{/// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.///diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rsindex 88710a37ea..7125d8e965 100644--- a/crates/call/src/domain/service/test.rs+++ b/crates/call/src/domain/service/test.rs@@ -24,7 +24,7 @@ use crate::domain::models::{};use crate::domain::ports::{CallRtcClient, CallService, CallSummarizer, MockCallRepository, MockCallRtcClient,- NoOpCallSearchIndexer, NoOpVoiceRepository,+ NoOpVoiceRepository,};use super::{@@ -1864,7 +1864,6 @@ type SummarizationCallService<B> = CallServiceImpl<StubNotificationIngress,StubRecordingStorage,StubCallSummarizer,- NoOpCallSearchIndexer,(),NoOpVoiceRepository,B,diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex 81603d6c3c..6fd0520d2e 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -1,6 +1,10 @@import * as pulumi from '@pulumi/pulumi';import { DynamoDBTable } from '../../packages/resources';-import { getSearchEventQueue, stack } from '../../packages/shared';+import {+ getKafkaClusterPolicy,+ getSearchEventQueue,+ stack,+} from '../../packages/shared';import { get_coparse_api_vpc } from '../../packages/vpc';import { SearchProcessingService } from './service';@@ -43,7 +47,10 @@ const BASE_NAME = 'search-processing-service';const searchProcessingService = new SearchProcessingService(`${BASE_NAME}-${stack}`,{- extraManagedPolicyArns: [backfillJobsTable.policy.arn],+ extraManagedPolicyArns: [+ backfillJobsTable.policy.arn,+ getKafkaClusterPolicy(),+ ],searchEventQueueArn,ecsClusterArn: cloudStorageClusterArn,documentStorageBucketArn,diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rsindex 26ebd65190..d0992fa593 100644--- a/services/document_storage_service/src/api/context.rs+++ b/services/document_storage_service/src/api/context.rs@@ -358,7 +358,6 @@ pub(crate) type DssCallService = CallServiceImpl<NotificationIngressType,Option<call::outbound::s3_recording_storage::S3RecordingStorage>,call::outbound::ai_call_summarizer::AiCallSummarizer,- crate::service::call_search_indexer::SqsCallSearchIndexer,DssVoipPushSender,call::outbound::pg_voice_repo::PgVoiceRepo,DssEventBroker,diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rsindex 4ac36cc461..8cd04deef2 100644--- a/services/document_storage_service/src/main.rs+++ b/services/document_storage_service/src/main.rs@@ -676,12 +676,8 @@ async fn main() -> anyhow::Result<()> {};let call_service_builder = call_service_builder.with_voip_push_sender(voip_sender);- let call_search_indexer = crate::service::call_search_indexer::SqsCallSearchIndexer::new(- Arc::new(sqs_client.clone()),- );let call_service = Arc::new(call_service_builder- .with_search_indexer(call_search_indexer).with_voice_repo(PgVoiceRepo::new(db.clone())).with_event_broker(macro_event_broker.clone()),);diff --git a/services/document_storage_service/src/service/call_search_indexer.rs b/services/document_storage_service/src/service/call_search_indexer.rsdeleted file mode 100644index d1fedf07a1..0000000000--- a/services/document_storage_service/src/service/call_search_indexer.rs+++ /dev/null@@ -1,47 +0,0 @@-use std::sync::Arc;--use call::domain::ports::CallSearchIndexer;-use sqs_client::{- SQS,- search::{- SearchQueueMessage,- call::{CallRecordMessage, RemoveCallRecord},- },-};-use uuid::Uuid;--#[derive(Clone)]-pub struct SqsCallSearchIndexer {- sqs: Arc<SQS>,-}--impl SqsCallSearchIndexer {- pub fn new(sqs: Arc<SQS>) -> Self {- Self { sqs }- }-}--impl CallSearchIndexer for SqsCallSearchIndexer {- async fn enqueue_upsert(&self, call_id: &Uuid) -> anyhow::Result<()> {- self.sqs- .send_message_to_search_event_queue(SearchQueueMessage::CallRecord(CallRecordMessage {- call_id: call_id.to_string(),- index_override: None,- }))- .await?;- Ok(())- }-- async fn enqueue_remove(&self, channel_id: &Uuid, call_id: &Uuid) -> anyhow::Result<()> {- self.sqs- .send_message_to_search_event_queue(SearchQueueMessage::RemoveCallRecord(- RemoveCallRecord {- channel_id: channel_id.to_string(),- call_id: Some(call_id.to_string()),- index_override: None,- },- ))- .await?;- Ok(())- }-}diff --git a/services/document_storage_service/src/service/mod.rs b/services/document_storage_service/src/service/mod.rsindex 487a973028..1d71089da3 100644--- a/services/document_storage_service/src/service/mod.rs+++ b/services/document_storage_service/src/service/mod.rs@@ -1,4 +1,3 @@-pub mod call_search_indexer;pub mod conn_gateway;#[cfg(feature = "delete_document_worker")]pub mod delete_document_worker;diff --git a/services/search_processing_service/Cargo.toml b/services/search_processing_service/Cargo.tomlindex 1d93ae757c..3dc0413aa2 100644--- a/services/search_processing_service/Cargo.toml+++ b/services/search_processing_service/Cargo.toml@@ -7,7 +7,15 @@ version = "0.1.0"[features]default = ["processing", "service", "pdf"]-processing = []+processing = [+ "dep:call",+ "dep:kafka_util",+ "dep:macro_event_broker",+ "dep:macro_event_topics",+ "dep:rdkafka",+ "dep:rootcause",+ "dep:tokio-retry",+]service = ["macro_db_client", "models_properties", "properties"]pdf = ["dep:pdfium-render"]@@ -26,11 +34,13 @@ aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true }+call = { path = "../../crates/call", default-features = false, optional = true }chrono = { workspace = true }comms_db_client = { path = "../../crates/comms_db_client" }email_db_client = { path = "../../crates/email_db_client" }futures = { workspace = true }http-body-util = { workspace = true }+kafka_util = { path = "../../crates/kafka_util", optional = true }lexical_client = { path = "../../crates/lexical_client" }macro_auth = { path = "../../crates/macro_auth" }macro_authorization = { path = "../../crates/macro_authorization" }@@ -41,6 +51,10 @@ macro_db_client = { path = "../../crates/macro_db_client", optional = true } # Mmacro_entrypoint = { path = "../../crates/macro_entrypoint" }macro_env = { path = "../../crates/macro_env" }macro_env_var = { path = "../../crates/macro_env_var" }+macro_event_broker = { path = "../../crates/macro_event_broker", default-features = false, features = [+ "outbound",+], optional = true }+macro_event_topics = { path = "../../crates/macro_event_topics", optional = true }macro_queues = { path = "../../crates/macro_queues" }macro_middleware = { path = "../../crates/macro_middleware", default-features = false }macro_user_id = { path = "../../crates/macro_user_id" }@@ -62,6 +76,8 @@ pdfium-render = { workspace = true, optional = true }properties = { path = "../../crates/properties", default-features = false, features = ["outbound",], optional = true }+rdkafka = { workspace = true, optional = true }+rootcause = { workspace = true, optional = true }rust-embed = "8.6.0"s3_client = { path = "../../crates/s3_client" }serde = { workspace = true }@@ -73,7 +89,8 @@ sqs_client = { path = "../../crates/sqs_client", default-features = false, featusqs_worker = { path = "../../crates/sqs_worker" }strum = { workspace = true }thiserror = { workspace = true }-tokio = { workspace = true, features = ["signal"] }+tokio = { workspace = true, features = ["signal", "sync", "time"] }+tokio-retry = { workspace = true, optional = true }tokio-util = { workspace = true }tower = { workspace = true }tower-http = { workspace = true }diff --git a/services/search_processing_service/README.md b/services/search_processing_service/README.mdindex b4adf401ea..f623cab7fb 100644--- a/services/search_processing_service/README.md+++ b/services/search_processing_service/README.md@@ -2,8 +2,9 @@This service owns the search-event pipeline:-- **Consume**: SQS workers drain `SEARCH_EVENT_QUEUE` and index into OpenSearch.-- **Backfill**: internal HTTP endpoints re-enqueue every indexable record of a given entity type onto that same queue. Every entity's backfill funnels through sps so operators have one URL surface to remember.+- **Live calls**: the `search-processing-service` Kafka consumer reads call lifecycle events from `macro.calls` and indexes them into OpenSearch.+- **Other live entities**: SQS workers drain `SEARCH_EVENT_QUEUE` for all other search entities.+- **Backfills**: internal HTTP endpoints enqueue every indexable record of a given entity type onto SQS. Call backfills remain on SQS alongside all other entity backfills.## Architecture@@ -11,14 +12,41 @@ sps is hexagonal:```src/- domain/ # models, ports (CallBackfill, ChatBackfill, ...), BackfillService trait + orchestrator- outbound/backfill/ # one Postgres-backed adapter per entity (calls/chats/channels/documents/emails)- api/internal/ # axum handlers — thin pass-throughs to the orchestrator- process/ # existing search-event workers+ domain/ # models, ports, BackfillService trait + orchestrator+ outbound/ # Postgres backfill source and SQS publisher adapters+ api/internal/ # axum handlers — thin pass-throughs to the orchestrator+ inbound/kafka_consumer.rs # live call event decoding, handoff, commits, and retries+ process/ # indexing shared by the SQS and Kafka inbound adapters```The orchestrator is the single inbound contract for HTTP handlers. Swapping an adapter (e.g. in-process → HTTP-proxied owner service) is a wiring change, not a handler rewrite.+## Ingestion Ownership and Event Mapping++Kafka is used only for live call indexing. SQS remains responsible for live events from other search entities and for every backfill, including call backfills. The SQS call message contract and handler remain available so `POST /internal/backfill/calls` can enqueue call records with the existing backfill path.++The `macro.calls` lifecycle events map to search actions as follows:++| Event | Search action |+|---|---|+| `call.record_archived` | Full upsert of the call and transcript segments |+| `call.record_updated` | Full upsert so edits such as `custom_name` reach search |+| `call.record_summarized` | Full upsert so the generated call name reaches search |+| `call.record_deleted` | Remove the individual call by `call_id` |+| `call.started` | Ignore after decoding |+| `call.recording_ready` | Ignore after decoding |++Upserts read the current call state from Postgres and overwrite the indexed representation, making repeated delivery safe. Kafka events do not carry an index override; reindexing and backfill-specific options belong to the SQS path.++### Kafka Delivery Contract++- The durable consumer group is `search-processing-service`. It subscribes only to `macro.calls`.+- The poll loop hands decoded events to a bounded 128-message channel. Sending waits when the channel is full, which stops polling and committing until the worker catches up.+- Exactly one worker drains the channel sequentially. This preserves partition/key ordering so an upsert cannot be processed after a later delete for the same call. Do not add naive concurrent workers; any future parallelism must consistently shard by `call_id`.+- An offset is committed asynchronously immediately after a successful in-memory handoff, not after OpenSearch processing. This commit-after-handoff design creates a loss window: a process or host crash can lose already committed events still in the 128-message buffer. If the worker channel closes before handoff, the offset is left uncommitted for redelivery.+- Malformed, keyless, and unsupported-schema records are logged and committed without handoff so a poison record cannot wedge a partition. Commit failures are logged and may cause duplicate delivery, which is safe because full upserts and per-call deletes are idempotent.+- Processing gets five total attempts. Failures are retried after 1, 2, 4, and 8 seconds; after the fifth failure, the event is logged with its call ID, event type, partition, offset, and final error, then dropped so later events can continue.+## Running LocallyNeeds valid AWS credentials (secrets manager + SQS).@@ -34,8 +62,23 @@ Two encrypted env bundles live at the repo root:# from repo root — pick one:just get_environment # .env-local.enc (local services)just get_environment dev # .env-localdev.enc (dev services)+```++The repository already provides a Kafka broker in `docker/docker-compose-databases.yml`. Start it for fully local processing:++```bash+docker compose --project-directory . -f docker/docker-compose-databases.yml up -d kafka+```+Use `KAFKA_BROKERS=localhost:9092` when sps runs directly on the host. A service container attached to the compose `databases` network must use `KAFKA_BROKERS=kafka:29092`; `localhost` inside that container refers to the container itself. Keep the broker value supplied by the dev environment bundle when running against dev infrastructure.++```bashcd services/search_processing_service++# Fully local host process:+KAFKA_BROKERS=localhost:9092 cargo run++# Or, with the dev-targeting environment bundle:cargo run```@@ -47,12 +90,33 @@ SEARCH_EVENT_QUEUE=search-event-queue-<scope>-<you> cargo runWhen `DATABASE_URL_READONLY` is set, backfill reads run against the macrodb read-replica so they do not contend with writes on the primary. The queue workers always read from the primary (replica lag could cause them to miss rows they are meant to index). When the env var is absent, backfills fall back to the primary.-To run the API surface without the worker loop:+To run the API surface without the SQS or Kafka worker loops:```bashcargo run --features disable_processing```+## Rollout, Monitoring, and Recovery++1. Configure `KAFKA_BROKERS` and the required MSK read permissions, then deploy the Kafka consumer while the live SQS call producer is still enabled.+2. On the first deployment, the new `search-processing-service` group has no committed offsets, so `auto.offset.reset=earliest` replays the retained `macro.calls` history. This replay and the temporary dual delivery from Kafka and SQS are safe: call upserts are full idempotent overwrites, and deletes are idempotent delete-by-query operations.+3. Before disabling live SQS call publication, confirm the consumer-group lag on `macro.calls` has caught up, worker errors are healthy, and the `call_records` index is fresh. Continue monitoring lag after cutover.+4. Watch service logs for Kafka receive/decode/commit errors, processing retry warnings, events dropped after five attempts, and consumer supervisor restarts. A commit error can result in a safe duplicate; a dropped processing event or crash in the commit-after-handoff window can require recovery.++For the local broker, inspect group lag with:++```bash+docker compose --project-directory . -f docker/docker-compose-databases.yml exec kafka \+ /opt/kafka/bin/kafka-consumer-groups.sh \+ --bootstrap-server kafka:29092 \+ --group search-processing-service \+ --describe+```++During the dual-delivery window, rollback the consumer deployment while SQS continues to provide live call indexing. After the SQS producer has been disabled, first roll back that producer change to resume SQS delivery, then roll back the consumer if needed.++Use `POST /internal/backfill/calls` after a rollback, a dropped upsert, or a suspected transition gap. An empty body re-enqueues every archived call through SQS; `{"call_ids": ["<uuid>"]}` targets known calls. This restores existing call documents but does not synthesize a delete event for a call that no longer exists, so investigate dropped delete logs by call ID.+## Backfill HTTP RoutesEvery search-indexed entity has a POST endpoint on sps's internal surface. They all share the same response shape (`{"enqueued": <usize>}`), share internal-auth via the `x-internal-auth-key` header, and accept a per-entity JSON filter in the request body.diff --git a/services/search_processing_service/src/api/mod.rs b/services/search_processing_service/src/api/mod.rsindex ad1e0d310d..7970501924 100644--- a/services/search_processing_service/src/api/mod.rs+++ b/services/search_processing_service/src/api/mod.rs@@ -1,6 +1,7 @@use anyhow::Context;use axum::Router;use context::ApiContext;+use tokio_util::sync::CancellationToken;use tower::ServiceBuilder;use tower_http::trace::TraceLayer;use utoipa::OpenApi;@@ -14,7 +15,16 @@ mod internal;pub(crate) mod context;mod swagger;-pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {+pub async fn setup_and_serve(+ state: ApiContext,+ shutdown_token: CancellationToken,+) -> anyhow::Result<()> {+ let server_result = serve(state, shutdown_token.clone()).await;+ shutdown_token.cancel();+ server_result+}++async fn serve(state: ApiContext, shutdown_token: CancellationToken) -> anyhow::Result<()> {let cors = macro_cors::cors_layer();let port = state.config.port;@@ -28,16 +38,16 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {.merge(health::router().layer(cors)).merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));- let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))+ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{port}")).await- .unwrap();+ .context("failed to bind API listener")?;tracing::info!("service is up and running with environment {:?} on port {}",env,port);axum::serve(listener, app.into_make_service())- .with_graceful_shutdown(shutdown_signal(backfill_jobs))+ .with_graceful_shutdown(shutdown_signal(backfill_jobs, shutdown_token)).await.context("error starting service")}@@ -47,7 +57,10 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {/// being killed mid-publish when the runtime exits. Only jobs running on/// this pod are cancelled — the registry is shared via DynamoDB but/// cancellation tokens are per-instance.-async fn shutdown_signal(backfill_jobs: crate::domain::jobs::BackfillJobs) {+async fn shutdown_signal(+ backfill_jobs: crate::domain::jobs::BackfillJobs,+ shutdown_token: CancellationToken,+) {let ctrl_c = async {if let Err(e) = tokio::signal::ctrl_c().await {tracing::error!(error=?e, "failed to install ctrl_c handler");@@ -77,6 +90,7 @@ async fn shutdown_signal(backfill_jobs: crate::domain::jobs::BackfillJobs) {tracing::info!("shutdown signal received; cancelling in-flight backfills on this pod");backfill_jobs.cancel_all_local();+ shutdown_token.cancel();}fn api_router() -> Router<ApiContext> {diff --git a/services/search_processing_service/src/config.rs b/services/search_processing_service/src/config.rsindex d3213ba210..3233ba0b6f 100644--- a/services/search_processing_service/src/config.rs+++ b/services/search_processing_service/src/config.rs@@ -11,6 +11,8 @@ env_vars! {pub struct OpensearchPassword;pub struct DocumentStorageBucket;pub struct BackfillJobsTable;+ /// Comma-separated Kafka bootstrap servers for live call lifecycle events.+ pub struct KafkaBrokers;}maybe_env_vars! {@@ -111,6 +113,9 @@ pub struct Config {/// The bucket where documents are storedpub document_storage_bucket: DocumentStorageBucket,+ /// Comma-separated Kafka bootstrap servers for live call lifecycle events.+ pub kafka_brokers: KafkaBrokers,+/// The number of workers to spawn#[macro_config_default(10)]pub worker_count: u8,diff --git a/services/search_processing_service/src/inbound/kafka_consumer.rs b/services/search_processing_service/src/inbound/kafka_consumer.rsnew file mode 100644index 0000000000..9d99295319--- /dev/null+++ b/services/search_processing_service/src/inbound/kafka_consumer.rs@@ -0,0 +1,429 @@+//! Kafka consumer for broker events that update the search index.+//!+//! The poll loop hands decoded events to one bounded, sequential worker and+//! commits each offset immediately after that handoff. Malformed records are+//! committed without a handoff so they cannot wedge a partition. Processing is+//! retried in-process; exhausted events are logged and dropped because their+//! offsets are already committed.++#[cfg(test)]+mod test;++use std::{future::Future, time::Duration};++use call::domain::events::{CallMacroEvent, CallTopicEvent};+use kafka_util::{GroupName, KafkaEventConsumer};+use macro_event_broker::{+ KafkaConsumerAdapter, MacroEvent as _, MacroEventCollection as _, MacroEventConsumerService,+};+use opensearch_client::OpensearchClient;+use rdkafka::{+ consumer::CommitMode,+ message::{BorrowedMessage, Message as _},+};+use rootcause::prelude::{Report, ResultExt as _};+use sqlx::PgPool;+use tokio::sync::mpsc;+use tokio_retry::{Retry, strategy::ExponentialBackoff};+use uuid::Uuid;++use crate::process::call::{process_call_record, process_remove_call_record};++/// Consumer group used for live search-index event offsets.+pub(crate) struct SearchProcessingConsumerGroup;++impl GroupName for SearchProcessingConsumerGroup {+ const GROUP_NAME: &'static str = "search-processing-service";+}++type SearchProcessingKafkaAdapter =+ KafkaConsumerAdapter<SearchProcessingConsumerGroup, SearchProcessingBrokerEvent>;+type SearchProcessingKafkaConsumer =+ MacroEventConsumerService<SearchProcessingBrokerEvent, SearchProcessingKafkaAdapter>;++macro_event_broker::declare_topics!(SearchProcessingBrokerEvent: CallMacroEvent);++/// Maximum number of decoded events waiting for the sequential worker.+const CHANNEL_CAPACITY: usize = 128;+/// Delay before polling Kafka again after a receive error.+const RECEIVE_ERROR_RETRY_DELAY: Duration = Duration::from_secs(1);+/// Total processing attempts before an event is dropped.+const MAX_PROCESSING_ATTEMPTS: u32 = 5;+/// Delay before the first retry; each later delay doubles.+const PROCESSING_RETRY_BASE_DELAY: Duration = Duration::from_secs(1);++/// A decoded search-processing event and its Kafka coordinates.+struct ReceivedEvent {+ event: SearchProcessingBrokerEvent,+ partition: i32,+ offset: i64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CallIndexAction {+ Upsert { call_id: Uuid },+ Remove { call_id: Uuid, channel_id: Uuid },+ Ignore,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+struct CallEventDescription {+ action: CallIndexAction,+ call_id: Uuid,+ event_type: &'static str,+}++/// Outcome after the worker handles one decoded broker event.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum EventOutcome {+ /// The corresponding search-index operation succeeded.+ Indexed,+ /// The recognized event does not require a search-index operation.+ Ignored,+ /// Processing failed after all retries and the already-committed event was dropped.+ Dropped,+}++/// Result of decoding and attempting a channel handoff.+///+/// Both successful handoffs and malformed records are safe to commit. A closed+/// worker channel must leave the current record uncommitted so supervision can+/// restart the consumer and redeliver it.+#[derive(Debug)]+enum HandoffOutcome<E> {+ HandedOff,+ MalformedRecord(E),+ WorkerClosed,+}++fn describe_call_event(event: &CallTopicEvent) -> CallEventDescription {+ match event {+ CallTopicEvent::Started(metadata) => CallEventDescription {+ action: CallIndexAction::Ignore,+ call_id: metadata.call_id,+ event_type: "call.started",+ },+ CallTopicEvent::RecordArchived(metadata) => CallEventDescription {+ action: CallIndexAction::Upsert {+ call_id: metadata.call_id,+ },+ call_id: metadata.call_id,+ event_type: "call.record_archived",+ },+ CallTopicEvent::RecordUpdated(metadata) => CallEventDescription {+ action: CallIndexAction::Upsert {+ call_id: metadata.call_id,+ },+ call_id: metadata.call_id,+ event_type: "call.record_updated",+ },+ CallTopicEvent::RecordDeleted(metadata) => CallEventDescription {+ action: CallIndexAction::Remove {+ call_id: metadata.call_id,+ channel_id: metadata.channel_id,+ },+ call_id: metadata.call_id,+ event_type: "call.record_deleted",+ },+ CallTopicEvent::RecordSummarized(metadata) => CallEventDescription {+ action: CallIndexAction::Upsert {+ call_id: metadata.call_id,+ },+ call_id: metadata.call_id,+ event_type: "call.record_summarized",+ },+ CallTopicEvent::RecordingReady(metadata) => CallEventDescription {+ action: CallIndexAction::Ignore,+ call_id: metadata.call_id,+ event_type: "call.recording_ready",+ },+ }+}++fn processing_retry_strategy() -> impl Iterator<Item = Duration> {+ ExponentialBackoff::from_millis(2)+ .factor(500)+ .take((MAX_PROCESSING_ATTEMPTS - 1) as usize)+}++async fn retry_processing_with_strategy<I, F, Fut, E>(+ strategy: I,+ mut operation: F,+) -> Result<(), E>+where+ I: Iterator<Item = Duration>,+ F: FnMut(u32) -> Fut,+ Fut: Future<Output = Result<(), E>>,+{+ let mut attempt = 0;+ Retry::start(strategy, || {+ attempt += 1;+ operation(attempt)+ })+ .await+}++async fn retry_processing<F, Fut, E>(operation: F) -> Result<(), E>+where+ F: FnMut(u32) -> Fut,+ Fut: Future<Output = Result<(), E>>,+{+ retry_processing_with_strategy(processing_retry_strategy(), operation).await+}++async fn handoff_decoded<T, E>(+ sender: &mpsc::Sender<T>,+ decoded: Result<T, E>,+) -> HandoffOutcome<E> {+ let event = match decoded {+ Ok(event) => event,+ Err(error) => return HandoffOutcome::MalformedRecord(error),+ };++ match sender.send(event).await {+ Ok(()) => HandoffOutcome::HandedOff,+ Err(_) => HandoffOutcome::WorkerClosed,+ }+}++fn attach_event_coordinates<E>(+ decoded: Result<SearchProcessingBrokerEvent, E>,+ partition: i32,+ offset: i64,+) -> Result<ReceivedEvent, E> {+ decoded.map(|event| ReceivedEvent {+ event,+ partition,+ offset,+ })+}++async fn process_call_index_action(+ db: &PgPool,+ opensearch_client: &OpensearchClient,+ action: CallIndexAction,+) -> anyhow::Result<()> {+ match action {+ CallIndexAction::Upsert { call_id } => {+ process_call_record(opensearch_client, db, call_id, None).await+ }+ CallIndexAction::Remove {+ call_id,+ channel_id,+ } => process_remove_call_record(opensearch_client, channel_id, Some(call_id), None).await,+ CallIndexAction::Ignore => Ok(()),+ }+}++async fn process_call_event(+ db: &PgPool,+ opensearch_client: &OpensearchClient,+ event: &CallMacroEvent,+ partition: i32,+ offset: i64,+) -> EventOutcome {+ let description = describe_call_event(&event.event().event);+ if description.action == CallIndexAction::Ignore {+ tracing::trace!(+ call_id = %description.call_id,+ event_type = description.event_type,+ partition,+ offset,+ "ignoring call event without a search-index action"+ );+ return EventOutcome::Ignored;+ }++ let result = retry_processing(|attempt| async move {+ tracing::trace!(+ call_id = %description.call_id,+ event_type = description.event_type,+ partition,+ offset,+ attempt,+ "processing call search-index event"+ );+ process_call_index_action(db, opensearch_client, description.action)+ .await+ .inspect_err(|error| {+ if attempt < MAX_PROCESSING_ATTEMPTS {+ let retry_delay =+ PROCESSING_RETRY_BASE_DELAY * 2u32.pow(attempt.saturating_sub(1));+ tracing::warn!(+ error = ?error,+ call_id = %description.call_id,+ event_type = description.event_type,+ partition,+ offset,+ attempt,+ delay_secs = retry_delay.as_secs(),+ "call search-index processing failed, retrying"+ );+ }+ })+ })+ .await;++ match result {+ Ok(()) => EventOutcome::Indexed,+ Err(error) => {+ tracing::error!(+ error = ?error,+ call_id = %description.call_id,+ event_type = description.event_type,+ partition,+ offset,+ attempts = MAX_PROCESSING_ATTEMPTS,+ "dropping call event after processing retries were exhausted"+ );+ EventOutcome::Dropped+ }+ }+}++#[tracing::instrument(skip(db, opensearch_client, event), fields(partition, offset))]+async fn process_event(+ db: &PgPool,+ opensearch_client: &OpensearchClient,+ event: &SearchProcessingBrokerEvent,+ partition: i32,+ offset: i64,+) -> EventOutcome {+ match event {+ SearchProcessingBrokerEvent::CallMacroEvent(event) => {+ process_call_event(db, opensearch_client, event, partition, offset).await+ }+ }+}++async fn run_event_worker(+ db: PgPool,+ opensearch_client: OpensearchClient,+ mut events: mpsc::Receiver<ReceivedEvent>,+) {+ while let Some(received) = events.recv().await {+ let _ = process_event(+ &db,+ &opensearch_client,+ &received.event,+ received.partition,+ received.offset,+ )+ .await;+ }+ tracing::trace!("search processing event worker drained");+}++fn commit_logged(consumer: &SearchProcessingKafkaConsumer, message: &BorrowedMessage<'_>) {+ match consumer.inner().commit_message(message, CommitMode::Async) {+ Ok(()) => tracing::trace!(+ topic = rdkafka::Message::topic(message),+ partition = message.partition(),+ offset = message.offset(),+ "committed search processing event offset"+ ),+ Err(error) => tracing::error!(+ error = ?error,+ topic = rdkafka::Message::topic(message),+ partition = message.partition(),+ offset = message.offset(),+ "failed to commit search processing event offset"+ ),+ }+}++async fn poll_events(+ consumer: &SearchProcessingKafkaConsumer,+ events: mpsc::Sender<ReceivedEvent>,+ shutdown: impl Future<Output = ()> + Send,+) -> Result<(), Report> {+ let mut shutdown = std::pin::pin!(shutdown);+ loop {+ tokio::select! {+ _ = &mut shutdown => {+ tracing::info!("search processing event consumer shutting down");+ break;+ }+ result = consumer.recv() => {+ let message = match result {+ Ok(message) => message,+ Err(_) => { // error is logged in tracing automatically+ tokio::time::sleep(RECEIVE_ERROR_RETRY_DELAY).await;+ continue;+ }+ };+ let kafka_message = message.inner();+ let decoded = attach_event_coordinates(+ message.decode_payload(),+ kafka_message.partition(),+ kafka_message.offset(),+ );++ match handoff_decoded(&events, decoded).await {+ HandoffOutcome::HandedOff => {}+ HandoffOutcome::MalformedRecord(error) => tracing::error!(+ error = ?error,+ topic = rdkafka::Message::topic(kafka_message),+ partition = kafka_message.partition(),+ offset = kafka_message.offset(),+ "dropping undecodable search processing event"+ ),+ HandoffOutcome::WorkerClosed => {+ tracing::error!(+ topic = rdkafka::Message::topic(kafka_message),+ partition = kafka_message.partition(),+ offset = kafka_message.offset(),+ "search processing event worker channel closed; leaving offset uncommitted"+ );+ return Err(rootcause::report!(+ "search processing event worker channel closed for topic {} at partition {} offset {}",+ rdkafka::Message::topic(kafka_message),+ kafka_message.partition(),+ kafka_message.offset(),+ ));+ }+ }++ // Deliberately commit immediately after a successful handoff. The worker+ // owns retries and drops exhausted events without requesting redelivery.+ commit_logged(consumer, kafka_message);+ }+ }+ }++ Ok(())+}++/// Runs the bounded broker event poll-loop/worker pair until `shutdown` resolves.+///+/// The caller is responsible for supervising this function. A closed worker+/// channel returns an error without committing the current Kafka message. On+/// normal shutdown the sender is dropped and all buffered events are processed+/// before this function returns.+#[tracing::instrument(skip(db, opensearch_client, shutdown), fields(brokers), err)]+pub(crate) async fn run_event_consumer(+ brokers: &str,+ db: PgPool,+ opensearch_client: OpensearchClient,+ shutdown: impl Future<Output = ()> + Send,+) -> Result<(), Report> {+ let consumer = KafkaEventConsumer::<SearchProcessingConsumerGroup>::from_env(brokers)?;+ let consumer = KafkaConsumerAdapter::<SearchProcessingConsumerGroup, ()>::new(consumer)+ .subscribe::<SearchProcessingBrokerEvent>()+ .context("failed to subscribe to search processing event topics")?;+ let consumer = SearchProcessingKafkaConsumer::new(consumer);+ tracing::info!(+ topics = ?SearchProcessingBrokerEvent::topics(),+ group = SearchProcessingConsumerGroup::GROUP_NAME,+ "search processing event consumer listening"+ );++ let (events_tx, events_rx) = mpsc::channel(CHANNEL_CAPACITY);+ let worker = tokio::spawn(run_event_worker(db, opensearch_client, events_rx));+ let poll_result = poll_events(&consumer, events_tx, shutdown).await;+ let worker_result = worker.await;++ poll_result?;+ worker_result.map_err(|error| rootcause::report!(error))?;+ Ok(())+}diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsnew file mode 100644index 0000000000..ebad2884ba--- /dev/null+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -0,0 +1,328 @@+use std::sync::Arc;+use std::sync::atomic::{AtomicU32, Ordering};++use call::domain::events::{+ CallArchiveReason, CallRecordArchivedMetadata, CallRecordDeletedMetadata,+ CallRecordSummarizedMetadata, CallRecordUpdatedMetadata, CallRecordingReadyMetadata,+ CallStartedMetadata,+};+use chrono::Utc;+use macro_event_broker::{Event, EventBrokerError, MacroEvent as _, MessageParts};+use macro_event_topics::{MacroCallsTopic, Topic as _};+use macro_user_id::user_id::MacroUserIdStr;++use super::*;++const CALL_ID: Uuid = Uuid::from_u128(1);+const CHANNEL_ID: Uuid = Uuid::from_u128(2);++struct TestMessage {+ key: Option<String>,+ payload: Option<Vec<u8>>,+}++impl MessageParts for TestMessage {+ fn key(&self) -> Option<&str> {+ self.key.as_deref()+ }++ fn payload(&self) -> Option<&[u8]> {+ self.payload.as_deref()+ }++ fn topic(&self) -> &str {+ MacroCallsTopic::TOPIC_STR+ }+}++fn user_id() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).expect("valid user id")+}++fn started_event() -> CallTopicEvent {+ CallTopicEvent::Started(CallStartedMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ created_by: user_id(),+ created_at: Utc::now(),+ recording_enabled: true,+ })+}++fn archived_event() -> CallTopicEvent {+ CallTopicEvent::RecordArchived(CallRecordArchivedMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ created_by: user_id(),+ started_at: Utc::now(),+ ended_at: Utc::now(),+ duration_ms: Some(1_000),+ participant_count: 2,+ has_recording: true,+ archive_reason: CallArchiveReason::LastParticipantLeft,+ })+}++fn updated_event() -> CallTopicEvent {+ CallTopicEvent::RecordUpdated(CallRecordUpdatedMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ actor_user_id: Some(user_id()),+ custom_name: Some("Renamed call".to_string()),+ share_with_team: None,+ })+}++fn deleted_event() -> CallTopicEvent {+ CallTopicEvent::RecordDeleted(CallRecordDeletedMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ actor_user_id: Some(user_id()),+ })+}++fn summarized_event() -> CallTopicEvent {+ CallTopicEvent::RecordSummarized(CallRecordSummarizedMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ ai_name_generated: true,+ })+}++fn recording_ready_event() -> CallTopicEvent {+ CallTopicEvent::RecordingReady(CallRecordingReadyMetadata {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ })+}++fn encoded_message(event: Event<CallTopicEvent>) -> TestMessage {+ TestMessage {+ key: Some(CALL_ID.to_string()),+ payload: Some(serde_json::to_vec(&event).expect("serializable call event")),+ }+}++#[test]+fn subscribes_to_declared_search_processing_topics_with_durable_group() {+ assert_eq!(+ SearchProcessingConsumerGroup::GROUP_NAME,+ "search-processing-service"+ );+ assert_eq!(+ SearchProcessingBrokerEvent::topics(),+ [MacroCallsTopic::TOPIC_STR]+ );+}++#[test]+fn maps_all_call_lifecycle_events_to_index_actions() {+ assert_eq!(+ describe_call_event(&started_event()),+ CallEventDescription {+ action: CallIndexAction::Ignore,+ call_id: CALL_ID,+ event_type: "call.started",+ }+ );+ assert_eq!(+ describe_call_event(&archived_event()),+ CallEventDescription {+ action: CallIndexAction::Upsert { call_id: CALL_ID },+ call_id: CALL_ID,+ event_type: "call.record_archived",+ }+ );+ assert_eq!(+ describe_call_event(&updated_event()),+ CallEventDescription {+ action: CallIndexAction::Upsert { call_id: CALL_ID },+ call_id: CALL_ID,+ event_type: "call.record_updated",+ }+ );+ assert_eq!(+ describe_call_event(&deleted_event()),+ CallEventDescription {+ action: CallIndexAction::Remove {+ call_id: CALL_ID,+ channel_id: CHANNEL_ID,+ },+ call_id: CALL_ID,+ event_type: "call.record_deleted",+ }+ );+ assert_eq!(+ describe_call_event(&summarized_event()),+ CallEventDescription {+ action: CallIndexAction::Upsert { call_id: CALL_ID },+ call_id: CALL_ID,+ event_type: "call.record_summarized",+ }+ );+ assert_eq!(+ describe_call_event(&recording_ready_event()),+ CallEventDescription {+ action: CallIndexAction::Ignore,+ call_id: CALL_ID,+ event_type: "call.recording_ready",+ }+ );+}++#[tokio::test]+async fn malformed_missing_key_and_unsupported_schema_messages_are_commit_safe() {+ let malformed = TestMessage {+ key: Some(CALL_ID.to_string()),+ payload: Some(b"not json".to_vec()),+ };+ let malformed =+ attach_event_coordinates(SearchProcessingBrokerEvent::decode(&malformed), 1, 10);+ assert!(matches!(malformed, Err(EventBrokerError::Serialization(_))));++ let missing_key = TestMessage {+ key: None,+ payload: encoded_message(Event::new(archived_event())).payload,+ };+ let missing_key =+ attach_event_coordinates(SearchProcessingBrokerEvent::decode(&missing_key), 1, 11);+ assert!(matches!(+ missing_key,+ Err(EventBrokerError::MissingMessageKey)+ ));++ let unsupported = encoded_message(Event::with_schema_version(archived_event(), 2));+ let unsupported =+ attach_event_coordinates(SearchProcessingBrokerEvent::decode(&unsupported), 1, 12);+ assert!(matches!(+ unsupported,+ Err(EventBrokerError::UnsupportedSchemaVersion {+ expected: 1,+ actual: 2,+ ..+ })+ ));++ let (sender, mut receiver) = mpsc::channel(1);+ for decoded in [malformed, missing_key, unsupported] {+ assert!(matches!(+ handoff_decoded(&sender, decoded).await,+ HandoffOutcome::MalformedRecord(_)+ ));+ }+ assert!(matches!(+ receiver.try_recv(),+ Err(mpsc::error::TryRecvError::Empty)+ ));+}++#[tokio::test]+async fn successful_handoff_carries_event_partition_and_offset() {+ let event = archived_event();+ let message = encoded_message(Event::new(event.clone()));+ let decoded = attach_event_coordinates(SearchProcessingBrokerEvent::decode(&message), 3, 42);+ let (sender, mut receiver) = mpsc::channel(1);++ assert!(matches!(+ handoff_decoded(&sender, decoded).await,+ HandoffOutcome::HandedOff+ ));++ let received = receiver.recv().await.expect("handed-off event");+ assert_eq!(received.partition, 3);+ assert_eq!(received.offset, 42);+ let SearchProcessingBrokerEvent::CallMacroEvent(received_event) = received.event;+ assert_eq!(received_event.event().event, event);+}++#[tokio::test]+async fn closed_worker_channel_leaves_the_current_message_uncommitted() {+ let message = encoded_message(Event::new(archived_event()));+ let decoded = attach_event_coordinates(SearchProcessingBrokerEvent::decode(&message), 3, 42);+ let (sender, receiver) = mpsc::channel(1);+ drop(receiver);++ assert!(matches!(+ handoff_decoded(&sender, decoded).await,+ HandoffOutcome::WorkerClosed+ ));+}++#[tokio::test]+async fn bounded_handoff_blocks_when_full_and_preserves_order() {+ let (sender, mut receiver) = mpsc::channel(1);+ assert!(matches!(+ handoff_decoded(&sender, Ok::<_, ()>(1)).await,+ HandoffOutcome::HandedOff+ ));++ let blocked_handoff =+ tokio::spawn(async move { handoff_decoded(&sender, Ok::<_, ()>(2)).await });+ tokio::task::yield_now().await;+ assert!(+ !blocked_handoff.is_finished(),+ "handoff must wait while the bounded channel is full"+ );++ assert_eq!(receiver.recv().await, Some(1));+ assert!(matches!(+ blocked_handoff.await.expect("handoff task did not panic"),+ HandoffOutcome::HandedOff+ ));+ assert_eq!(receiver.recv().await, Some(2));+}++#[test]+fn production_channel_and_retry_bounds_match_the_delivery_contract() {+ let (sender, _receiver) = mpsc::channel::<ReceivedEvent>(CHANNEL_CAPACITY);+ assert_eq!(sender.max_capacity(), 128);+ assert_eq!(+ processing_retry_strategy().collect::<Vec<_>>(),+ [+ Duration::from_secs(1),+ Duration::from_secs(2),+ Duration::from_secs(4),+ Duration::from_secs(8),+ ]+ );+}++#[tokio::test]+async fn processing_retries_until_success() {+ let attempts = Arc::new(AtomicU32::new(0));+ let operation_attempts = Arc::clone(&attempts);++ retry_processing_with_strategy(std::iter::repeat_n(Duration::ZERO, 4), move |_| {+ let operation_attempts = Arc::clone(&operation_attempts);+ async move {+ let attempt = operation_attempts.fetch_add(1, Ordering::SeqCst) + 1;+ if attempt <= 2 {+ Err("temporary processing failure")+ } else {+ Ok(())+ }+ }+ })+ .await+ .expect("third processing attempt succeeds");++ assert_eq!(attempts.load(Ordering::SeqCst), 3);+}++#[tokio::test]+async fn processing_is_dropped_after_exactly_five_failed_attempts() {+ let attempts = Arc::new(AtomicU32::new(0));+ let operation_attempts = Arc::clone(&attempts);++ retry_processing_with_strategy(std::iter::repeat_n(Duration::ZERO, 4), move |_| {+ let operation_attempts = Arc::clone(&operation_attempts);+ async move {+ operation_attempts.fetch_add(1, Ordering::SeqCst);+ Err::<(), _>("persistent processing failure")+ }+ })+ .await+ .expect_err("persistent processing failure is dropped by the worker");++ assert_eq!(attempts.load(Ordering::SeqCst), MAX_PROCESSING_ATTEMPTS);+}diff --git a/services/search_processing_service/src/inbound/mod.rs b/services/search_processing_service/src/inbound/mod.rsnew file mode 100644index 0000000000..952fa6aa96--- /dev/null+++ b/services/search_processing_service/src/inbound/mod.rs@@ -0,0 +1 @@+pub(crate) mod kafka_consumer;diff --git a/services/search_processing_service/src/main.rs b/services/search_processing_service/src/main.rsindex 66d4c5b1e2..ccd8fbf563 100644--- a/services/search_processing_service/src/main.rs+++ b/services/search_processing_service/src/main.rs@@ -1,6 +1,10 @@#![recursion_limit = "256"]use std::sync::Arc;+#[cfg(feature = "processing")]+use std::time::Duration;+#[cfg(feature = "processing")]+use crate::inbound::kafka_consumer::run_event_consumer;use crate::{api::context::{ApiContext, AuthorizationService},config::DatabaseUrlReadonly,@@ -18,10 +22,16 @@ use opensearch_client::OpensearchClient;use rust_embed::RustEmbed;use sqlx::PgPool;use sqlx::postgres::PgPoolOptions;+#[cfg(feature = "processing")]+use tokio_retry::{Retry, strategy::FixedInterval};+use tokio_util::sync::CancellationToken;mod api;mod config;mod domain;+#[cfg(feature = "processing")]+#[allow(dead_code)] // Wired into service startup with the Kafka configuration.+mod inbound;mod outbound;mod parsers;mod process;@@ -62,6 +72,71 @@ async fn resolve_readonly_pool(read_only_db_url: DatabaseUrlReadonly) -> Option<#[folder = "pdfium-lib/linux/"]struct PdfiumLib;+#[cfg(feature = "processing")]+const CONSUMER_RESTART_DELAY: Duration = Duration::from_secs(5);++#[cfg(feature = "processing")]+async fn supervise_event_consumer(+ brokers: String,+ db: PgPool,+ opensearch_client: OpensearchClient,+ shutdown_token: CancellationToken,+) {+ let _ = Retry::start(FixedInterval::new(CONSUMER_RESTART_DELAY), || {+ let consumer_brokers = brokers.clone();+ let consumer_db = db.clone();+ let consumer_opensearch_client = opensearch_client.clone();+ let consumer_shutdown_token = shutdown_token.clone();++ async move {+ if consumer_shutdown_token.is_cancelled() {+ return Ok(());+ }++ let task_shutdown_token = consumer_shutdown_token.clone();+ let consumer_result = tokio::spawn(async move {+ run_event_consumer(+ &consumer_brokers,+ consumer_db,+ consumer_opensearch_client,+ task_shutdown_token.cancelled_owned(),+ )+ .await+ })+ .await;++ if consumer_shutdown_token.is_cancelled() {+ tracing::info!("search processing event consumer stopped after shutdown");+ return Ok(());+ }++ match consumer_result {+ Ok(Ok(())) => {+ tracing::error!("search processing event consumer exited unexpectedly");+ }+ Ok(Err(error)) => {+ tracing::error!(error = ?error, "search processing event consumer failed");+ }+ Err(error) if error.is_panic() => {+ tracing::error!(error = ?error, "search processing event consumer panicked");+ }+ Err(error) => {+ tracing::error!(error = ?error, "search processing event consumer task was cancelled");+ }+ }++ tracing::warn!(+ restart_delay_seconds = CONSUMER_RESTART_DELAY.as_secs(),+ "search processing event consumer stopped; waiting before restart"+ );+ Err(())+ }+ })+ .await;++ tracing::info!("search processing event consumer supervisor stopped");+}+#[tokio::main]async fn main() -> anyhow::Result<()> {MacroEntrypoint::default().init();@@ -139,8 +214,10 @@ async fn main() -> anyhow::Result<()> {SqsSearchEventPublisher::new(sqs_client.clone()),));+ let shutdown_token = CancellationToken::new();+#[cfg(feature = "processing")]- {+ let consumer_supervisor = {use std::sync::Arc;// Ensures that pdfium binary exists so we can kill the container early on failure@@ -171,7 +248,14 @@ async fn main() -> anyhow::Result<()> {lexical_client: Arc::new(lexical_client),};run_search_processing_workers(ctx, config.worker_count);- }++ tokio::spawn(supervise_event_consumer(+ config.kafka_brokers.as_ref().to_owned(),+ db.clone(),+ opensearch_client.clone(),+ shutdown_token.clone(),+ ))+ };let dynamodb_client = aws_sdk_dynamodb::Client::new(&aws_config);let backfill_jobs = BackfillJobs::new(@@ -186,15 +270,25 @@ async fn main() -> anyhow::Result<()> {.context("failed to ensure backfill jobs table exists")?;}- api::setup_and_serve(ApiContext {- db,- authorization_state,- sqs_client,- opensearch_client: Arc::new(opensearch_client),- config: Arc::new(config),- backfill_service,- backfill_jobs,- })- .await?;- Ok(())+ let api_result = api::setup_and_serve(+ ApiContext {+ db,+ authorization_state,+ sqs_client,+ opensearch_client: Arc::new(opensearch_client),+ config: Arc::new(config),+ backfill_service,+ backfill_jobs,+ },+ shutdown_token.clone(),+ )+ .await;++ shutdown_token.cancel();+ #[cfg(feature = "processing")]+ consumer_supervisor+ .await+ .context("search processing event consumer supervisor failed")?;++ api_result}diff --git a/services/search_processing_service/src/process/call.rs b/services/search_processing_service/src/process/call.rsindex 0929b82f02..3e87664257 100644--- a/services/search_processing_service/src/process/call.rs+++ b/services/search_processing_service/src/process/call.rs@@ -5,7 +5,6 @@ use opensearch_client::{};use properties::outbound::entity_properties_get_query::get_entity_properties_for_index;use sqlx::PgPool;-use sqs_client::search::call::{CallRecordMessage, RemoveCallRecord};use uuid::Uuid;use crate::process::properties::to_indexed_properties;@@ -14,13 +13,9 @@ use crate::process::properties::to_indexed_properties;pub async fn process_call_record(opensearch_client: &OpensearchClient,db: &PgPool,- message: &CallRecordMessage,+ call_id: Uuid,+ index_override: Option<&str>,) -> anyhow::Result<()> {- let call_id: Uuid = message- .call_id- .parse()- .context("failed to parse call_id as UUID")?;-let Some(payload) =macro_db_client::call_record::get::get_call_record_search_payload(db, &call_id).await?else {@@ -78,7 +73,7 @@ pub async fn process_call_record(.collect::<Result<Vec<_>, _>>()?;let result = opensearch_client- .bulk_upsert_call_record_segments(&segments, message.index_override.as_deref())+ .bulk_upsert_call_record_segments(&segments, index_override).await.context("failed to bulk upsert call record segments")?;@@ -97,16 +92,19 @@ pub async fn process_call_record(#[tracing::instrument(skip(opensearch_client), err)]pub async fn process_remove_call_record(opensearch_client: &OpensearchClient,- message: &RemoveCallRecord,+ channel_id: Uuid,+ call_id: Option<Uuid>,+ index_override: Option<&str>,) -> anyhow::Result<()> {- let index_override = message.index_override.as_deref();- if let Some(call_id) = &message.call_id {+ if let Some(call_id) = call_id {+ let call_id = call_id.to_string();opensearch_client- .delete_call_record(call_id, index_override)+ .delete_call_record(&call_id, index_override).await?;} else {+ let channel_id = channel_id.to_string();opensearch_client- .delete_call_records_by_channel(&message.channel_id, index_override)+ .delete_call_records_by_channel(&channel_id, index_override).await?;}Ok(())diff --git a/services/search_processing_service/src/process/mod.rs b/services/search_processing_service/src/process/mod.rsindex 02c99023c0..954539ecbe 100644--- a/services/search_processing_service/src/process/mod.rs+++ b/services/search_processing_service/src/process/mod.rs@@ -1,4 +1,4 @@-mod call;+pub(crate) mod call;mod channel;mod chat;pub mod context;@@ -11,6 +11,7 @@ pub mod worker;use anyhow::Context;use sqs_client::search::SearchQueueMessage;+use uuid::Uuid;use crate::process::context::SearchProcessingContext;@@ -107,10 +108,36 @@ pub async fn process_message(chat::remove_chat_message(&ctx.opensearch_client, &message).await?;}SearchQueueMessage::CallRecord(message) => {- call::process_call_record(&ctx.opensearch_client, &ctx.db, &message).await?;+ let call_id = message+ .call_id+ .parse::<Uuid>()+ .context("failed to parse call_id as UUID")?;+ call::process_call_record(+ &ctx.opensearch_client,+ &ctx.db,+ call_id,+ message.index_override.as_deref(),+ )+ .await?;}SearchQueueMessage::RemoveCallRecord(message) => {- call::process_remove_call_record(&ctx.opensearch_client, &message).await?;+ let channel_id = message+ .channel_id+ .parse::<Uuid>()+ .context("failed to parse channel_id as UUID")?;+ let call_id = message+ .call_id+ .as_deref()+ .map(Uuid::parse_str)+ .transpose()+ .context("failed to parse call_id as UUID")?;+ call::process_remove_call_record(+ &ctx.opensearch_client,+ channel_id,+ call_id,+ message.index_override.as_deref(),+ )+ .await?;}SearchQueueMessage::UpsertProject(message) => {project::upsert_project(&ctx.opensearch_client, &ctx.db, &message).await?;