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
fix(call): call transcription voice (#3179)
Will Hutchinson2e6fd1979c06
diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.pyindex a30ae21ea4..6a9d9bf2e1 100644--- a/agents/transcription/transcriber.py+++ b/agents/transcription/transcriber.py@@ -3,6 +3,7 @@ import asyncioimport loggingimport osimport uuid+import warningsfrom collections import Counter, dequefrom datetime import datetime, timedelta, timezone@@ -26,6 +27,16 @@ from livekit.agents import (WorkerOptions,)from livekit.plugins import silero++# `resemblyzer` imports `webrtcvad`, which currently emits a noisy setuptools+# `pkg_resources` deprecation warning once per worker process. It is not+# actionable for the agent, so keep production logs focused on runtime issues.+warnings.filterwarnings(+ "ignore",+ message=r"pkg_resources is deprecated as an API.*",+ category=UserWarning,+ module=r"webrtcvad",+)from resemblyzer import VoiceEncoder, preprocess_wavload_dotenv()@@ -471,4 +482,15 @@ def prewarm(proc: JobProcess):if __name__ == "__main__":- cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, prewarm_fnc=prewarm, agent_name="macro-transcriber"))+ cli.run_app(+ WorkerOptions(+ entrypoint_fnc=entrypoint,+ prewarm_fnc=prewarm,+ agent_name="macro-transcriber",+ # Each prewarmed process loads Silero + Resemblyzer and is expected+ # to sit around ~3 GiB RSS. Keep fewer warm processes and raise the+ # warning threshold so healthy workers do not spam logs every 5s.+ num_idle_processes=1,+ job_memory_warn_mb=4096,+ )+ )diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex 4615a61a44..bb912f7182 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -168,6 +168,17 @@ pub trait CallRepository: Send + Sync + 'static {voice_id: Option<Uuid>,) -> impl Future<Output = Result<(), Self::Err>> + Send;+ /// Return a voice id already attached to this speaker in the active call,+ /// if one exists. Prefer `diarized_speaker_id` when present because a+ /// single participant track can contain multiple diarized voices; otherwise+ /// fall back to the LiveKit speaker/participant id.+ fn get_transcript_voice_id_for_speaker<'a>(+ &self,+ call_id: &Uuid,+ speaker_id: &'a str,+ diarized_speaker_id: Option<&'a str>,+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;+/// Get the profile picture URL for a user by their `MacroUserIdStr`.fn get_user_profile_picture<'a>(&self,@@ -606,9 +617,11 @@ pub trait VoiceRepository: Send + Sync + 'static {/// The error type returned by repository operations.type Err: Into<anyhow::Error> + Send + Debug;- /// Insert a new `voice` row with the supplied embedding and return its id.- /// Does not attempt to deduplicate — callers that want similarity-based- /// dedup should first try [`Self::find_nearest_user`] or query directly.+ /// Return the id for the supplied voice embedding.+ ///+ /// Implementations may reuse an existing nearby embedding instead of+ /// inserting a new row, so repeated transcript segments from the same+ /// speaker resolve to the same `voice.id`.fn upsert_voice(&self,embedding: &[f32],diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 75b7f3b0a7..ca737c4a72 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -1018,17 +1018,40 @@ impl<.map_err(|e| CallError::Internal(e.into()))?.ok_or_else(|| CallError::NotFound(channel_id.to_string()))?;- // Upsert the speaker embedding (if the agent sent one) so we can- // store the resulting voice id on the transcript row. Failure to- // persist the embedding must not block transcript ingest — log and- // continue without a voice id.+ // Attach a stable voice id to each transcript row. Reuse an earlier+ // voice id for the same diarized speaker in this call before falling+ // back to embedding-based upsert; this prevents creating a fresh+ // `voice.id` for every finalized utterance from the same user.+ // Failure to persist the embedding must not block transcript ingest —+ // log and continue without a voice id.let voice_id = match segment.embedding.as_deref() {- Some(embedding) if !embedding.is_empty() => self- .voice_repo- .upsert_voice(embedding)- .await- .inspect_err(|e| tracing::error!(error=?e, "failed to upsert voice embedding"))- .ok(),+ Some(embedding) if !embedding.is_empty() => {+ let existing_voice_id = self+ .repo+ .get_transcript_voice_id_for_speaker(+ &call.id,+ &segment.speaker_id,+ segment.diarized_speaker_id.as_deref(),+ )+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, "failed to look up existing speaker voice id")+ })+ .ok()+ .flatten();++ match existing_voice_id {+ Some(voice_id) => Some(voice_id),+ None => self+ .voice_repo+ .upsert_voice(embedding)+ .await+ .inspect_err(+ |e| tracing::error!(error=?e, "failed to upsert voice embedding"),+ )+ .ok(),+ }+ }_ => None,};diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex b8ac029884..2dd95bff3e 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -837,6 +837,34 @@ impl CallRepository for PgCallRepo {Ok(())}+ #[tracing::instrument(err, skip(self))]+ async fn get_transcript_voice_id_for_speaker(+ &self,+ call_id: &Uuid,+ speaker_id: &str,+ diarized_speaker_id: Option<&str>,+ ) -> Result<Option<Uuid>, Self::Err> {+ sqlx::query_scalar::<_, Uuid>(+ r#"+ SELECT voice_id+ FROM call_transcripts+ WHERE call_id = $1+ AND voice_id IS NOT NULL+ AND (+ ($3::text IS NOT NULL AND diarized_speaker_id = $3)+ OR ($3::text IS NULL AND diarized_speaker_id IS NULL AND speaker_id = $2)+ )+ ORDER BY sequence_num ASC+ LIMIT 1+ "#,+ )+ .bind(call_id)+ .bind(speaker_id)+ .bind(diarized_speaker_id)+ .fetch_optional(&self.pool)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn get_call_record_by_call_id(&self,diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rsindex 73811f4767..7d6a2cf796 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs@@ -48,6 +48,21 @@ fn repo(pool: Pool<Postgres>) -> PgCallRepo {PgCallRepo::new(pool)}+fn axis_unit_vector(axis: usize) -> Vec<f32> {+ let mut v = vec![0.0_f32; 256];+ v[axis] = 1.0;+ v+}++async fn insert_voice(pool: &Pool<Postgres>, voice_id: Uuid, axis: usize) -> anyhow::Result<()> {+ sqlx::query("INSERT INTO voice (id, embedding) VALUES ($1, $2)")+ .bind(voice_id)+ .bind(pgvector::Vector::from(axis_unit_vector(axis)))+ .execute(pool)+ .await?;+ Ok(())+}+// -- create_call --------------------------------------------------------------#[sqlx::test(@@ -746,6 +761,106 @@ async fn create_transcript_segment_stores_and_increments_sequence(Ok(())}+#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_transcript_voice_id_for_speaker_uses_diarized_speaker_id(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let now = Utc::now();+ let voice_a = macro_uuid::generate_uuid_v7();+ let voice_b = macro_uuid::generate_uuid_v7();+ insert_voice(&pool, voice_a, 0).await?;+ insert_voice(&pool, voice_b, 1).await?;++ let seg_a = TranscriptSegmentRequest {+ segment_id: "seg-voice-a".to_string(),+ speaker_id: USER_A.to_string(),+ diarized_speaker_id: Some("spk-a0".to_string()),+ content: "first voice".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ stream_started_at: None,+ embedding: None,+ };+ let seg_b = TranscriptSegmentRequest {+ segment_id: "seg-voice-b".to_string(),+ speaker_id: USER_A.to_string(),+ diarized_speaker_id: Some("spk-a1".to_string()),+ content: "second voice".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ stream_started_at: None,+ embedding: None,+ };++ repo.create_transcript_segment(&CALL1, &seg_a, Some(voice_a))+ .await?;+ repo.create_transcript_segment(&CALL1, &seg_b, Some(voice_b))+ .await?;++ assert_eq!(+ repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("spk-a0"))+ .await?,+ Some(voice_a)+ );+ assert_eq!(+ repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("spk-a1"))+ .await?,+ Some(voice_b)+ );+ assert_eq!(+ repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), Some("missing"))+ .await?,+ None+ );+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_transcript_voice_id_for_speaker_falls_back_to_participant_id(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let now = Utc::now();+ let voice_id = macro_uuid::generate_uuid_v7();+ insert_voice(&pool, voice_id, 0).await?;++ let segment = TranscriptSegmentRequest {+ segment_id: "seg-voice-participant".to_string(),+ speaker_id: USER_A.to_string(),+ diarized_speaker_id: None,+ content: "voice without diarization".to_string(),+ started_at: now,+ ended_at: Some(now),+ is_final: true,+ stream_started_at: None,+ embedding: None,+ };++ repo.create_transcript_segment(&CALL1, &segment, Some(voice_id))+ .await?;++ assert_eq!(+ repo.get_transcript_voice_id_for_speaker(&CALL1, USER_A.as_ref(), None)+ .await?,+ Some(voice_id)+ );+ assert_eq!(+ repo.get_transcript_voice_id_for_speaker(&CALL1, USER_B.as_ref(), None)+ .await?,+ None+ );+ Ok(())+}+// -- archive_call copies transcripts ------------------------------------------#[sqlx::test(diff --git a/rust/cloud-storage/call/src/outbound/pg_voice_repo.rs b/rust/cloud-storage/call/src/outbound/pg_voice_repo.rsindex ad675934ac..522c6c26f7 100644--- a/rust/cloud-storage/call/src/outbound/pg_voice_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_voice_repo.rs@@ -9,6 +9,28 @@ use uuid::Uuid;use crate::domain::ports::VoiceRepository;+/// Cosine-distance cutoff for treating two embeddings as the same voice.+///+/// This keeps transcript ingestion from creating a fresh `voice.id` for every+/// finalized utterance from the same speaker while still allowing clearly+/// different speakers to get separate ids.+const VOICE_DEDUP_DISTANCE_THRESHOLD: f64 = 0.25;++fn embedding_advisory_lock_key(embedding: &[f32]) -> i64 {+ const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;+ const FNV_PRIME: u64 = 0x100000001b3;++ let mut hash = FNV_OFFSET_BASIS;+ for value in embedding {+ for byte in value.to_le_bytes() {+ hash ^= u64::from(byte);+ hash = hash.wrapping_mul(FNV_PRIME);+ }+ }++ hash as i64+}+/// Postgres adapter implementing [`VoiceRepository`].#[derive(Clone)]pub struct PgVoiceRepo {@@ -27,17 +49,42 @@ impl VoiceRepository for PgVoiceRepo {async fn upsert_voice(&self, embedding: &[f32]) -> Result<Uuid, Self::Err> {let id = macro_uuid::generate_uuid_v7();+ let lock_key = embedding_advisory_lock_key(embedding);let vec = Vector::from(embedding.to_vec());- let row = sqlx::query!(+ let mut tx = self.pool.begin().await?;++ sqlx::query("SELECT pg_advisory_xact_lock($1::bigint)")+ .bind(lock_key)+ .fetch_one(tx.as_mut())+ .await?;++ let voice_id = sqlx::query_scalar::<_, Uuid>(r#"- INSERT INTO voice (id, embedding) VALUES ($1, $2) RETURNING id+ WITH nearest AS (+ SELECT id+ FROM voice+ WHERE (embedding <=> $1) <= $2+ ORDER BY embedding <=> $1 ASC+ LIMIT 1+ ), inserted AS (+ INSERT INTO voice (id, embedding)+ SELECT $3, $1+ WHERE NOT EXISTS (SELECT 1 FROM nearest)+ RETURNING id+ )+ SELECT id FROM nearest+ UNION ALL+ SELECT id FROM inserted+ LIMIT 1"#,- id,- vec as Vector,)- .fetch_one(&self.pool)+ .bind(vec)+ .bind(VOICE_DEDUP_DISTANCE_THRESHOLD)+ .bind(id)+ .fetch_one(tx.as_mut()).await?;- Ok(row.id)+ tx.commit().await?;+ Ok(voice_id)}async fn link_user_voice(diff --git a/rust/cloud-storage/call/src/outbound/pg_voice_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_voice_repo/test.rsindex 8ac541092d..1cbc0c3236 100644--- a/rust/cloud-storage/call/src/outbound/pg_voice_repo/test.rs+++ b/rust/cloud-storage/call/src/outbound/pg_voice_repo/test.rs@@ -42,11 +42,30 @@ async fn upsert_voice_inserts_row(pool: Pool<Postgres>) -> anyhow::Result<()> {fixtures(path = "../../../fixtures", scripts("voice_repo")),migrator = "MACRO_DB_MIGRATIONS")]-async fn upsert_voice_returns_distinct_ids(pool: Pool<Postgres>) -> anyhow::Result<()> {- let repo = repo(pool);+async fn upsert_voice_reuses_existing_nearby_embedding(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool.clone());let v1 = repo.upsert_voice(&axis_unit_vector(0)).await?;let v2 = repo.upsert_voice(&axis_unit_vector(0)).await?;- assert_ne!(v1, v2, "each upsert generates a fresh id");+ assert_eq!(v1, v2, "same speaker embedding should reuse one voice id");++ let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM voice")+ .fetch_one(&pool)+ .await?;+ assert_eq!(count, 1);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn upsert_voice_inserts_distinct_id_for_different_embedding(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let v1 = repo.upsert_voice(&axis_unit_vector(0)).await?;+ let v2 = repo.upsert_voice(&axis_unit_vector(1)).await?;+ assert_ne!(v1, v2, "orthogonal voices should not be deduplicated");Ok(())}@@ -201,16 +220,22 @@ async fn find_nearest_user_skips_unlinked_voices(pool: Pool<Postgres>) -> anyhowasync fn find_nearest_user_for_voice_resolves_via_embedding_lookup(pool: Pool<Postgres>,) -> anyhow::Result<()> {- let repo = repo(pool);+ let repo = repo(pool.clone());// user_a is enrolled with axis-0 vector.let enrolled = repo.upsert_voice(&axis_unit_vector(0)).await?;repo.link_user_voice(&USER_A, &enrolled).await?;- // A separate voice row with the *same* embedding (the typical- // post-archive transcript case) must resolve back to user_a via- // similarity, not exact id match.- let segment_voice = repo.upsert_voice(&axis_unit_vector(0)).await?;+ // Insert a separate transcript sample directly so this exercises the+ // lookup-by-voice path even though `upsert_voice` now deduplicates nearby+ // embeddings.+ let segment_voice = macro_uuid::generate_uuid_v7();+ sqlx::query("INSERT INTO voice (id, embedding) VALUES ($1, $2)")+ .bind(segment_voice)+ .bind(pgvector::Vector::from(axis_unit_vector(0)))+ .execute(&pool)+ .await?;assert_ne!(enrolled, segment_voice);+let match_id = repo.find_nearest_user_for_voice(&segment_voice, 0.1).await?;