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(calls): remove existing voice auto-assign (#3396)

Will Hutchinson2bc6ea17ea33
diff --git a/rust/cloud-storage/.sqlx/query-006ebc0f8730714a1755ea1dbfee6e8c5bdc57566579a482dedb774aeda6a1c2.json b/rust/cloud-storage/.sqlx/query-006ebc0f8730714a1755ea1dbfee6e8c5bdc57566579a482dedb774aeda6a1c2.json
deleted file mode 100644
index 78f1631b26..0000000000
--- a/rust/cloud-storage/.sqlx/query-006ebc0f8730714a1755ea1dbfee6e8c5bdc57566579a482dedb774aeda6a1c2.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE call_record_transcripts AS t\n SET custom_speaker = u.id\n FROM UNNEST($2::text[], $3::uuid[]) AS a(diarized_speaker_id, macro_user_id)\n JOIN \"User\" u ON u.macro_user_id = a.macro_user_id\n WHERE t.call_record_id = $1\n AND t.diarized_speaker_id = a.diarized_speaker_id\n AND t.custom_speaker IS NULL\n AND EXISTS (\n SELECT 1\n FROM team_user matched_user_team\n JOIN team_user participant_team\n ON participant_team.team_id = matched_user_team.team_id\n JOIN call_record_participants p\n ON p.user_id = participant_team.user_id\n AND p.call_record_id = $1\n WHERE matched_user_team.user_id = u.id\n )\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray",
- "UuidArray"
- ]
- },
- "nullable": []
- },
- "hash": "006ebc0f8730714a1755ea1dbfee6e8c5bdc57566579a482dedb774aeda6a1c2"
-}
diff --git a/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.json b/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.json
deleted file mode 100644
index 55ddf0bcc3..0000000000
--- a/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT DISTINCT diarized_speaker_id AS \"diarized_speaker_id!\", voice_id AS \"voice_id!\"\n FROM call_record_transcripts\n WHERE call_record_id = $1\n AND diarized_speaker_id IS NOT NULL\n AND voice_id IS NOT NULL\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "diarized_speaker_id!",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "voice_id!",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid"
- ]
- },
- "nullable": [
- true,
- true
- ]
- },
- "hash": "7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d"
-}
diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rs
index 127a94170e..28ba9c6f94 100644
--- a/rust/cloud-storage/call/src/domain/ports.rs
+++ b/rust/cloud-storage/call/src/domain/ports.rs
@@ -278,27 +278,6 @@ pub trait CallRepository: Send + Sync + 'static {
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.
- fn get_distinct_voice_speakers_for_call_record(
- &self,
- call_record_id: &Uuid,
- ) -> impl Future<Output = Result<Vec<(String, Uuid)>, Self::Err>> + Send;
-
- /// Apply auto-matched speaker assignments to `call_record_transcripts`
- /// rows, only where `custom_speaker IS NULL` (so manual overrides are
- /// never clobbered) and the matched macro user shares a team with at least
- /// one call participant. Each tuple is `(diarized_speaker_id,
- /// macro_user_id)`; the canonical `User.id` is resolved inline via the
- /// `User` row whose `macro_user_id` matches and stored in
- /// `custom_speaker`. Empty `assignments` is a no-op.
- fn patch_call_transcript_speakers_from_voice_match(
- &self,
- call_record_id: &Uuid,
- assignments: &[(String, Uuid)],
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
-
/// Persist the AI-generated summary text on the archived call record.
///
/// Tolerates unknown `call_id` (no row matches): the summarization flow
@@ -671,9 +650,8 @@ pub trait VoiceRepository: Send + Sync + 'static {
) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;
/// Same as [`Self::find_nearest_user`] but looks the embedding up by
- /// `voice_id` in the `voice` table first. Used by the call-finished
- /// matcher, which already has `voice_id`s on the transcript rows and
- /// shouldn't need to re-load the embeddings client-side.
+ /// `voice_id` in the `voice` table first, so callers that already have a
+ /// persisted voice id don't need to re-load embeddings client-side.
fn find_nearest_user_for_voice(
&self,
voice_id: &Uuid,
diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rs
index d4db64fc2a..8732f0f448 100644
--- a/rust/cloud-storage/call/src/domain/service.rs
+++ b/rust/cloud-storage/call/src/domain/service.rs
@@ -20,7 +20,7 @@ use notification::domain::models::{
use notification::domain::ports::VoipPushSender;
use notification::domain::service::NotificationIngress;
use serde::{Deserialize, Serialize};
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use uuid::Uuid;
@@ -37,18 +37,6 @@ use super::ports::{
CallSummarizer, NoOpCallSearchIndexer, NoOpVoiceRepository, RecordingStorage, VoiceRepository,
};
-/// Cosine distance threshold used by the post-archive voice matcher when
-/// resolving a transcript's `voice_id` to an enrolled macro user.
-///
-/// pgvector exposes cosine *distance* via `<=>` (range 0.0–2.0; 0.0 ≈
-/// identical, 1.0 ≈ orthogonal). Resemblyzer's docs report ~0.75 cosine
-/// *similarity* for same-speaker pairs, which corresponds to ~0.25
-/// cosine distance — that's our starting point. Lower = stricter (fewer
-/// false matches, more missed matches); higher = looser. Tune with real
-/// enrollment data; consider promoting to per-tenant config once we have
-/// signal on false-positive vs miss rates.
-pub const VOICE_MATCH_DISTANCE_THRESHOLD: f32 = 0.25;
-
/// The concrete call service implementation.
pub struct CallServiceImpl<
R: CallRepository,
@@ -1352,26 +1340,18 @@ impl<
});
}
- /// Fire-and-forget spawn of finished-call voice processing.
+ /// Fire-and-forget spawn of finished-call voice enrollment.
///
/// Called from `process_webhook_event` immediately after `archive_call`
- /// finalizes the `call_records` row. First, voice ids for consistently
- /// diarized speakers 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.
+ /// finalizes the `call_records` row. Voice ids for consistently diarized
+ /// speakers are enrolled for the users who spoke them. This intentionally
+ /// does not populate `custom_speaker`; speaker overrides are only changed
+ /// through explicit edit requests.
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,
- call_record_id,
- VOICE_MATCH_DISTANCE_THRESHOLD,
- )
- .await;
});
}
}
@@ -1424,98 +1404,6 @@ async fn enroll_stable_speaker_voices_for_call_record<R: CallRepository, Vr: Voi
);
}
-/// Match the voice ids on a freshly archived call to enrolled users and
-/// populate `custom_speaker` for the matched diarized speakers.
-///
-/// Pulls the distinct `(diarized_speaker_id, voice_id)` pairs from the
-/// call's transcripts, resolves each `voice_id` to a macro user via
-/// the voice repository's nearest-neighbour lookup, then writes eligible
-/// assignments back via [`CallRepository::patch_call_transcript_speakers_from_voice_match`]
-/// (which only fills `custom_speaker` rows that are still `NULL` and whose
-/// matched user shares a team with at least one participant, so manual
-/// corrections are preserved and cross-team matches are ignored).
-async fn match_voices_for_call_record<R: CallRepository, Vr: VoiceRepository>(
- repo: &R,
- voice_repo: &Vr,
- call_record_id: Uuid,
- distance_threshold: f32,
-) {
- let pairs = match repo
- .get_distinct_voice_speakers_for_call_record(&call_record_id)
- .await
- {
- Ok(p) => p,
- Err(e) => {
- tracing::error!(
- error=?e, %call_record_id,
- "failed to load voice/speaker pairs for matching"
- );
- return;
- }
- };
-
- if pairs.is_empty() {
- return;
- }
-
- let total = pairs.len();
- let mut raw_assignments: Vec<(String, Uuid)> = Vec::new();
- for (diarized_speaker_id, voice_id) in pairs {
- match voice_repo
- .find_nearest_user_for_voice(&voice_id, distance_threshold)
- .await
- {
- Ok(Some(user_id)) => raw_assignments.push((diarized_speaker_id, user_id)),
- Ok(None) => {}
- Err(e) => tracing::error!(
- error=?e, %call_record_id, %voice_id,
- "voice match lookup failed; skipping speaker"
- ),
- }
- }
-
- // The same diarized_speaker_id can appear with multiple voice_ids, each
- // potentially resolving to a different user. The patch query joins only on
- // diarized_speaker_id, so collapse to one winner per speaker — most-frequent
- // user wins, ties broken by earliest appearance for determinism.
- let mut tally: HashMap<(String, Uuid), (usize, usize)> = HashMap::new();
- for (idx, (speaker, user)) in raw_assignments.iter().enumerate() {
- tally.entry((speaker.clone(), *user)).or_insert((0, idx)).0 += 1;
- }
- let mut winners: HashMap<String, (Uuid, usize, usize)> = HashMap::new();
- for ((speaker, user), (count, first_idx)) in tally {
- let replace = winners
- .get(&speaker)
- .is_none_or(|(_, cur_count, cur_first)| {
- count > *cur_count || (count == *cur_count && first_idx < *cur_first)
- });
- if replace {
- winners.insert(speaker, (user, count, first_idx));
- }
- }
- let assignments: Vec<(String, Uuid)> = winners
- .into_iter()
- .map(|(speaker, (user, _, _))| (speaker, user))
- .collect();
-
- let matched = assignments.len();
- if let Err(e) = repo
- .patch_call_transcript_speakers_from_voice_match(&call_record_id, &assignments)
- .await
- {
- tracing::error!(
- error=?e, %call_record_id,
- "failed to persist voice-matched speakers"
- );
- return;
- }
-
- tracing::info!(
- %call_record_id, matched, total,
- "voice match completed"
- );
-}
-
/// Extract the recording key from a full S3 URL.
///
/// Given `https://bucket.s3.amazonaws.com/calls/UUID/TIMESTAMP.mp4`,
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 736227a85f..b571e792f5 100644
--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
@@ -1493,69 +1493,6 @@ impl CallRepository for PgCallRepo {
.collect())
}
- #[tracing::instrument(err, skip(self))]
- async fn get_distinct_voice_speakers_for_call_record(
- &self,
- call_record_id: &Uuid,
- ) -> Result<Vec<(String, Uuid)>, Self::Err> {
- let rows = sqlx::query!(
- r#"
- SELECT DISTINCT diarized_speaker_id AS "diarized_speaker_id!", voice_id AS "voice_id!"
- FROM call_record_transcripts
- WHERE call_record_id = $1
- AND diarized_speaker_id IS NOT NULL
- AND voice_id IS NOT NULL
- "#,
- call_record_id,
- )
- .fetch_all(&self.pool)
- .await?;
- Ok(rows
- .into_iter()
- .map(|r| (r.diarized_speaker_id, r.voice_id))
- .collect())
- }
-
- #[tracing::instrument(skip(self, assignments), fields(num_assignments = assignments.len()), err)]
- async fn patch_call_transcript_speakers_from_voice_match(
- &self,
- call_record_id: &Uuid,
- assignments: &[(String, Uuid)],
- ) -> Result<(), Self::Err> {
- if assignments.is_empty() {
- return Ok(());
- }
- let diarized_ids: Vec<&str> = assignments.iter().map(|(d, _)| d.as_str()).collect();
- let user_ids: Vec<Uuid> = assignments.iter().map(|(_, u)| *u).collect();
- sqlx::query!(
- r#"
- UPDATE call_record_transcripts AS t
- SET custom_speaker = u.id
- FROM UNNEST($2::text[], $3::uuid[]) AS a(diarized_speaker_id, macro_user_id)
- JOIN "User" u ON u.macro_user_id = a.macro_user_id
- WHERE t.call_record_id = $1
- AND t.diarized_speaker_id = a.diarized_speaker_id
- AND t.custom_speaker IS NULL
- AND EXISTS (
- SELECT 1
- FROM team_user matched_user_team
- JOIN team_user participant_team
- ON participant_team.team_id = matched_user_team.team_id
- JOIN call_record_participants p
- ON p.user_id = participant_team.user_id
- AND p.call_record_id = $1
- WHERE matched_user_team.user_id = u.id
- )
- "#,
- call_record_id,
- &diarized_ids as &[&str],
- &user_ids,
- )
- .execute(&self.pool)
- .await?;
- Ok(())
- }
-
#[tracing::instrument(skip(self, summary), err)]
async fn insert_call_summary(&self, call_id: &Uuid, summary: &str) -> Result<(), Self::Err> {
// Tolerate missing rows: summarization can race with record deletion.
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 8233ce2b90..9e5105fafe 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
@@ -102,32 +102,6 @@ async fn insert_user_mapping(
Ok(())
}
-async fn insert_team_members(
- pool: &Pool<Postgres>,
- team_id: Uuid,
- owner_id: &str,
- member_ids: &[&str],
-) -> anyhow::Result<()> {
- sqlx::query(r#"INSERT INTO team (id, name, owner_id) VALUES ($1, $2, $3)"#)
- .bind(team_id)
- .bind(format!("test team {team_id}"))
- .bind(owner_id)
- .execute(pool)
- .await?;
-
- for member_id in member_ids {
- sqlx::query(
- r#"INSERT INTO team_user (user_id, team_id, team_role) VALUES ($1, $2, 'member')"#,
- )
- .bind(member_id)
- .bind(team_id)
- .execute(pool)
- .await?;
- }
-
- Ok(())
-}
-
// -- create_call --------------------------------------------------------------
#[sqlx::test(
@@ -1199,102 +1173,6 @@ async fn get_stable_speaker_voices_for_call_record_returns_all_voices_for_consis
Ok(())
}
-// -- patch_call_transcript_speakers_from_voice_match -------------------------
-
-#[sqlx::test(
- fixtures(path = "../../../fixtures", scripts("call_repo")),
- migrator = "MACRO_DB_MIGRATIONS"
-)]
-async fn patch_call_transcript_speakers_from_voice_match_requires_same_team_as_participant(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- let repo = repo(pool.clone());
- let user_d = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let macro_user_d = Uuid::now_v7();
-
- insert_user_mapping(&pool, USER_A.deref(), MACRO_USER_A).await?;
- insert_user_mapping(&pool, USER_C.deref(), MACRO_USER_C).await?;
- insert_user_mapping(&pool, &user_d, macro_user_d).await?;
-
- // USER_A is a participant in CALL_ARCHIVED. USER_C is not a participant,
- // but is in USER_A's team, so C is eligible for auto-assignment.
- insert_team_members(
- &pool,
- Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaa01),
- USER_A.as_ref(),
- &[USER_A.as_ref(), USER_C.as_ref()],
- )
- .await?;
-
- // USER_D has an enrolled voice match but belongs to a team with no call
- // participants, so D must not be auto-assigned.
- insert_team_members(
- &pool,
- Uuid::from_u128(0xdddddddd_dddd_dddd_dddd_dddddddddd01),
- user_d.as_ref(),
- &[user_d.as_ref()],
- )
- .await?;
-
- let now = Utc::now();
- sqlx::query(
- r#"
- INSERT INTO call_record_transcripts
- (call_record_id, segment_id, speaker_id, diarized_speaker_id, custom_speaker, content, started_at, ended_at, sequence_num)
- VALUES
- ($1, 'seg-team-match', $2, 'spk-team-match', NULL, 'team match', $3, $3, 10),
- ($1, 'seg-cross-team-match', $2, 'spk-cross-team-match', NULL, 'cross team match', $3, $3, 11)
- "#,
- )
- .bind(CALL_ARCHIVED)
- .bind(USER_A.as_ref())
- .bind(now)
- .execute(&pool)
- .await?;
-
- repo.patch_call_transcript_speakers_from_voice_match(
- &CALL_ARCHIVED,
- &[
- ("spk-team-match".to_string(), MACRO_USER_C),
- ("spk-cross-team-match".to_string(), macro_user_d),
- ],
- )
- .await?;
-
- let rows = sqlx::query(
- r#"
- SELECT diarized_speaker_id, custom_speaker
- FROM call_record_transcripts
- WHERE call_record_id = $1
- AND diarized_speaker_id IN ('spk-team-match', 'spk-cross-team-match')
- ORDER BY sequence_num
- "#,
- )
- .bind(CALL_ARCHIVED)
- .fetch_all(&pool)
- .await?;
-
- use sqlx::Row as _;
- assert_eq!(rows.len(), 2);
- assert_eq!(
- rows[0].get::<String, _>("diarized_speaker_id"),
- "spk-team-match"
- );
- assert_eq!(
- rows[0]
- .get::<Option<String>, _>("custom_speaker")
- .as_deref(),
- Some(USER_C.as_ref())
- );
- assert_eq!(
- rows[1].get::<String, _>("diarized_speaker_id"),
- "spk-cross-team-match"
- );
- assert_eq!(rows[1].get::<Option<String>, _>("custom_speaker"), None);
-
- Ok(())
-}
-
// -- get_call_record_by_call_id ----------------------------------------------
#[sqlx::test(