Skip to content

fix(backend): reserve PTT stream STT budget at connect - #12721

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/ptt-stream-budget-reserve
Sep 4, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
aryanorastar:fix/ptt-stream-budget-reserve

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Concurrent /v2/voice-message/transcribe-stream sessions probed the shared daily STT duration budget without reserving (check_budget = try_consume_budget(uid, 0)), froze that remaining slice mid-session, then record_actual_duration(..., force=1) at end. Two sessions near the limit could both admit the same remaining slice and overspend #12720.

Fix: atomically try_reserve_session_budget (Lua force=2 consume-up-to MAX_SESSION_DURATION_S) at connect, cap mid-session audio to the reservation, settle_reserved_duration after a successful drain, and refund the full reservation on terminal provider failure. Single-session force-record for tracking is unchanged on the fail-open path.

Product invariants affected

none

How it was verified

cd backend
echo 'tests/unit/test_voice_duration_limiter.py
tests/unit/test_desktop_transcribe.py' > /tmp/bug5-tests.txt
PYTHON=/path/to/backend/.venv/bin/python \
BACKEND_UNIT_TEST_FILE_LIST=/tmp/bug5-tests.txt BACKEND_PYTEST_FILE_ISOLATION=0 BACKEND_PYTEST_XDIST=0 \
  bash test.sh -q
# → 103 passed, 5 deselected

Pre-fix hermetic Lua (fakeredis): seed DAILY_BUDGET_MS - 60_000; two probes both see 60s remaining; two force-records → used DAILY_BUDGET_MS + 60_000. Reserve-up-to admits only the first concurrent session.

Tests

  • test_legacy_probe_and_force_overspends_under_concurrency
  • test_reserve_up_to_admits_only_remaining_under_concurrency
  • test_settle_refunds_unused_reservation
  • Updated WS budget / no-charge-on-provider-failure settle assertions

Failure class (fixes)

Failure-Class: new

Line count

Line-Count-Exception: backend/routers/chat.py | 2130 -> 2159 | Atomic probe-only WS budget admit with reserve-at-connect + settle/refund in the PTT stream handler.

Honest gaps

  • No live multi-client Redis/provider soak (hermetic Lua + WS unit coverage only).
  • Physical / on-device smoke not run (no kit).

Review in cubic

Concurrent transcribe-stream sessions probed the shared daily duration
pool without reserving, so each could freeze the same remaining slice
and force-record past DAILY_BUDGET_MS. Atomically reserve up to one
session at connect and settle or refund on drain.

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.

4 issues found across 6 files

Confidence score: 2/5

  • backend/utils/voice_duration_limiter.py in settle_reserved_duration can produce incorrect duration accounting when the negative settlement entry ages out of order relative to the positive reservation; fix the reservation/settlement expiry handling and add coverage for short sessions.
  • backend/routers/chat.py can leave a connect-time reservation consuming a user’s budget for up to 24 hours if the worker dies or Redis is unavailable during settlement; add an expiring, idempotent recovery mechanism.
  • backend/routers/chat.py performs synchronous Redis work in the WebSocket finally path, so Redis latency or timeouts can block the event loop when a provider fails; offload settlement and refunds through run_blocking or an equivalent async-safe path.
  • backend/tests/unit/test_voice_duration_limiter.py assumes fakeredis is available for the new concurrency tests, which can make the test suite fail in environments where that optional dependency is unavailable; guard the import and test registration consistently with test_rate_limiting.py.
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/utils/voice_duration_limiter.py">

<violation number="1" location="backend/utils/voice_duration_limiter.py:253">
P1: After a short session, `settle_reserved_duration` writes a negative entry at settlement time while the positive reservation keeps its connect timestamp. When the reservation ages out first, the negative entry makes `used_ms` negative and grants budget beyond `DAILY_BUDGET_MS`; reconcile the original reservation entry or preserve its timestamp for the refund.</violation>
</file>

<file name="backend/tests/unit/test_voice_duration_limiter.py">

<violation number="1" location="backend/tests/unit/test_voice_duration_limiter.py:492">
P3: The new TestConcurrentSessionReservation tests evaluate a Lua script over fakeredis without guarding availability, unlike the sibling unit test in test_rate_limiting.py which wraps `import fakeredis`/registration in try/except and calls `self.skipTest('fakeredis with Lua support unavailable under the guarded runner')`. `lupa` is not declared in requirements.txt or openapi-requirements.txt, so in the same guarded runner environment these three tests will error (collection/runtime failure) instead of skipping. Wrap the `_bind_lua` registration in a try/except and raise `pytest.skip` (or `self.skipTest`) when Lua support is unavailable, matching the existing convention.</violation>
</file>

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

<violation number="1" location="backend/routers/chat.py:1635">
P2: When a provider fails, this synchronous Redis call runs in the WebSocket `finally` path and can block the event loop on Redis latency or timeout. Offload reservation settlement and refunds through `run_blocking` (or use an async Redis client) before marking the usage settled.</violation>

<violation number="2" location="backend/routers/chat.py:1661">
P2: If the worker dies or Redis is unavailable during settlement, this connect-time reservation is never released and can consume the user's budget for the next 24 hours despite no settled session. Add an expiring, identifiable reservation lease with durable recovery so abandoned reservations cannot remain charged indefinitely.</violation>
</file>

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

Re-trigger cubic

reserved_ms = 0
if actual_ms < 0:
actual_ms = 0
return record_actual_duration(uid, actual_ms - reserved_ms)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: After a short session, settle_reserved_duration writes a negative entry at settlement time while the positive reservation keeps its connect timestamp. When the reservation ages out first, the negative entry makes used_ms negative and grants budget beyond DAILY_BUDGET_MS; reconcile the original reservation entry or preserve its timestamp for the refund.

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

<comment>After a short session, `settle_reserved_duration` writes a negative entry at settlement time while the positive reservation keeps its connect timestamp. When the reservation ages out first, the negative entry makes `used_ms` negative and grants budget beyond `DAILY_BUDGET_MS`; reconcile the original reservation entry or preserve its timestamp for the refund.</comment>

<file context>
@@ -181,6 +240,19 @@ def record_actual_duration(uid: str, duration_ms: int) -> bool:
+        reserved_ms = 0
+    if actual_ms < 0:
+        actual_ms = 0
+    return record_actual_duration(uid, actual_ms - reserved_ms)
+
+
</file context>

Comment thread backend/routers/chat.py
return
actual_duration_ms = compute_pcm_duration_ms(accepted_audio_bytes, sample_rate, channels)
record_actual_duration(uid, actual_duration_ms)
settle_reserved_duration(uid, budget_reserved_ms, 0)

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: When a provider fails, this synchronous Redis call runs in the WebSocket finally path and can block the event loop on Redis latency or timeout. Offload reservation settlement and refunds through run_blocking (or use an async Redis client) before marking the usage settled.

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 1635:

<comment>When a provider fails, this synchronous Redis call runs in the WebSocket `finally` path and can block the event loop on Redis latency or timeout. Offload reservation settlement and refunds through `run_blocking` (or use an async Redis client) before marking the usage settled.</comment>

<file context>
@@ -1617,12 +1613,26 @@ async def send_stt_audio_or_close(audio: bytes) -> bool:
             return
-        actual_duration_ms = compute_pcm_duration_ms(accepted_audio_bytes, sample_rate, channels)
-        record_actual_duration(uid, actual_duration_ms)
+        settle_reserved_duration(uid, budget_reserved_ms, 0)
         usage_recorded = True
 
</file context>

