Repository navigation
Shared flagged final-pass diarization and speaker assignment - #21424
Git-on-my-level merged 10 commits into
Conversation
…ed transcript edits
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8717ec9a8e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if os.getenv('TRANSCRIPTION_FINAL_PASS_DIARIZER', 'legacy') != 'pyannote_shadow': | ||
| return False | ||
| allowlist = {s.strip() for s in os.getenv('TRANSCRIPTION_FINAL_PASS_UID_ALLOWLIST', '').split(',') if s.strip()} | ||
| percent = max(0.0, min(100.0, float(os.getenv('TRANSCRIPTION_FINAL_PASS_PERCENT', '0')))) |
There was a problem hiding this comment.
Reject non-finite rollout percentages
When TRANSCRIPTION_FINAL_PASS_PERCENT is set to NaN, Python accepts the value and this min/max expression evaluates it to 100.0, so enabled_for admits every UID instead of failing closed; once the sync or authoritative switches are on, a malformed gradual-rollout value becomes a fleet-wide cutover. Validate math.isfinite and treat invalid values as zero before bucketing.
Useful? React with 👍 / 👎.
| if speaker_embedding_configured(): | ||
| for segment in sorted(evidence_segments, key=lambda s: s.end - s.start, reverse=True)[:32]: | ||
| evidence = collect_speaker_audio(audio, [(segment.start, segment.end)]) | ||
| if evidence.clips and segment.id: | ||
| vectors[segment.id] = extract_embedding_from_bytes(evidence.clips[0][0]) |
There was a problem hiding this comment.
Bound embedding triage outside the sync worker pool
When the embedding endpoint is slow during an enabled sync final pass, backend/utils/sync/pipeline.py dispatches _process_one_segment on sync_executor, but this loop invokes extract_embedding_from_bytes synchronously and inherits its 300-second per-call timeout; 16 concurrent segment jobs can therefore occupy every sync worker and stop unrelated sync jobs. Pass a bounded shared deadline below the worker limit or perform this remote wait through async orchestration or a dedicated sized pool.
AGENTS.md reference: backend/AGENTS.md:L268-L275
Useful? React with 👍 / 👎.
| backend = os.getenv('TRANSCRIPTION_FINAL_PASS_BACKEND', 'pyannote') | ||
| if backend == 'legacy_ahc': | ||
| return LegacyAHC() | ||
| if backend in {'pyannote', 'nemotron'}: | ||
| return HttpDiarizer(backend) |
There was a problem hiding this comment.
Move final-pass provider parsing into config
When TRANSCRIPTION_FINAL_PASS_BACKEND changes, this utility itself parses provider tokens and chooses implementations (while HttpDiarizer separately maps providers to URL environment variables), leaving no pure configuration contract for runtime consumers and configuration checks to share. Move the token parsing and required bindings into config/transcription_final_pass.py, and have this module consume the typed selection.
AGENTS.md reference: backend/AGENTS.md:L171-L171
Useful? React with 👍 / 👎.
| DEPTH.set(queue.depth) | ||
| body = bytearray() | ||
| while True: | ||
| message = await request.receive() |
There was a problem hiding this comment.
Time out uploads while holding queue admission
When three clients send a partial body and keep their connections open, each request has already consumed one of the default three admission tokens before this unbounded request.receive(), so every legitimate caller receives 429 while the GPU remains idle. Apply an upload deadline, including between chunks, and let the existing finally release the token.
Useful? React with 👍 / 👎.
…21482) ## Summary Single runtime-env PR for the shared model Gateway rollout. Two independently revertible commits: 1. David-only batch diarization shadow on backend, backend-sync and pusher through `http://172.16.160.20/diarizer-batch`. Both cohort percentages 0, authoritative false, sync false. Strict scope/parity checks accept only a complete reviewed ramp stage. The pyannote adapter appends `/v2/diarization`. 2. NLLB → `/nllb`, VAD → `/vad/v1/vad`, and every speaker-embedding caller → `/diarizer` in dev/prod, including Parakeet's embedding fallback. Parakeet STT endpoints remain unchanged. **Reserved addresses:** dev `172.16.48.49` (fresh ro-dev lookup after reservation appeared), prod `172.16.160.20` (ro-prod lookup). Both environments use concrete IPs. Reservation is not serving qualification: lead must probe Gateway programming, routes and caller reachability before deploying. No production user API calls, merge, deploy or ramp were performed. ## Exact ramp data Complete env sets: `config/diarization-cohort-stages.json`. Common values on backend/backend-sync/pusher: ```text HOSTED_DIARIZATION_API_URL=http://172.16.160.20/diarizer-batch TRANSCRIPTION_FINAL_PASS_DIARIZER=pyannote_shadow TRANSCRIPTION_FINAL_PASS_BACKEND=pyannote TRANSCRIPTION_FINAL_PASS_UID_ALLOWLIST=vi7SA9ckQCe4ccobWNxlbdcNdC23 TRANSCRIPTION_FINAL_PASS_SYNC_ENABLED=false TRANSCRIPTION_SHADOW_ENABLED=true TRANSCRIPTION_SHADOW_KILL_SWITCH=false TRANSCRIPTION_SHADOW_UID_ALLOWLIST=vi7SA9ckQCe4ccobWNxlbdcNdC23 ``` Combine these constants with this exact stage data (column names abbreviate `TRANSCRIPTION_`; values are strings): | Stage | FINAL_PASS_PERCENT | SHADOW_PERCENT | FINAL_PASS_AUTHORITATIVE | SHADOW_DAILY_AUDIO_HOURS | One-line prod overlay change, then redeploy all three | |---|---:|---:|---|---:|---| | A David shadow | 0 | 0 | false | 1 | `&batch_cohort` line: percentages `"0"`, authoritative `"false"`, hours `"1"` | | B David authoritative | 0 | 0 | true | 1 | Same line: authoritative `"true"` | | C 1% authoritative + David | 1 | 1 | true | 80 | Same line: both percentages `"1"`, hours `"80"` | | D 5% authoritative + David | 5 | 5 | true | 400 | Same line: both percentages `"5"`, hours `"400"` | `backend/deploy/runtime_env/prod.overlay.yaml` owns the shared mapping. After that one-line data edit, recompose `runtime_env.yaml`, align pusher chart literals with the selected stage, validate, and redeploy. No runtime code or guard changes per stage. Do not exceed 5%; wait **≥12h at D** before proposing expansion. Hold every stage for sufficient gate samples. At **each A/B/C/D** check failure rate (`omi_transcription_final_pass_total`, failed:*; `omi_transcription_shadow_total`), p95 latency (`omi_transcription_final_pass_latency_seconds`, `omi_transcription_shadow_latency_seconds`), speaker agreement (`omi_transcription_final_pass_agreement`) and word distance (`omi_transcription_shadow_word_distance`), owner parity (`omi_transcription_shadow_owner_delta_ratio`), remap correctness (`omi_transcription_shadow_remap_success_rate`, `omi_transcription_shadow_remap_safe_total`), and out-of-profile / determined language rate (`omi_stt_output_language_segments_total` conformance labels; `live_stt_language_summary` logs). Also inspect `event=transcription_shadow`, scalar v2 results, batch queue `omi_diarization_v2_queue_depth`, 429/5xx, GPU load and current-revision/manual-annotation promotion receipts. Empty series do not pass; use matched baselines and review parity before B. No UID labels exist in aggregate metrics. ## Capacity / limits The existing Redis daily cap is configurable and charges all selected stored audio, not just multi-speaker GPU work. At planning load 6,300 h/day, C/D select ~63/315 h; 80/400 h provide headroom. D's ~140 multi-speaker h/day × supplied T4 RTF .06 = **8.4 GPU-h/day**, ~35% average occupancy on one T4. This is planning arithmetic, not a new T4 load-test receipt; queue/latency/bursts gate the ramp. Two-hour worker/API cap remains bounded: ~432s inference at .06 RTF versus 600s worker deadline and 900s Gateway timeout. ASR/decoding/queue consume the same worker budget. Longer calls retain legacy attribution; inspect `failed:too_long` metadata and excluded duration share. Sync stays false through D. Cloud Run process-local shadow dispatch is not durable: equal env does not prove Cloud Run receipt completion; durable shadow dispatch remains required for reliable Cloud Run coverage. ## Deploy order / rollback See `backend/docs/diarizer-batch-cohort.md`, `backend/docs/internal-gateway-callers.md` and `backend/charts/internal-gateway/README.md` for lead operations. Qualify Gateway/routes from GKE and Cloud Run first. Dev caller migration first, then prod; NLLB/VAD readouts and ≥30m hold, followed by coordinated embedding switches across all six speaker-ID hosts plus Parakeet fallback. Use listen/pusher workflows, `gcp_backend.yml`, `gcp_parakeet.yml`. Then independently deploy batch A and advance through gates. Listen carries NLLB/VAD/embedding together; qualify every route before that workflow and review NLLB/VAD separately before finishing the embedding cohort. Rollback caller commit alone and redeploy every affected caller, including Parakeet fallback; restore legacy hostnames/cluster-local fallback from the runbook. Keep the Gateway while batch still uses it. After either revert, recompose `runtime_env.yaml` from the retained overlays (this also resolves generated-manifest conflicts without undoing the other commit). Rollback cohort commit alone and redeploy backend/backend-sync/pusher, or return to A to stop promotion; incident stop sets shadow kill switch true plus final-pass diarizer legacy. Disable batch callers before removing its capacity. Keep legacy Ingress/DNS ≥7d. No historical record rewriting. ## Validation - `backend/scripts/pre-deploy-check.sh`: dev/prod manifest and workflow/render validation passed; 305 deploy-safety tests passed. - `BACKEND_UNIT_TEST_FILE_LIST=/tmp/cohort-fast-tests.txt bash backend/test.sh` (run from backend with its local Python): 65 tests passed across cohort, caller, co-host guard and adapter contracts; CPU duration guard enabled. - `backend/test.sh` with `test_verify_pusher_config_references.py`: 28 rendered binding contract tests passed, CPU duration guard enabled. - `python scripts/test_check_feature_flag_registry.py`: 24 tests passed, including shared-map resolution. - `make preflight`: 41 selected checks passed; final pre-push passed the manifest checks, typecheck (0 errors), source closure (16 images) and changed backend tests. - Independent rollback verified with a temporary Git index and recomposed overlays: each configuration preserves the other migration. Cohort revert requires regenerating the shared manifest as documented. Runtime-only changes exercise rendering and hermetic adapters rather than calling production user APIs. Lead-owned serving probes and acceptance are not performed by this PR. ## Product invariants affected - INV-MEM-4 — runtime manifest changes preserve the existing canonical memory authority bindings. Why isn't this a shared primitive instead? The shared final-pass policy, Redis cap and adapter already exist (#21424); this PR binds them and reuses the shared Gateway (#21473). Stage data and the existing co-host guard prevent the obsolete endpoint or widened/mixed cohorts prepared in 3ec0377. Registry rendering resolves the shared overlay mapping so documented effective bindings remain accurate.
Introduce a default-off shared diarization result, config-selected pyannote/legacy AHC/Nemotron HTTP adapters, and common word assignment and centroid naming for the final-pass shadow and sync/safety WAL. Add community-1
/v2/diarizationwith bounded upload/inference admission, compatible WeSpeaker centroids, overlap output and Prometheus metrics.Authoritative promotion separately checks the completed record revision and changes only speaker fields on stored segments: text, IDs, clocks, translations and structured references are retained. Conflicting speakers within a stored segment veto promotion. Manual receipts and person edits are preserved; either direction of a bare legacy is_user disagreement is protected. All cutovers remain off. Live matching and batch centroid naming use the existing shared
select_speaker_matchpolicy with unchanged thresholds. Health and metrics remain responsive when legacy embedding workers are saturated. No dead paths are deleted; no workflow is added.Product invariants: none mapped by
scripts/pr-preflight --suggest.Failure-Class: none
Validation: 56 focused tests pass through the file-isolated backend/test.sh runner. They include fatal startup failure for all legacy/batch model loads, embedding completion while batch inference holds its slot, differing stored text, bare legacy owner edits in both directions, sync clock rebasing, and byte parity against a synthetic fixture executed from main e2edc7c. All 40 preflight checks pass. Changed-source Pyright has zero errors; legacy and batch Helm releases render successfully. All six GitHub Backend unit shards and the aggregate suite passed on exact head 8717ec9; applicable checks are terminal with no failures. The shared private-cache assignment scores 94.36% on 10,541 labeled words across all five conversations; cached baseline scores 93.29%. Original three: 95.26% versus 94.13%. Public natural-length AMI through the actual v2 HTTP route on a dev L4: 5/30/120 min RTF 0.02972/0.02953/0.03138, 1.62 GiB peak CUDA allocation, no OOM. Shared GPU, 40% CUDA memory cap, pinned pipeline/Torch in isolated Python 3.12 venv; shipping image is Python 3.11. Full receipt: backend/scripts/diarization_eval/capacity.md. No private words/audio/vectors are committed.
Deployment is lead-owned: additive diarizer image (existing default main eagerly initializes both embeddings and v1 before TCP readiness), then a separate batch Helm release using the same image and batch_main:app with DIARIZATION_V2_ENABLED=true on dedicated GPU pods, then backend/pusher flags off and a separate cohort flag PR. /v2/diarization routes through prod-omi-diarizer-batch:8080 ClusterIP; it is intentionally absent from the embedding ingress so it cannot consume that GPU. Legacy routes take no batch lock; only batch inference is serialized and decoding remains outside the lock. Batch startup failure is fatal. The existing release defaults and ingress remain unchanged. Disable authoritative/sync first and restore legacy mode for rollback; record rewrites have no automatic historical inverse.
Known limits: the Nemotron adapter requires a compatible serving endpoint and qualification. Background speaker-only promotions do not rerun earlier summary/memory effects; external derived references and ambiguous speaker projections veto promotion. Native exclusive private inference is not reconstructed from cached activity; the cache score qualifies the deterministic fallback. A separate batch endpoint with six L4 batch replicas initially, max eighteen, queue-depth target one. At 6,300 audio-h/day and 45% multi-speaker share (measured range 12–50%), the worst measured RTF requires 89.0 GPU-h/day. This sizing is provisional: RTF was measured with a 40% CUDA cap on a shared L4. The batch deployment is separate from live embeddings; ingress timeout and metrics adapter must be configured before cohort enablement.
Line-Count-Exception: backend/database/conversations.py | 3902 -> 3973 | Add a narrow adapter at the existing persistence or batch orchestration boundary; shared implementation lives in new focused modules.
Line-Count-Exception: backend/utils/sync/pipeline.py | 3169 -> 3195 | Add a narrow adapter at the existing persistence or batch orchestration boundary; shared implementation lives in new focused modules.
Line-Count-Exception: backend/utils/conversations/speaker_resolution.py | 1644 -> 1649 | Add a narrow adapter at the existing persistence or batch orchestration boundary; shared implementation lives in new focused modules.