Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(call): auto-assign voice to macro user (#3183)

Will Hutchinson120940f38d46
diff --git a/rust/cloud-storage/.sqlx/query-1135cf21b6f164a59956cffb56b929369dc09dc71c131ba722d84082a8e98f85.json b/rust/cloud-storage/.sqlx/query-1135cf21b6f164a59956cffb56b929369dc09dc71c131ba722d84082a8e98f85.json
new file mode 100644
index 0000000000..d78d22d89c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-1135cf21b6f164a59956cffb56b929369dc09dc71c131ba722d84082a8e98f85.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH per_speaker AS (\n SELECT\n u.macro_user_id,\n COUNT(*) AS total_segments,\n COUNT(t.voice_id) AS voiced_segments,\n COUNT(DISTINCT t.voice_id) AS distinct_voice_ids,\n (array_agg(DISTINCT t.voice_id) FILTER (WHERE t.voice_id IS NOT NULL))[1] AS voice_id,\n MIN(t.sequence_num) AS first_sequence_num\n FROM call_record_transcripts t\n JOIN \"User\" u\n ON u.id = t.speaker_id\n AND u.macro_user_id IS NOT NULL\n WHERE t.call_record_id = $1\n GROUP BY t.speaker_id, u.macro_user_id\n )\n SELECT macro_user_id AS \"macro_user_id!\", voice_id AS \"voice_id!\"\n FROM per_speaker\n WHERE total_segments = voiced_segments\n AND distinct_voice_ids = 1\n ORDER BY first_sequence_num ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "macro_user_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "voice_id!",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ null
+ ]
+ },
+ "hash": "1135cf21b6f164a59956cffb56b929369dc09dc71c131ba722d84082a8e98f85"
+}
diff --git a/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.json b/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.json
deleted file mode 100644
index 6cb53cec9b..0000000000
--- a/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO voice (id, embedding) VALUES ($1, $2) RETURNING id\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- {
- "Custom": {
- "name": "vector",
- "kind": "Simple"
- }
- }
- ]
- },
- "nullable": [
- false
- ]
- },
- "hash": "c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0"
-}
diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rs
index bb912f7182..9cfa30db37 100644
--- a/rust/cloud-storage/call/src/domain/ports.rs
+++ b/rust/cloud-storage/call/src/domain/ports.rs
@@ -266,6 +266,17 @@ pub trait CallRepository: Send + Sync + 'static {
assignments: &[CustomSpeakerAssignment],
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Stable `(macro_user_id, voice_id)` pairs inferred from a finished
+ /// call's archived transcripts. A speaker is returned only when every
+ /// transcript row for that `speaker_id` has a non-NULL `voice_id` and all
+ /// of those voice ids are the same. The `speaker_id` is resolved through
+ /// the canonical `User` row to get the `macro_user.id` used by
+ /// `macro_user_voice`.
+ fn get_stable_speaker_voices_for_call_record(
+ &self,
+ call_record_id: &Uuid,
+ ) -> impl Future<Output = Result<Vec<(Uuid, Uuid)>, Self::Err>> + Send;
+
/// Distinct `(diarized_speaker_id, voice_id)` pairs from a call's
/// archived transcripts. Used by the post-archive voice matcher; rows
/// with NULL `diarized_speaker_id` or NULL `voice_id` are skipped.
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index ca737c4a72..3efec3ab28 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -681,7 +681,7 @@ impl<
// Fire-and-forget summarization now that the
// `call_records` row is persisted.
self.spawn_summarize_call(call.id);
- self.spawn_match_voices_for_call(call.id);
+ self.spawn_process_voices_for_call(call.id);
if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {
tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");
@@ -791,7 +791,7 @@ impl<
// Fire-and-forget summarization now that the
// `call_records` row is persisted.
self.spawn_summarize_call(call.id);
- self.spawn_match_voices_for_call(call.id);
+ self.spawn_process_voices_for_call(call.id);
if let Err(e) = self.search_indexer.enqueue_upsert(&call.id).await {
tracing::error!(error=?e, call_id=%call.id, "failed to enqueue call record for search indexing");
@@ -1352,15 +1352,18 @@ impl<
});
}
- /// Fire-and-forget spawn of [`match_voices_for_call_record`].
+ /// Fire-and-forget spawn of finished-call voice processing.
///
/// Called from `process_webhook_event` immediately after `archive_call`
- /// finalizes the `call_records` row so voice matching runs off the
- /// request path. Errors are logged inside the spawned task.
- fn spawn_match_voices_for_call(&self, call_record_id: Uuid) {
+ /// finalizes the `call_records` row. First, stable speaker voice ids are
+ /// enrolled for the users who spoke them; then the regular voice matcher
+ /// can use both pre-existing and newly-enrolled voices to populate speaker
+ /// overrides. Errors are logged inside the spawned task.
+ fn spawn_process_voices_for_call(&self, call_record_id: Uuid) {
let repo = self.repo.clone();
let voice_repo = self.voice_repo.clone();
tokio::spawn(async move {
+ enroll_stable_speaker_voices_for_call_record(&repo, &voice_repo, call_record_id).await;
match_voices_for_call_record(
&repo,
&voice_repo,
@@ -1372,6 +1375,53 @@ impl<
}
}
+/// Enroll stable speaker voice ids observed in a freshly archived call.
+///
+/// For each `speaker_id` in the call transcript, the repository returns a
+/// candidate only when every transcript row for that speaker has the same
+/// non-NULL `voice_id`. Those unambiguous pairs are linked to the resolved
+/// macro user in `macro_user_voice` via [`VoiceRepository::link_user_voice`].
+async fn enroll_stable_speaker_voices_for_call_record<R: CallRepository, Vr: VoiceRepository>(
+ repo: &R,
+ voice_repo: &Vr,
+ call_record_id: Uuid,
+) {
+ let stable_voices = match repo
+ .get_stable_speaker_voices_for_call_record(&call_record_id)
+ .await
+ {
+ Ok(stable_voices) => stable_voices,
+ Err(e) => {
+ tracing::error!(
+ error=?e, %call_record_id,
+ "failed to load stable speaker voices for enrollment"
+ );
+ return;
+ }
+ };
+
+ if stable_voices.is_empty() {
+ return;
+ }
+
+ let total = stable_voices.len();
+ let mut linked = 0usize;
+ for (macro_user_id, voice_id) in stable_voices {
+ match voice_repo.link_user_voice(&macro_user_id, &voice_id).await {
+ Ok(()) => linked += 1,
+ Err(e) => tracing::error!(
+ error=?e, %call_record_id, %macro_user_id, %voice_id,
+ "failed to link stable speaker voice to user"
+ ),
+ }
+ }
+
+ tracing::info!(
+ %call_record_id, linked, total,
+ "stable speaker voice enrollment completed"
+ );
+}
+
/// Match the voice ids on a freshly archived call to enrolled users and
/// populate `custom_speaker` for the matched diarized speakers.
///
diff --git a/rust/cloud-storage/call/src/domain/service/test.rs b/rust/cloud-storage/call/src/domain/service/test.rs
index cb5248a6a7..2013290f11 100644
--- a/rust/cloud-storage/call/src/domain/service/test.rs
+++ b/rust/cloud-storage/call/src/domain/service/test.rs
@@ -4,10 +4,80 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::{exclude_voip_recipients, extract_recording_key};
+#[cfg(feature = "outbound")]
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+#[cfg(feature = "outbound")]
+use uuid::Uuid;
+
fn user(email: &'static str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email(email).unwrap()
}
+#[cfg(feature = "outbound")]
+const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
+#[cfg(feature = "outbound")]
+const MACRO_USER_A: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaa1);
+#[cfg(feature = "outbound")]
+const MACRO_USER_B: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbb2);
+
+#[cfg(feature = "outbound")]
+fn axis_unit_vector(axis: usize) -> Vec<f32> {
+ let mut v = vec![0.0_f32; 256];
+ v[axis] = 1.0;
+ v
+}
+
+#[cfg(feature = "outbound")]
+async fn insert_voice(
+ pool: &sqlx::Pool<sqlx::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(())
+}
+
+#[cfg(feature = "outbound")]
+async fn insert_user_mapping(
+ pool: &sqlx::Pool<sqlx::Postgres>,
+ user_id: &MacroUserIdStr<'_>,
+ macro_user_id: Uuid,
+) -> anyhow::Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(user_id.as_ref())
+ .bind(user_id.email_str())
+ .bind(format!("cus_{macro_user_id}"))
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO "User" (id, email, "stripeCustomerId", macro_user_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO UPDATE SET macro_user_id = EXCLUDED.macro_user_id
+ "#,
+ )
+ .bind(user_id.as_ref())
+ .bind(user_id.email_str())
+ .bind(format!("cus_{macro_user_id}"))
+ .bind(macro_user_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
#[test]
fn extract_key_from_full_s3_url() {
let url = "https://macro-call-recording-prod.s3.amazonaws.com/calls/0195cea6-fc16-72f2-93b6-144df711f270/2026-04-10T210832.mp4";
@@ -52,3 +122,72 @@ fn exclude_voip_recipients_returns_empty_when_all_users_received_voip() {
assert!(filtered.is_empty());
}
+
+#[cfg(feature = "outbound")]
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn enroll_stable_speaker_voices_links_only_unambiguous_speakers(
+ pool: sqlx::Pool<sqlx::Postgres>,
+) -> anyhow::Result<()> {
+ use crate::domain::models::TranscriptSegmentRequest;
+ use crate::domain::ports::{CallRepository as _, VoiceRepository as _};
+ use crate::outbound::{pg_call_repo::PgCallRepo, pg_voice_repo::PgVoiceRepo};
+ use chrono::{Duration, Utc};
+
+ let call_repo = PgCallRepo::new(pool.clone());
+ let voice_repo = PgVoiceRepo::new(pool.clone());
+ let user_a = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let user_b = MacroUserIdStr::parse_from_str("macro|[email protected]")?;
+ let voice_a = macro_uuid::generate_uuid_v7();
+ let voice_b = macro_uuid::generate_uuid_v7();
+ let now = Utc::now();
+
+ insert_user_mapping(&pool, &user_a, MACRO_USER_A).await?;
+ insert_user_mapping(&pool, &user_b, MACRO_USER_B).await?;
+ insert_voice(&pool, voice_a, 0).await?;
+ insert_voice(&pool, voice_b, 1).await?;
+
+ let segments = [
+ ("stable-a-1", user_a.as_ref(), Some("spk-a0"), voice_a),
+ ("stable-a-2", user_a.as_ref(), Some("spk-a1"), voice_a),
+ ("ambiguous-b-1", user_b.as_ref(), Some("spk-b0"), voice_a),
+ ("ambiguous-b-2", user_b.as_ref(), Some("spk-b1"), voice_b),
+ ];
+
+ for (idx, (segment_id, speaker_id, diarized_speaker_id, voice_id)) in
+ segments.into_iter().enumerate()
+ {
+ let started_at = now + Duration::seconds(idx as i64);
+ call_repo
+ .create_transcript_segment(
+ &CALL1,
+ &TranscriptSegmentRequest {
+ segment_id: segment_id.to_string(),
+ speaker_id: speaker_id.to_string(),
+ diarized_speaker_id: diarized_speaker_id.map(str::to_string),
+ content: segment_id.to_string(),
+ started_at,
+ ended_at: Some(started_at + Duration::milliseconds(100)),
+ is_final: true,
+ stream_started_at: None,
+ embedding: None,
+ },
+ Some(voice_id),
+ )
+ .await?;
+ }
+
+ let call_record_id = call_repo.archive_call(&CALL1).await?;
+
+ super::enroll_stable_speaker_voices_for_call_record(&call_repo, &voice_repo, call_record_id)
+ .await;
+
+ assert_eq!(
+ voice_repo.get_user_voices(&MACRO_USER_A).await?,
+ vec![voice_a]
+ );
+ assert!(voice_repo.get_user_voices(&MACRO_USER_B).await?.is_empty());
+ Ok(())
+}
diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
index 2dd95bff3e..b67c7ed2f4 100644
--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
@@ -1440,6 +1440,52 @@ impl CallRepository for PgCallRepo {
Ok(())
}
+ /// Return stable `(macro_user_id, voice_id)` pairs for one archived call.
+ ///
+ /// `call_record_id` scopes the scan to a single call's archived transcript rows.
+ /// A speaker is returned only when every row for that `speaker_id` has the
+ /// same non-NULL `voice_id`; ambiguous, missing, or unresolved speakers are
+ /// skipped. The returned `macro_user_id` is the user's canonical
+ /// `macro_user.id`, suitable for linking to `voice_id` in `macro_user_voice`.
+ #[tracing::instrument(err, skip(self))]
+ async fn get_stable_speaker_voices_for_call_record(
+ &self,
+ call_record_id: &Uuid,
+ ) -> Result<Vec<(Uuid, Uuid)>, Self::Err> {
+ let rows = sqlx::query!(
+ r#"
+ WITH per_speaker AS (
+ SELECT
+ u.macro_user_id,
+ COUNT(*) AS total_segments,
+ COUNT(t.voice_id) AS voiced_segments,
+ COUNT(DISTINCT t.voice_id) AS distinct_voice_ids,
+ (array_agg(DISTINCT t.voice_id) FILTER (WHERE t.voice_id IS NOT NULL))[1] AS voice_id,
+ MIN(t.sequence_num) AS first_sequence_num
+ FROM call_record_transcripts t
+ JOIN "User" u
+ ON u.id = t.speaker_id
+ AND u.macro_user_id IS NOT NULL
+ WHERE t.call_record_id = $1
+ GROUP BY t.speaker_id, u.macro_user_id
+ )
+ SELECT macro_user_id AS "macro_user_id!", voice_id AS "voice_id!"
+ FROM per_speaker
+ WHERE total_segments = voiced_segments
+ AND distinct_voice_ids = 1
+ ORDER BY first_sequence_num ASC
+ "#,
+ call_record_id,
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| (row.macro_user_id, row.voice_id))
+ .collect())
+ }
+
#[tracing::instrument(err, skip(self))]
async fn get_distinct_voice_speakers_for_call_record(
&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.rs
index 7d6a2cf796..eec60f6068 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
@@ -37,6 +37,9 @@ const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);
const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);
const CALL2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca220);
const CALL_ARCHIVED: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca2ed);
+const MACRO_USER_A: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaa1);
+const MACRO_USER_B: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbb2);
+const MACRO_USER_C: Uuid = Uuid::from_u128(0xcccccccc_cccc_cccc_cccc_ccccccccccc3);
static USER_A: LazyLock<MacroUserIdStr<'static>> =
LazyLock::new(|| MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap());
static USER_B: LazyLock<MacroUserIdStr<'static>> =
@@ -63,6 +66,42 @@ async fn insert_voice(pool: &Pool<Postgres>, voice_id: Uuid, axis: usize) -> any
Ok(())
}
+async fn insert_user_mapping(
+ pool: &Pool<Postgres>,
+ user_id: &MacroUserIdStr<'_>,
+ macro_user_id: Uuid,
+) -> anyhow::Result<()> {
+ sqlx::query(
+ r#"
+ INSERT INTO macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO NOTHING
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(user_id.as_ref())
+ .bind(user_id.email_str())
+ .bind(format!("cus_{macro_user_id}"))
+ .execute(pool)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO "User" (id, email, "stripeCustomerId", macro_user_id)
+ VALUES ($1, $2, $3, $4)
+ ON CONFLICT (id) DO UPDATE SET macro_user_id = EXCLUDED.macro_user_id
+ "#,
+ )
+ .bind(user_id.as_ref())
+ .bind(user_id.email_str())
+ .bind(format!("cus_{macro_user_id}"))
+ .bind(macro_user_id)
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
// -- create_call --------------------------------------------------------------
#[sqlx::test(
@@ -1044,6 +1083,91 @@ async fn archive_call_rolls_up_consecutive_same_speaker_transcripts(
Ok(())
}
+// -- get_stable_speaker_voices_for_call_record -------------------------------
+
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("call_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn get_stable_speaker_voices_for_call_record_returns_only_unambiguous_speakers(
+ 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?;
+ insert_user_mapping(&pool, USER_A.deref(), MACRO_USER_A).await?;
+ insert_user_mapping(&pool, USER_B.deref(), MACRO_USER_B).await?;
+ insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;
+
+ let segments = [
+ // USER_A is stable: every transcript row has the same non-null voice id.
+ ("stable-a-1", USER_A.as_ref(), Some("spk-a0"), Some(voice_a)),
+ ("stable-a-2", USER_A.as_ref(), Some("spk-a1"), Some(voice_a)),
+ // USER_B is ambiguous: more than one distinct voice id.
+ (
+ "ambiguous-b-1",
+ USER_B.as_ref(),
+ Some("spk-b0"),
+ Some(voice_a),
+ ),
+ (
+ "ambiguous-b-2",
+ USER_B.as_ref(),
+ Some("spk-b1"),
+ Some(voice_b),
+ ),
+ // USER_C is incomplete: at least one transcript row has no voice id.
+ (
+ "missing-c-1",
+ USER_C.as_ref(),
+ Some("spk-c0"),
+ Some(voice_a),
+ ),
+ ("missing-c-2", USER_C.as_ref(), Some("spk-c0"), None),
+ // Unknown speaker ids are ignored even if their voice id is stable.
+ (
+ "unknown-speaker",
+ Some("spk-unknown"),
+ Some(voice_a),
+ ),
+ ];
+
+ for (idx, (segment_id, speaker_id, diarized_speaker_id, voice_id)) in
+ segments.into_iter().enumerate()
+ {
+ let started_at = now + Duration::seconds(idx as i64);
+ repo.create_transcript_segment(
+ &CALL1,
+ &TranscriptSegmentRequest {
+ segment_id: segment_id.to_string(),
+ speaker_id: speaker_id.to_string(),
+ diarized_speaker_id: diarized_speaker_id.map(str::to_string),
+ content: segment_id.to_string(),
+ started_at,
+ ended_at: Some(started_at + Duration::milliseconds(100)),
+ is_final: true,
+ stream_started_at: None,
+ embedding: None,
+ },
+ voice_id,
+ )
+ .await?;
+ }
+
+ let record_id = repo.archive_call(&CALL1).await?;
+
+ let stable = repo
+ .get_stable_speaker_voices_for_call_record(&record_id)
+ .await?;
+
+ assert_eq!(stable, vec![(MACRO_USER_A, voice_a)]);
+ Ok(())
+}
+
// -- get_call_record_by_call_id ----------------------------------------------
#[sqlx::test(