Skip to content

fix(backend): fail closed when WAV duration is unreadable for STT budget - #12719

Closed
aryanorastar wants to merge 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/wav-unreadable-duration-budget
Closed

aryanorastar wants to merge 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/wav-unreadable-duration-budget

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

When read_wav_duration_ms returned None, /v2/voice-messages and multipart /v2/voice-message/transcribe skipped try_consume_budget but still ran paid STT (#12718). Reject with typed invalid_input (400) before STT so unmeterable audio cannot bypass the daily duration budget. PCM REST already always meters via compute_pcm_duration_ms.

Product invariants affected

none

How it was verified

cd backend
echo 'tests/unit/test_desktop_transcribe.py' > /tmp/bug4-tests.txt
BACKEND_UNIT_TEST_FILE_LIST=/tmp/bug4-tests.txt BACKEND_PYTEST_FILE_ISOLATION=0 BACKEND_PYTEST_XDIST=0 \
  bash test.sh -k 'unreadable_duration or multipart_multi_file_budget or budget_exhausted or budget_consumed or octet_stream_budget' -q
# → 69 passed, 5 deselected

Pre-fix hermetic proof: with read_wav_duration_ms patched to None, multipart and /v2/voice-messages returned 200 and invoked STT without try_consume_budget; multi-file charged only readable files while still transcribing the unreadable one.

Tests

  • test_multipart_unreadable_duration_rejects_before_stt
  • test_voice_messages_unreadable_duration_rejects_before_stt
  • test_multipart_any_unreadable_duration_rejects_before_stt

Failure class (fixes)

Failure-Class: new

Line count

Line-Count-Exception: backend/routers/chat.py | 2130 -> 2137 | Fail-closed unreadable WAV duration checks at both voice STT budget gates.

Honest gaps

  • No live provider / Redis budget integration run (hermetic unit coverage only).
  • Physical / on-device smoke not run (no kit).

Made with Cursor

Review in cubic

Reject WAV/multipart/SSE voice STT when duration cannot be metered so
paid transcription cannot skip the daily budget gate (BasedHardware#12718).

Failure-Class: new
Co-authored-by: Cursor <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 3 files

Confidence score: 4/5

  • In backend/routers/chat.py, read_wav_duration_ms treats valid but unmeterable audio the same as corrupt input when PyAV lacks usable duration metadata or computes a non-positive duration, which could trigger incorrect rejection or fallback behavior; distinguish these cases or add targeted handling/tests.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/routers/chat.py">

<violation number="1" location="backend/routers/chat.py:879">
P2: read_wav_duration_ms returns None for valid-but-unmeterable audio too, not only corrupt files: it returns None whenever PyAV finds no container.duration and no stream.duration, or when the computed duration is <= 0 (backend/utils/voice_duration_limiter.py lines 226-238). In the multipart path the raw .wav/.webm/.mp4 upload is saved directly to wav_paths and read here, so a legitimate webm/mp4/wav lacking duration metadata (common for streamed/incomplete captures) now rejects with 400 invalid_input even though it previously transcribed fine. Before merging, confirm rejecting valid unmeterable audio is intended across all three accepted extensions, and consider logging/counting these rejections separately so a spike in real-user 400s is distinguishable from genuinely corrupt input.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread backend/routers/chat.py
allowed, used_ms, remaining_ms = try_consume_budget(uid, duration_ms)
if not allowed:
raise HTTPException(status_code=429, detail='Daily transcription budget exhausted')
if duration_ms is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: read_wav_duration_ms returns None for valid-but-unmeterable audio too, not only corrupt files: it returns None whenever PyAV finds no container.duration and no stream.duration, or when the computed duration is <= 0 (backend/utils/voice_duration_limiter.py lines 226-238). In the multipart path the raw .wav/.webm/.mp4 upload is saved directly to wav_paths and read here, so a legitimate webm/mp4/wav lacking duration metadata (common for streamed/incomplete captures) now rejects with 400 invalid_input even though it previously transcribed fine. Before merging, confirm rejecting valid unmeterable audio is intended across all three accepted extensions, and consider logging/counting these rejections separately so a spike in real-user 400s is distinguishable from genuinely corrupt input.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/chat.py, line 879:

<comment>read_wav_duration_ms returns None for valid-but-unmeterable audio too, not only corrupt files: it returns None whenever PyAV finds no container.duration and no stream.duration, or when the computed duration is <= 0 (backend/utils/voice_duration_limiter.py lines 226-238). In the multipart path the raw .wav/.webm/.mp4 upload is saved directly to wav_paths and read here, so a legitimate webm/mp4/wav lacking duration metadata (common for streamed/incomplete captures) now rejects with 400 invalid_input even though it previously transcribed fine. Before merging, confirm rejecting valid unmeterable audio is intended across all three accepted extensions, and consider logging/counting these rejections separately so a spike in real-user 400s is distinguishable from genuinely corrupt input.</comment>

<file context>
@@ -873,14 +873,18 @@ def _record_preparation_failure(failure: TranscriptionFailure) -> None:
-            allowed, used_ms, remaining_ms = try_consume_budget(uid, duration_ms)
-            if not allowed:
-                raise HTTPException(status_code=429, detail='Daily transcription budget exhausted')
+        if duration_ms is None:
+            raise TranscriptionFailure(
+                TranscriptionOutcome.INVALID_INPUT,
</file context>

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified — this closes a real unmetered-STT bypass on both WAV routes, and the fix is correct. Thank you @aryanorastar!

What I checked against the head commit:

  • backend/routers/chat.py (/v2/voice-messages): previously read_wav_duration_ms(first_wav) returning None skipped try_consume_budget entirely while the stream still ran paid STT. Now it raises TranscriptionFailure(INVALID_INPUT, retryable=False) before any provider call, which maps to HTTP 400 via _transcription_http_error, records the prep-failure metric through the existing handler, and keeps the temp-file cleanup. Good use of the existing typed boundary.
  • backend/routers/chat.py (multipart /v2/voice-message/transcribe): the old loop summed only readable files, and the total_duration_ms > 0 guard meant an all-unreadable upload transcribed with zero metering. Now any None in the loop fails closed with INVALID_INPUT and the sum is always fully metered; dropping the now-dead > 0 condition was the right call.
  • Scope check: the WS (/v2/voice-message/transcribe-stream) and PCM REST paths meter via compute_pcm_duration_ms, which is byte-derived and never None — so these two sites were the only bypass gates, and the fix covers them all.
  • backend/tests/unit/test_desktop_transcribe.py: the three new tests pin the right contract — try_consume_budget AND the STT helper are both uncalled when duration is None, per route, including the multi-file partial case. Rewriting test_multipart_multi_file_budget_sums_durations from "None skipped" to an all-readable sum correctly retires the old buggy semantics.
  • .github/failure-classes/FC-unmeterable-audio-skips-stt-budget-gate.json: matches the registry's schema and the violated-contract/prevention text is accurate to the diff; the Failure-Class: new declaration and line-count exception in the PR body check out.

Two behavior notes for maintainers (not blocking):

  1. read_wav_duration_ms also returns None for valid-but-unmeterable audio (PyAV finds neither container nor stream duration, or computes <= 0 — backend/utils/voice_duration_limiter.py). Such uploads now get 400 instead of free STT; that's the right fail-closed default for a billing gate, but it is an availability trade-off for legitimately header-less files (same point the cubic review raised — agreed it's intentional here).
  2. The SSE route still meters only the first WAV (pre-existing, documented as matching actual Deepgram usage). Fine to leave as a follow-up if multi-file SSE becomes real.

CI is green including the hermetic backend gates. Leaving formal merge sign-off to the maintainers since this changes billing-adjacent budget enforcement (previously-accepted unmeterable uploads now rejected); would be glad to see it land.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces labels Sep 4, 2026
kodjima33 added a commit that referenced this pull request Sep 4, 2026
…leanup (#12740)

The `Backend unit suite` CI lane (added in c094859, merged this morning)
fails unconditionally on every PR to main:

- tests/slow_guardrail_manifest.txt lists tests/unit/test_ws_g_module_aliases.py,
  which was deleted by a7bc5fd (dead-code removal) the day before the
  manifest was built, so run-slow-guardrails-ci.sh exits 1 before running
  anything.
- Once that's fixed, test_managed_call_sites_absent_from_the_inventory_fail_ci
  (backend/tests/unit/test_llm_gateway_coverage_guardrails.py) fails because
  docs/llm/model_endpoint_inventory.yaml still lists call sites in
  utils/llm/promotion_proposals.py and utils/llm/promotion_routes.py, also
  removed by a7bc5fd.

Both are stale references to the same commit's deletions, not code bugs.
Verified: 5 of 6 currently-open backend PRs (#12739, #12721, #12719, #12714,
#12712) show this exact "Backend unit suite" FAILURE.

Fix: remove the stale manifest line (with a dated note per the file's own
"never silently dropped" convention) and the two stale inventory entries.

Tested: `PYTHON=.venv/bin/python bash scripts/run-slow-guardrails-ci.sh` now
passes (103 passed, 1 skipped, was: hard-failing before any test ran). Also
ran test_llm_gateway_coverage_guardrails.py + test_firestore_query_contract.py
directly: 72 passed.

Failure-Class: none
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Closing — superseded on main by #12723 (e0d970d888), which fixed #12718 today.

The bug was real and both fixes close it. They differ on what to do with audio whose duration cannot be read, and main picked the better answer:

# main (#12723)
budget_duration_ms = duration_ms if duration_ms is not None else MAX_SESSION_DURATION_S * 1000
allowed, used_ms, remaining_ms = try_consume_budget(uid, budget_duration_ms)
# this PR
if duration_ms is None:
    raise TranscriptionFailure(TranscriptionOutcome.INVALID_INPUT, provider=stt_provider, retryable=False)

Mine refuses the upload. main transcribes it and charges the worst case — MAX_SESSION_DURATION_S. Both make it impossible to get unmetered STT, which was the actual defect, but only one of them keeps working for the user.

That difference is exactly the objection cubic raised on this PR and I did not act on: read_wav_duration_ms returns None for valid-but-unmeterable audio too, not just corrupt input — no container duration, no stream duration, or a computed duration <= 0, which is ordinary for streamed or truncated webm/mp4 captures. Under this PR those uploads start returning 400 having previously transcribed fine. Under #12723 they still transcribe, and the billing hole is closed by over-charging rather than by rejecting.

Git-on-my-level called my version "the right fail-closed default for a billing gate" while noting the availability trade-off, and I agreed and moved on. Charging the ceiling closes the same hole without spending real users' working uploads to do it — the conservative choice was available on the billing side alone, and I put the cost on availability instead.

Nothing here is worth carrying forward: #12723 covers both routes, and the WS and PCM REST paths were never affected since compute_pcm_duration_ms is byte-derived and never returns None.

One item from the review that is still open and outlived both PRs: the SSE route meters only the first WAV. That is pre-existing and documented as matching actual Deepgram usage, so it is a follow-up rather than a defect — worth its own issue if multi-file SSE ever becomes real.

@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Hey @aryanorastar 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants