Skip to content

fix(stt): harden cost-router exclusions and shared health - #20422

Merged
Git-on-my-level merged 14 commits into
mainfrom
fix/stt-router-hardening
Oct 4, 2026
Merged

Git-on-my-level merged 14 commits into
mainfrom
fix/stt-router-hardening

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Harden live STT routing before a separately approved router-on rollout. Addresses independent-review findings 3, 4, 5, 6 and 9, plus their composition with main's default-off recovery controller (#20391). Non-draft for review; no merge, deployment or router-on rollout approval.

Round 5 — Luna's requested changes on 0dbe1574ff

Continued with git merge --ff-only origin/fix/stt-router-hardening, preserving the separately pushed identity-rotation commit. The first git merge origin/main found main already included. After main advanced during verification, normally merged its new head cd3326b3a5 in c033629891; the PR diff remains the same 27 router-hardening paths, with no authored workflow, client, chart, runtime-env or recovery/send-path edits.

  • Credential rotation: Process-local selection identity is provider + endpoint + stage, with credential/account identity tracked separately. Rotating a key clears only account/quota protection and invalidates stale callbacks, not an unchanged endpoint's connect/serve outage, deadline, escalation or recovery requirements. Selection evidence temporarily superseded by an account bench is restored on rotation. Endpoint changes start fresh selection state while an unchanged credential's account protection remains; stage changes start fresh scoped state. Redis fleet/cost namespaces remain unchanged.
  • Custom endpoint death: The typed plain-socket fallback opens the endpoint-keyed local target circuit, not the family default, matching the Redis quarantine scope. Credential account failures retain family-wide protection.
  • Tests: The existing credential-rotation assertion that expected a fresh custom breaker encoded the reviewed defect; it now requires the same open breaker. The custom-endpoint test now checks the actual local custom breaker, family/default breaker and sibling endpoint, in addition to Redis state. New cases cover account-only rotation, mixed outage/account evidence, repeated rotation, stale callbacks and explicit endpoint/stage transitions.

Round-5 test evidence

  • Pre-fix regression reproduction: eight failures, including key-rotation outage preservation and the custom-endpoint local-family assertion (.local/r5-prefix-red.log).
  • Ran all requested live-STT families plus connect-refusal/circuit coverage through file-isolated backend/test.sh: 72 files, including slow cases. The full run found one failed-account-probe regression; corrected it and verified the original assertion on canonical retry (.local/r5-retry-testsh.log). The new hardening file passed all 156 cases.
  • Local full-run exit remains nonzero for the unchanged 0.30-second CPU guard in test_live_recovery_matrix, test_live_shadow_replay and test_live_gate_replay, including single-file retries. The gate-replay timing failure also reproduces on unmodified 0dbe1574ff (/tmp/r5-baseline-gate.log). This is not claimed as a green local full run; no threshold, marker or allowlist was changed.
  • Canonical backend typecheck: 0 errors; Python Black check clean; async scan 0 findings; backend environment preflight 18 passed, 0 failed.
  • Post-main-merge canonical backend/test.sh check: 465 passed across 8 files, exit 0, including hardening, cost router, live chain, provider resilience, Deepgram account probe and transcript/Soniox paths (.local/r5-postmerge-testsh.log). OMI_PR_BODY_FILE=.local/pr-20422-body.md make preflight and explicit body validation each passed 31 checks; the line-count ratchet passed with streaming.py 2324 -> 2367. Pinned Black check passed. Logs: r5-make-preflight.log, r5-pr-preflight-body.log, r5-black-check.log.
  • Full evidence: .local/r5-full-files.txt, r5-full-testsh.log, r5-focused-testsh2.log, r5-retry-testsh.log, r5-pyright.log, r5-async-scan.log. Normal push and pre-push gates passed for c033629891087f866d5dd22dc6fdb960d5035af3. Exact-head GitHub CI green, first attempt: Backend Unit Tests run 37162666478 passed all four shards, slow guardrails and aggregate suite; Repo Checks run 37162666406 passed Hygiene (including line-count metadata) and Formatting. Hermetic backend E2E/merge gate, CodeQL, source closure and OpenAPI also passed; unrelated client/deployment checks correctly skipped. PR remains non-draft; no merge or deployment.

Canonical full-set command from backend/:

PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/r5-full-files.txt bash test.sh

Round 3 reproduces and fixes the eight backend CI failures on a5d66e8067 (run 37140378015). The seven recovery/replay failures were not caused by merging recovery target IDs: live_cost_health.py:238 correctly refused unread language health, but live_chain.py:263-287 then replaced registry targets with target-less family callbacks. This lost distinct candidates, endpoints, replay declarations and the known Modulate demotion. The eighth failure was a stale private breaker-map key assertion.

Round 4 addresses Luna's two REQUEST CHANGES findings on bdf23e8899. Normally merged origin/main (6eb534630fdb) in bbc941f837, committed the reviewed fixes in cb7fb6efb9, then normally merged the subsequently fetched main d4062b9ee8 in 62750e215e. The second merge changes no STT source/test bytes, and the app/workflow diff against main remains empty. No upstream workflow or client edits were authored in this round.

  • Redis round trips: _write_result reads endpoint-selection and family-account state together in one bounded MGET, then retains the identity fences and atomic compare-delete cleanup. A normal text outcome takes two Redis round trips (one batch read, one pipeline execution), matching main; no-text takes one. Each expired state still requires its existing cleanup EVAL, intentionally preserving renewal-race protection.
  • Breaker eviction: At the 64-identity cap, only the oldest closed breaker is evicted. Open and half-open breakers remain cached even after cooldown, until a normal probe closes them. If all entries are protected, a constant-size denial circuit refuses uncached identities, including forced probes; cached identities and family defaults remain usable. This is deliberately conservative and can temporarily reduce custom-target availability under extreme identity churn, rather than resetting an unhealthy endpoint to closed.
  • Optional assertion: The Soniox non-refusal test now explicitly asserts the returned fallback provider is Modulate, including auth/quota cases.

Failure-Class: FC-cache-merge-write-race

Continued from remote head 21d6b94cde, normally merged main's 8fb7dc1ccf (#20391), then continued round 3 from pushed head a5d66e8067. Preserve David's failure-class guard citation in that head. No force-push, stash, hook bypass, merge of this PR, or deployment.

Findings and prevention

Finding Change Regression proof
3 — hard-exclusion closure / endpoint attribution One permission closure enforces actual engine, capabilities, explicit ramp and account protection in every mode. Transcript and connect/serving failure evidence follows the actual endpoint, not the configured primary. Account failures remain credential-family scoped. Zero dials for withdrawn/quarantined/incapable targets; custom endpoint text/no-text and failure evidence leave default and sibling endpoint selection state untouched. Both recovery flag states covered.
4 — atomic shared quarantine Atomic Lua update preserves account priority and maximum expiry across stale writers; compare/delete cannot erase a renewed bench. A custom selection writer learning existing account quarantine protects all siblings immediately, including with routing off. Two-pod priority/expiry/renewal races and stale-writer learning. Earlier isolated production-Lua checks passed 17/17.
5 — independent recovery evidence Per-user success/failure caps constrain promotion evidence. Stage 5 requires 30 admitted outcomes / 10 witnesses / 300 seconds; stage 25 requires 60 / 20 / 600. Existing healthy-stage gate and backoff unchanged. Repeated single-user outcomes cannot promote; exact breadth/dwell boundaries, held windows and generation fences.
6 — environment/endpoint/account identity Stage-scoped cost-v8/fleet-v2 keys separate dev from prod. Non-account fleet state follows actual endpoint; account state spans endpoints sharing credentials. Off-mode snapshots merge account-only exclusion with neutral scores, retaining strongest known live account deadlines despite stale cache/Redis failure. Environment/endpoint/credential isolation; two-pod off-mode propagation; account-only reads; on/shadow-to-off transitions; stale selection cannot shed the configured chain.
9 — per-language freshness Missing language entries cannot borrow global freshness. Bounded full-language preload and per-key freshness expose unknown/stale views. First Korean request sees its remote bench; unread/stale language state and bounded comparison metrics. Round 3 retains the unread-health exception rather than inventing freshness.
Breaker identity (round 5) Local selection circuits key on provider + actual endpoint + stage, locked and capped at 64. Credential identity is synchronized separately: rotation clears only account state and retains endpoint outage evidence. Endpoint changes start fresh selection; stage changes start fresh scoped state. Aliases on the same endpoint share a breaker. Credential rotations retain open connect/serve benches while clearing credential-only account benches; mixed outage/account evidence survives rotation. Endpoint/stage isolation, alias reuse, cache bound and supplied default-object identity remain. Distinct target IDs remain distinct recovery candidates even on a shared breaker.
Round 3 — registry-preserving fail-open Router-on canary cache/router faults keep permitted registry targets in configured provider/registry order, not anonymous family callbacks. Cache exceptions carry conservative per-target views; known restricted states stay demoted without becoming fresh. A withdrawn/incapable default cannot suppress a permitted custom sibling. Non-canary static planning stays unchanged. Existing recovery matrix and 135-second replay assertions pass unchanged. New cases cover both recovery flags, cache/router faults, shared-breaker distinct IDs, known demotion, unread freshness and withdrawn-default/custom-sibling composition.

Serving behaviour changes

File:line Serving change
backend/utils/stt/live_router.py:66-120,151-190 Shared hard-permission filter; endpoint/stage-scoped custom selection circuit identity with separate credential-account synchronization. Closed-only eviction and conservative saturated-cache admission remain.
backend/utils/stt/streaming.py:190-221,245-263; backend/utils/stt/provider_resilience.py:458-503 Round 5 clears credential account state without erasing unchanged-endpoint outages; explicit endpoint changes reset selection while preserving unchanged-account protection. Known custom-endpoint serve deaths open their existing target circuit rather than the family default.
backend/config/live_stt_state.py:98-107 Local selection identity excludes credentials; Redis fleet/cost identities and all routing defaults remain unchanged.
backend/utils/stt/live_health.py:333-355 Round 4 batches endpoint/account state reads into one MGET; identity checks and renewal-safe Lua cleanup remain.
backend/utils/stt/live_chain.py:163-325 Filter static/proposed/fail-open paths; typed NoPermittedTarget. Round 3's fallback_routes preserves canary registry target identity while maintaining hard exclusions and existing capacity admission.
backend/utils/stt/live_chain.py; backend/utils/stt/live_session.py:583-603,660-669 Attribute custom connect rejection, serving death and transcript outcomes to actual endpoint; keep account quarantine family-wide. Both recovery modes preserve routing profile in static-only engine-mismatch fallback.
backend/config/live_stt_registry.py:38-41 Window ramp remains the minimum of registry percentage and existing window allocation.
backend/config/live_stt_state.py:38-119; backend/utils/stt/live_health.py:94-122,177-229,569 Environment/endpoint/account namespaces, atomic quarantine, scoped memory/async writes and account-only off-mode snapshots. No raw endpoint, credential or UID labels/logs.
backend/utils/stt/live_gate.py:132,277,301; backend/utils/stt/live_cost_health.py Admitted-only recovery evidence, breadth/dwell and truthful excluded-vote accounting.
backend/utils/stt/live_cost_health.py:39-45,181-243; backend/utils/stt/live_metrics.py:214 Per-key/full-language health freshness; cache refusal carries only conservative state for fail-open demotion, not qualification; bounded no-permitted-target/language-comparison metrics.

Test changes and why

  • Round 4: Network-round-trip assertions count MGET, GET, pipeline execution and cleanup EVAL separately across missing/live/expired account and selection state. Existing renewal-race and identity-change tests move their injection seam from GET to MGET without weakening the assertions. Breaker tests cover oldest-open and occupied half-open preservation, all-open denial even with force, one cached recovery probe, subsequent closed-entry recycling, unaffected family defaults, and real-chain Deepgram fallback under both recovery flag states.
  • Round 4 optional: test_live_stt_chain.py::test_non_refusal_outcomes_do_not_count_toward_the_gate asserts Modulate serves every fallback; the intended one Soniox auth/quota dial remains unchanged.
  • Round 3: test_soniox_rate_limit.py used _target_circuits['soniox-b'], a genuinely wrong identity after the endpoint/credential key change. It now obtains the circuit through target_circuit(selected_target), asserts the same object remains, and retains closed/zero-failure/no-quarantine checks while adding zero target probes in flight. No recovery-matrix or replay-provider-pair assertions changed.
  • New hardening tests exercise production candidate planning, with synthetic callbacks/fake Redis; no new timing exceptions, guard bypasses, scoring changes or workflow edits.
  • Earlier rounds intentionally retired one-user promotion expectations and unread-language-as-fresh expectations. One merged off-mode account-protection test now expects one dial, not three, after auth/quota rejection; connect-refusal-backoff assertions remain unchanged.

Compatibility, rollout and scope

  • Production defaults stay STT_ROUTING_MODE=shadow, STT_ROUTING_ON_PERCENT=0; recovery stays default off. No provider-order, allocation, chart, runtime-env or workflow changes. .github/failure-classes/FC-cache-merge-write-race.json only cites the reusable hardening regression guard.
  • fix(stt): bound live recovery and replay under one session owner #20391's receiver, recovery-controller, replay and send-queue implementation is untouched. Round 3 only changes router-on canary fail-open candidate planning, independent of the recovery flag.
  • cost-v8/fleet-v2 start fresh on rollout; older namespaces are not read, migrated, backfilled or deleted. Endpoint rotation resets endpoint-specific state, not shared credential-account quarantine.
  • Synthetic/offline verification only; no user transcript/audio or shared dev/prod state accessed. Independent-review findings outside 3/4/5/6/9 remain outside this PR. Green CI is not rollout qualification.
  • Earlier merge-hook Dart formatting was corrected with a normal commit restoring exact upstream bytes; final app diff against main is empty.

Product invariants affected

none

