Repository navigation
fix(stt): enforce finite allowances before sync and batch cloud spend - #23388
Conversation
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: b01f573159
ℹ️ 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".
| def offline_admission_enabled(uid: str, lane: str) -> bool: | ||
| """Sync/batch spend fails closed independently of the legacy live rollout.""" | ||
| return bool(uid) and (offline_enforcement_enabled(lane) or execution_admission_enabled(uid, lane)) |
There was a problem hiding this comment.
Gate the batch intake language probe with offline admission
When offline enforcement is on but the legacy batch lane is unselected—which is the default because _BATCH_LANE_READY is false—the intake callback in backend/utils/batch_pipeline/intake.py:515-516 still short-circuits on not execution_admission_enabled(...). For an upload with an unknown language, resolve_language() therefore sends the paid Modulate LID request without ever calling sync_allowed, even for an exhausted account. Route this boundary through the new offline predicate (while preserving the admitted BYOK exception), otherwise capped batch uploads can continue generating cloud-provider spend before the later GPU/provider gates hold them.
Useful? React with 👍 / 👎.
| def offline_enforcement_enabled(lane: str | None) -> bool: | ||
| """Ship existing sync/batch allowance enforcement on; never widen live scope.""" | ||
| return lane in {'sync', 'batch'} and default_on('STT_CAP_OFFLINE_ENFORCEMENT') |
There was a problem hiding this comment.
Wire the offline kill switch into serving manifests
The new policy defaults on whenever STT_CAP_OFFLINE_ENFORCEMENT is absent, but the repository's deployment contracts never set or expose that variable: I checked backend/deploy/runtime_env.yaml, _base.yaml, and the batch worker chart, whose template only wires the older cap flags. Consequently the documented rollback cannot be applied through the normal Cloud Run/runtime-env or Helm deployment paths; in particular, a batch worker continues requiring policy authorization and can stall during the incident that prompted rollback if its policy host is unavailable. Add this variable to the relevant runtime-env entries and to a batch-worker value/template so operators can durably set it to false.
Useful? React with 👍 / 👎.
| if admitted_as_byok(job): | ||
| record_decision(DispatchPath.SPEECH_REDRIVE, True, DispatchReason.BYOK) | ||
| elif not sync_allowed(uid, item.duration_seconds, 'modulate', lane='batch', path=DispatchPath.SPEECH_REDRIVE): |
There was a problem hiding this comment.
Meter accepted speech redrives under offline enforcement
For an account admitted only by the new default-on offline scope, this branch can now authorize and execute the Modulate redrive, but the success path at speech_redrive.py:136 still guards record_audio with the legacy execution_admission_enabled alias. Because batch legacy selection is code-fenced off, successful offline-only redrives never contribute accepted seconds to omi_stt_cap_provider_audio_seconds_total, undercounting exactly the provider spend the rollout instructions require operators to monitor. Use the offline admission predicate for the post-call metering guard, as the GPU and quarantine paths now do.
Useful? React with 👍 / 👎.
…ror connections (#23406) ## Summary The `Backend Unit Tests` shard job's `Install native audio replay dependencies` step died three times on 2026-10-23 with the identical signature (`##[error]The action 'Install native audio replay dependencies' has timed out after 5 minutes.` mid-download against `azure.archive.ubuntu.com`): - [Run 39951629124 shard 1](https://github.com/BasedHardware/omi/actions/runs/39951629124/job/120407218965) (PR #23388, 12:19Z) — 15 of 87 packages fetched when the 5m ceiling hit; Gets 6→11 alone took 4m15s. - [Run 39954484165 shard 2](https://github.com/BasedHardware/omi/actions/runs/39954484165) (12:41Z) — same cache-miss + crawl + timeout. - [Run 39929405042 shard 4](https://github.com/BasedHardware/omi/actions/runs/39929405042) (09:12Z) — same signature. Flake, not a regression: in run 39951629124 itself, shard 5/6 ran the identical cold download (same total cache miss on both the primary key and the `restore-keys` prefix) and finished the whole 62.8 MB set in ~60-90s on a healthy connection. The trigger was the eviction of the repo's only `native-audio-apt-v1-*-ubuntu24-*` cache entry (a fresh one was saved by a main run at 12:50Z, after which runs went warm again): with no cache, every shard cold-downloads, and the ones whose apt connection lands on a degraded mirror path crawl below the 5m ceiling. Why the existing bounds don't cover it: apt rides **one pipelined TCP connection per mirror host**, and `Acquire::http::Timeout=30` only bounds *silent* reads — a trickling connection never trips it (shard 1 fetched a 66 kB package in 1.2s, then spent 4m15s on the next four). ## Changes **`backend-unit-tests.yml`, only inside this flake's own step** (plus the one contract line that pins the job's budget): - **`recycle_apt` connection recycling for the network-bearing commands** (`update` and cold/repair `install`): each runs under `timeout --signal=TERM --kill-after=15 120s` and is restarted until a shared **450s step-wall budget**. Completed `.deb`s persist in `Dir::Cache::archives`, so every restart *resumes* the download rather than starting over, on a fresh mirror connection — converting an indefinite crawl into bounded slices. A control-flow simulation (stub `apt-get`: two crawling invocations, then success) confirms kill/restart/recover and bounded failure when the mirror never recovers. - **Warm path untouched**: cached closures still replay via `dpkg -i` with no network at all; recycling only engages when the replay fails or the cache is cold. - **Step ceiling 5m → 10m** on measured evidence (three cold downloads past 300s in one day; fast path 60-90s): bounds the worst recycled cold wall at ~570s (last slice starts at SECONDS<450 + 120s slice). - **Job ceiling 20m → 25m**, re-pinned in `scripts/ci/test_nightly_main_workflow.py`'s `INTENTIONAL_BUDGET_CHANGES` (the reviewed path this registry exists for): 25m keeps the hang bound above worst-plausible setup (72s worst checkout + ~90s toolchain + ~570s apt) plus the unchanged 720s test budget, preserving the invariant documented on the job. The 720s step regression gate is unchanged and warm-path walls are identical, so `budget_p50` stays 8 in `.github/ci-budget.yaml` (no fixture change needed — timeouts are not a pinned field). `.github` is edited only for this flake's own step, no workflows added, per the 10-22 CI flake-fix and caching direction from David. ## Verification - `actionlint` clean; `bash -n` on the rewritten run block; recycle loop simulated with stub commands (recover and bounded-exhaustion cases). - `scripts/ci/test_nightly_main_workflow.py` (5 tests), `.github/scripts/test_check_ci_budget.py` + `test_check_workflow_apt_network_bounds.py` (30 tests) pass locally with the locked backend venv. - `scripts/run-workflow-apt-network-bounds.sh` OK across all 84 workflows / 12 composite actions (the step keeps its `timeout-minutes`). - `scripts/pr-preflight --suggest`: ci lane, no product-invariant citations, no failure-class declaration required. ## Risk - A restart can land mid-`dpkg`-unpack only in the narrow window where a slice expires after the download completes; the next iteration's `install -y -f` resolves the partial state, and the same repair already existed for the replay-failure path. - The 450s budget failing red on a truly dead mirror is 10m instead of 5m of lost wall — bounded and rare, versus today's guaranteed red on any crawl. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/23406?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/23406?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23406&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. -->
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 35d196033c
ℹ️ 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 not offline_admission_enabled(uid, lane): | ||
| return TranscriptionAllowance('managed', None, 'dispatch_scope_disabled', limit_seconds=None) | ||
| if not enabled() and execution_admission_configured(): | ||
| if not enabled() and not offline_enforcement_enabled(lane) and execution_admission_configured(): |
There was a problem hiding this comment.
Apply launch-date validation to offline-only enforcement
When offline enforcement is enabled without legacy cohort membership, a missing or malformed SUBSCRIPTION_LAUNCH_DATE still permits cloud spend for exhausted finite-plan accounts. This path calls resolve_transcription_allowance(), but its usage reader, get_monthly_usage_for_subscription(), rejects invalid configuration only when any_legacy_admission_enabled(uid) is true; otherwise it returns {}, making the account appear to have used zero seconds. Extend the strict configuration check to offline admission so an unavailable usage ledger produces a hold rather than renewed allowance.
Useful? React with 👍 / 👎.
| DISPATCH_DECISIONS = Counter( | ||
| 'omi_stt_cap_dispatch_decisions', | ||
| 'Allowance decisions before offline provider spend; bounded labels, no account identifiers', | ||
| ['path', 'outcome', 'reason'], |
There was a problem hiding this comment.
Export the new decision counter from sync services
For production backend-sync and backend-sync-backfill, the new counter is discarded by the action: keep metric-name allowlist in backend/deploy/cloud_run_gmp_sync.yaml:31-34: omi_stt_cap_dispatch_decisions_total matches none of its alternatives. Consequently, the documented fleet rollout checks cannot observe sync held decisions or held/decision ratios in GMP, even though the application increments the counter. Add the new metric to the sync exporter allowlist alongside its declaration.
Useful? React with 👍 / 👎.
…never drop, the cloud stream (#23610) * proto: CLOUD_LIVE_STT_MODE policy switch (stream/when_watched/off), local_preview handshake, saved-seconds metrics Dark foundation for the batch-only cloud transcription proposal. Default stream reproduces today's behavior exactly; when_watched forces the existing #21481 live-demand machinery to admit every session (no parallel switch); off opens no cloud streaming STT session at all while audio is still received and persisted (the #23388 cap_paused receive/persist shape), with BYOK custom STT never suppressed. local_preview is a client capability declaration on /v4/listen. Metrics: omi_cloud_live_stt_mode_sessions_total and omi_cloud_live_stt_saved_seconds_total. * feat(listen): mobile local-preview lane for batch-lane users; defer, never drop, the cloud stream A mobile session that declares local_preview=enabled and whose uid is on the batch record lane (allowlist or batch percent), with private cloud sync and no custom STT, is admitted to the local-preview lane: ready and every mobile_batch_admission renewal carry local_preview=true with mobile_standard_batch=true, so the client journals all pendant audio through the lossless mobile Standard batch route and renders its own on-device preview. Integrations no longer hold these sessions on the live stream (David, 2026-10-25: realtime apps/webhooks degrade). Listen defers the provider stream instead of dropping it: live segments are what keep a listen conversation alive and register it for batch, so a session with audio and no stream loses its transcript. The first socket audio opens today's stream. CLOUD_LIVE_STT_MODE=off (#23498) now uses the same deferral. Kill switch LOCAL_PREVIEW_BATCH_ENABLED, on unless set off; no separate ramp. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(listen): start demand routing once a deferred or cap-paused stream actually opens Luna r1 P2 on #23610: a deferred open that cap admission pauses creates no socket, and the later cap-recovery re-init never started the demand-routing task the session skipped. ensure_live_demand_routing() starts it exactly once whenever a stream exists (session start, deferred open, cap recovery); the deferred-open counter now counts only opens that produced a socket. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(listen): label local-preview admission outcomes through the closed reason enum CI test_reason_label_enums: outcome labels must come from a reasons.py enum via reason_label(). Adds LocalPreviewOutcome (LIVE_STT family); REASONS derives from it. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(listen): count a deferred stream once however it opens; document late routing tasks Luna r2 on #23610: a deferred open that cap admission paused, then cap recovery opened, was never counted; note_deferred_stream_opened() counts once from either path. Routing tasks started after supervise() snapshots its set are tracked and cancelled at teardown but cannot end the session; that fail-soft behaviour is intended and now documented at the call. Failure-Class: none Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Problem and change
Exhausted finite-allowance audio could reach cloud STT through sync output locking or an unselected/code-disabled batch scope. This PR checks the existing allowance before spend and preserves raw audio custody.
omi_stt_cap_dispatch_decisions_total{path,outcome,reason}. The common offline admission predicate is the shared primitive; the regression matrix guards each boundary instead of adding per-route policy copies.Rollout and kill switch
Ship on at 100% for offline sync/batch in the first approved release.
STT_CAP_OFFLINE_ENFORCEMENTdefaults true; no default-off flag or new cohort is added. The existingrollout_cohorts/stt-cap-dispatchramp remains the live/recovery control and is unchanged here.The subscription session owns merge and the lead owns deployment. At that release the lead applies matching switch values to API/sync policy hosts and GPU workers, then reviews one complete 15-minute post-revision window. Watch the held/decision ratio by path and reason in
omi_stt_cap_dispatch_decisions_total, alongsideomi_stt_cap_provider_audio_seconds_total, provider/sync errors and queue age. Verify a capped synthetic canary makes zero provider calls and entitled/BYOK canaries still complete. Unexpected entitlement refusals, lost custody, stuck funded work or error regressions block acceptance.Rollback: set
STT_CAP_OFFLINE_ENFORCEMENT=falseon those hosts and drain old revisions. This restores prior lane/cohort admission; preserve all holds, receipts and custody cleanup. Existing selected enforcement remains active. No production writes, merge or deployment are performed by this PR.Validation
Created
sub/cap-enforce-gapsfromorigin/mainin/Volumes/Ephemeral/scratch/worktrees/omi/cap-enforce-gaps;make setuppassed with a worktree-owned backend environment. The separate baseline worktree also passed setup.Backend tests run only through
backend/test.sh, with four file-isolated workers, underniceand the workspace heavy-command gate:4d3c06c98e4and read-only admission fix: 5,936 passed, zero failures, plus two pre-existing optional PyTorch/pyannote checks skipped because those dependencies are absent. This includes all sim/batch filenames, the original 45-file targeted union, and subscription read/wire contracts. No skip or xfail was added.cap-enforce-gaps-compare-tests.txt(test_fresh_latency_sim.py,test_recovered_release_sim.py) passed 7 tests on mainb70ac58025dand PR head2e41191e; failing headb01f5731reproduced 4 failures / 3 passes in the isolated baseline worktree.cap-enforce-gaps-pump-rerun-tests.txt. The new fake callback matrix passed 11 cases; all eight real worker/Parakeet adapter cases passed, including offline enforcement with legacy batch scope closed and denied recovery with no second provider call.The CI simulation regression was a harness defect: module-scoped replays preceded the function-scoped billing override and activated callbacks against a stale retry fake. The production worker is wired to
ParakeetWords.recover_empty, which already supports these callbacks and returns a custody-preserving refusal. Billing isolation now precedes module fixtures; the synthetic simulator explicitly excludes real funding lookup; its retry fake also honors refusal, padded bounds and acceptance callbacks. Two pump tests now use start/release barriers instead of assuming compute started after a 20 ms sleep, and assert shutdown/cancellation remains pending until compute is released. No production recovery behavior is changed to accommodate simulations.The hermetic erasure regression also exposed a production side effect: the allowance resolver's default lookup provisions a missing subscription and can recreate an erased user root. Offline admission now explicitly requests read-only subscription resolution, including the desktop-trial lookup. The existing entitlement decision is unchanged; reviewers still bypass reads and inactive paid accounts retain paid-through access. Eight new tests exercise missing roots, roots without subscriptions, paid-through accounts and reviewers through the real subscription lookup. The existing hermetic erasure assertion is retained.
Normal push hooks run without bypasses, including source preflight, typecheck, selected unit tests, runtime closure, OpenAPI and formatting. The earlier explicit
make preflightpassed 37 checks and metadata-only preflight passed all four contracts.Follow-ups and limits
PTT voice-message monthly allowance enforcement is out of scope and remains a follow-up. Live outside its cohort is unchanged; its existing ramp to 100% closes that gap. Held-backlog consent/recovery membership is preserved, so newly held sources outside that recovery scope remain in custody until it expands. These checks do not add distributed monthly reservations: concurrent or already-admitted work can still finish before usage is persisted. Decision counters are boundary counts, not unique uploads or certified savings.
Failure-Class: FC-stt-allowance-not-enforced-at-dispatch
Line-Count-Exception: backend/utils/sync/pipeline.py | 3690 -> 3707 | Wire the shared spend-admission primitive into probe/retry/fallback custody boundaries; policy and metrics live in shared helpers.
Line-Count-Exception: backend/utils/subscription.py | 2063 -> 2070 | Expose non-provisioning subscription and trial lookups to offline spend admission without changing existing caller defaults.
🤖 Generated with Claude Code