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(calls): voice id live kit agent (#3167)
Will Hutchinsona10f8f8d4815
diff --git a/.github/workflows/code-check-cloud-storage.yml b/.github/workflows/code-check-cloud-storage.ymlindex 384b17536e..f1d489f70c 100644--- a/.github/workflows/code-check-cloud-storage.yml+++ b/.github/workflows/code-check-cloud-storage.yml@@ -222,7 +222,7 @@ jobs:RUSTFLAGS: "-Dwarnings -C link-arg=-fuse-ld=mold"services:postgres:- image: postgres:16+ image: pgvector/pgvector:pg16env:POSTGRES_USER: userPOSTGRES_PASSWORD: password@@ -274,9 +274,9 @@ jobs:sccache --version- name: configure postgres for concurrent testsrun: |- postgres_container="$(docker ps --format '{{.ID}} {{.Image}}' | awk '$2 == "postgres:16" { print $1; exit }')"+ postgres_container="$(docker ps --format '{{.ID}} {{.Image}}' | awk '$2 == "pgvector/pgvector:pg16" { print $1; exit }')"if [ -z "$postgres_container" ]; then- echo "postgres:16 service container not found" >&2+ echo "pgvector/pgvector:pg16 service container not found" >&2docker psexit 1fidiff --git a/agents/transcription/requirements.txt b/agents/transcription/requirements.txtindex 3eda388b6a..bf9d28c183 100644--- a/agents/transcription/requirements.txt+++ b/agents/transcription/requirements.txt@@ -1,3 +1,4 @@python-dotenvlivekit-agents[silero]==1.5.7httpx+resemblyzer==0.1.4diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.pyindex 66a25fc30a..a30ae21ea4 100644--- a/agents/transcription/transcriber.py+++ b/agents/transcription/transcriber.py@@ -1,11 +1,13 @@+import arrayimport asyncioimport loggingimport osimport uuid-from collections import Counter+from collections import Counter, dequefrom datetime import datetime, timedelta, timezoneimport httpx+import numpy as npfrom dotenv import load_dotenvfrom livekit import rtcfrom livekit.agents import (@@ -24,6 +26,7 @@ from livekit.agents import (WorkerOptions,)from livekit.plugins import silero+from resemblyzer import VoiceEncoder, preprocess_wavload_dotenv()@@ -42,6 +45,7 @@ class Transcriber(Agent):participant_identity: str,channel_id: str,http_client: httpx.AsyncClient,+ voice_encoder: VoiceEncoder | None = None,):super().__init__(instructions="Transcribe user speech.",@@ -67,6 +71,16 @@ class Transcriber(Agent):self.participant_identity = participant_identityself.channel_id = channel_idself.http_client = http_client+ self.voice_encoder = voice_encoder+ # Rolling buffer of recent audio frames keyed off this participant's+ # stream. Used to compute a speaker-embedding on turn completion.+ # `_audio_sample_rate` and `_audio_num_channels` are captured from+ # the first frame so we can stitch the buffer back into a flat PCM+ # array at embed time without re-inspecting every frame.+ self._audio_frames: deque[rtc.AudioFrame] = deque()+ self._audio_buffered_samples: int = 0+ self._audio_sample_rate: int | None = None+ self._audio_num_channels: int | None = None# Word counts per Deepgram speaker int, accumulated across final# transcripts inside a single user turn and cleared on turn completion.self._pending_speakers: Counter[int] = Counter()@@ -102,8 +116,96 @@ class Transcriber(Agent):self._speaker_uuids[dg_speaker] = valuereturn value+ # Keep at most ~3 seconds of audio in the rolling buffer per participant.+ # Resemblyzer needs at least ~1.5s of speech for a useful embedding; the+ # cap keeps memory bounded for long-running sessions.+ _AUDIO_BUFFER_MAX_SECONDS = 3.0++ def _record_audio_frame(self, frame: rtc.AudioFrame) -> None:+ if self._audio_sample_rate is None:+ self._audio_sample_rate = frame.sample_rate+ self._audio_num_channels = frame.num_channels+ self._audio_frames.append(frame)+ self._audio_buffered_samples += frame.samples_per_channel+ if self._audio_sample_rate:+ max_samples = int(+ self._AUDIO_BUFFER_MAX_SECONDS * self._audio_sample_rate+ )+ while (+ self._audio_buffered_samples > max_samples+ and self._audio_frames+ ):+ dropped = self._audio_frames.popleft()+ self._audio_buffered_samples -= dropped.samples_per_channel++ def _drain_audio_buffer(self) -> tuple[array.array, int, int] | None:+ """Return the buffered audio as (interleaved int16 PCM, rate, channels).++ Returns `None` when no audio has been captured yet. Clears the buffer+ so the next turn starts fresh.+ """+ if not self._audio_frames or self._audio_sample_rate is None:+ return None+ pcm = array.array("h")+ for frame in self._audio_frames:+ pcm.frombytes(bytes(frame.data))+ sample_rate = self._audio_sample_rate+ num_channels = self._audio_num_channels or 1+ self._audio_frames.clear()+ self._audio_buffered_samples = 0+ return pcm, sample_rate, num_channels++ # Resemblyzer needs at least ~1s of speech for a usable embedding;+ # shorter buffers produce noisy / unreliable vectors.+ _MIN_EMBED_SECONDS = 1.0++ async def _compute_voice_embedding(self) -> list[float] | None:+ """Drain the audio buffer and embed it with Resemblyzer.++ Runs the CPU-bound preprocess+embed on a worker thread to keep the+ agent event loop responsive. Returns `None` when there isn't enough+ speech, when no encoder is configured, or when the model raises.+ """+ if self.voice_encoder is None:+ return None+ drained = self._drain_audio_buffer()+ if drained is None:+ return None+ pcm, sample_rate, num_channels = drained+ if len(pcm) == 0:+ return None+ duration_seconds = len(pcm) / float(sample_rate * max(num_channels, 1))+ if duration_seconds < self._MIN_EMBED_SECONDS:+ return None++ encoder = self.voice_encoder+ pcm_bytes = pcm.tobytes()++ def _embed() -> list[float] | None:+ samples = np.frombuffer(pcm_bytes, dtype=np.int16).astype(np.float32) / 32768.0+ if num_channels > 1:+ samples = samples.reshape(-1, num_channels).mean(axis=1)+ try:+ wav = preprocess_wav(samples, source_sr=sample_rate)+ except Exception:+ logger.exception("preprocess_wav failed")+ return None+ try:+ embedding = encoder.embed_utterance(wav)+ except Exception:+ logger.exception("voice encoder embed_utterance failed")+ return None+ return embedding.astype(np.float32).tolist()++ return await asyncio.to_thread(_embed)+async def stt_node(self, audio, model_settings):- async for event in super().stt_node(audio, model_settings):+ async def _tee():+ async for frame in audio:+ self._record_audio_frame(frame)+ yield frame++ async for event in super().stt_node(_tee(), model_settings):if isinstance(event, stt_pkg.SpeechEvent) and (event.type == stt_pkg.SpeechEventType.FINAL_TRANSCRIPT):@@ -158,6 +260,13 @@ class Transcriber(Agent):self._pending_first_word_offset = Noneself._pending_last_word_offset = Noneself._pending_speakers = Counter()+ # Always drain the audio buffer at turn boundary even on empty+ # content so leftover frames don't bleed into the next turn's+ # embedding. _compute_voice_embedding returns None when there's+ # nothing usable.+ embedding = await self._compute_voice_embedding() if content else None+ if not content:+ self._drain_audio_buffer()if content:now = datetime.now(timezone.utc)@@ -209,6 +318,7 @@ class Transcriber(Agent):if self._stream_t0_wall is not Noneelse None),+ "embedding": embedding,"isFinal": True,}max_attempts = 3@@ -318,6 +428,7 @@ class MultiUserTranscriber:participant_identity=participant.identity,channel_id=self.ctx.room.name,http_client=self.http_client,+ voice_encoder=self.ctx.proc.userdata.get("voice_encoder"),),room=self.ctx.room,room_options=room_io.RoomOptions(@@ -354,6 +465,9 @@ async def entrypoint(ctx: JobContext):def prewarm(proc: JobProcess):proc.userdata["vad"] = silero.VAD.load()+ # Load the Resemblyzer encoder once per worker process so per-turn+ # embedding doesn't pay the model-load cost on the hot path.+ proc.userdata["voice_encoder"] = VoiceEncoder()if __name__ == "__main__":diff --git a/docker-compose-databases.yml b/docker-compose-databases.ymlindex 09bf1bf8b9..341565b3f8 100644--- a/docker-compose-databases.yml+++ b/docker-compose-databases.yml@@ -5,7 +5,7 @@ name: macroservices:postgres:- image: postgres:16+ image: pgvector/pgvector:pg16healthcheck:test: ["CMD-SHELL", "pg_isready -U user"]interval: 2sdiff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 6f33d52a4d..da8ec9b5bc 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -657,6 +657,7 @@ export * from './threadResponse';export * from './threadUpdatedAt';export * from './transcriptSegmentRequest';export * from './transcriptSegmentRequestDiarizedSpeakerId';+export * from './transcriptSegmentRequestEmbedding';export * from './transcriptSegmentRequestEndedAt';export * from './transcriptSegmentRequestStreamStartedAt';export * from './typedSuccessResponse';diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.tsindex a11c44735e..90d2c5f190 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { TranscriptSegmentRequestDiarizedSpeakerId } from './transcriptSegmentRequestDiarizedSpeakerId';+import type { TranscriptSegmentRequestEmbedding } from './transcriptSegmentRequestEmbedding';import type { TranscriptSegmentRequestEndedAt } from './transcriptSegmentRequestEndedAt';import type { TranscriptSegmentRequestStreamStartedAt } from './transcriptSegmentRequestStreamStartedAt';@@ -18,6 +19,11 @@ export interface TranscriptSegmentRequest {pass. Namespaced upstream by audio track so values are unique across alltracks in a call. `None` when the provider didn't return a speaker label. */diarizedSpeakerId?: TranscriptSegmentRequestDiarizedSpeakerId;+ /** Speaker voice embedding computed by the transcription agent+(e.g. a Resemblyzer 256-dim vector). When present, the server+upserts a `voice` row and stores the resulting id on the transcript+segment so the call-finished pipeline can match it to enrolled users. */+ embedding?: TranscriptSegmentRequestEmbedding;/** When the speaker stopped talking for this segment. */endedAt?: TranscriptSegmentRequestEndedAt;/** Whether this is a final transcription (not interim). */diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEmbedding.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEmbedding.tsnew file mode 100644index 0000000000..fc34627917--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestEmbedding.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Speaker voice embedding computed by the transcription agent+(e.g. a Resemblyzer 256-dim vector). When present, the server+upserts a `voice` row and stores the resulting id on the transcript+segment so the call-finished pipeline can match it to enrolled users.+ */+export type TranscriptSegmentRequestEmbedding = number[] | null;diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex e3f0224b82..b9e0ae9a20 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1192,6 +1192,12 @@ export const ingestTranscriptBody = zod.describe("Stable per-speaker identifier produced by the STT provider's diarization\npass. Namespaced upstream by audio track so values are unique across all\ntracks in a call. `None` when the provider didn't return a speaker label."),+ embedding: zod+ .array(zod.number())+ .nullish()+ .describe(+ 'Speaker voice embedding computed by the transcription agent\n(e.g. a Resemblyzer 256-dim vector). When present, the server\nupserts a `voice` row and stores the resulting id on the transcript\nsegment so the call-finished pipeline can match it to enrolled users.'+ ),endedAt: zod.iso.datetime({}).nullish()diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 73665b4a13..f6f203d0a3 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -12120,6 +12120,14 @@"type": ["string", "null"],"description": "Stable per-speaker identifier produced by the STT provider's diarization\npass. Namespaced upstream by audio track so values are unique across all\ntracks in a call. `None` when the provider didn't return a speaker label."},+ "embedding": {+ "type": ["array", "null"],+ "items": {+ "type": "number",+ "format": "float"+ },+ "description": "Speaker voice embedding computed by the transcription agent\n(e.g. a Resemblyzer 256-dim vector). When present, the server\nupserts a `voice` row and stores the resulting id on the transcript\nsegment so the call-finished pipeline can match it to enrolled users."+ },"endedAt": {"type": ["string", "null"],"format": "date-time",diff --git a/rust/cloud-storage/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.json b/rust/cloud-storage/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.jsondeleted file mode 100644index ac6329e83c..0000000000--- a/rust/cloud-storage/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.json+++ /dev/null@@ -1,20 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, $7, (\n SELECT COALESCE(MAX(sequence_num), 0) + 1\n FROM call_transcripts\n WHERE call_id = $1\n ))\n ON CONFLICT (call_id, segment_id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text",- "Text",- "Text",- "Timestamptz",- "Timestamptz"- ]- },- "nullable": []- },- "hash": "12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7"-}diff --git a/rust/cloud-storage/.sqlx/query-3652fd4b477c2b12eab280f53ad27d442aba1aa7c6485dedb96a9e104b567491.json b/rust/cloud-storage/.sqlx/query-3652fd4b477c2b12eab280f53ad27d442aba1aa7c6485dedb96a9e104b567491.jsonnew file mode 100644index 0000000000..e60170d91c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-3652fd4b477c2b12eab280f53ad27d442aba1aa7c6485dedb96a9e104b567491.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num, voice_id)\n SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num, voice_id\n FROM call_transcripts\n WHERE call_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "3652fd4b477c2b12eab280f53ad27d442aba1aa7c6485dedb96a9e104b567491"+}diff --git a/rust/cloud-storage/.sqlx/query-55776d3a26b7c89897de6d58d17686ac9efbb516589692adcb97ffd1ace56ac9.json b/rust/cloud-storage/.sqlx/query-55776d3a26b7c89897de6d58d17686ac9efbb516589692adcb97ffd1ace56ac9.jsonnew file mode 100644index 0000000000..f0d020a34b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-55776d3a26b7c89897de6d58d17686ac9efbb516589692adcb97ffd1ace56ac9.json@@ -0,0 +1,21 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, voice_id, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, (\n SELECT COALESCE(MAX(sequence_num), 0) + 1\n FROM call_transcripts\n WHERE call_id = $1\n ))\n ON CONFLICT (call_id, segment_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "55776d3a26b7c89897de6d58d17686ac9efbb516589692adcb97ffd1ace56ac9"+}diff --git a/rust/cloud-storage/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.json b/rust/cloud-storage/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.jsondeleted file mode 100644index 7d528c9086..0000000000--- a/rust/cloud-storage/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)\n SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $2\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Uuid"- ]- },- "nullable": []- },- "hash": "669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30"-}diff --git a/rust/cloud-storage/.sqlx/query-691f6d6cfbd8bd9e7bd3e141231efe90a96a9ba79d142abbcd4846b3400dfa57.json b/rust/cloud-storage/.sqlx/query-691f6d6cfbd8bd9e7bd3e141231efe90a96a9ba79d142abbcd4846b3400dfa57.jsonnew file mode 100644index 0000000000..dd55647733--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-691f6d6cfbd8bd9e7bd3e141231efe90a96a9ba79d142abbcd4846b3400dfa57.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO macro_user_voice (macro_user_id, voice_id)\n VALUES ($1, $2)\n ON CONFLICT (macro_user_id, voice_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "691f6d6cfbd8bd9e7bd3e141231efe90a96a9ba79d142abbcd4846b3400dfa57"+}diff --git a/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.json b/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.jsonnew file mode 100644index 0000000000..55ddf0bcc3--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-7f7c60b83ef187f0c679361ddd9f69f9a92cdaaef099943664c48b20467b1c4d.json@@ -0,0 +1,28 @@+{+ "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/.sqlx/query-88e09c541b42bddb46449241492a7dc2d2ca72f9fc3d55a412460a0d8231555e.json b/rust/cloud-storage/.sqlx/query-88e09c541b42bddb46449241492a7dc2d2ca72f9fc3d55a412460a0d8231555e.jsonnew file mode 100644index 0000000000..59638b0311--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-88e09c541b42bddb46449241492a7dc2d2ca72f9fc3d55a412460a0d8231555e.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT voice_id FROM macro_user_voice WHERE macro_user_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "voice_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "88e09c541b42bddb46449241492a7dc2d2ca72f9fc3d55a412460a0d8231555e"+}diff --git a/rust/cloud-storage/.sqlx/query-b7d24d8fd171b58f03a8c4bab503279140fef9ddccbf7caebc285913adae2e3f.json b/rust/cloud-storage/.sqlx/query-b7d24d8fd171b58f03a8c4bab503279140fef9ddccbf7caebc285913adae2e3f.jsonnew file mode 100644index 0000000000..5fd0f3ee4a--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b7d24d8fd171b58f03a8c4bab503279140fef9ddccbf7caebc285913adae2e3f.json@@ -0,0 +1,16 @@+{+ "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 ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "b7d24d8fd171b58f03a8c4bab503279140fef9ddccbf7caebc285913adae2e3f"+}diff --git a/rust/cloud-storage/.sqlx/query-bb2b5a276542bf95f2600f3e60366b08133a54fbde183a5df7a9b99dd7381ca5.json b/rust/cloud-storage/.sqlx/query-bb2b5a276542bf95f2600f3e60366b08133a54fbde183a5df7a9b99dd7381ca5.jsonnew file mode 100644index 0000000000..b64038d03c--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-bb2b5a276542bf95f2600f3e60366b08133a54fbde183a5df7a9b99dd7381ca5.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT muv.macro_user_id\n FROM voice v\n JOIN macro_user_voice muv ON muv.voice_id = v.id\n WHERE (v.embedding <=> $1) <= $2\n ORDER BY v.embedding <=> $1 ASC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_user_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ {+ "Custom": {+ "name": "vector",+ "kind": "Simple"+ }+ },+ "Float8"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "bb2b5a276542bf95f2600f3e60366b08133a54fbde183a5df7a9b99dd7381ca5"+}diff --git a/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.json b/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.jsonnew file mode 100644index 0000000000..6cb53cec9b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c255e5fa6e1a70682e1a33445a1a3748f4cb91c46ad1216cf656b75e92e093f0.json@@ -0,0 +1,28 @@+{+ "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/.sqlx/query-fa0c2815727b1e1d81f6fc75f7b1b0bd250c9b56ab63138ac60b52e9174c48b1.json b/rust/cloud-storage/.sqlx/query-fa0c2815727b1e1d81f6fc75f7b1b0bd250c9b56ab63138ac60b52e9174c48b1.jsonnew file mode 100644index 0000000000..e79acf2cbe--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-fa0c2815727b1e1d81f6fc75f7b1b0bd250c9b56ab63138ac60b52e9174c48b1.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT macro_user_id FROM macro_user_voice WHERE voice_id = $1 LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_user_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "fa0c2815727b1e1d81f6fc75f7b1b0bd250c9b56ab63138ac60b52e9174c48b1"+}diff --git a/rust/cloud-storage/.sqlx/query-fb28d507d6c6e160fdf0e56d5fc7a70bfbf8709ea5473b3ec59e8f547cbeaed9.json b/rust/cloud-storage/.sqlx/query-fb28d507d6c6e160fdf0e56d5fc7a70bfbf8709ea5473b3ec59e8f547cbeaed9.jsonnew file mode 100644index 0000000000..e89466fcd6--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-fb28d507d6c6e160fdf0e56d5fc7a70bfbf8709ea5473b3ec59e8f547cbeaed9.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH target AS (SELECT embedding FROM voice WHERE id = $1)\n SELECT muv.macro_user_id\n FROM voice v\n JOIN macro_user_voice muv ON muv.voice_id = v.id\n WHERE (v.embedding <=> (SELECT embedding FROM target)) <= $2\n ORDER BY v.embedding <=> (SELECT embedding FROM target) ASC\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "macro_user_id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Float8"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "fb28d507d6c6e160fdf0e56d5fc7a70bfbf8709ea5473b3ec59e8f547cbeaed9"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex c7e9e62dc0..fd51c67c91 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -209,7 +209,7 @@ dependencies = ["reqwest 0.13.3","serde","serde_json",- "sha2",+ "sha2 0.10.8","tracing",]@@ -546,10 +546,10 @@ dependencies = ["async-stripe-types","chrono","hex",- "hmac",+ "hmac 0.12.1","miniserde","serde",- "sha2",+ "sha2 0.10.8","thiserror 2.0.17",]@@ -921,14 +921,14 @@ dependencies = ["bytes","fastrand 2.3.0","hex",- "hmac",+ "hmac 0.12.1","http 0.2.12","http 1.3.1","http-body 0.4.6","lru","percent-encoding","regex-lite",- "sha2",+ "sha2 0.10.8","tracing","url",]@@ -1104,13 +1104,13 @@ dependencies = ["crypto-bigint 0.5.5","form_urlencoded","hex",- "hmac",+ "hmac 0.12.1","http 0.2.12","http 1.3.1","p256 0.11.1","percent-encoding","ring",- "sha2",+ "sha2 0.10.8","subtle","time","tracing",@@ -1141,10 +1141,10 @@ dependencies = ["hex","http 0.2.12","http-body 0.4.6",- "md-5",+ "md-5 0.10.6","pin-project-lite","sha1",- "sha2",+ "sha2 0.10.8","tracing",]@@ -1529,7 +1529,7 @@ dependencies = ["bitflags 2.11.1","cexpr","clang-sys",- "itertools 0.10.5",+ "itertools 0.11.0","log","prettyplease","proc-macro2",@@ -1594,6 +1594,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"+dependencies = [+ "hybrid-array",+]+[[package]]name = "block2"version = "0.6.2"@@ -1736,12 +1745,12 @@ dependencies = ["axum","chrono","hex",- "hmac",+ "hmac 0.12.1","model-error-response","rootcause","serde","serde_json",- "sha2",+ "sha2 0.10.8","thiserror 2.0.17","tracing","utoipa",@@ -1776,6 +1785,7 @@ dependencies = ["models_pagination","models_permissions","notification",+ "pgvector","schemars","serde","serde_json",@@ -1957,7 +1967,7 @@ version = "0.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"dependencies = [- "crypto-common",+ "crypto-common 0.1.6","inout",]@@ -2033,6 +2043,12 @@ dependencies = ["cc",]+[[package]]+name = "cmov"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"+[[package]]name = "color_quant"version = "1.1.0"@@ -2320,6 +2336,12 @@ version = "0.9.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"+[[package]]+name = "const-oid"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"+[[package]]name = "const_format"version = "0.2.34"@@ -2545,7 +2567,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2fd92aca2c6001b1bf5ba0ff84ee74ec8501b52bbef0cac80bf25a6c1d87a83d"dependencies = ["crc",- "digest",+ "digest 0.10.7","rustversion","spin 0.10.0",]@@ -2691,6 +2713,15 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77727bb15fa921304124b128af125e7e3b968275d1b108b379190264f4423710"+dependencies = [+ "hybrid-array",+]+[[package]]name = "cssparser"version = "0.31.2"@@ -2727,6 +2758,15 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "ctutils"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"+dependencies = [+ "cmov",+]+[[package]]name = "curve25519-dalek"version = "4.1.3"@@ -2736,7 +2776,7 @@ dependencies = ["cfg-if","cpufeatures 0.2.17","curve25519-dalek-derive",- "digest",+ "digest 0.10.7","fiat-crypto","rustc_version","subtle",@@ -2949,7 +2989,7 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1a467a65c5e759bce6e65eaf91cc29f466cdc57cb65777bd646872a8a1fd4de"dependencies = [- "const-oid",+ "const-oid 0.9.6","zeroize",]@@ -2959,7 +2999,7 @@ version = "0.7.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0"dependencies = [- "const-oid",+ "const-oid 0.9.6","pem-rfc7468","zeroize",]@@ -3048,12 +3088,24 @@ version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "const-oid",- "crypto-common",+ "block-buffer 0.10.4",+ "const-oid 0.9.6",+ "crypto-common 0.1.6","subtle",]+[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.0",+ "const-oid 0.10.2",+ "crypto-common 0.2.1",+ "ctutils",+]+[[package]]name = "dispatch2"version = "0.3.1"@@ -3388,7 +3440,7 @@ dependencies = ["schemars","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","sync_service_client","thiserror 2.0.17",@@ -3428,7 +3480,7 @@ dependencies = ["s3_key","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","sqs_client","tokio",@@ -3555,7 +3607,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"dependencies = ["der 0.7.9",- "digest",+ "digest 0.10.7","elliptic-curve 0.13.8","rfc6979 0.4.0","signature 2.2.0",@@ -3581,7 +3633,7 @@ dependencies = ["curve25519-dalek","ed25519","serde",- "sha2",+ "sha2 0.10.8","subtle","zeroize",]@@ -3610,7 +3662,7 @@ dependencies = ["base16ct 0.1.1","crypto-bigint 0.4.9","der 0.6.1",- "digest",+ "digest 0.10.7","ff 0.12.1","generic-array","group 0.12.1",@@ -3629,7 +3681,7 @@ checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"dependencies = ["base16ct 0.2.0","crypto-bigint 0.5.5",- "digest",+ "digest 0.10.7","ff 0.13.1","generic-array","group 0.13.0",@@ -3716,7 +3768,7 @@ version = "0.1.0"dependencies = ["askama","chrono",- "hmac",+ "hmac 0.12.1","macro_env","macro_service_urls","macro_user_id",@@ -3724,7 +3776,7 @@ dependencies = ["notification","rootcause","serde",- "sha2",+ "sha2 0.10.8","tracing",]@@ -3839,7 +3891,7 @@ dependencies = ["secretsmanager_client","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","sqlx-core","sqs_client",@@ -4118,6 +4170,12 @@ dependencies = ["zune-inflate",]+[[package]]+name = "fallible-iterator"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4443176a9f2c162692bd3d352d745ef9413eec5782a80d8fd6f8a1ac692a07f7"+[[package]]name = "fancy-regex"version = "0.12.0"@@ -4589,7 +4647,7 @@ dependencies = ["entity_access","fusionauth","hex",- "hmac",+ "hmac 0.12.1","http-body-util","jsonwebtoken 10.3.0 (git+https://github.com/whutchinson98/jsonwebtoken)","macro_db_migrator",@@ -4607,7 +4665,7 @@ dependencies = ["reqwest 0.13.3","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","subtle","thiserror 2.0.17",@@ -4863,7 +4921,7 @@ version = "0.12.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"dependencies = [- "hmac",+ "hmac 0.12.1",][[package]]@@ -4872,7 +4930,16 @@ version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"dependencies = [- "digest",+ "digest 0.10.7",+]++[[package]]+name = "hmac"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"+dependencies = [+ "digest 0.11.3",][[package]]@@ -5047,6 +5114,15 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]+name = "hybrid-array"+version = "0.4.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214"+dependencies = [+ "typenum",+]+[[package]]name = "hyper"version = "0.14.32"@@ -5787,7 +5863,7 @@ dependencies = ["base64 0.22.1","ed25519-dalek","getrandom 0.2.15",- "hmac",+ "hmac 0.12.1","js-sys","p256 0.13.2","p384",@@ -5795,7 +5871,7 @@ dependencies = ["rsa","serde","serde_json",- "sha2",+ "sha2 0.10.8","signature 2.2.0",]@@ -5807,7 +5883,7 @@ dependencies = ["base64 0.22.1","ed25519-dalek","getrandom 0.2.15",- "hmac",+ "hmac 0.12.1","js-sys","p256 0.13.2","p384",@@ -5816,7 +5892,7 @@ dependencies = ["rsa","serde","serde_json",- "sha2",+ "sha2 0.10.8","signature 2.2.0","simple_asn1",]@@ -5957,7 +6033,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"dependencies = ["cfg-if",- "windows-targets 0.48.5",+ "windows-targets 0.52.6",][[package]]@@ -6019,7 +6095,7 @@ dependencies = ["scopeguard","serde","serde_json",- "sha2",+ "sha2 0.10.8","thiserror 2.0.17","url",]@@ -6557,7 +6633,7 @@ dependencies = ["redis","serde","serde_json",- "sha2",+ "sha2 0.10.8","thiserror 2.0.17","tower 0.5.2","tower-http",@@ -6620,7 +6696,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"dependencies = ["cfg-if",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "md-5"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"+dependencies = [+ "cfg-if",+ "digest 0.11.3",][[package]]@@ -7199,7 +7285,7 @@ dependencies = ["native_app_service","rootcause","semver",- "sha2",+ "sha2 0.10.8","tokio","tower-http","tracing",@@ -7219,7 +7305,7 @@ dependencies = ["semver","serde","serde_json",- "sha2",+ "sha2 0.10.8","strum","thiserror 2.0.17","tokio",@@ -7317,7 +7403,7 @@ dependencies = ["either","futures","hex",- "hmac",+ "hmac 0.12.1","http-body-util","itertools 0.14.0","last_online_tracker",@@ -7338,7 +7424,7 @@ dependencies = ["schemars","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","strum","thiserror 2.0.17",@@ -7379,7 +7465,7 @@ dependencies = ["chrono","either","email_formatting",- "hmac",+ "hmac 0.12.1","inquire","macro_aws_config","macro_env",@@ -7393,7 +7479,7 @@ dependencies = ["rootcause","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx","tokio","tracing",@@ -7415,7 +7501,7 @@ dependencies = ["decode_jwt","email_formatting","email_validator",- "hmac",+ "hmac 0.12.1","http-body-util","itertools 0.14.0","last_online_tracker",@@ -7448,7 +7534,7 @@ dependencies = ["serde","serde_json","ses_client",- "sha2",+ "sha2 0.10.8","sns_client","sqlx","thiserror 2.0.17",@@ -7977,7 +8063,7 @@ checksum = "51f44edd08f51e2ade572f141051021c5af22677e42b7dd28a88155151c33594"dependencies = ["ecdsa 0.14.8","elliptic-curve 0.12.3",- "sha2",+ "sha2 0.10.8",][[package]]@@ -7989,7 +8075,7 @@ dependencies = ["ecdsa 0.16.9","elliptic-curve 0.13.8","primeorder",- "sha2",+ "sha2 0.10.8",][[package]]@@ -8001,7 +8087,7 @@ dependencies = ["ecdsa 0.16.9","elliptic-curve 0.13.8","primeorder",- "sha2",+ "sha2 0.10.8",][[package]]@@ -8094,8 +8180,8 @@ version = "0.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"dependencies = [- "digest",- "hmac",+ "digest 0.10.7",+ "hmac 0.12.1",][[package]]@@ -8168,6 +8254,17 @@ dependencies = ["indexmap 2.14.0",]+[[package]]+name = "pgvector"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc58e2d255979a31caa7cabfa7aac654af0354220719ab7a68520ae7a91e8c0b"+dependencies = [+ "bytes",+ "postgres-types",+ "sqlx",+]+[[package]]name = "phf"version = "0.10.1"@@ -8370,6 +8467,35 @@ version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"+[[package]]+name = "postgres-protocol"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56201207dac53e2f38e848e31b4b91616a6bb6e0c7205b77718994a7f49e70fc"+dependencies = [+ "base64 0.22.1",+ "byteorder",+ "bytes",+ "fallible-iterator",+ "hmac 0.13.0",+ "md-5 0.11.0",+ "memchr",+ "rand 0.10.0",+ "sha2 0.11.0",+ "stringprep",+]++[[package]]+name = "postgres-types"+version = "0.2.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8dc729a129e682e8d24170cd30ae1aa01b336b096cbb56df6d534ffec133d186"+dependencies = [+ "bytes",+ "fallible-iterator",+ "postgres-protocol",+]+[[package]]name = "powerfmt"version = "0.2.0"@@ -8625,7 +8751,7 @@ checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"dependencies = ["bytes","heck 0.5.0",- "itertools 0.10.5",+ "itertools 0.11.0","log","multimap","once_cell",@@ -8645,7 +8771,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1"dependencies = ["anyhow",- "itertools 0.10.5",+ "itertools 0.11.0","proc-macro2","quote","syn 2.0.98",@@ -9225,7 +9351,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7743f17af12fa0b03b803ba12cd6a8d9483a587e89c69445e3909655c0b9fabb"dependencies = ["crypto-bigint 0.4.9",- "hmac",+ "hmac 0.12.1","zeroize",]@@ -9235,7 +9361,7 @@ version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"dependencies = [- "hmac",+ "hmac 0.12.1","subtle",]@@ -9355,8 +9481,8 @@ version = "0.9.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d"dependencies = [- "const-oid",- "digest",+ "const-oid 0.9.6",+ "digest 0.10.7","num-bigint-dig","num-integer","num-traits",@@ -9400,7 +9526,7 @@ version = "8.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5a2fcdc9f40c8dc2922842ca9add611ad19f332227fc651d015881ad1552bd9a"dependencies = [- "sha2",+ "sha2 0.10.8","walkdir",]@@ -10242,7 +10368,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -10259,7 +10385,18 @@ checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "digest 0.11.3",][[package]]@@ -10330,7 +10467,7 @@ version = "1.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"dependencies = [- "digest",+ "digest 0.10.7","rand_core 0.6.4",]@@ -10340,7 +10477,7 @@ version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"dependencies = [- "digest",+ "digest 0.10.7","rand_core 0.6.4",]@@ -10606,7 +10743,7 @@ dependencies = ["rustls 0.23.36","serde","serde_json",- "sha2",+ "sha2 0.10.8","smallvec","thiserror 2.0.17","tokio",@@ -10645,7 +10782,7 @@ dependencies = ["quote","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqlx-core","sqlx-mysql","sqlx-postgres",@@ -10668,7 +10805,7 @@ dependencies = ["bytes","chrono","crc",- "digest",+ "digest 0.10.7","dotenvy","either","futures-channel",@@ -10678,10 +10815,10 @@ dependencies = ["generic-array","hex","hkdf",- "hmac",+ "hmac 0.12.1","itoa","log",- "md-5",+ "md-5 0.10.6","memchr","once_cell","percent-encoding",@@ -10689,7 +10826,7 @@ dependencies = ["rsa","serde","sha1",- "sha2",+ "sha2 0.10.8","smallvec","sqlx-core","stringprep",@@ -10718,17 +10855,17 @@ dependencies = ["futures-util","hex","hkdf",- "hmac",+ "hmac 0.12.1","home","itoa","log",- "md-5",+ "md-5 0.10.6","memchr","once_cell","rand 0.8.5","serde","serde_json",- "sha2",+ "sha2 0.10.8","smallvec","sqlx-core","stringprep",@@ -11812,7 +11949,7 @@ dependencies = ["openssl","serde","serde_json",- "sha2",+ "sha2 0.10.8","sqs_client","tempfile","tokio",@@ -13018,7 +13155,7 @@ dependencies = ["displaydoc","flate2","getrandom 0.3.1",- "hmac",+ "hmac 0.12.1","indexmap 2.14.0","lzma-rs","memchr",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex f404004e99..af08fbcb60 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -219,6 +219,7 @@ sqlx = { version = "0.8.6", features = ["uuid",] }sqlx-core = { version = "0.8.6" }+pgvector = { version = "0.4", features = ["sqlx", "postgres"] }strum = { version = "0.27.1", features = ["derive"] }thiserror = "2.0.0"time = "0.3.37"diff --git a/rust/cloud-storage/call/Cargo.toml b/rust/cloud-storage/call/Cargo.tomlindex 240b63a9e7..d559101fe6 100644--- a/rust/cloud-storage/call/Cargo.toml+++ b/rust/cloud-storage/call/Cargo.toml@@ -23,6 +23,7 @@ outbound = ["dep:livekit-api","dep:livekit-protocol","dep:macro_aws_config",+ "dep:pgvector","dep:sqlx","ports",]@@ -58,6 +59,7 @@ model_user = { path = "../model_user", optional = true, features = ["axum"] }models_pagination = { path = "../models_pagination" }models_permissions = { path = "../models_permissions" }notification = { path = "../notification" }+pgvector = { workspace = true, optional = true }schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/call/fixtures/voice_repo.sql b/rust/cloud-storage/call/fixtures/voice_repo.sqlnew file mode 100644index 0000000000..3ac819f6a6--- /dev/null+++ b/rust/cloud-storage/call/fixtures/voice_repo.sql@@ -0,0 +1,7 @@+-- Fixture for pg_voice_repo integration tests.+--+-- Seeds two macro_user rows that tests link/unlink voices against.++INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id") VALUES+ ('11111111-1111-1111-1111-111111111111', 'voice-user-a', '[email protected]', 'cus_voice_a'),+ ('22222222-2222-2222-2222-222222222222', 'voice-user-b', '[email protected]', 'cus_voice_b');diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rsindex a42e8d7b88..eadd5c8093 100644--- a/rust/cloud-storage/call/src/domain/models.rs+++ b/rust/cloud-storage/call/src/domain/models.rs@@ -149,6 +149,12 @@ pub struct TranscriptSegmentRequest {/// (it stamps egress bootstrap, not first audio frame).#[serde(default)]pub stream_started_at: Option<DateTime<Utc>>,+ /// Speaker voice embedding computed by the transcription agent+ /// (e.g. a Resemblyzer 256-dim vector). When present, the server+ /// upserts a `voice` row and stores the resulting id on the transcript+ /// segment so the call-finished pipeline can match it to enrolled users.+ #[serde(default)]+ pub embedding: Option<Vec<f32>>,}/// Edit call requestdiff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex a2fca49f3d..4615a61a44 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -158,11 +158,14 @@ pub trait CallRepository: Send + Sync + 'static {started_at: chrono::DateTime<chrono::Utc>,) -> impl Future<Output = Result<bool, Self::Err>> + Send;- /// Insert a transcript segment for an active call.+ /// Insert a transcript segment for an active call. When `voice_id` is+ /// `Some`, it's stored on the row so the call-finished pipeline can+ /// resolve the speaker to a macro user.fn create_transcript_segment(&self,call_id: &Uuid,segment: &TranscriptSegmentRequest,+ voice_id: Option<Uuid>,) -> impl Future<Output = Result<(), Self::Err>> + Send;/// Get the profile picture URL for a user by their `MacroUserIdStr`.@@ -252,6 +255,26 @@ pub trait CallRepository: Send + Sync + 'static {assignments: &[CustomSpeakerAssignment],) -> impl Future<Output = Result<(), 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). 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@@ -513,6 +536,21 @@ pub trait CallService: Send + Sync + 'static {/// and empty transcripts are also no-ops — no AI call is made in those/// cases.fn summarize_call(&self, call_id: &Uuid) -> impl Future<Output = Result<(), CallError>> + Send;++ /// List the voice ids currently enrolled for `macro_user_id`.+ fn get_user_voices(+ &self,+ macro_user_id: &Uuid,+ ) -> impl Future<Output = Result<Vec<Uuid>, CallError>> + Send;++ /// Enroll a new voice embedding for `macro_user_id`. Inserts a row into+ /// the `voice` table and links it to the user via `macro_user_voice`.+ /// Returns the new `voice.id`.+ fn set_user_voice(+ &self,+ macro_user_id: &Uuid,+ embedding: &[f32],+ ) -> impl Future<Output = Result<Uuid, CallError>> + Send;}/// Lightweight read-only port for querying call records in Soup.@@ -556,6 +594,113 @@ pub trait CallSearchIndexer: Send + Sync + 'static {) -> impl Future<Output = anyhow::Result<()>> + Send;}+/// Repository port for persisting speaker voice embeddings and their+/// association with macro users.+///+/// `voice` stores a row per distinct speaker fingerprint (a `vector(N)`+/// embedding produced by the LiveKit agent's speaker-embedding model).+/// `macro_user_voice` is a many-to-many join linking enrolled users to+/// the voice rows that identify them.+#[cfg_attr(test, mockall::automock(type Err = anyhow::Error;))]+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.+ fn upsert_voice(+ &self,+ embedding: &[f32],+ ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;++ /// Link a `voice` row to a macro user. Idempotent on the composite+ /// primary key `(macro_user_id, voice_id)`.+ fn link_user_voice(+ &self,+ macro_user_id: &Uuid,+ voice_id: &Uuid,+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;++ /// All voice ids currently linked to a macro user.+ fn get_user_voices(+ &self,+ macro_user_id: &Uuid,+ ) -> impl Future<Output = Result<Vec<Uuid>, Self::Err>> + Send;++ /// Resolve a `voice_id` back to its linked macro user, if any. Uses the+ /// `macro_user_voice` join — does not perform similarity search.+ fn find_user_by_voice(+ &self,+ voice_id: &Uuid,+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;++ /// Find the macro user whose enrolled voice embedding is closest to+ /// `embedding`, provided the cosine distance is `<= threshold`. Returns+ /// `None` when no enrolled voice is within the threshold.+ fn find_nearest_user(+ &self,+ embedding: &[f32],+ threshold: f32,+ ) -> 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.+ fn find_nearest_user_for_voice(+ &self,+ voice_id: &Uuid,+ threshold: f32,+ ) -> impl Future<Output = Result<Option<Uuid>, Self::Err>> + Send;+}++/// No-op [`VoiceRepository`] used as the default for services that do not+/// have speaker-identification wired up. All operations are no-ops or+/// return `None`/empty results.+#[derive(Default, Clone, Copy)]+pub struct NoOpVoiceRepository;++impl VoiceRepository for NoOpVoiceRepository {+ type Err = anyhow::Error;++ async fn upsert_voice(&self, _embedding: &[f32]) -> Result<Uuid, Self::Err> {+ anyhow::bail!("voice repository not configured");+ }++ async fn link_user_voice(+ &self,+ _macro_user_id: &Uuid,+ _voice_id: &Uuid,+ ) -> Result<(), Self::Err> {+ Ok(())+ }++ async fn get_user_voices(&self, _macro_user_id: &Uuid) -> Result<Vec<Uuid>, Self::Err> {+ Ok(Vec::new())+ }++ async fn find_user_by_voice(&self, _voice_id: &Uuid) -> Result<Option<Uuid>, Self::Err> {+ Ok(None)+ }++ async fn find_nearest_user(+ &self,+ _embedding: &[f32],+ _threshold: f32,+ ) -> Result<Option<Uuid>, Self::Err> {+ Ok(None)+ }++ async fn find_nearest_user_for_voice(+ &self,+ _voice_id: &Uuid,+ _threshold: f32,+ ) -> Result<Option<Uuid>, Self::Err> {+ Ok(None)+ }+}+/// No-op for services without search.pub struct NoOpCallSearchIndexer;diff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 6e52ce532f..75b7f3b0a7 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::HashSet;+use std::collections::{HashMap, HashSet};use uuid::Uuid;@@ -34,9 +34,21 @@ use super::models::{};use super::ports::{CallRecordQueryService, CallRepository, CallRtcClient, CallSearchIndexer, CallService,- CallSummarizer, NoOpCallSearchIndexer, RecordingStorage,+ 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,@@ -48,6 +60,7 @@ pub struct CallServiceImpl<Sm: CallSummarizer = NoopCallSummarizer,I: CallSearchIndexer = NoOpCallSearchIndexer,V: VoipPushSender = (),+ Vr: VoiceRepository = NoOpVoiceRepository,> {repo: R,rtc_client: C,@@ -61,6 +74,7 @@ pub struct CallServiceImpl<internal_call_secret: Option<String>,summarizer: Option<Sm>,voip_push_sender: V,+ voice_repo: Vr,}impl<@@ -71,7 +85,7 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer, ()>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer, (), NoOpVoiceRepository>{/// Create a new call service.pub fn new(@@ -96,6 +110,7 @@ impl<internal_call_secret: None,summarizer: None,voip_push_sender: (),+ voice_repo: NoOpVoiceRepository,}}}@@ -110,7 +125,8 @@ impl<Sm: CallSummarizer,I: CallSearchIndexer,V: VoipPushSender,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>+ Vr: VoiceRepository,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>{/// Enable auto-recording with the given S3 configuration.pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {@@ -136,7 +152,7 @@ impl<pub fn with_voip_push_sender<V2: VoipPushSender>(self,sender: V2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2, Vr> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -150,6 +166,7 @@ impl<internal_call_secret: self.internal_call_secret,summarizer: self.summarizer,voip_push_sender: sender,+ voice_repo: self.voice_repo,}}@@ -157,7 +174,7 @@ impl<pub fn with_search_indexer<I2: CallSearchIndexer>(self,indexer: I2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V, Vr> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -171,6 +188,29 @@ impl<internal_call_secret: self.internal_call_secret,summarizer: self.summarizer,voip_push_sender: self.voip_push_sender,+ voice_repo: self.voice_repo,+ }+ }++ /// 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> {+ 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: self.search_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,}}@@ -325,7 +365,8 @@ impl<Sm: CallSummarizer + Clone,I: CallSearchIndexer,V: VoipPushSender,-> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>+ Vr: VoiceRepository + Clone,+> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>{fn validate_internal_call(&self, token: &str) -> bool {self.internal_call_secret@@ -640,6 +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);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");@@ -749,6 +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);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");@@ -975,8 +1018,22 @@ 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.+ 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(),+ _ => None,+ };+self.repo- .create_transcript_segment(&call.id, &segment)+ .create_transcript_segment(&call.id, &segment, voice_id).await.map_err(|e| CallError::Internal(e.into()))?;@@ -1154,6 +1211,32 @@ impl<Ok(())}++ #[tracing::instrument(err, skip(self))]+ async fn get_user_voices(&self, macro_user_id: &Uuid) -> Result<Vec<Uuid>, CallError> {+ self.voice_repo+ .get_user_voices(macro_user_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))+ }++ #[tracing::instrument(err, skip(self, embedding))]+ async fn set_user_voice(+ &self,+ macro_user_id: &Uuid,+ embedding: &[f32],+ ) -> Result<Uuid, CallError> {+ let voice_id = self+ .voice_repo+ .upsert_voice(embedding)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ self.voice_repo+ .link_user_voice(macro_user_id, &voice_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ Ok(voice_id)+ }}impl<@@ -1166,7 +1249,8 @@ impl<Sm: CallSummarizer + Clone,I: CallSearchIndexer,V: VoipPushSender,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>+ Vr: VoiceRepository + Clone,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>{/// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.///@@ -1244,6 +1328,116 @@ impl<}});}++ /// Fire-and-forget spawn of [`match_voices_for_call_record`].+ ///+ /// 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) {+ let repo = self.repo.clone();+ let voice_repo = self.voice_repo.clone();+ tokio::spawn(async move {+ match_voices_for_call_record(+ &repo,+ &voice_repo,+ call_record_id,+ VOICE_MATCH_DISTANCE_THRESHOLD,+ )+ .await;+ });+ }+}++/// 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 the+/// assignments back via [`CallRepository::patch_call_transcript_speakers_from_voice_match`]+/// (which only fills `custom_speaker` rows that are still `NULL` so+/// manual corrections are preserved).+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.diff --git a/rust/cloud-storage/call/src/outbound/mod.rs b/rust/cloud-storage/call/src/outbound/mod.rsindex c973bb2cdc..8af1bd792d 100644--- a/rust/cloud-storage/call/src/outbound/mod.rs+++ b/rust/cloud-storage/call/src/outbound/mod.rs@@ -4,5 +4,7 @@ pub mod ai_call_summarizer;pub mod livekit_rtc_client;/// Postgres-backed repository implementing [`CallRepository`](crate::domain::ports::CallRepository).pub mod pg_call_repo;+/// Postgres-backed repository implementing [`VoiceRepository`](crate::domain::ports::VoiceRepository).+pub mod pg_voice_repo;/// S3-backed recording storage implementing [`RecordingStorage`](crate::domain::ports::RecordingStorage).pub mod s3_recording_storage;diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex 7e7394e0e1..99ee143f54 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -572,8 +572,8 @@ impl CallRepository for PgCallRepo {// Copy transcripts to call_record_transcripts.sqlx::query!(r#"- INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)- SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num+ INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num, voice_id)+ SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num, voice_idFROM call_transcriptsWHERE call_id = $2"#,@@ -692,11 +692,12 @@ impl CallRepository for PgCallRepo {&self,call_id: &Uuid,segment: &TranscriptSegmentRequest,+ voice_id: Option<Uuid>,) -> Result<(), Self::Err> {sqlx::query!(r#"- INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)- VALUES ($1, $2, $3, $4, $5, $6, $7, (+ INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, voice_id, sequence_num)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, (SELECT COALESCE(MAX(sequence_num), 0) + 1FROM call_transcriptsWHERE call_id = $1@@ -710,6 +711,7 @@ impl CallRepository for PgCallRepo {segment.content,segment.started_at,segment.ended_at,+ voice_id,).execute(&self.pool).await?;@@ -1344,6 +1346,59 @@ impl CallRepository for PgCallRepo {Ok(())}+ #[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+ "#,+ 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.rsindex 15b81480d2..3478a01a77 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@@ -704,6 +704,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(ended_at: Some(now),is_final: true,stream_started_at: None,+ embedding: None,};let seg2 = TranscriptSegmentRequest {segment_id: "seg-002".to_string(),@@ -714,13 +715,14 @@ async fn create_transcript_segment_stores_and_increments_sequence(ended_at: Some(now),is_final: true,stream_started_at: None,+ embedding: None,};- repo.create_transcript_segment(&CALL1, &seg1).await?;- repo.create_transcript_segment(&CALL1, &seg2).await?;+ repo.create_transcript_segment(&CALL1, &seg1, None).await?;+ repo.create_transcript_segment(&CALL1, &seg2, None).await?;// Duplicate segment_id should be ignored.- repo.create_transcript_segment(&CALL1, &seg1).await?;+ repo.create_transcript_segment(&CALL1, &seg1, None).await?;let rows = sqlx::query!(r#"@@ -764,8 +766,9 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Resultended_at: Some(now),is_final: true,stream_started_at: None,+ embedding: None,};- repo.create_transcript_segment(&CALL1, &seg).await?;+ repo.create_transcript_segment(&CALL1, &seg, None).await?;// Archive the call.let record_id = repo.archive_call(&CALL1).await?;@@ -825,7 +828,9 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Reended_at: Some(now),is_final: true,stream_started_at: None,+ embedding: None,},+ None,).await?;repo.create_transcript_segment(@@ -839,7 +844,9 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Reended_at: Some(now),is_final: true,stream_started_at: None,+ embedding: None,},+ None,).await?;diff --git a/rust/cloud-storage/call/src/outbound/pg_voice_repo.rs b/rust/cloud-storage/call/src/outbound/pg_voice_repo.rsnew file mode 100644index 0000000000..ad675934ac--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/pg_voice_repo.rs@@ -0,0 +1,137 @@+//! Postgres-backed repository for speaker voice embeddings.++#[cfg(test)]+mod test;++use pgvector::Vector;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::ports::VoiceRepository;++/// Postgres adapter implementing [`VoiceRepository`].+#[derive(Clone)]+pub struct PgVoiceRepo {+ pool: PgPool,+}++impl PgVoiceRepo {+ /// Construct a new repository wrapping the given pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++impl VoiceRepository for PgVoiceRepo {+ type Err = sqlx::Error;++ async fn upsert_voice(&self, embedding: &[f32]) -> Result<Uuid, Self::Err> {+ let id = macro_uuid::generate_uuid_v7();+ let vec = Vector::from(embedding.to_vec());+ let row = sqlx::query!(+ r#"+ INSERT INTO voice (id, embedding) VALUES ($1, $2) RETURNING id+ "#,+ id,+ vec as Vector,+ )+ .fetch_one(&self.pool)+ .await?;+ Ok(row.id)+ }++ async fn link_user_voice(+ &self,+ macro_user_id: &Uuid,+ voice_id: &Uuid,+ ) -> Result<(), Self::Err> {+ sqlx::query!(+ r#"+ INSERT INTO macro_user_voice (macro_user_id, voice_id)+ VALUES ($1, $2)+ ON CONFLICT (macro_user_id, voice_id) DO NOTHING+ "#,+ macro_user_id,+ voice_id,+ )+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ async fn get_user_voices(&self, macro_user_id: &Uuid) -> Result<Vec<Uuid>, Self::Err> {+ let rows = sqlx::query!(+ r#"+ SELECT voice_id FROM macro_user_voice WHERE macro_user_id = $1+ "#,+ macro_user_id,+ )+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().map(|r| r.voice_id).collect())+ }++ async fn find_user_by_voice(&self, voice_id: &Uuid) -> Result<Option<Uuid>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT macro_user_id FROM macro_user_voice WHERE voice_id = $1 LIMIT 1+ "#,+ voice_id,+ )+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.macro_user_id))+ }++ async fn find_nearest_user(+ &self,+ embedding: &[f32],+ threshold: f32,+ ) -> Result<Option<Uuid>, Self::Err> {+ let vec = Vector::from(embedding.to_vec());+ // f64 cast because pgvector's `<=>` returns float8; the bound+ // parameter has to match or sqlx complains about type mismatch.+ let threshold = threshold as f64;+ let row = sqlx::query!(+ r#"+ SELECT muv.macro_user_id+ FROM voice v+ JOIN macro_user_voice muv ON muv.voice_id = v.id+ WHERE (v.embedding <=> $1) <= $2+ ORDER BY v.embedding <=> $1 ASC+ LIMIT 1+ "#,+ vec as Vector,+ threshold,+ )+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.macro_user_id))+ }++ async fn find_nearest_user_for_voice(+ &self,+ voice_id: &Uuid,+ threshold: f32,+ ) -> Result<Option<Uuid>, Self::Err> {+ let threshold = threshold as f64;+ // The CTE pulls the target embedding once; the main query then uses+ // it for both the WHERE threshold and the ORDER BY ranking.+ let row = sqlx::query!(+ r#"+ WITH target AS (SELECT embedding FROM voice WHERE id = $1)+ SELECT muv.macro_user_id+ FROM voice v+ JOIN macro_user_voice muv ON muv.voice_id = v.id+ WHERE (v.embedding <=> (SELECT embedding FROM target)) <= $2+ ORDER BY v.embedding <=> (SELECT embedding FROM target) ASC+ LIMIT 1+ "#,+ voice_id,+ threshold,+ )+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|r| r.macro_user_id))+ }+}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.rsnew file mode 100644index 0000000000..8ac541092d--- /dev/null+++ b/rust/cloud-storage/call/src/outbound/pg_voice_repo/test.rs@@ -0,0 +1,251 @@+use crate::domain::ports::VoiceRepository;+use crate::outbound::pg_voice_repo::PgVoiceRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};+use uuid::{Uuid, uuid};++const USER_A: Uuid = uuid!("11111111-1111-1111-1111-111111111111");+const USER_B: Uuid = uuid!("22222222-2222-2222-2222-222222222222");++fn repo(pool: Pool<Postgres>) -> PgVoiceRepo {+ PgVoiceRepo::new(pool)+}++/// 256-dim unit vector with `1.0` on `axis` and `0.0` elsewhere. Using+/// orthogonal axis vectors makes cosine distance trivially predictable:+/// identical → 0, orthogonal → 1.+fn axis_unit_vector(axis: usize) -> Vec<f32> {+ let mut v = vec![0.0_f32; 256];+ v[axis] = 1.0;+ v+}++// -- upsert_voice -------------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn upsert_voice_inserts_row(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool.clone());+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;++ let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM voice WHERE id = $1")+ .bind(voice_id)+ .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_returns_distinct_ids(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(0)).await?;+ assert_ne!(v1, v2, "each upsert generates a fresh id");+ Ok(())+}++// -- link_user_voice / get_user_voices ----------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn link_user_voice_then_get_user_voices(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_A, &voice_id).await?;++ let voices = repo.get_user_voices(&USER_A).await?;+ assert_eq!(voices, vec![voice_id]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn link_user_voice_idempotent_on_duplicate(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_A, &voice_id).await?;+ // Duplicate link must not error or insert a second row.+ repo.link_user_voice(&USER_A, &voice_id).await?;++ let voices = repo.get_user_voices(&USER_A).await?;+ assert_eq!(voices, vec![voice_id]);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_user_voices_empty_for_user_without_links(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ assert!(repo.get_user_voices(&USER_A).await?.is_empty());+ Ok(())+}++// -- find_user_by_voice -------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_user_by_voice_resolves_linked_user(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_B, &voice_id).await?;++ assert_eq!(repo.find_user_by_voice(&voice_id).await?, Some(USER_B));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_user_by_voice_returns_none_for_unlinked_voice(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ assert_eq!(repo.find_user_by_voice(&voice_id).await?, None);+ Ok(())+}++// -- find_nearest_user --------------------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_matches_identical_embedding(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_A, &voice_id).await?;++ // Same embedding → cosine distance 0, well under threshold.+ let match_id = repo.find_nearest_user(&axis_unit_vector(0), 0.1).await?;+ assert_eq!(match_id, Some(USER_A));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_returns_none_above_threshold(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let voice_id = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_A, &voice_id).await?;++ // Orthogonal embedding → cosine distance 1.0, above 0.25.+ let match_id = repo.find_nearest_user(&axis_unit_vector(1), 0.25).await?;+ assert_eq!(match_id, None);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_picks_closest_of_multiple(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ let v_a = repo.upsert_voice(&axis_unit_vector(0)).await?;+ let v_b = repo.upsert_voice(&axis_unit_vector(1)).await?;+ repo.link_user_voice(&USER_A, &v_a).await?;+ repo.link_user_voice(&USER_B, &v_b).await?;++ // Query aligned with axis-1 → user_b wins, even though user_a is also+ // enrolled.+ let match_id = repo.find_nearest_user(&axis_unit_vector(1), 0.1).await?;+ assert_eq!(match_id, Some(USER_B));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_skips_unlinked_voices(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let repo = repo(pool);+ // Insert an embedding that is NOT linked to any user — the matcher+ // must ignore it even though it would be the closest row in `voice`.+ let _unlinked = repo.upsert_voice(&axis_unit_vector(0)).await?;+ // Enroll user_b with a perpendicular embedding (distance 1).+ let v_b = repo.upsert_voice(&axis_unit_vector(1)).await?;+ repo.link_user_voice(&USER_B, &v_b).await?;++ // Querying axis-0 should not return user_b at threshold 0.25, and it+ // must not "see" the unlinked closer row.+ let match_id = repo.find_nearest_user(&axis_unit_vector(0), 0.25).await?;+ assert_eq!(match_id, None);+ Ok(())+}++// -- find_nearest_user_for_voice ----------------------------------------------++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_for_voice_resolves_via_embedding_lookup(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ // 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?;+ assert_ne!(enrolled, segment_voice);+ let match_id = repo+ .find_nearest_user_for_voice(&segment_voice, 0.1)+ .await?;+ assert_eq!(match_id, Some(USER_A));+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_for_voice_returns_none_for_unknown_voice_id(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let missing = Uuid::nil();+ let match_id = repo.find_nearest_user_for_voice(&missing, 0.5).await?;+ assert_eq!(match_id, None);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("voice_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn find_nearest_user_for_voice_returns_none_above_threshold(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let v_a = repo.upsert_voice(&axis_unit_vector(0)).await?;+ repo.link_user_voice(&USER_A, &v_a).await?;++ // A voice perpendicular to the only enrolled user — distance 1.0.+ let orthogonal = repo.upsert_voice(&axis_unit_vector(1)).await?;+ let match_id = repo.find_nearest_user_for_voice(&orthogonal, 0.25).await?;+ assert_eq!(match_id, None);+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 6cbdf4ff5b..bddf03d448 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -209,6 +209,7 @@ pub(crate) type DssCallService = CallServiceImpl<call::outbound::ai_call_summarizer::AiCallSummarizer,crate::service::call_search_indexer::SqsCallSearchIndexer,DssVoipPushSender,+ call::outbound::pg_voice_repo::PgVoiceRepo,>;/// Type alias for the call router state.diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 9215a650c6..1753edc420 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -20,7 +20,7 @@ use call::{inbound::axum_router::{CallRouterState, InternalCallRouterState, WebhookRouterState},outbound::{ai_call_summarizer::AiCallSummarizer, livekit_rtc_client::LivekitRtcClient,- pg_call_repo::PgCallRepo,+ pg_call_repo::PgCallRepo, pg_voice_repo::PgVoiceRepo,},};use channels::{@@ -498,7 +498,11 @@ async fn main() -> anyhow::Result<()> {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));+ let call_service = Arc::new(+ call_service_builder+ .with_search_indexer(call_search_indexer)+ .with_voice_repo(PgVoiceRepo::new(db.clone())),+ );let call_state = CallRouterState::new(call_service.clone(), entity_access_service.clone());let call_webhook_state = WebhookRouterState::new(call_service.clone());diff --git a/rust/cloud-storage/macro_db_client/migrations/20260511131821_enable_pgvector.sql b/rust/cloud-storage/macro_db_client/migrations/20260511131821_enable_pgvector.sqlnew file mode 100644index 0000000000..0aa0fc2255--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260511131821_enable_pgvector.sql@@ -0,0 +1 @@+CREATE EXTENSION IF NOT EXISTS vector;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260511131822_add_voice_tables.sql b/rust/cloud-storage/macro_db_client/migrations/20260511131822_add_voice_tables.sqlnew file mode 100644index 0000000000..e7e8274f20--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260511131822_add_voice_tables.sql@@ -0,0 +1,18 @@+CREATE TABLE IF NOT EXISTS voice (+ id UUID PRIMARY KEY,+ embedding vector(256) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_voice_embedding_cosine+ ON voice USING hnsw (embedding vector_cosine_ops);++CREATE TABLE IF NOT EXISTS macro_user_voice (+ macro_user_id UUID NOT NULL REFERENCES macro_user(id) ON DELETE CASCADE,+ voice_id UUID NOT NULL REFERENCES voice(id) ON DELETE CASCADE,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (macro_user_id, voice_id)+);++CREATE INDEX IF NOT EXISTS idx_macro_user_voice_voice_id+ ON macro_user_voice (voice_id);diff --git a/rust/cloud-storage/macro_db_client/migrations/20260511131823_call_transcripts_voice_id.sql b/rust/cloud-storage/macro_db_client/migrations/20260511131823_call_transcripts_voice_id.sqlnew file mode 100644index 0000000000..92a57bcd0d--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260511131823_call_transcripts_voice_id.sql@@ -0,0 +1,2 @@+ALTER TABLE call_transcripts+ ADD COLUMN voice_id UUID REFERENCES voice(id) ON DELETE SET NULL;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260511131824_call_record_transcripts_voice_id.sql b/rust/cloud-storage/macro_db_client/migrations/20260511131824_call_record_transcripts_voice_id.sqlnew file mode 100644index 0000000000..328f978905--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260511131824_call_record_transcripts_voice_id.sql@@ -0,0 +1,5 @@+ALTER TABLE call_record_transcripts+ ADD COLUMN voice_id UUID REFERENCES voice(id) ON DELETE SET NULL;++CREATE INDEX IF NOT EXISTS idx_call_record_transcripts_voice_id+ ON call_record_transcripts (voice_id);