Round 4 test plan / evidence

  • Pre-fix canonical-runner reproduction: 17 failed, 120 passed in the new/migrated hardening cases (.local/pr-20422-r4-baseline.log).
  • Initial focused backend/test.sh run: hardening 137, live chain 104 and cost router 73 passed; local CPU thresholds unchanged (.local/pr-20422-r4-focused.log).
  • Full requested test_live_*, test_soniox_*, test_modulate_*, test_parakeet_*, test_deepgram_*, test_stt_* families plus connect-refusal backoff through backend/test.sh: 71 files, 3757 passed, no functional assertion failures, including slow cases. Runner exit is nonzero on the unchanged local 0.30s CPU guard in six files, not claimed as a green local full run. Hardening has 141 passing cases including malformed MGET batch responses; no CPU-budget changes.
  • Load-sensitive recovery-pacing and batch-pressure guard failures clear on canonical single-file retry. Remaining slow-marked replay/matrix guards are outside the normal fast lane. Unchanged speaker-carry test takes 0.56s here versus a borderline 0.30s warning on detached main d4062b9ee8 (36 assertions pass on both); the round-4 main probe did not reproduce a failure. No threshold, marker, allowlist, or out-of-scope code changes.
  • Touched-source Pyright: zero errors; black check clean; async scan zero findings. make preflight and explicit body validation each pass 31 checks. Logs: .local/pr-20422-r4-full.log, pr-20422-r4-retry.log, pr-20422-r4-main-speaker.log, pr-20422-r4-pyright.log, pr-20422-r4-async.log, pr-20422-r4-repo-preflight.log, and pr-20422-r4-body.log.
  • Normal push of head 62750e215e2974151fffb78c784dbc2fb744c0fa; pre-commit and bounded pre-push gates passed, including latest-main body validation. PR remains draft. No merge or deployment.
  • Exact-head GitHub CI green on 62750e215e2974151fffb78c784dbc2fb744c0fa, first attempt: Backend Unit Tests run 37154015517 passed all four shards, slow guardrails and aggregate suite. Hermetic Backend E2E/merge gate, CodeQL, source closure, formatting/hygiene, OpenAPI and PR metadata checks passed. Applicable client checks correctly skipped. PR remains draft; no merge or deployment.

Round-4 full-set command from backend/:

PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/pr-20422-r4-full-files.txt bash test.sh

Historical round 3 evidence

  • Round 3 pre-fix reproduction through backend/test.sh: all eight reported failures reproduced across the three named files.
  • Initial corrected four-file run: recovery matrix 97, replay pairs 27, Soniox rate-limit 12 and hardening 109 cases passed. Follow-up hardening review cases: 113 passed.
  • Touched-source Pyright zero errors; Python formatting clean. No fast CPU threshold change.
  • Full requested hermetic file-family set through backend/test.sh: 69 matching unit files plus test_connect_refusal_backoff.py, file-isolated, including slow-marked cases (BACKEND_PYTEST_MARK_EXPR='not integration'), zero assertion failures. The combined run exits 1 on CPU guards; this is not claimed as a completely green local run.
  • Canonical slow lane (backend/scripts/run-slow-guardrails-ci.sh): 1438 passed. Slow-heavy gate/shadow/recovery files also pass their normal fast lane. The early-provider-deaths load-only CPU failure passes its documented single-file retry.
  • Remaining local timing failure independently reproduced on pristine main 7b40315647 in a separate owned worktree: unchanged test_live_speaker_carry.py::test_matcher_does_not_emit_an_automatic_alternative_for_a_carried_person takes 0.47s CPU against the 0.30s guard on both main and this branch; 36 assertions pass in each. No threshold, marker, allowlist or assertion changed. GitHub's existing 1.0s-ceiling unit lane passed.
  • make preflight and scripts/pr-preflight --pr-body-file .local/pr-20422-body.md: 31 checks passed in each.
  • Round-3 head bdf23e8899b4dc2ca4138d0950ed9ce60bc1ff8c pushed normally; pre-commit and bounded pre-push gates passed; PR remains draft.
  • CI run 37146871133 passed the original eight regression cases, shards 2/3/4 and slow guardrails. Its initial shard-1 failure is the unchanged test_log_sanitizer.py::test_soniox_persistent_rate_limit_log_redacts_payload: the test resets its last-log timestamp to zero but does not control monotonic time, and soniox.py:145 suppresses logging below 300 seconds. Executing that original assertion with monotonic=100 reproduces the failure on both main 7b40315647 and this branch; monotonic=400 passes on both, and the unchanged full sanitizer file passes 115 cases on the main baseline. The normal failed-job retry passed; no code, production/test assertions or checks were changed for this unrelated condition.
  • All applicable GitHub CI green after retry: Backend Unit Tests run 37146871133, attempt 2, exact head bdf23e8899. All four shards, slow guardrails and aggregate suite passed; hermetic backend E2E/merge gate, CodeQL, source closure, OpenAPI and selected repo checks passed. PR remains draft; no merge or deployment.

Full-set command from backend/:

PYTHON=.venv/bin/python BACKEND_PYTEST_WORKERS=2 \
  BACKEND_PYTEST_MARK_EXPR='not integration' \
  BACKEND_UNIT_TEST_FILE_LIST=../.local/pr-20422-r3-full-files.txt bash test.sh

Local evidence is ignored under .local/: pr-20422-r3-before.log, pr-20422-r3-after.log, pr-20422-r3-hardening.log, pr-20422-r3-full.log, pr-20422-r3-retry.log, pr-20422-r3-slow.log, pr-20422-r3-fast-retry.log, pr-20422-r3-main-speaker.log, pr-20422-r3-preflight.log and pr-20422-r3-body.log. File-isolated execution preserves test import isolation and the local 0.30-second fast-test CPU blocking limit.

Line-Count-Exception: backend/utils/stt/streaming.py | 2324 -> 2367 | Reviewed router hardening: separate endpoint selection and credential account rotation, and route custom endpoint serving deaths to their local target circuit. No socket send/recovery path changes.

Generated with Devin

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-03T23:55:23.970274Z c033629 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: eeb0651fe7

ℹ️ 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".

Comment thread backend/config/live_stt_state.py Resolved
Comment thread backend/utils/stt/live_router.py Resolved
Comment thread backend/utils/stt/live_gate.py Resolved

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

All reported issues were addressed across 18 files

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

Re-trigger cubic

Comment thread backend/utils/stt/live_chain.py Resolved
Comment thread backend/utils/stt/live_health.py Resolved
Comment thread backend/utils/stt/live_health.py Resolved
Comment thread backend/config/live_stt_state.py Resolved
Comment thread backend/utils/stt/ARCHITECTURE.md Resolved
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Published the reviewed follow-up in 9c69acc. All 14 initial comments have been addressed: static mismatch fallback preserves profile/cohort, account and endpoint state have separate atomic scopes, qualified capped cohorts can advance after dwell without extra evidence, and reset/fake-expiry/await-boundary coverage is strengthened. The two CI failures were reproduced and fixed by explicitly warming the existing fixture's fake health cache; recovery assertions and implementations are unchanged. Local evidence: 668 cases across the relevant suites before the final additional tests, 224 cases across the final four affected files, 17/17 production-Lua checks on isolated Redis, and the complete pre-push gate passing on this head. Updated-head CI is running; no merge or deployment.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9c69acc3d8

ℹ️ 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".

Comment thread backend/config/live_stt_state.py Outdated
Comment on lines +101 to +103
def fleet_score_keys(family: str, language: str, bucket: int) -> tuple[str, str]:
stem = f'{fleet_prefix(family)}:score:{family}:{language}:{bucket}'
return stem + ':text', stem + ':no_text'

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 Badge Key fleet health by the selected target endpoint

