Repository navigation
fix(stt): classify Modulate out-of-credits (429 "Insufficient credits", 402) as provider_budget_exhausted - #23234
Conversation
…_exhausted
Velma-2 answered 429 "Insufficient credits" from ~02:00Z 2026-10-22 for over
an hour. The budget page keys on
omi_stt_stream_close_total{reason="provider_budget_exhausted"} and the
kind=account circuit; every Modulate path saw an untyped provider error, so
the page never fired and the outage surfaced through the generic sync
failure-rate alerts an hour late.
Live (utils/stt/streaming.py):
- in-stream budget markers gain "insufficient credits"; the marker tuple now
lives in stream_close.MODULATE_BUDGET_MARKERS so live and batch paths match
the same wordings
- a refused WebSocket upgrade is typed: HTTP 402, or 429 whose visible
refusal text (reason phrase, body, or header values) carries a budget
marker, records the stream close and raises ModulateConnectionRejection;
the configured chain benches kind=account through
ACCOUNT_REJECTION_REASONS, the legacy walk through
record_account_rejection
- a plain 429 stays rate-limited (provider_rate_limited / provider_429)
Prerecorded (utils/stt/pre_recorded.py):
- Modulate batch 402, or 429 with credits text, raises a terminal
TranscriptionFailure(provider_budget_exhausted, provider="modulate",
retryable=false) instead of a retryable upstream_error under
provider="unknown"; omi_sync_transcription_job_total gains the bounded
outcome value provider_budget_exhausted (vocabulary contract updated)
- Parakeet prerecorded unchanged: self-hosted, no billing response shape
Vendor bodies are matched, never logged or labeled; no key material touched.
Failure-Class: FC-deterministic-provider-rejection-burns-connect-retries
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: eea02330e9
ℹ️ 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".
| for index, item in enumerate(headers): | ||
| if index >= _MODULATE_REJECTION_HEADER_CAP: | ||
| break | ||
| parts.append(str(item[-1])[:_MODULATE_REJECTION_TEXT_CAP]) |
There was a problem hiding this comment.
Read values from the WebSocket header mapping
With the pinned websockets==12.0, InvalidStatusCode.headers is a Headers mapping, so iterating it yields header names rather than (name, value) pairs; item[-1] therefore appends only the final character of each name. When a 429's Insufficient credits text is available only in a response header—the legacy-client scenario this code is intended to handle—the refusal remains provider_rate_limited, so the budget metric, page, and account bench still do not fire. Iterate mapping values/items (while optionally supporting tuple sequences); the current test's list-of-tuples fake does not model the production container.
Useful? React with 👍 / 👎.
| return ' '.join(parts).lower() | ||
|
|
||
|
|
||
| def modulate_connect_rejection_reason(error: BaseException) -> Optional[str]: |
There was a problem hiding this comment.
Update the owned transcription pipeline documentation
This commit changes live WebSocket rejection classification and introduces a new prerecorded transcription outcome, but its changed-file set leaves backend/docs/listen_pusher_pipeline.mdx untouched. The backend guide explicitly requires that document to be updated alongside transcription or listen/WebSocket changes, so the operational pipeline contract remains stale unless this behavior is documented there.
AGENTS.md reference: backend/AGENTS.md:L159-L159
Useful? React with 👍 / 👎.
…dget_exhausted outcome value
…terministic-provider-rejection-burns-connect-retries guard artifacts
…vider_budget_exhausted outcome value" This reverts commit 0b098cf.
…budget value The released app-client OpenAPI froze components.schemas.TranscriptionOutcome and its generated decoders reject unknown values, so the internal provider_budget_exhausted value must not reach response models or error payloads. Response models now carry models/transcription_wire.TranscriptionOutcome (same class name, frozen values, identical $ref target); TranscriptionFailure.as_detail() maps the budget outcome onto upstream_error while the error code keeps stt_provider_budget_exhausted. The regenerated app-client export is byte-identical to main's.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca0142d4ae
ℹ️ 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".
| raises here instead of silently laundering past the frozen contract. | ||
| """ | ||
|
|
||
| from config.prerecorded_stt import TranscriptionOutcome as InternalOutcome |
There was a problem hiding this comment.
Move the enum import to module scope
Move InternalOutcome to the module imports rather than importing it each time from_internal() runs. This newly added function-local import violates the backend's explicit import convention, and config.prerecorded_stt is a pure configuration module, so there is no apparent import-time side effect requiring the lazy import.
AGENTS.md reference: backend/AGENTS.md:L163-L163
Useful? React with 👍 / 👎.
| 'stt_timeout': TranscriptionOutcome.TIMEOUT, | ||
| # Budget outranks the generic upstream error so a job that hit an | ||
| # out-of-credits provider keeps the actionable outcome at rollup. | ||
| 'stt_provider_budget_exhausted': TranscriptionOutcome.PROVIDER_BUDGET_EXHAUSTED, |
There was a problem hiding this comment.
Add the budget outcome to the finalized-job whitelist
When a sync job rolls a segment failure up through this mapping, its result contains outcome="provider_budget_exhausted", but database/sync_jobs.py still omits that token from _SYNC_JOB_OUTCOMES; consequently _log_sync_job_finalized() rewrites the canonical finalization event to upstream_error. This makes the finalization log contradict the new segment/job metrics precisely during the budget incident this change is intended to identify, so the whitelist and its contract test should include the new bounded outcome.
Useful? React with 👍 / 👎.
| raise TranscriptionFailure( | ||
| TranscriptionOutcome.PROVIDER_BUDGET_EXHAUSTED, | ||
| provider=PrerecordedSTTService.MODULATE, | ||
| retryable=False, |
There was a problem hiding this comment.
Preserve the provider that produced the budget outcome
When Parakeet is the selected sync provider but its double-empty recovery calls Modulate, this exception is correctly recorded at segment level with provider='modulate', but the job rollup retains only error-code strings and later labels the promoted provider_budget_exhausted outcome with the original sync_provider/sync_model. The resulting omi_sync_transcription_job_total and stored final result therefore report a Parakeet budget failure even though Modulate rejected the recovery call; carry the provider/model associated with the error code into the job rollup.
Useful? React with 👍 / 👎.
| 'monthly usage limit', | ||
| 'usage limit reached', | ||
| 'quota exceeded', | ||
| 'insufficient credits', |
There was a problem hiding this comment.
Honor in-stream budget typing in the legacy connect walk
When the legacy (use_config=False) Modulate path accepts the upgrade and then emits the newly recognized Insufficient credits frame during its liveness grace, typed_death_reason is provider_budget_exhausted, but the primary not-serving branches reparse the raw detail with _fallback_failure_reason(), which does not match credits and records provider_5xx; the fallback helper likewise rethrows a plain RuntimeError. Consequently the account circuit never opens, so the exhausted credential is retried after the short selection cooldown and by fallback legs that ignore that selection bench; propagate the typed budget reason into record_account_rejection() through both paths.
Useful? React with 👍 / 👎.
…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]>
…r budget (#23271) ## Why - **Local delivery deaths are no longer covered.** P34 (#23074, train P 2026-10-21 22:24Z) moved Soniox/Modulate local delivery deaths off `reason="capacity_full"`. `omi-stt-capacity-full-exhausted` therefore no longer sees sessions exhausted by our own send path. - **Vendor out-of-credits paged nothing purpose-built.** Modulate's 429 "Insufficient credits" (2026-10-22 from ~02:00Z) was only caught ~1h late, by the generic sync failure-rate rules. #23234 now types it `provider_budget_exhausted` on `omi_sync_transcription_job_total`. ## What | Rule | Severity / for | Condition | |---|---|---| | `omi-stt-local-delivery-exhausted` (Live STT) | warning / 30m | `omi_fallback_total{component="stt_live_session",reason=~"send_queue_full\|replay_send_stalled\|delivery_expired",outcome="exhausted"}` / listen-accepted > 0.03, with >= 100 accepted per 15m | | `omi-sync-provider-budget-exhausted` (Backend-sync, gmp-cloud-run) | critical / 5m | `sum by (namespace) increase(omi_sync_transcription_job_total{outcome="provider_budget_exhausted"}[15m]) >= 3` on backend-sync and backfill | - **Where the rules live:** in `alert-rules.json` and the split exports (`alerts/live-stt.json`, `alerts/backend-sync.json`). - **Supporting changes:** - the live-STT rule is added to the pusher live-alert import allowlist (`live-alert-gate.json`, `verify_pusher_live_alert_route.py`); - the GMP inventory is regenerated; - a contract test is added. ## Verification - **Backtest of the local-delivery rule** (prod Prometheus, 15m steps): | Window | p50 | max | Result | |---|---|---|---| | Post-P34, pre-#23147 (10-21 22:40Z to 10-22 03:10Z, replay-pacing bug live) | 0.039 | 0.060 | fires | | Post-#23147 (10-22 03:40Z to 08:00Z) | 0.000 | 0.012 | silent | Thresholds were set off-peak; I'll revisit after the 10-22 14–16Z peak read. - **Budget rule:** the outcome is new, so there is no history. It stays silent until #23234 is deployed to Cloud Run. - **Tests:** `BACKEND_UNIT_TEST_FILE_LIST` covering all 25 monitoring, alert and GMP unit files passes. Review: infra rollout lead before merge. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23271?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/23271?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23271&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
… burn counter (P58 Phase 0) (#23263) ## Summary P58 Phase 0 (approved by David 2026-10-22): prerecorded Modulate calls fail fast instead of amplifying a vendor outage. On 10-22 02:00–04:00Z Modulate returned 429 "Insufficient credits"; every failed segment cost 5 POSTs (bytes path attempts 0/1/2, then the URL wrapper re-entered at 1/2) and the LID probe swallowed the 429 as `und`. - **Out-of-credits keeps #23234's typed outcome**: 402, or 429 with a credits body, raises `TranscriptionFailure(PROVIDER_BUDGET_EXHAUSTED, retryable=False)` after **1 POST**; Phase 0 adds its burn accounting and breaker feed. Other auth/quota rejections (401/403, or a credits marker on another status) raise `ModulateQuotaError` (a `RuntimeError` keeping the `Modulate transcription failed` prefix, so classification is unchanged: `UPSTREAM_ERROR`, retryable) after 1 POST. A plain 429 is a rate limit and stays transient. - **Transient errors** (5xx, timeout, transport, malformed body) retry once with 0.25–0.75 s jitter: **≤2 POSTs**. The URL wrapper retries only the download and never re-enters the paid path. - **Circuit breaker** per endpoint (`stt`, `lid`), process-local: 5 quota errors in 60 s open it; while open, calls make no HTTP request; after 60 s one half-open trial (success closes, quota re-opens, non-quota failure releases the trial and keeps it open; an abandoned trial expires after 360 s). A breaker opened by budget refusals raises the same typed `PROVIDER_BUDGET_EXHAUSTED` outcome, so #23234's page and sync outcome counting hold. Gauge `omi_prerecorded_vendor_breaker_open`. - **Signals**: `omi_batch_pipeline_language_probe_total{outcome}` (one per `detect()` call: accepted, quota, http_5xx, http_4xx, timeout, transport, invalid_response, unsupported_format, no_key, skipped, breaker_open, error) and `omi_prerecorded_vendor_audio_seconds_total{provider,endpoint,outcome}` (Modulate burn, the missing spend signal). `detect()` returns exactly the same decisions as before. - **Kill switch** `STT_PRERECORDED_VENDOR_FAIL_FAST` (default on; only `false` restores today's exact retry ladder and disables the breaker). Not done: the voice-message `stt_provider` mislabel needs the selected provider surfaced from the transcription call; out of the contained budget, left for a follow-up. Failure-Class: FC-deterministic-provider-rejection-burns-connect-retries ## Test plan - `backend/test.sh` with `BACKEND_UNIT_TEST_FILE_LIST`: `test_prerecorded_vendor_fail_fast.py` (35: quota → 1 POST, 503/timeout → 2 POSTs, URL 429 → 1 GET + 1 POST, kill switch → legacy 3/5 POSTs, breaker open/half-open/re-open/ wedge/expiry, every `detect()` outcome), `test_modulate_prerecorded_language.py` (49), `test_batch_audio_language.py` (62); 14-file related set 182 passed. - Three existing tests that encode the legacy 3-POST ladder (two in `test_modulate_prerecorded_language.py`, #23234's `test_plain_429_stays_a_retryable_upstream_error`) now pin it with `STT_PRERECORDED_VENDOR_FAIL_FAST=false` (assertions unchanged); the new behaviour (2 POSTs) is asserted in the new file. After merging main: 280 pass across the fail-fast, modulate STT, modulate language, batch language and transcription-outcome suites. - `scan_async_blockers.py`, `scan_import_time_side_effects.py`, feature-flag registry: clean. - Independent GLM review: see PR comment. ## Deploy / rollback Cloud Run backend services (backend, backend-sync, backend-sync-backfill, backend-integration) via the normal train. Rollback: `STT_PRERECORDED_VENDOR_FAIL_FAST=false`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…r budget P34 (BasedHardware#23074) moved Soniox/Modulate local delivery deaths off capacity_full, so omi-stt-capacity-full-exhausted no longer sees them. Add omi-stt-local-delivery-exhausted (warning, >3% of accepted sessions exhausted on send_queue_full|replay_send_stalled|delivery_expired, >=100 accepted/15m, for 30m). Backtest: fires through the pre-BasedHardware#23147 pacing bug (p50 0.039, max 0.060), silent after BasedHardware#23147 (max 0.012). Modulate's 429 "Insufficient credits" (10-22 from ~02:00Z) paged nothing purpose-built. BasedHardware#23234 types it provider_budget_exhausted on sync jobs; add omi-sync-provider-budget-exhausted (critical, >=3 jobs/15m on backend-sync or backfill via gmp-cloud-run, for 5m). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Why
Since ~02:00Z 2026-10-22, Modulate (Velma-2) has answered 429 "Insufficient credits"
when the account is out of credits. The purpose-built page "Live STT - provider
budget/quota exhausted (top up)" keys on
omi_stt_stream_close_total{reason="provider_budget_exhausted"}plusomi_stt_provider_circuit_open{kind="account"}. The vendor's out-of-credits answerreached us as an untyped 429/HTTP error, so the page never fired and the outage was
found an hour late, through the generic sync failure-rate alerts.
What changed
Backend only, one theme — classify Modulate out-of-credits (402, or 429 "Insufficient
credits") as
provider_budget_exhausted:backend/utils/stt/stream_close.pyMODULATE_BUDGET_MARKERStuple, now including"insufficient credits". No new stream-close reason values.backend/utils/stt/streaming.pymodulate_death_reason); a refused WebSocket upgrade is typed via the shared seamtyped_modulate_connect_failure(classify + record + raise) —modulate_connect_rejection_reasonfor the rule,ModulateConnectionRejectionfor the typed token; the legacy walk (_fallback_failure_reason+ both except ladders) classifies it and benches the account circuit for budget.backend/utils/stt/live_target_connect.pybackend/utils/stt/live_chain.pyfailure_reasonmapsModulateConnectionRejectionto its bounded token soACCOUNT_REJECTION_REASONSdrivesrecord_account_failure+health.quarantine(kind='account')— the same path as Soniox's typed budget death.backend/utils/stt/connect_metrics.pyprovider_rate_limitedfolds to error_classrate_limited(provider_429 already did).backend/utils/stt/pre_recorded.pyTranscriptionFailure(never retried, never re-wrapped by the RuntimeError ladder); the URL variant passes it through.backend/config/prerecorded_stt.pybackend/utils/stt/outcomes.pystt_provider_budget_exhausted, non-retryable,provider='modulate'.backend/utils/sync/pipeline.py_SYNC_ERROR_CODE_OUTCOMESmaps the new error code (budget outranks generic upstream at job rollup); the closed reason-code set gains it.backend/models/transcription_wire.py+backend/routers/chat.pycomponents.schemas.TranscriptionOutcome, so response models carry a frozen same-named wire enum (identical$ref, byte-identical regenerated export) andas_detail()maps the budget outcome ontoupstream_errorwhile theerrorcode keepsstt_provider_budget_exhausted.tests/unit/test_modulate_serve_error_deaths.py,tests/unit/test_modulate_stt.py,tests/unit/test_transcription_outcomes.py.Outcome value (new, bounded, server-side only):
provider_budget_exhaustedon
omi_sync_transcription_job_total(and the sibling segment /voice-transcription counters that consume
TranscriptionOutcome), withprovider="modulate"instead of"unknown"on this failure. The wire-facingoutcome enum is unchanged (frozen by the released app-client contract; see the
table above). The vocabulary contract test pins both sets; the metric family
stays in the declared-sparse set (children appear on real outcomes); exporter
prefixes and alert rules are unchanged (the observability lane adds the
sync/prerecorded budget-alert sibling once this lands).
Exact matching rule for 429 (case-insensitive substring on lowercased text; the
markers are
monthly usage limit|usage limit reached|quota exceeded|insufficient credits):still visible on the rejected-upgrade exception (HTTP reason phrase, body (capped
at 2000 chars), or header values (capped at 50) — websockets 12.0's legacy client
keeps only status + headers, so headers are the live surface there) contains a
marker; a plain 429 stays rate-limited (
provider_rate_limitedstream-close,rate_limitedconnect error class) and never trips the account circuit. Any otherstatus stays unclassified.
modulate_death_reasonnormalization(strip / lowercase / drop trailing period).
contains a marker; otherwise
raise_for_status()keeps the retryableupstream_errorpath.Parakeet prerecorded is intentionally untouched (self-hosted, no billing response
shape). Vendor bodies are matched but never logged or used as label values; no keys
are read, printed, or rotated. No
.githubchanges.Verification
scripts/select_backend_unit_tests.py --changed-files <changed paths>→BACKEND_UNIT_TEST_FILE_LIST=<list> ./test.sh(backend worktree venv, nice -n 19,rebased on current main): 413 file-isolated sessions, 12,699 tests passed,
0 failures, exit 0.
.venv/bin/python -m pytest tests/unit/test_modulate_serve_error_deaths.py tests/unit/test_modulate_stt.py tests/unit/test_transcription_outcomes.py -q→168 passed. These drive the real
SafeModulateSocketreceive loop, the realprocess_audio_modulateconnect path (patchedwebsockets), and realhttpxstatus-error shapes on the batch path — unit layer, no live vendor calls.case, trailing punctuation) → budget (in-stream frame, connect phrase/body/header,
batch body); plain 429 → not budget (rate-limited, retried, no account bench);
other statuses unclassified; outcome vocabulary contract updated.
GLM pre-PR review on a detached copy: round 1 (head 63f3231b) VERDICT: SHIP —
one P2 (routed registry-endpoint dial bypassed the connect-time typing) and two
minors (duplicate import; uncapped header value) — all three fixed in the delta;
round 2 delta review (head e9fa71af) VERDICT: SHIP, no findings (fix verified
complete, tests load-bearing, no remaining Modulate dial bypasses the seam). One
pre-existing non-blocking observation noted for a possible follow-up: the routed
dial does not call
observe_connect_secondson success while the default dial does.Line-Count-Exception: backend/utils/stt/streaming.py | 2466 -> 2603 | typed Modulate connect-rejection classifier + shared seam and the two legacy-walk classification branches; provider-local, no natural split without moving live-STT selection logic in an incident-fix PR
Line-Count-Exception: backend/utils/sync/pipeline.py | 3647 -> 3651 | one bounded outcome mapping entry and the matching closed reason-code token
Line-Count-Exception: backend/routers/chat.py | 1800 -> 1803 | wire-frozen outcome enum import and boundary comments on the two response models
Failure-Class: FC-deterministic-provider-rejection-burns-connect-retries