Repository navigation
feat(stt): self-hosted spoken-language gate for prerecorded routing (P58) - #23264
Conversation
Parakeet serves POST /v2/language: MMS-LID-126 (fp16, GPU worker queue, loaded before the VRAM baseline) returns P(supported) over the Parakeet-25 languages and a route. Thresholds 0.90 for >=6 s, 0.95 below, never under 1 s. PARAKEET_LID_MODEL=off (code default) disables it; the charts select the model. /v2 also counts transcript text language (parakeet_output_language_total) as the wrong-language alarm. Backend: every unknown-language prerecorded probe also asks the self gate (shadow, default on, STT_PRERECORDED_LANGUAGE_GATE_SHADOW=false kills it) and records omi_stt_language_gate_shadow_total against the vendor decision, with a content-free log line for the dangerous direction. STT_PRERECORDED_LANGUAGE_GATE_PERCENT (default 0, uid cohort on legacy sync) replaces the vendor probe with the self gate; the backend re-derives the threshold rather than trusting the service route, and any gate failure falls back to today's vendor path. Batch intake is shadow-only until its worker accepts self_lid evidence. Regression: the staging Arabic 6 s canary (Modulate en 0.9258 -> Parakeet) routes multilingual under enforcement. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
facebook/mms-lid-126 is licensed CC-BY-NC-4.0 and cannot serve a commercial product. Whisper-base (openai/whisper-base, Apache-2.0) was the approved alternative: encoder plus one decoder step, softmax over the language tokens. Offline its highest P(supported) on unsupported speech was 0.679 at >=6 s and 0.941 on 3 s crops, so the short threshold rises to 0.97 (long stays 0.90). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…g-code eval Re-running the whole offline set (4,191 clips, 2,349 unsupported) through parakeet/language_gate.py found two unsupported clips above 0.90/0.97: Hindi 10.7 s read as Romanian at P(supported) 0.922 and a 3 s Indonesian crop read as Italian at 0.978. 0.95 (>=6 s) and 0.985 (<6 s) clear both with 0 misroutes; supported speech leaks to the paid vendor on 6/420 full clips, 21/420 6 s crops, 189/420 3 s crops and 100/420 8 kHz copies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Language ID takes a priority lane on the GPU worker so it never waits behind a queued transcription batch (backend timeout is 6 s). - /v1/transcribe prerecorded results feed the wrong-language alarm too (voice messages are undiarized /v1), off the response path; live-window does not. - /v2/language refuses uploads over 16 MiB before decoding. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Incident 2026-10-22 02:00Z: Modulate 429 "Insufficient credits" made every
prerecorded segment cost 5 POSTs (bytes path retried 3x on any exception,
URL wrapper recursed and re-entered it), and LID probe failures were
indistinguishable from unknown language.
- STT_PRERECORDED_VENDOR_FAIL_FAST (default on, call-time read, pure
config/prerecorded_vendor.py): only explicit false restores the exact
legacy 3-POST bytes / 5-POST URL retry ladder.
- utils/stt/vendor_guard.py: ModulateQuotaError (RuntimeError subclass,
'Modulate transcription failed' prefix kept) for 401/402/403/429 or an
insufficient-credits body (body never logged); per-endpoint thread-safe
circuit breaker (5 quota errors / 60s, one half-open trial) with gauge
omi_prerecorded_vendor_breaker_open{provider,endpoint}; burn counter
omi_prerecorded_vendor_audio_seconds_total{provider,endpoint,outcome}
fed by WAV-header seconds (STT) and probe seconds (LID).
- modulate_prerecorded_from_bytes: quota raises immediately; other
transient errors retry at most once behind 0.25-0.75s jitter;
verification-deadline and held-single-attempt guards unchanged.
- modulate_prerecorded: retries only the download, never re-enters the
bytes path; <=2 Modulate POSTs per URL call.
- detect(): exactly one omi_batch_pipeline_language_probe_total{outcome}
increment per call (accepted/invalid_response/quota/http_5xx/http_4xx/
timeout/transport/unsupported_format/no_key/skipped/breaker_open/error);
decisions unchanged; quota feeds the lid breaker.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
A non-quota trial failure (5xx, timeout) left trial_in_flight set, so the breaker stayed open until the process restarted and blocked every Modulate call. Release the trial and re-open for a window on any non-quota failure, and expire an abandoned trial after 360 s. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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. |
…he batch1 regression Co-Authored-By: Claude Opus 5.5 <[email protected]>
…3234) #23234 types Modulate out-of-credits (402, or 429 with a credits body) as a terminal TranscriptionFailure(PROVIDER_BUDGET_EXHAUSTED). Keep that outcome; Phase 0 now records its burn and feeds the breaker, and an open breaker tripped by budget refusals raises the same typed outcome. A plain 429 is a rate limit: transient, at most 2 POSTs. Quota (ModulateQuotaError) narrows to 401/403 and a credits marker on any other status. #23234's plain-429 test keeps its 3-attempt assertion under STT_PRERECORDED_VENDOR_FAIL_FAST=false. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e gate Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9324f59eb4
ℹ️ 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".
| # Spoken-language gate (/v2/language) for prerecorded routing. "off" is the | ||
| # kill switch: the endpoint returns 503 and backend callers keep their vendor path. | ||
| - name: PARAKEET_LID_MODEL | ||
| value: "whisper-base" |
There was a problem hiding this comment.
Expose the language endpoint through the ingress
Enabling the LID model here does not make its endpoint reachable: ingress.hosts[0].paths above omits /v2/language, with the same omission in the dev values. Deployed backends use these legacy ingress hosts for HOSTED_PARAKEET_API_URL, so self_detect() requests are routed to GCE's unmatched-path backend instead of FastAPI. Consequently, the default-on shadow always sees the self gate as unavailable, and enforcement silently falls back to the vendor; add /v2/language to both ingress path lists.
Useful? React with 👍 / 👎.
| if is_quota_error(e): | ||
| record_breaker_quota_error(ENDPOINT_STT) | ||
| # Quota/auth rejections are terminal: the account is out of credits, | ||
| # retrying only burns more vendor quota. The prefix keeps callers and | ||
| # tests matching 'Modulate transcription failed' working. | ||
| raise ModulateQuotaError('Modulate transcription failed: vendor quota error') from e |
There was a problem hiding this comment.
Preserve a terminal outcome for quota failures
For 401/403 or marker-based quota responses, this raises ModulateQuotaError, which is only a RuntimeError. utils/stt/outcomes.failure_from_exception() therefore maps it to a retryable UPSTREAM_ERROR, so sync/Cloud Tasks can retry the supposedly terminal failure; since the breaker opens only after five failures and is process-local, those retries can continue reaching the vendor. Raise or translate this to a non-retryable TranscriptionFailure, as the 402/credit-429 path already does.
Useful? React with 👍 / 👎.
| while self._running: | ||
| try: | ||
| item = self._queue.get(timeout=self._poll_timeout) | ||
| item = self._priority.get_nowait() | ||
| except queue.Empty: | ||
| continue | ||
| try: | ||
| item = self._queue.get(timeout=self._poll_timeout) |
There was a problem hiding this comment.
Bound language-ID priority bursts
Under sustained /v2/language traffic, this loop always drains _priority before taking any item from _queue; the 16 in-flight gate slots can be continuously replenished, so the priority queue need never become empty. ASR and embedding work uses the normal queue, meaning default-on shadow traffic can indefinitely starve live and prerecorded transcription until callers time out. Limit consecutive priority dequeues or otherwise interleave normal work.
Useful? React with 👍 / 👎.
| else: | ||
| # Gate unavailable in an enforced cohort falls back to today's vendor path. | ||
| decision = detect(audio, before_probe=before_probe, **audio_options) |
There was a problem hiding this comment.
Record the enforced vendor fallback centrally
When an enforced cohort receives a timeout, 503, or malformed self-gate response, this branch falls back to the vendor probe but emits only the new omi_stt_language_gate_enforced_total{route=vendor_fallback} counter. The shared fallback telemetry therefore misses the event, so existing fleet fallback dashboards and alerts cannot observe this degradation; call utils.observability.fallback.record_fallback when taking this branch.
AGENTS.md reference: backend/AGENTS.md:L314-L314
Useful? React with 👍 / 👎.
| with httpx.Client(timeout=GATE_TIMEOUT) as client: | ||
| response = client.post(base + '/v2/language', files={'file': ('language.wav', probe, 'audio/wav')}) |
There was a problem hiding this comment.
Update the owning transcription wire contract
This introduces a new backend-to-Parakeet POST /v2/language inter-service call and associated environment/rollout behavior, but the commit does not update backend/docs/listen_pusher_pipeline.mdx. That leaves the repository's owning transcription wire-contract document unaware of the endpoint and its fallback path; document the new call there alongside the implementation.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
| if not language_guard_enabled() or language_class(language) != 'unknown': | ||
| return LanguageDecision(code, 1.0, 'declared') | ||
| decision = detect(audio, before_probe=before_probe, **audio_options) | ||
| enforced, verdict = _self_gate(audio, surface, cohort_key, audio_options) |
There was a problem hiding this comment.
Keep shadow probing off the routing critical path
With the default shadow enabled and enforcement at 0%, _self_gate() completes before the vendor probe is started. A slow or unavailable Parakeet gate therefore adds the full six-second timeout to every unknown-language route; batch intake evaluates as many as 128 units sequentially, so a gate outage can delay one upload by many minutes even though shadowing is documented as routing-neutral and fail-open. Run the shadow call concurrently with the vendor probe or detach it from the routing result.
Useful? React with 👍 / 👎.
| 'p_supported': round(self.p_supported, 6), | ||
| 'language': self.language, | ||
| 'language_probability': round(self.language_probability, 6), | ||
| 'audio_seconds': round(self.audio_seconds, 3), |
There was a problem hiding this comment.
Preserve exact gate values across the wire
Rounding these routing inputs before returning them can make the backend reach a different verdict from the service. In particular, audio just below six seconds is rounded to 6.0, causing the backend to apply the 0.95 long-audio floor instead of the 0.985 short-audio floor; similarly, a probability just below either floor can round up to it. The backend deliberately re-derives the route from these response fields, so such clips can be sent to Parakeet even though decide() returned multilingual; return the unrounded values or transmit exact sample-count evidence.
Useful? React with 👍 / 👎.
…rt unchanged The #21910 helm guard requires the Parakeet pod template to match main apart from the reviewed dark flags, so a chart env for PARAKEET_LID_MODEL fails it. The model now defaults to whisper-base when unset; "off" (or any unknown value) is the kill switch. GPU worker tests pin it off so they never load the real model. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 01a3c1b0d4
ℹ️ 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".
| data = await file.read() | ||
| if len(data) > _LID_MAX_UPLOAD_BYTES: |
There was a problem hiding this comment.
Bound the upload before reading it into memory
When a client submits more than 16 MiB, await file.read() materializes the entire multipart payload before the size check runs, so the new cap does not actually bound process memory. An oversized request—or several of the 16 admitted requests concurrently—can consume memory far beyond the configured limit and potentially terminate the GPU pod; read at most _LID_MAX_UPLOAD_BYTES + 1 bytes or reject using the parsed upload size before materializing the body.
Useful? React with 👍 / 👎.
…sync, move ramp to 10-23 (#23282) ## Summary Three P58 language-gate follow-ups (lead rulings 2de1ea, ca3cc3): 1. **Sync metrics were dropped (fix).** `backend/deploy/cloud_run_gmp_sync.yaml` keeps only allowlisted `omi_*` names on backend-sync and backend-sync-backfill. `omi_stt_language_gate_*` (#23264) and `omi_prerecorded_vendor_*` (#23263) were not on the list. Legacy sync makes almost all prerecorded probes. Prod 10:05–10:35Z after train T: 23,015 vendor probes on sync with 0 shadow series, against 43/43 on backend. So the shadow readout that gates enforcement, and the Phase 0 vendor burn and breaker metrics, were invisible there. The PR adds both prefixes, plus a test that reads the real keep regex and asserts every such collector matches it. 2. **`/v2/language` was never routed (fix).** The `parakeet.omi.me` Ingress lists only `/v1/transcribe`, `/v2/transcribe`, `/v3/stream` and `/health`. Every gate call 404ed at the internal load balancer: on 10:47Z, the new cfbcf20 pods served `/v2/transcribe` and received zero `/v2/language` requests. This PR adds the path in prod and dev values. The #21910 pod-template guard now admits exactly that one Ingress path, on the same backend as `/v2/transcribe`; new mutation cases reject a different backend or any other path. It ships with a `gcp_parakeet` helm apply (an Ingress URL-map change, no pod restart from it). Rollback: `helm rollback prod-omi-parakeet`. Callers fall back to the vendor probe either way. 3. **Registry (chore).** The `STT_PRERECORDED_LANGUAGE_GATE_PERCENT` ramp `done_by` moves 2026-10-22 → 2026-10-23, with the ruling in the notes. On 10-22, the lead (ruling ca3cc3, under David's 6 h rule) ruled the same-day rollout not worth finishing: shadow accrues and enforcement ramps 5/25/100 off-peak on 10-23. The rendered doc was regenerated, and `check_feature_flag_registry.py` reports OK. No behaviour change. The sync allowlist takes effect on the next Cloud Run deploy of backend-sync and backfill, which must land before the 10-23 ramp readout. Failure-Class: FC-metric-dropped-by-scrape-allowlist ## Verification - `test_batch_audio_language.py` (new allowlist test), `test_attach_cloud_run_gmp_sidecar.py`, `test_fleet_deployment.py`, `test_parakeet_request_metrics.py`, `test_monitoring_gmp_shadow.py`: pass via `test.sh`. - `test_audio_fleet_helm.py` and the other 11 files that render Parakeet/Ingress charts: pass (dev and prod against current main). - Prod (ro-prod GMP): `omi_stt_language_gate_*` series exist only for service_name=backend. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Summary
Stacked on PR A (#23263,
p58/phase0-vendor-fail-fast, merged in with a merge commit): merge PR A first; this PR's ownchange is everything after it.
Self-hosted spoken-language gate for prerecorded STT routing (P58, approved by David 2026-10-22). Today a vendor
(Modulate) LID probe decides whether
multi-language audio may go to Parakeet, which transcribes only 25 Europeanlanguages. That probe costs ≈$34/day, blocked English entirely when Modulate ran out of credits (10-22 02:00–04:00Z),
and misroutes: staging canary 10-22 05:29Z sent 6 s Arabic to Parakeet as
en0.926, and soak003 sent 6 s Chineseas
en0.80–0.84.POST /v2/language: Whisper-base language-token head (fp16, Apache-2.0) through the GPU worker queue,loaded before the VRAM baseline; returns
p_supported(summed probability of the 25 TDT languages), the toplanguage and a route. Parakeet only if
p_supported ≥ 0.95(≥6 s) or≥ 0.985(1–6 s); never under 1 s.PARAKEET_LID_MODELdefaults towhisper-basein code (the chart is unchanged, per the fix(parakeet): bound backfill work and add demand-based packing #21910 pod-template guard);offis the kill switch. A load failure leavestranscription serving.
/v2/transcribealso counts transcript text language (parakeet_output_language_total) asthe wrong-language alarm.
STT_PRERECORDED_LANGUAGE_GATE_SHADOW=falsekills it): every unknown-languageprobe also asks the gate;
omi_stt_language_gate_shadow_totalrecords self vs vendor; the dangerous direction logsevent=language_gate_shadow_disagreementwith bounded codes and scores only. Routing unchanged.STT_PRERECORDED_LANGUAGE_GATE_PERCENT(default 0; uid cohort on legacy sync, audio-hash cohortfor voice): the gate replaces the vendor probe. The backend re-derives the threshold rather than trusting the
service
route, and requires the top language to be supported. Any gate failure falls back to today's vendor probepath. Batch intake stays shadow-only until its GPU worker accepts
self_lidevidence (Phase 4).MMS-LID-126 scored better offline but is CC-BY-NC-4.0, so it is not used.
Evidence (offline, through this serving code; not prod audio)
FLEURS 15 languages × 60 clips (full, 6 s, 3 s, 8 kHz copies) + owned synthetic corpus, 4,191 clips, 2,349
unsupported (
/Volumes/Ephemeral/scratch/p58-language-routing/eval/out/gate-whisper-base.final.jsonl):en0.926)ar, p_supported 0.0072 → multilingualzh, p_supported ≤ 0.011 → multilingualProduction enforcement is gated on the shadow readout (dangerous-direction disagreement ≤0.1% of self-Parakeet
segments, output alarm no worse than baseline) and a serving-SHA staging multilingual mini-soak.
Ramp plan (
STT_PRERECORDED_LANGUAGE_GATE_PERCENT)parakeet_output_language_totalnon-P25 share ≤ baseline; syncupstream_errorand empty-ASR rates flat; multilingual share within ±2 pp of shadow; Parakeet p99/GPU in bounds.PARAKEET_LID_MODEL=offorSTT_PRERECORDED_LANGUAGE_GATE_SHADOW=false.Deploy
Parakeet GPU image (prod-omi-backend; no chart change): 1 pod first, check VRAM after load (Whisper-base fp16 ≈150 MB) and
/v2/transcribep99, then fleet. Cloud Run backend services (config train) for the backend half. No new env neededfor shadow; enforcement percent is a later env flip.
Failure-Class: FC-deterministic-provider-rejection-burns-connect-retries
Line-Count-Exception: backend/utils/sync/pipeline.py | 3659 -> 3660 | passes the uid as the language-gate cohort key at the existing resolve_file call
Test plan
BACKEND_UNIT_TEST_FILE_LISTviabackend/test.sh:test_prerecorded_language_gate.py(38),test_batch_audio_language.py(62),test_parakeet_endpoints.py(62),test_parakeet_gpu_worker.py(72),test_parakeet_language_gate.py(19), all pass.make preflight(local lane) passed; feature-flag registry OK.language_gate.load('mps')over the 4,191-clip eval (table above).commit: GPU priority lane for language ID,
/v1prerecorded wrong-language alarm, 16 MiB probe cap.🤖 Generated with Claude Code