When a registry target uses a custom endpoint (for example modulate-next), LiveLegSocket._record_transcript_outcome() and the connection-failure paths still call health.record()/health.quarantine() with only the provider family. These helpers reach fleet_score_keys() and fleet_state_key(), which always fingerprint family_endpoint(family) rather than the selected target's endpoint. Consequently, outcomes from the custom endpoint are written into the default Modulate endpoint's score/selection namespace, so the replacement endpoint is not isolated and can poison the default endpoint's fleet health. Pass the selected target/endpoint through the fleet-health APIs when recording non-account state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed from the call graph: live_session.py:625 records only the family, and live_chain.py:494 / streaming.py:204-210 similarly lose selected endpoint identity for non-account evidence. Cost-v8 target state is scoped, but the legacy fleet attribution boundary is not complete. These callers overlap the explicitly protected #20391 areas, so I stopped before editing them and documented this as a remaining finding-6 blocker. The PR is now draft despite green CI; scope coordination is required.

Comment thread backend/utils/stt/live_chain.py Resolved
Comment on lines +160 to +164
self._local.clear()
self._benches.clear()
self._interests.clear()
self._cached_scores.clear()
self._cached_benches.clear()

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 Badge Reset local circuits when routing identity changes

When a credential or endpoint changes in a long-lived process, _check_identity() clears the Redis-backed health views but leaves both live_router._target_circuits and the family circuits returned by _circuit_for_primary() untouched. A rotated credential can therefore inherit the old credential's account-open circuit and remain undialable for up to the 30-minute account cooldown even though its new account key and cost state correctly start fresh; an endpoint rotation similarly inherits selection/serve-error state. Scope those breakers to the same identity or reset them during this transition.

AGENTS.md reference: backend/AGENTS.md:L167-L167

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed for the custom breaker seam: two Target values with the same ID and different endpoints returned the same circuit, still account-open with over 1700 seconds remaining. Family breakers are also unscoped in streaming._circuit_for_primary(). Redis-view invalidation alone is insufficient. Completing this needs coordination with the protected serving-owner/circuit callsites in #20391, so I stopped and documented the finding-6 blocker rather than clearing it on CI success.

@Git-on-my-level
Git-on-my-level marked this pull request as draft October 3, 2026 09:02
Git-on-my-level and others added 3 commits October 3, 2026 19:23
Prevent static fail-open from reopening withdrawn accounts and require
independent, time-qualified recovery evidence across atomic shared state.

Failure-Class: FC-cache-merge-write-race

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Preserve permissions during mismatch fallback, keep endpoint evidence apart
from credential-wide account protection, and advance qualified trials after
dwell without admitting capped outcomes.

Failure-Class: FC-cache-merge-write-race

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Finding 3 remaining blocker (review PRRT_kwDOLkKqys6olkiO): in
STT_ROUTING_MODE=off the permission filter consults FleetHealth, but
quarantine() refused to record new benches, _drain_pending_benches()
never flushed them, refresh_once() loaded no shared state, and
cached_snapshot() ignored pod-local benches. A quota/auth rejection on
one pod therefore did not withdraw the credential anywhere while the
kill switch was off, although account exclusion is documented as a hard
exclusion in every mode.