Comment thread backend/routers/chat.py
# Probe-only check_budget + force-record at end lets concurrent WS
# sessions each freeze the same remaining slice and overspend.
try:
allowed, reserved_ms, _used_ms, _remaining_ms = try_reserve_session_budget(

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: If the worker dies or Redis is unavailable during settlement, this connect-time reservation is never released and can consume the user's budget for the next 24 hours despite no settled session. Add an expiring, identifiable reservation lease with durable recovery so abandoned reservations cannot remain charged indefinitely.

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 1661:

<comment>If the worker dies or Redis is unavailable during settlement, this connect-time reservation is never released and can consume the user's budget for the next 24 hours despite no settled session. Add an expiring, identifiable reservation lease with durable recovery so abandoned reservations cannot remain charged indefinitely.</comment>

<file context>
@@ -1644,6 +1654,22 @@ async def drain_stt_or_close() -> bool:
+        # Probe-only check_budget + force-record at end lets concurrent WS
+        # sessions each freeze the same remaining slice and overspend.
+        try:
+            allowed, reserved_ms, _used_ms, _remaining_ms = try_reserve_session_budget(
+                uid, MAX_SESSION_DURATION_S * 1000
+            )
</file context>

class TestConcurrentSessionReservation:
"""Prove probe+force overspend and that reserve-up-to prevents it."""

def _bind_lua(self):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: The new TestConcurrentSessionReservation tests evaluate a Lua script over fakeredis without guarding availability, unlike the sibling unit test in test_rate_limiting.py which wraps import fakeredis/registration in try/except and calls self.skipTest('fakeredis with Lua support unavailable under the guarded runner'). lupa is not declared in requirements.txt or openapi-requirements.txt, so in the same guarded runner environment these three tests will error (collection/runtime failure) instead of skipping. Wrap the _bind_lua registration in a try/except and raise pytest.skip (or self.skipTest) when Lua support is unavailable, matching the existing convention.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_voice_duration_limiter.py, line 492:

<comment>The new TestConcurrentSessionReservation tests evaluate a Lua script over fakeredis without guarding availability, unlike the sibling unit test in test_rate_limiting.py which wraps `import fakeredis`/registration in try/except and calls `self.skipTest('fakeredis with Lua support unavailable under the guarded runner')`. `lupa` is not declared in requirements.txt or openapi-requirements.txt, so in the same guarded runner environment these three tests will error (collection/runtime failure) instead of skipping. Wrap the `_bind_lua` registration in a try/except and raise `pytest.skip` (or `self.skipTest`) when Lua support is unavailable, matching the existing convention.</comment>

<file context>
@@ -479,3 +479,65 @@ def test_daily_budget(self):
+class TestConcurrentSessionReservation:
+    """Prove probe+force overspend and that reserve-up-to prevents it."""
+
+    def _bind_lua(self):
+        import fakeredis
+        import utils.voice_duration_limiter as limiter
</file context>

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks @aryanorastar — this is a well-constructed fix for the concurrent-session overspend in #12720, and the tests genuinely pin the failure class. File-by-file:

backend/utils/voice_duration_limiter.py — The force=2 reserve-up-to branch is the right shape: it computes take = math.min(request, remaining) inside the atomic script, ZADDs a reservation entry with an INCR nonce, and returns the 4-tuple so the caller knows exactly how much was reserved. settle_reserved_duration charging only the delta (record_actual_duration(uid, actual - reserved)) keeps successful short sessions charged at actuals. Changing the record guard from request > 0 to request ~= 0 correctly admits negative refund entries. Two bounded notes for a follow-up: (1) the refund entry carries the settle timestamp, not the reservation's connect timestamp — near the 24h window edge a refund can outlive its positive reservation and briefly undercount used_ms (bounded by one <=120s reservation); stamping refunds with the original reservation timestamp would close it. (2) If a worker dies between reserve and settle, the reservation stays charged for the remainder of the window — also bounded at one session's worth, but an expiring lease would make it self-healing.

backend/routers/chat.py — Moving admission inside the session try (chat.py:1656-1669) so every exit path can settle/refund is the correct structure, and refund_reservation_once() on the no-drain branch of the finally (chat.py:1804-1806) means provider failures no longer charge users. usage_recorded still guarantees settle-or-refund happens exactly once per session. Two observations: the settle/refund calls are synchronous Redis calls in the async WS finally path — consistent with how this handler already calls the sync limiter, and the Lua is short, but worth noting. And budget_remaining_ms = reserved_ms caps mid-session audio to the reservation (the chat.py:1765-1772 check), which means a client that opens two concurrent sessions near the limit now gets one full session plus one 1008 instead of two short ones — reasonable for a cost cap, flagging it as a user-visible trade-off.

backend/tests/unit/test_voice_duration_limiter.py — The three TestConcurrentSessionReservation tests are the strongest part of this PR: they replay the exact pre-fix failure mode (two probes both seeing 60s remaining, two force-records ending at DAILY_BUDGET_MS + 60_000) and then prove reserve-up-to admits only one of two concurrent callers. They all passed in CI at this head.

backend/tests/unit/test_desktop_transcribe.py — The assertion migrations are honest behavior changes, not mechanical renames: refund paths now assert settle_reserved_duration('test-uid', reserved, 0) where before they asserted record_actual_duration was never called (e.g. provider-failure and finalize-failure cases), and the settle test asserts (120000, 1000) — reserved 120s, actual 1s. Good.

backend/tests/unit/_chat_router_test_harness.py — Stubs for the new entry points plus MAX_SESSION_DURATION_S = 120 keep the shared harness consistent with the limiter stubs in test_desktop_transcribe.py.

.github/failure-classes/FC-concurrent-ptt-stream-budget-overspend.json — Matches the existing failure-class schema (schema_version, violated_contract, canonical_prevention + artifacts, evidence_prs, scope_hints, status: open) and accurately describes the fixed contract.

CI note — The failing Backend unit suite is pre-existing drift on the base, not from this PR: test_pinned_conversation_dump_set_is_exact flags two model_dump sites in utils/llm/external_integrations.py (_basic_daily_summary, generate_comprehensive_daily_summary), that file is identical between this PR's base and head, and main has since pinned those sites. A rebase onto current main should clear it.

Leaving for human maintainer review — the accounting edge cases above are bounded and don't reproduce the overspend, but the reservation-lifetime design (refund timestamps, crash-abandoned reservations) deserves a maintainer's eye before this becomes the pattern for other budgeted streams.


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 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

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Confidence 4/5: stated root cause (concurrent PTT stream sessions overspend shared STT budget, #12720), scoped fix mirrored by extensive new tests (TestConcurrentSessionReservation), CI green except the shared stale-guardrail-base 'Backend unit suite' failure (fixed by #12740, now on main). Diff is 311 lines (11 over the 300 soft cap) but every other gate signal is strong. No overlap with #12717/#12739 (different subsystem - chat quota vs STT duration budget).

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants