Repository navigation
fix(stt): fail over prerecorded Modulate refusals to Soniox - #25029
Conversation
Preserve bounded paid attempts, serving metadata, and an explicit default-on rollback switch. Failure-Class: new
Codex Review Summary: ✅ CompletedThis 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. |
Accept existing two-value voice adapter results while retaining opt-in serving metadata. Preserve the default single-language STT call signature by omitting unrequested language and provider options. Failure-Class: FC-prerecorded-single-vendor-refusal-outage
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4000035560
ℹ️ 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".
| words, detected_language = soniox_transcribe( | ||
| audio_bytes, | ||
| duration, | ||
| language=language, | ||
| failover=True, |
There was a problem hiding this comment.
Keep Soniox polling outside the shared sync executor
When Modulate refuses credits and Soniox remains queued or processing, this invokes the synchronous Soniox adapter, which polls with time.sleep() for up to 120 seconds. Both voice handlers in backend/routers/chat.py and segment processing in backend/utils/sync/pipeline.py execute this path on the shared 16-worker sync_executor; 16 overlapping replacements therefore occupy every worker and stall unrelated sync work until transcription completes or times out. Unlike the previous terminal credit refusal, the new outage path introduces a long-lived polling coordinator into that pool. Use the existing asynchronous Soniox client with coordination outside the executor rather than retaining a worker throughout polling, as required by the backend execution guidance.
AGENTS.md reference: backend/AGENTS.md:L275-L275
Useful? React with 👍 / 👎.
| # An explicit unsupported hint keeps the original Modulate failure. | ||
| if normalized_language not in {'', 'multi'} and not soniox_accepts_language_hint(normalized_language): | ||
| raise | ||
| duration = _wav_duration_seconds(audio_bytes) |
There was a problem hiding this comment.
Measure WebM and MP4 duration before authorizing failover
For browser voice recordings, this duration calculation always returns zero: _wav_duration_seconds only parses WAV or FLAC, while backend/routers/chat.py:768-771 deliberately preserves uploaded .webm and .mp4 files without conversion, and the signed-URL helper uploads their original bytes. These are the formats produced by web/app/src/components/chat/VoiceRecorder.tsx:10. After a Modulate credit refusal, Soniox's authorization consequently rejects the zero duration before making any request, so the new failover never recovers browser voice messages. Decode or probe the supported containers, or normalize them to WAV, before applying the positive-duration bound.
Useful? React with 👍 / 👎.
| # In particular, a Soniox 429 is terminal and returns the original | ||
| # Modulate error class. Timeouts after submission have unknown | ||
| # billing state too; neither case loops or tries another provider. | ||
| raise modulate_error |
There was a problem hiding this comment.
Preserve the original exception chain when failover fails
If a non-budget Modulate breaker is open and the Soniox key is missing, raising modulate_error inside this nested handler attaches the Soniox configuration exception as its __context__. failure_from_exception in backend/utils/stt/outcomes.py traverses that context and prioritizes configuration errors, so the voice boundary converts the original retryable Modulate upstream_error into a non-retryable Soniox config_error (HTTP 503 instead of 502). Thus catching the replacement failure does not actually preserve the original public failure semantics, and clients are told not to retry a temporary breaker failure. Preserve the original causal chain without attaching the replacement exception when rethrowing.
Useful? React with 👍 / 👎.
What changed and why
The 2026-11-10 Modulate credit refusal made pre-recorded voice transcription return 502. A selected Modulate provider now retries the same audio once through the existing Soniox batch client on a typed credit refusal or a local open breaker, under a default-on kill switch. Soniox language, serving-surface and positive duration bounds remain mandatory; Deepgram is never selected.
Successful voice responses retain their shape and report Soniox's actual provider/model. Multipart responses disclose Soniox if any segment used it. Sync transcript storage and bounded outcome telemetry also retain the serving model.
Product invariants affected
INV-DATA-1: preserves existing account, Firebase and serving authorities; this is not a data-plane migration. INV-MEM-4: preserves canonical promotion and projection authority; the runtime manifest change only registers the STT kill switch. Preserve audio custody, released response fields, language resolution and one paid replacement attempt. Empty Modulate results, direct auth/client failures and transient errors do not trigger fallback. A prior failed Modulate POST suppresses fallback even if a later retry receives a credit refusal, because the prior billing state cannot be proved safe. A Soniox 429 ends this failover immediately and preserves the original Modulate failure class.
Tuning
PRERECORDED_SONIOX_FAILOVER_ENABLED is new: initial 1 (true); false restores the previous Modulate-only behavior. Before: 0 replacement providers; after: at most 1 Soniox transcription submission after a qualifying refusal. Existing Soniox limits are unchanged: duration greater than 0 and at most 7200 seconds, 120-second client deadline. No added workers, capacity, queues or rollout cohorts. Owner refactor-lead; flag budget review_by 2026-11-24.
New states and exits
No durable state is added. A qualifying Modulate refusal either recovers via Soniox or exits exhausted with the original Modulate error. Soniox rate limiting never loops. Held recovery, prompt verification and fenced batch calls (attempts >= 2) keep their coordinator-owned attempt and receipt budgets; they cannot gain this implicit paid hop. Their separate recovery route is unchanged. An explicitly constructed Parakeet provider's internal fleet-off escape is outside the selected-Modulate fallback boundary; ordinary fleet-off selection chooses Modulate before dispatch.
Resumed-lane audit and scope
Kept the prior shared fallback structure, existing Soniox adapter, default-on flag and bounded telemetry. Kept chart, workflow, runtime manifest/generator and reference-test changes because each only registers the kill switch in a distinct serving configuration source; no new workflow is added. Kept a compact backend/AGENTS.md provider-map update and link to the owned transcription contract; dropped its verbose duplicated provider/flag prose to satisfy the guide's existing byte budget. Kept the env/pipeline and transcription documentation.
Changed refusal classification to reject direct 401/403 auth failures, stopped Soniox's internal 429 retries for this call, preserved uncertainty across Modulate retries, protected coordinator-owned attempts, corrected multipart and sync serving metadata, and added real HTTP-transport/route regressions. Dropped the unused Soniox deadline override. The follow-up below restores the existing two-value adapter result at the HTTP boundary. No unrelated prior file changes were retained.
CI regression follow-up
Run 42792050758 at daf9d35 exposed two call-contract regressions introduced by metadata propagation: voice handlers unconditionally unpacked four values from existing two-value transcription adapters, and default single-language PCM calls gained
return_language=False/return_provider=Falsekeywords. The resulting ValueError/TypeError was mapped to HTTP 400 or media_transcription failures. The HTTP boundary now accepts the existing two-value adapter result and retains actual provider/model metadata when supplied. Default calls omit unrequested optional keywords. No existing tests were changed. All 18 CI-reported regressions pass locally.How it was verified
BasedHardware/omi, worktree omi-lane-sonioxprerec-upstream-keep-clean, branch lane/sonioxprerec, additive commit 4000035. All unit runs use normal /Users/dazheng/workspace/omi/bin/omi-heavy admission and the repository's file-isolated bash backend/test.sh, with credential-scrubbed env, BACKEND_UNIT_FILE_BUDGET_SECONDS=3600 and BACKEND_PYTEST_WORKERS=2. Verification measures local backend behavior with synthetic audio and provider fakes. GCP tier: none; no production access or deployment.
The first normal credential-scrubbed push passed all 67 shared preflight checks, backend type validation, all eight hook-selected unit files, OpenAPI/released-client compatibility, runtime-env and pinned-formatting checks. No hook or check was skipped. The follow-up was pushed normally on top of daf9d35; no amend, rebase or force-push was used. GitHub CI for 4000035 is tracked separately from these local checks.
Tests
The scope covers all available STT, pre-recorded, voice-message and chat-route files from shards 5/8, with a conservative superset of shared quota/runtime/coordinator references and four direct fallback/metadata suites outside those shards. Lists and receipts are in .agent-brief/ci-regression-test-files.txt, ci-regression-extra-files.txt and ci-regression-results.json.
Logs: .agent-brief/ci-regression-tests.log, ci-regression-extra-tests.log, desktop-all-tests.log and native-audio-rerun.log. The original failure list and CI logs remain available for comparison. Tests and source verification are separate from GitHub CI and deployment.
UI evidence
UI-Evidence: none -- backend change only.
Failure class
Failure-Class: new
The new FC-prerecorded-single-vendor-refusal-outage defines the violated contract: an explicit vendor refusal must degrade without duplicating uncertain paid work or changing client responses. The shared bounded failover and behavioral tests in test_prerecorded_soniox_failover.py and test_soniox_batch.py provide its reusable prevention surface. The 2026-11-10 outage in the original brief is the incident evidence; this PR is its first fix.
Rollback and landing
Set PRERECORDED_SONIOX_FAILOVER_ENABLED=false on the declared runtime hosts. Default is on. This PR does not mutate production settings. Two independent Luna lenses reviewed the candidate and found no blocking issues after fixes. The runtime lens accepted strict unresolved-language exclusion; the contract lens confirmed sync callback propagation, multipart aggregation and deployment registration scope. Route acceptance metrics retain their original selected-provider attribution; actual replacement spend and success are separately recorded by the Soniox vendor-burn and fallback metrics. The CI regression follow-up is also reviewed by both Luna lenses. Lead2's MERGE-OK and the next release train remain required; do not merge from this lane. GitHub CI is tracked separately from this local verification.
Scoped file growth
Line-Count-Exception: backend/routers/chat.py | 1809 -> 1828 | Propagate actual serving metadata through the two existing voice handlers without restructuring unrelated routes.
Line-Count-Exception: backend/utils/stt/pre_recorded.py | 1484 -> 1648 | Keep the shared refusal boundary beside both selected-Modulate adapters so bytes, URL, coordinator budgets and paid retry uncertainty share one policy.
Line-Count-Exception: backend/utils/sync/pipeline.py | 4005 -> 4010 | Add one serving-metadata callback at the existing STT boundary; avoid an unrelated sync coordinator refactor.