Account-bench lifecycle is now mode-independent: quarantine() accepts
account kind in off mode, the drain flushes account deadlines, and
refresh_once() reads only fleet account state keys (scores, selection
benches, probe leases and interests stay routing-only state).
cached_snapshot() enforces known pod-local benches even with routing
off. Both account-quarantine callsites (live_chain.py and the
#20391-owned live_session.py/streaming.py legs) get the fix through the
shared FleetHealth API without touching those files.

The end-to-end off-mode NoPermittedTarget reproduction from the review
thread now passes: an account bench written by one pod denies the dial
on a fresh pod before any connect attempt.

Failure-Class: FC-cache-merge-write-race

Tests: an autouse fixture resets the module-level FleetHealth singleton
in place (sibling modules keep import-time references), four new
regressions in test_live_router_hardening.py (red pre-fix on three),
109 + 262 + 721 + 1118 passed across the affected suites; the two
combined-run failures in test_listen_ready_provider.py and
test_streaming_deepgram_backoff.py reproduce identically on the
pristine branch and are pre-existing order-dependence.
@Git-on-my-level
Git-on-my-level force-pushed the fix/stt-router-hardening branch from 9c69acc to 21d6b94 Compare October 3, 2026 13:05
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Off-mode account quarantine fixed (finding 3 remaining blocker, thread PRRT_kwDOLkKqys6olkiO) — pushed in 21d6b94, CI green.

STT_ROUTING_MODE=off previously disabled the account-bench lifecycle end to end: quarantine() recorded nothing, pending deadlines never flushed, refresh_once() loaded no shared state, and cached_snapshot() ignored pod-local benches — so a quota/auth rejection on one pod withdrew the credential nowhere while the kill switch was off, despite account exclusion being a documented hard exclusion in every mode.

Account-bench reads/writes are now mode-independent: off mode records and flushes account benches, reads only the credential-account state keys (scores, selection benches, probe leases, interests stay routing-only), and enforces known local benches. Because the fix lives in the shared FleetHealth API, the live_session.py/streaming.py quarantine callsites owned by #20391 get the behavior without editing those files. The runbook kill-switch note now states that off never reopens a credential another pod withdrew.

Verification: the exact reproduction from the review thread (one pod's account bench → NoPermittedTarget on a fresh pod in off mode, zero dials) is now a regression test, red pre-fix; 3 further off-mode regressions added; 262 + 721 + 1118 tests green across every affected suite; the two combined-run failures in test_listen_ready_provider.py/test_streaming_deepgram_backoff.py reproduce identically on the pristine branch (pre-existing order-dependence). Synthetic MemoryRedis only — no real Redis, credentials, or shared state touched.

Threads …kiL (selected-endpoint attribution) and …kiQ (local circuit identity) remain intentionally open: their callsites are owned by #20391 and need coordinated changes there.

Git-on-my-level and others added 9 commits October 3, 2026 22:35
…ening

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The formatter requires the worktree's resolved package language version.
Restore unrelated upstream files after bootstrapping that metadata.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…off mode

Attribute custom endpoint outcomes and selection quarantine to their actual
serving identity, keep credential quarantine effective with routing off,
and avoid inheriting a replaced endpoint's local breaker.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Keep permitted registry candidates and known demotions through canary
fail-open planning instead of collapsing to anonymous provider callbacks.
Recovery target IDs remain distinct from endpoint-and-credential breakers.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Batch endpoint and account health reads to avoid an extra Redis round trip.
Refuse uncached identities when all bounded breakers need protection.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Complete the circuit-identity half of review finding 6: family breakers
returned by _circuit_for_primary() were process-global singletons, so a
rotated credential or stage change inherited the old identity's
account-open circuit and stayed undialable for up to the 30-minute
cooldown even though the Redis health views already start fresh. The
target-circuit half landed earlier as identity-keyed _target_circuits;
serving-owner callsites no longer block the family seam.

Also thread the selected endpoint through the terminal-path serve-death
quarantine: note_typed_provider_death() drops the socket's
routing_endpoint today, so a custom-endpoint death benches the family
default's selection state. open_provider_selection_circuit() now
accepts endpoint= and quarantine() writes the scoped key.

Verification (worktree venv, repo runner test.sh with
BACKEND_UNIT_TEST_FILE_LIST):
- tests/unit/test_live_router_hardening.py: 115 passed
- 12 other STT suites touched by the seam (chain, modulate serve-error
  deaths, failover flag, soniox rate limit, routing health, evidence
  settlement, shadow replay, cost router, bench escalation, serve-death
  circuit, soniox vocabulary/rejections): 601 passed total
- black --line-length 120 --skip-string-normalization: clean

Failure-Class: FC-cache-merge-write-race | none

Co-Authored-By: Hermes Agent (GLM) <[email protected]>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 3, 2026 21:52

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

12 issues found across 27 files

Confidence score: 3/5

  • live_chain.py can synthesize a route that dials a target with ramp_percent=0 or incompatible capabilities. Preserve the registry’s ramp and capability checks in the fallback path.
  • live_router.py skips circuit admission in the legacy path when recovery is disabled, the production default, so a refused request can still dial the provider. Call allow_request() before dialing in that path.
  • streaming.py keeps the process-local circuit family-wide even when the Redis quarantine is endpoint-scoped, so a failed custom endpoint can make failover skip a healthy default Modulate target. Key the circuit by endpoint too.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/stt/ARCHITECTURE.md">

<violation number="1" location="backend/utils/stt/ARCHITECTURE.md:215">
P3: Two added paragraphs contradict each other about router-fault fallback order. Here (backend/utils/stt/ARCHITECTURE.md:214-215) "a generic router error carries no snapshot and keeps pure configured order," but the new paragraph at 232-236 states "Router exceptions and cache unavailability with a valid registry fail open to the same filtered chain ... canary sessions keep permitted registry target identities, non-canary sessions keep the filtered static chain — never the raw configured order." Both describe the same router-error path, so a reader cannot tell whether a generic router error yields the pure configured order or the filtered chain. Align the two statements so the fail-open contract is unambiguous.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_soniox_rate_limit.py:360">
P3: `circuit._probes_in_flight == 0` passes without ever exercising probe release: the fresh target circuit stays `closed` for the whole test, and `ProviderCircuitBreaker.allow_request` returns True in the closed state without claiming a probe, so the 429 has no probe to release. A regression that leaks or mis-balances target-circuit probes on the router-on path would still pass this test, contradicting its stated coverage. Drive the breaker open (threshold 3, so three `record_failure()` calls) and claim a forced half-open probe before connecting, mirroring `test_half_open_429_releases_probe_slot_without_extending_bench`, so the assertion verifies the release path.</violation>
</file>

<file name="backend/config/live_stt_registry.py">

<violation number="1" location="backend/config/live_stt_registry.py:40">
P3: The new hard-cap branch has no direct test coverage: existing tests exercise parakeet-window only with the default ramp_percent=100 (e.g. test_live_cost_router.py::test_sticky_ramp_cohort_and_router_gate sets PARAKEET_WINDOW_ALLOCATION_PERCENT to 25 and only checks DEFAULT_TARGETS, where min(100, env) never binds), so nothing asserts the config cap actually cuts the allocation. Add a test with a custom 'parakeet-window' target whose ramp_percent is below the env allocation and assert ramp() returns the narrower value.</violation>
</file>

<file name=".github/failure-classes/FC-cache-merge-write-race.json">

<violation number="1" location=".github/failure-classes/FC-cache-merge-write-race.json:6">
P2: The declared guard artifact does not exercise the race this class records. All bench-quarantine tests in test_live_router_hardening.py run one writer at a time (observing pod flushes, then a sibling reads), so they pass unchanged if the BENCH_UPDATE Lua script in backend/utils/stt/live_health.py regresses to a GET-modify-SET: no two writers interleave their read/write on the shared account state key. Ratchet then treats the class as guarded while the exact loss it was filed for recurs. Add a test that interleaves two pods' write of the shared account key (e.g., pod A reads, pod B writes, pod A SETs on stale read) and asserts both entries survive; or point the artifact at the script guard itself.</violation>
</file>

<file name="backend/utils/stt/live_chain.py">

<violation number="1" location="backend/utils/stt/live_chain.py:208">
P1: This fallback synthesizes an unconstrained default route whenever a configured family has only endpoint targets, so a registry target with `ramp_percent=0` or incompatible capabilities can still be dialed through the legacy callback. Treat a configured family with no permitted canonical default as unavailable; only synthesize the legacy target for genuinely unregistered families or an explicitly supported legacy-engine case.</violation>
</file>

<file name="backend/scripts/stt/reset_fleet_provider.py">

<violation number="1" location="backend/scripts/stt/reset_fleet_provider.py:47">
P2: This reset only scans the family-default endpoint partition, so it cannot clear a named provider's custom-endpoint bench, probe, or scores. Scan every configured endpoint partition or require an endpoint selector when resetting providers with custom targets.</violation>
</file>

<file name="backend/utils/stt/live_router.py">

<violation number="1" location="backend/utils/stt/live_router.py:185">
P1: This admission-refused circuit is bypassed when recovery is disabled, which is the production default: the legacy attempt path never calls `allow_request()` before dialing. Enforce the circuit admission in that path or otherwise reject the target before `connect()` so a full breaker cache actually denies new identities.</violation>
</file>

<file name="backend/utils/stt/streaming.py">

<violation number="1" location="backend/utils/stt/streaming.py:255">
P1: `endpoint=endpoint` scopes only the Redis quarantine; the process-local circuit remains family-wide, so a custom-endpoint death can make failover skip the healthy default Modulate target. Use the endpoint-keyed target circuit for selection deaths and reserve the family circuit for account failures.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/test_live_router_hardening.py:887">
P2: These subprocess and fresh-module-loading tests are unmarked in the unit-test directory, so the normal unit lane runs non-unit process/reload work and subjects this 2,262-line file to the fast-test duration guard. Mark the affected tests (or the module) `slow`/`integration` and add the file to the slow guardrail manifest if it is intended to run in that lane.</violation>
</file>

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

<violation number="1" location="backend/tests/unit/conftest.py:233">
P3: `vars(shared).update(vars(fresh))` copies the fresh instance's `_lock` (a brand-new unlocked RLock) into `shared` while the fixture is inside `with shared._lock:`. The lock protecting the swap is therefore replaced mid-copy, so any code that grabs the new `_lock` concurrently sees a half-reset singleton and the held old lock is abandoned. Copy the state attributes but keep the existing lock.</violation>

<violation number="2" location="backend/tests/unit/conftest.py:240">
P3: Clearing `_family_circuits_identity` only resets the identity latch; the module-level family breakers (`_parakeet_circuit`, `_modulate_circuit`, etc.) keep whatever state the previous test left them in. After `clear()`, `_circuit_for_primary` takes its first-seen branch (`identity.get(family) is None`) and does not call `circuit.reset()`, so a breaker left open/half-open by an earlier test carries into the next test in files that do not swap the breakers via their own fixture. Reset the family circuits alongside the identity clear.</violation>
</file>

<file name="backend/utils/stt/live_cost_health.py">

<violation number="1" location="backend/utils/stt/live_cost_health.py:541">
P3: `refresh_cost_once` now reads `self._cost_interests` outside `self._lock` (the dedented `keys = sorted(...)` block), while the dict is mutated only under that lock in `cost_snapshot` and in this function's own locked section. This read is also outside the function's try/except, so a resize-detection `RuntimeError` from concurrent mutation would propagate up through `refresh_forever` and kill the periodic refresh task. Snapshot the interests under the lock before building `keys`.</violation>
</file>

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

Re-trigger cubic

):
return target, routing_models
engine = (routing_models or {}).get(service.value)
pseudo = Target(

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: This fallback synthesizes an unconstrained default route whenever a configured family has only endpoint targets, so a registry target with ramp_percent=0 or incompatible capabilities can still be dialed through the legacy callback. Treat a configured family with no permitted canonical default as unavailable; only synthesize the legacy target for genuinely unregistered families or an explicitly supported legacy-engine case.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/live_chain.py, line 208:

<comment>This fallback synthesizes an unconstrained default route whenever a configured family has only endpoint targets, so a registry target with `ramp_percent=0` or incompatible capabilities can still be dialed through the legacy callback. Treat a configured family with no permitted canonical default as unavailable; only synthesize the legacy target for genuinely unregistered families or an explicitly supported legacy-engine case.</comment>

<file context>
@@ -148,30 +155,114 @@ async def connect_configured_chain(
+                ):
+                    return target, routing_models
+        engine = (routing_models or {}).get(service.value)
+        pseudo = Target(
+            id=engine or ('parakeet' if service.value == 'parakeet' else DEFAULT_IDS.get(service.value, service.value)),
+            family=service.value,
</file context>

None,
)
if evicted is None:
return _target_circuit_admission_refused

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: This admission-refused circuit is bypassed when recovery is disabled, which is the production default: the legacy attempt path never calls allow_request() before dialing. Enforce the circuit admission in that path or otherwise reject the target before connect() so a full breaker cache actually denies new identities.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/live_router.py, line 185:

<comment>This admission-refused circuit is bypassed when recovery is disabled, which is the production default: the legacy attempt path never calls `allow_request()` before dialing. Enforce the circuit admission in that path or otherwise reject the target before `connect()` so a full breaker cache actually denies new identities.</comment>

<file context>
@@ -73,14 +148,44 @@ def engine_matches(target: Target, models: dict[str, str | None] | None) -> bool
+                    None,
+                )
+                if evicted is None:
+                    return _target_circuit_admission_refused
+                del _target_circuits[evicted]
+            circuit = _target_circuits[identity] = ProviderCircuitBreaker(failure_threshold=3, cooldown_seconds=30)
</file context>

if reason in ACCOUNT_REJECTION_REASONS
else circuit.serve_error_bench_seconds
),
endpoint=endpoint,

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: endpoint=endpoint scopes only the Redis quarantine; the process-local circuit remains family-wide, so a custom-endpoint death can make failover skip the healthy default Modulate target. Use the endpoint-keyed target circuit for selection deaths and reserve the family circuit for account failures.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/streaming.py, line 255:

<comment>`endpoint=endpoint` scopes only the Redis quarantine; the process-local circuit remains family-wide, so a custom-endpoint death can make failover skip the healthy default Modulate target. Use the endpoint-keyed target circuit for selection deaths and reserve the family circuit for account failures.</comment>

<file context>
@@ -217,6 +252,7 @@ def open_provider_selection_circuit(provider: str | None, *, reason: str) -> boo
             if reason in ACCOUNT_REJECTION_REASONS
             else circuit.serve_error_bench_seconds
         ),
+        endpoint=endpoint,
     )
     # Logged AFTER the record so bench_seconds is the window just armed — an
</file context>

"id": "FC-cache-merge-write-race",
"violated_contract": "A cache value that multiple independent writers merge into -- each request reads the whole blob, edits only its own entry, and writes the whole blob back -- must serialize that read-modify-write. Otherwise two writers racing on the same key silently drop whichever entry the losing writer's SET overwrote, indistinguishable from a successful write, and nothing detects or heals the loss.",
"canonical_prevention": "Perform the merge as a single atomic server-side operation (a Lua script, or a per-field command such as HSET) instead of a GET-modify-SET in the caller, so no writer's read can observe a value another writer is about to overwrite.",
"canonical_prevention_artifact": [

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: The declared guard artifact does not exercise the race this class records. All bench-quarantine tests in test_live_router_hardening.py run one writer at a time (observing pod flushes, then a sibling reads), so they pass unchanged if the BENCH_UPDATE Lua script in backend/utils/stt/live_health.py regresses to a GET-modify-SET: no two writers interleave their read/write on the shared account state key. Ratchet then treats the class as guarded while the exact loss it was filed for recurs. Add a test that interleaves two pods' write of the shared account key (e.g., pod A reads, pod B writes, pod A SETs on stale read) and asserts both entries survive; or point the artifact at the script guard itself.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At .github/failure-classes/FC-cache-merge-write-race.json, line 6:

<comment>The declared guard artifact does not exercise the race this class records. All bench-quarantine tests in test_live_router_hardening.py run one writer at a time (observing pod flushes, then a sibling reads), so they pass unchanged if the BENCH_UPDATE Lua script in backend/utils/stt/live_health.py regresses to a GET-modify-SET: no two writers interleave their read/write on the shared account state key. Ratchet then treats the class as guarded while the exact loss it was filed for recurs. Add a test that interleaves two pods' write of the shared account key (e.g., pod A reads, pod B writes, pod A SETs on stale read) and asserts both entries survive; or point the artifact at the script guard itself.</comment>

<file context>
@@ -3,6 +3,9 @@
   "id": "FC-cache-merge-write-race",
   "violated_contract": "A cache value that multiple independent writers merge into -- each request reads the whole blob, edits only its own entry, and writes the whole blob back -- must serialize that read-modify-write. Otherwise two writers racing on the same key silently drop whichever entry the losing writer's SET overwrote, indistinguishable from a successful write, and nothing detects or heals the loss.",
   "canonical_prevention": "Perform the merge as a single atomic server-side operation (a Lua script, or a per-field command such as HSET) instead of a GET-modify-SET in the caller, so no writer's read can observe a value another writer is about to overwrite.",
+  "canonical_prevention_artifact": [
+    "backend/tests/unit/test_live_router_hardening.py"
+  ],
</file context>

retry_on_timeout=False,
)
keys: list[bytes | str] = [f'{PREFIX}:state:{args.provider}', f'{PREFIX}:probe:{args.provider}']
prefix = live_stt_state.fleet_prefix(args.provider)

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: This reset only scans the family-default endpoint partition, so it cannot clear a named provider's custom-endpoint bench, probe, or scores. Scan every configured endpoint partition or require an endpoint selector when resetting providers with custom targets.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/stt/reset_fleet_provider.py, line 47:

<comment>This reset only scans the family-default endpoint partition, so it cannot clear a named provider's custom-endpoint bench, probe, or scores. Scan every configured endpoint partition or require an endpoint selector when resetting providers with custom targets.</comment>

<file context>
@@ -32,10 +44,16 @@ def main() -> int:
         retry_on_timeout=False,
     )
-    keys: list[bytes | str] = [f'{PREFIX}:state:{args.provider}', f'{PREFIX}:probe:{args.provider}']
+    prefix = live_stt_state.fleet_prefix(args.provider)
+    keys: list[bytes | str] = [
+        live_stt_state.fleet_state_key(args.provider),
</file context>

assert live_router.target_circuit(selected) is circuit
assert circuit.state == 'closed'
assert circuit._failures == 0
assert circuit._probes_in_flight == 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.

P3: circuit._probes_in_flight == 0 passes without ever exercising probe release: the fresh target circuit stays closed for the whole test, and ProviderCircuitBreaker.allow_request returns True in the closed state without claiming a probe, so the 429 has no probe to release. A regression that leaks or mis-balances target-circuit probes on the router-on path would still pass this test, contradicting its stated coverage. Drive the breaker open (threshold 3, so three record_failure() calls) and claim a forced half-open probe before connecting, mirroring test_half_open_429_releases_probe_slot_without_extending_bench, so the assertion verifies the release path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_soniox_rate_limit.py, line 360:

<comment>`circuit._probes_in_flight == 0` passes without ever exercising probe release: the fresh target circuit stays `closed` for the whole test, and `ProviderCircuitBreaker.allow_request` returns True in the closed state without claiming a probe, so the 429 has no probe to release. A regression that leaks or mis-balances target-circuit probes on the router-on path would still pass this test, contradicting its stated coverage. Drive the breaker open (threshold 3, so three `record_failure()` calls) and claim a forced half-open probe before connecting, mirroring `test_half_open_429_releases_probe_slot_without_extending_bench`, so the assertion verifies the release path.</comment>

<file context>
@@ -352,9 +354,10 @@ async def connect():
+    assert live_router.target_circuit(selected) is circuit
+    assert circuit.state == 'closed'
+    assert circuit._failures == 0
+    assert circuit._probes_in_flight == 0
     assert streaming._soniox_circuit._probes_in_flight == 0
     assert quarantined == []
</file context>

def ramp(self) -> float:
return percent('PARAKEET_WINDOW_ALLOCATION_PERCENT', 0) if self.id == 'parakeet-window' else self.ramp_percent
if self.id == 'parakeet-window':
return min(self.ramp_percent, percent('PARAKEET_WINDOW_ALLOCATION_PERCENT', 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.

P3: The new hard-cap branch has no direct test coverage: existing tests exercise parakeet-window only with the default ramp_percent=100 (e.g. test_live_cost_router.py::test_sticky_ramp_cohort_and_router_gate sets PARAKEET_WINDOW_ALLOCATION_PERCENT to 25 and only checks DEFAULT_TARGETS, where min(100, env) never binds), so nothing asserts the config cap actually cuts the allocation. Add a test with a custom 'parakeet-window' target whose ramp_percent is below the env allocation and assert ramp() returns the narrower value.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/config/live_stt_registry.py, line 40:

<comment>The new hard-cap branch has no direct test coverage: existing tests exercise parakeet-window only with the default ramp_percent=100 (e.g. test_live_cost_router.py::test_sticky_ramp_cohort_and_router_gate sets PARAKEET_WINDOW_ALLOCATION_PERCENT to 25 and only checks DEFAULT_TARGETS, where min(100, env) never binds), so nothing asserts the config cap actually cuts the allocation. Add a test with a custom 'parakeet-window' target whose ramp_percent is below the env allocation and assert ramp() returns the narrower value.</comment>

<file context>
@@ -36,7 +36,9 @@ def capable(self, language: str | None, features: frozenset[str] = frozenset({'s
     def ramp(self) -> float:
-        return percent('PARAKEET_WINDOW_ALLOCATION_PERCENT', 0) if self.id == 'parakeet-window' else self.ramp_percent
+        if self.id == 'parakeet-window':
+            return min(self.ramp_percent, percent('PARAKEET_WINDOW_ALLOCATION_PERCENT', 0))
+        return self.ramp_percent
 
</file context>

# a freshly swapped breaker.
from utils.stt import streaming

streaming._family_circuits_identity.clear()

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: Clearing _family_circuits_identity only resets the identity latch; the module-level family breakers (_parakeet_circuit, _modulate_circuit, etc.) keep whatever state the previous test left them in. After clear(), _circuit_for_primary takes its first-seen branch (identity.get(family) is None) and does not call circuit.reset(), so a breaker left open/half-open by an earlier test carries into the next test in files that do not swap the breakers via their own fixture. Reset the family circuits alongside the identity clear.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/conftest.py, line 240:

<comment>Clearing `_family_circuits_identity` only resets the identity latch; the module-level family breakers (`_parakeet_circuit`, `_modulate_circuit`, etc.) keep whatever state the previous test left them in. After `clear()`, `_circuit_for_primary` takes its first-seen branch (`identity.get(family) is None`) and does not call `circuit.reset()`, so a breaker left open/half-open by an earlier test carries into the next test in files that do not swap the breakers via their own fixture. Reset the family circuits alongside the identity clear.</comment>

<file context>
@@ -203,3 +205,37 @@ def __setitem__(self, key, value):
+        # a freshly swapped breaker.
+        from utils.stt import streaming
+
+        streaming._family_circuits_identity.clear()
+    yield
</file context>
Suggested change
streaming._family_circuits_identity.clear()
from utils.stt import streaming
for name in ('_parakeet_circuit', '_deepgram_circuit', '_modulate_circuit', '_soniox_circuit'):
circuit = getattr(streaming, name, None)
if circuit is not None:
circuit.reset()
streaming._family_circuits_identity.clear()

shared = live_health.health
fresh = type(shared)()
with shared._lock:
vars(shared).update(vars(fresh))

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: vars(shared).update(vars(fresh)) copies the fresh instance's _lock (a brand-new unlocked RLock) into shared while the fixture is inside with shared._lock:. The lock protecting the swap is therefore replaced mid-copy, so any code that grabs the new _lock concurrently sees a half-reset singleton and the held old lock is abandoned. Copy the state attributes but keep the existing lock.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/conftest.py, line 233:

<comment>`vars(shared).update(vars(fresh))` copies the fresh instance's `_lock` (a brand-new unlocked RLock) into `shared` while the fixture is inside `with shared._lock:`. The lock protecting the swap is therefore replaced mid-copy, so any code that grabs the new `_lock` concurrently sees a half-reset singleton and the held old lock is abandoned. Copy the state attributes but keep the existing lock.</comment>

<file context>
@@ -203,3 +205,37 @@ def __setitem__(self, key, value):
+    shared = live_health.health
+    fresh = type(shared)()
+    with shared._lock:
+        vars(shared).update(vars(fresh))
+    if 'utils.stt.streaming' in sys.modules:
+        # Family circuits re-derive their per-family endpoint/credential identity
</file context>

preferred = dict(self._cost_preferred)
keys = sorted(
{(target.id, lang) for target in targets for lang in ('all', *sorted(live_stt_state.ROUTED_LANGUAGES))}
| set(self._cost_interests)

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: refresh_cost_once now reads self._cost_interests outside self._lock (the dedented keys = sorted(...) block), while the dict is mutated only under that lock in cost_snapshot and in this function's own locked section. This read is also outside the function's try/except, so a resize-detection RuntimeError from concurrent mutation would propagate up through refresh_forever and kill the periodic refresh task. Snapshot the interests under the lock before building keys.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/stt/live_cost_health.py, line 541:

<comment>`refresh_cost_once` now reads `self._cost_interests` outside `self._lock` (the dedented `keys = sorted(...)` block), while the dict is mutated only under that lock in `cost_snapshot` and in this function's own locked section. This read is also outside the function's try/except, so a resize-detection `RuntimeError` from concurrent mutation would propagate up through `refresh_forever` and kill the periodic refresh task. Snapshot the interests under the lock before building `keys`.</comment>

<file context>
@@ -417,14 +535,24 @@ async def refresh_cost_once(self) -> None:
             preferred = dict(self._cost_preferred)
+        keys = sorted(
+            {(target.id, lang) for target in targets for lang in ('all', *sorted(live_stt_state.ROUTED_LANGUAGES))}
+            | set(self._cost_interests)
+        )
         if not keys or now < self._redis_retry_at:
</file context>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0dbe1574ff

ℹ️ 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".

retry_on_timeout=False,
)
keys: list[bytes | str] = [f'{PREFIX}:state:{args.provider}', f'{PREFIX}:probe:{args.provider}']
prefix = live_stt_state.fleet_prefix(args.provider)

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 Badge Reset every configured endpoint for the provider

When the provider has a registry target with a custom endpoint, its scores, selection bench, and probe are stored under fleet_prefix(provider, endpoint=target.endpoint), but this reset scans and deletes only the configured family-default prefix. Consequently, --execute modulate can report success while leaving a custom Modulate endpoint quarantined after an operator repair. Enumerate the provider's registered endpoint prefixes, or accept an explicit target/endpoint to reset.

Useful? React with 👍 / 👎.

# a freshly swapped breaker.
from utils.stt import streaming

streaming._family_circuits_identity.clear()

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 Badge Reset family breaker state between unit tests

This autouse fixture clears only the family-to-identity map, while the process-global ProviderCircuitBreaker objects retain their open/half-open state. If one test opens a family account or selection circuit, the next test's first _circuit_for_primary() call sees no recorded identity, records the current identity without calling reset(), and returns the still-open breaker, making otherwise unrelated tests order-dependent. Reset the family breaker objects as part of this fixture rather than clearing only their identity bookkeeping.

AGENTS.md reference: backend/AGENTS.md:L219-L219

Useful? React with 👍 / 👎.

Comment on lines +218 to +225
if permitted_target(
target,
routing_uid,
routing_language,
routing_languages,
engine_models,
account_states,
):

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 Badge Handle permission parsing failures as chain unavailability

When a configured Parakeet chain has a malformed PARAKEET_WINDOW_ALLOCATION_PERCENT—for example a nonnumeric value or one outside 0–100—permitted_target() calls Target.ramp() here and raises ValueError outside the router's guarded section. Because this new permission pass runs in on, shadow, and off, even the kill-switch modes now terminate initial sessions as initialization_failed, while recovery misclassifies the same configuration fault as an individual provider-connect error. Catch configuration errors around this hard-permission pass and raise the bounded ProviderChainUnavailable path, or reject them during startup validation.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 4, 2026 06:30
Separate local endpoint selection evidence from credential account benches so key rotation cannot reopen a failing endpoint. Keep custom-endpoint deaths off the family default breaker.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c033629891

ℹ️ 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".

Comment on lines 711 to 712
self._cached_scores = scores
self._cached_benches = benches

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 Badge Preserve endpoint health while caching account-only views

When an endpoint has both a longer selection bench and a currently active account bench, benches contains only the account tuple; in routing-off mode it likewise contains only account state while scores is empty. Replacing both caches here therefore discards previously learned endpoint selection deadlines and scores. If the account bench expires or routing is re-enabled before another successful Redis refresh—especially during a Redis outage—this pod treats the endpoint as neutral and can dial an endpoint whose selection quarantine is still live. Keep account and selection state independently, or merge account-only refreshes without erasing the endpoint caches.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 3ab92d5 into main Oct 4, 2026
59 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-router-hardening branch October 4, 2026 00:36
Git-on-my-level added a commit that referenced this pull request Oct 6, 2026
…amp (#20741)

Malformed window allocation escaped the configured-chain failure
boundary; endpoint selection quarantine disappeared after account
masking or an OFF refresh; and refresh read cost interests without its
owning lock. This draft retains the typed five-second config retry,
preserves cached endpoint evidence across masking/OFF and Redis outages,
and snapshots interests under the lock. The unit singleton reset now
retains its RLock and resets all four family breakers in place.

Keep draft. Coordinator owns review/merge/deployment; no production
configuration changes.

## Validation

- All ten new tests in `test_live_router_cache_isolation.py` fail
against origin/main cf8201c and pass with this change:
default/custom endpoint account-expiry and OFF→ON outage cases,
authoritative clearing, lock-held interest iteration, singleton
lock/reference preservation, and all four family breakers.
- Existing malformed-allocation regression: 15 failing-on-main cases
covering OFF/SHADOW/ON.
- Focused router/session/health suites through `backend/test.sh`; `make
preflight` and normal commit/push hooks. Test cloud credentials
stripped, isolated CLOUDSDK_CONFIG, synthetic providers/Redis only.
- Shared cache and fixture primitives close #20422 threads
28/29/30/32/34 without adding another admission guard.

## Ramp handoff

`.local/READINESS.md` and `.local/GATES.md` hold the coordinator
handoff. Corrected aggregate-only ro-prod Prometheus access succeeds.
Modulate qualification is not a blocker for the default-only first ramp
per coordinator decision. Custom-endpoint operator reset (#20422 threads
22/31) is a filed follow-up, outside this draft. Separate cohort
instrumentation draft supplies missing
terminal/transcript/exhausted/TAT/paid-audio splits. Live acceptance,
paid headroom, alert delivery and uniform serving configuration remain
coordinator prerequisites.

## Rollback

Revert through a normal PR. Later routing ramps roll back through the
canonical reviewed config path to percent 0 / shadow. This draft changes
no routing allocation.

## Product invariants affected

none

Failure-Class: none

The triggering cache/concurrency/test-isolation findings are #20422
discussion_r4175455504, discussion_r4175035352, discussion_r4175035349
and discussion_r4175055824; no registry edit is made in this lane.

Line-Count-Exception: backend/utils/stt/live_chain.py | 1066 -> 1079 |
Catch malformed hard-permission configuration at the existing
configured-chain boundary and emit typed unavailability plus bounded
diagnostics in all routing modes.

CI at aecaed4: full unit shards 1/4 and
4/4 plus aggregate are red for five baseline failures, reproduced
identically on restored main cf8201c and restored lane. Four
desktop TTS fixtures reject check_tts_rate_limit_for_user; one
shared-action-item fixture patches removed _wake_task_changes. Evidence
and a separately scoped follow-up are recorded in
.local/FOLLOW_UP_BASELINE_CI.md. Other terminal checks passed; no
STT-caused failure found.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant