Repository navigation
feat(backend): add isolated listen canary and dev STT soak - #20418
Merged
Merged
Conversation
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
4 of 6 tasks
Git-on-my-level
added a commit
that referenced
this pull request
Oct 3, 2026
) ## Summary **Supersedes #20357. Merges inert; enabled only on the canary Deployment via `STT_FAILOVER_RECOVERY_ENABLED=true`. No PR merge or deployment performed.** The pod-level switch defaults false in code, dev/prod listen charts, runtime base and overlays. One mode is read at session construction and propagated to the receiver, successor legs, callbacks and spawned writers; a session never switches mid-flight. Unset/false/invalid values retain current main's recovery, replay, capture, paid writer, rejection/circuit and settlement behavior, including #20393's managed `owner_closing` fence. The semantics-preserving PCM ring optimization below remains active in both modes. Failure-Class: FC-live-stt-audio-lost-on-provider-death No provider-order, allocation, routing-default, health namespace or workflow changes. Keep `STT_ROUTING_MODE=shadow`, `STT_ROUTING_ON_PERCENT=0`. Main through `bf48ed0e68674a0d5d3c3e17f57dff042156b15d` was merged normally in `abcadb4bc5b6418d9fe969baa5262e7eda054540`, retaining upstream STT log sanitization, #20418 canary tooling, #20433 abandoned Parakeet queue cleanup and subsequent serving changes. The legacy controller/replay/paid-writer baseline remains `147f77d86a`: later main merges change none of those extracted recovery functions. The new main Parakeet POST-budget/queue-timeout contract applies identically in both flag modes, and unrelated deployment settings retain latest main exactly. The merge hook's unrelated Flutter formatting was restored byte-for-byte to main; locked dependency resolution made all 117 restored files format-stable, and the repair commit passed the normal hook. No stash, rebase, force-push, hook bypass, customer transcript/audio read, cloud mutation, PR merge or deploy. ## PCM ring hot path — independent of recovery enablement `AudioRingBuffer._append_bytes` now keeps the newest capacity-sized suffix with at most two memoryview bulk copies, replacing a Python loop for every byte. Capacity, physical overwrite order, absolute counters, span ledger and read APIs are unchanged. No await, lock, thread or bytearray resize was added; the existing caller ownership/scheduling contract is unchanged. Local Python 3.11.15 microbenchmark, `time.process_time_ns`, median of five runs over 135 s of 16 kHz mono PCM16 (4,320,000 bytes). Allocation/payload creation are outside timing; the public positioned-write path and span recording are included. These are local measurements under load, not production CPU measurements: | Input | Before CPU / 135 s | After CPU / 135 s | CPU per second of audio, before → after | | --- | ---: | ---: | ---: | | 4,500 live 30 ms packets | 127.055 ms | 3.410 ms | 0.941148 → 0.025259 ms (37.3× faster) | | One full-ring write | 125.977 ms | 0.099 ms | 0.933163 → 0.000733 ms (1,272.5× faster) | Both public write APIs have full-ring and live-packet tests asserting <0.10 s CPU, below the unchanged 0.30 s fast-test guard. All four performance cases failed before the optimization and pass after it. Small reference-model tests cover capacities 1/2/7/10, empty/exact-wrap/oversized multi-wrap/subsequent writes, counters, extraction and timestamps. The retained boundaries are asserted exactly: profiling pinned pytest 8.4.1 proved its first scalar `pytest.approx` equality imports NumPy (`is_bool`), dominating the tiny ten-byte test. Removing that unnecessary approximate comparison strengthens the assertions and removes a real cold-import cost; payloads, timed regions and both performance/guard thresholds are unchanged. The profiled NumPy import accounted for 0.485 of 0.487 cumulative profile seconds in that test (diagnostic profile time, not a production CPU measurement). Evidence: `.pytest-tmp/pcm-cold-approx.pstats`; the strengthened ring file passes 24 tests with zero guard warnings (`inert-exact-ring-assertions.log`). Seven selected files through `backend/test.sh`: 336 passed, one slow deselected. Evidence: `.pytest-tmp/pcm_ring_benchmark.py`, `pcm-ring-before.json`, `pcm-ring-after.json`, and `.pytest-tmp/logs/test-sh-selected.log`. The previously unpushed all-cooling/test-isolation round and ring fix were published normally at `e67b5ebfb9cb8d995d57c202bcbff8abd7b494ec`. All local hooks passed, including the 0.30 s CPU guard; `make preflight` passed 31 checks. That intermediate head had a main merge conflict and only CodeQL ran remotely, so it is not a backend-CI receipt. Logs: `.pytest-tmp/logs/pcm-ring-push.log`, `pcm-ring-make-preflight.log`. ## Flag-off equivalence and validation Baseline: main `147f77d86a2de9d68cec63b6adeb69bd282aeeae`. - **Ten extracted function bodies match baseline AST**, normalizing only helper-module qualification, the finishing-helper name and function docstrings: receiver failover/rebuild/monitor/flush; replay reconnect/rejected-successor retry/synchronous send; configured-chain attempt; replacement selection; reconnect admission. Evidence: lead-authored `.pytest-tmp/flag_equivalence_audit.py` and `flag-equivalence-audit.json`. - **285 original main tests passed with false, and the same 285 passed unset**, through `test.sh` and the unchanged guard. The ten test files were byte-identical to pinned main: death monitor, resilient stream, session failover, managed fence, Parakeet exhaustion, Soniox rate-limit/typed rejection, Modulate socket/capacity, configured chain. No assertion edits. Preserved original sources and hashes: `.pytest-tmp/baseline-stt-recovery-sources/`, `baseline-stt-hashes.txt`, `flag-equivalence-audit.json`; logs `test-sh-baseline-{false,unset}.log`. After the ring pin correction, the unmodified original resilient suite passed again both false and unset (22 each). - **42 flag-contract tests passed**: fail-closed parsing; runtime/receiver/ring/VAD/real paid successor pins in both env-flip directions; task/context propagation and cancellation reset; plain 2,000-item queues and unchanged EOS off; legacy vs enabled 429 circuits; 135/150 s caps and legacy reconnect budgets; managed fence retained; departure settlement; no new counter or histogram observations off while baseline replay metrics still emit. File-local fixtures isolate circuits, backoff and health, with no network/Redis access. Initial log: `test-sh-flag-isolated-final.log`; final pin-entry regressions: `inert-ci-pin-fix.log`. - **Flag-on matrix: 97 fast passed; provider-pair suite: 27 passed.** File-local ON fixtures preserve the matrix and branch qualification assertions; there is no global fixture silently forcing production default on. Flag-contract plus matrix/provider-pair narrow run: 162 passed, one slow deselected (`test-sh-narrow-final.log`). Cost-router, speaker/capture-birth and evidence-settlement follow-up files also passed after explicitly enabling their qualification fixtures. After integrating #20433, the window suite (161), matrix (97) and provider pairs (27) passed together with the unchanged guard (`inert-main-queue-composition.log`). Eleven byte-identical newest-main queue-contract cases also passed OFF, including the actual marked-503 receiver failover (`inert-main-queue-off.log`). - **196 deployment/default checks passed** (Helm/env/render/validator/key bindings); runtime compose `--check` and feature-flag registry checks passed. Typecheck: **0 errors** (`typecheck-rework.log`). No timing-guard/duration-allowlist, CI threshold or security-policy relaxations. The proper flag-on slow lane also passed: **1 passed, 97 deselected** (`.pytest-tmp/logs/inert-slow.log`). Final local preflight passed **41 checks**, and PR-body CI-lane preflight passed **40 checks**, after registering the new flag's non-secret/config and listen-only ownership. Evidence: `inert-make-preflight.log`, `inert-pr-preflight.log`; those metadata additions are committed before publication. After the final main merge, compose/registry checks and **24 upstream canary-tooling tests** passed with the default timing guard (`inert-post-merge.log`); the worktree is clean with no app/workflow diff against main. The first inert push was correctly blocked by fixtures that bypassed receiver construction and by two qualification files missing explicit ON mode. A test-only follow-up pins those doubles coherently and enables only the affected test modules; all assertions remain unchanged. The three failing files now pass **192 tests**, and the two affected original-main baseline files pass again false and unset (**42 each**) without silently enabling their imported shared fixture. Logs: `inert-fixture-followup.log`, `inert-baseline-helper-{false,unset}.log`. No production follow-up or timing-budget relaxation was needed. A subsequent full normal-hook retry passed every assertion but blocked on one existing Parakeet case at 0.35 s CPU; the required single-file `test.sh` rerun passed all 151 tests, with that case at 0.24 s under the unchanged 0.30 s guard (`inert-timing-single-file.log`). Normal push and complete remote CI remain pending; the receipt below will be updated on the exact published head. ## Serving behaviour changes — complete gate map Paths below are the final serving surface. OFF preserves pinned-main behavior; ON enables the described recovery changes. Declarative limits/metric registration may exist in OFF images but have no OFF serving consumers/emissions. | File:line | Gate / serving change | | --- | --- | | `backend/utils/audio.py:41` | Ungated, semantics-preserving two-copy PCM hot-path optimization described above. | | `backend/config/live_stt_recovery.py:18,21,28` | Pure fail-closed env/context lookup and explicit owner pin; no per-user cohort or Redis switch. | | `backend/routers/listen/runtime.py:134,410,920` | Session-start snapshot, whole-run context lifetime and ON-only terminal-after-text emission; existing any-text SLI unchanged. | | `backend/routers/listen/receiver.py:243,867,1253,1294,1420,1578,1666,2075` | ON-only controller, unified dial/replay/adoption/ingestion/birth path; OFF dispatches original locked/synchronous recovery, capture and monitor behavior. | | `backend/routers/listen/legacy_recovery.py:27,46,147,183` | OFF-only main failover/rebuild/monitor/flush implementations, including old failure latch, attempt limits and synchronous prefix replay. | | `backend/utils/stt/recovery_state.py:59,115,279` | ON-only controller instantiated by receiver: lifecycle, episode/time/unique-target accounting and candidate-bound recovery proof. | | `backend/utils/stt/resilient_stream.py:73,162,188,323,357,478` | Pinned 135 s OFF / 150 s ON headroom; restored 3-total/2-per-minute/30 s cumulative OFF reconnect budget. Managed owner fence stays in both; unmanaged raw finishing remains authoritative OFF. New bounded capture/paced replay is ON-only. | | `backend/utils/stt/legacy_replay.py:24,120,149` | OFF-only main Soniox reconnect, rejected-successor retry and synchronous replay, with baseline metrics. | | `backend/utils/stt/live_recovery.py:25,32,69` | OFF retains 3 managed / 2 legacy rebuild limits and main rescue condition; ON uses shared controller and the sole qualified Soniox repeat. | | `backend/utils/stt/live_chain.py:139,305,332,520,861` | OFF exact main attempt body, cleanup and 429 breaker semantics; ON target reservations, bounded dials, refusal backoff and one earliest-expiry all-cooling escape. | | `backend/utils/stt/connect_backoff.py:22,108,178` | ON-only serving use via chain gate; per-target 3-in-10 s refusal history, 2/4/8/10 s backoff, exclusive probe, bounded escape and healthy reset. OFF never acquires a lease or mutates this state. | | `backend/utils/stt/streaming.py:419,466,484,521,1403,1531,1593` | OFF legacy-primary 429 failure handling and plain Modulate writer/EOS; ON admission release and recovery-only paced/deadline-aware writer. Parakeet replay declarations at `1856,2095` are consumed only ON. | | `backend/utils/stt/soniox.py:196,263,268,357` | Pinned plain queue/no pacing/original send-finalize-EOS OFF; ON bounded queued/in-flight accounting, writer cadence and capture-age expiry. | | `backend/utils/stt/send_queue.py:16` | `AudioSendQueue` allocated only ON by paid adapters; OFF uses exact `asyncio.Queue(maxsize=2000)`. | | `backend/utils/stt/replay_delivery.py:145,211,354,492` | ON-only serving activation of writer pacing, newest-unanswered prefix, bounded birth ledger and ordered live tail; OFF never enters pump/skip/expiry paths. | | `backend/utils/stt/live_session.py:57,384,463,847,858,947` | Managed leg inherits session pin; ON-only cancellation disposal, waits, typed endpoint limits, controller departure and departing settlement; OFF main lifecycle retained. | | `backend/utils/stt/vad_gate.py:736,762` | VAD wrapper pins underlying mode and forwards new capacity waits only ON. | | `backend/utils/stt/live_failure.py:160,239,577` | Pending settlement inherits source/session mode; departure degradation and extra post-await lifecycle checks only ON; OFF existing exhaustion/termination semantics. | | `backend/utils/stt/live_outcome.py:53` | Mode metadata only; existing single serving-owned emission seam remains authoritative. | | `backend/utils/stt/live_metrics.py:5,24,29,113` | New bounded families can register/preinitialize at zero in either mode; all recovery observation sites and terminal-after-text emission are ON-only. Baseline metrics unchanged OFF. | | `backend/config/live_stt_replay.py:11`; `backend/config/live_stt_registry.py:26`; `backend/utils/stt/safe_socket.py:60` | Typed endpoint/adapter replay declarations are data only OFF and consumed by ON pumps; order/ramp defaults unchanged. | | `backend/deploy/runtime_env/_base.yaml:100`; `backend/deploy/runtime_env/dev.overlay.yaml:50`; `backend/deploy/runtime_env/prod.overlay.yaml:43`; `backend/deploy/runtime_env.yaml:139,2151` | Default-off runtime declaration and composed dev/prod manifests. | | `backend/charts/backend-listen/dev_omi_backend_listen_values.yaml:378`; `backend/charts/backend-listen/prod_omi_backend_listen_values.yaml:405`; `config/feature-flags.yaml:132` | Explicit false chart defaults and reviewed flag registry. | | `config/deployment-setting-classification.json:229`; `backend/scripts/verify_pusher_cohost_env_diff.py:99,203` | Declare the new boolean as non-secret configuration and as listen-only STT ownership in both environments; no secret mappings, shared-finalizer requirements or enforcement thresholds changed. | Line-Count-Exception: backend/routers/listen/receiver.py | 1842 -> 2237 | Default-off main recovery dispatch plus explicit ON session-owner replay/adoption/ingestion integration. Line-Count-Exception: backend/utils/stt/streaming.py | 2205 -> 2322 | Separate pinned OFF writer and ON recovery cadence/deadline branches plus shared target-aware bounded dials. ## Enabled recovery design and known trade-offs Only flag-on sessions use `serving → provider_died → recovering → replaying → recovered`, or terminal `exhausted` / `client_leaving`. Departure is owner/application lifecycle, never managed raw cleanup. One 60 s episode covers actual dials, replay and proof; real dials are capped at min(5 s, episode remaining). Up to 20 unique identities/episodes and one qualified Soniox repeat bound work. Skips consume no dial. Prefix adoption plus current-candidate text or an observed 5 s healthy-connected dwell releases the episode; silence is normal. Connected proof does not synthesize transcript success or settle a hop recovered. Replay defaults: 1× audio time, ≤16 KiB frames, two queued+in-flight slots, ≤2 s capacity wait. [Soniox real-time cadence](https://soniox.com/docs/stt/rt/error-handling#real-time-cadence) supports near-real-time delivery; [Modulate streaming reference](https://docs.modulate.ai/api-reference/stt/streaming.md) supplies no qualified accelerated ceiling, so 1× is conservative. Window/RNNT/Deepgram use conservative pump limits and their existing admission contracts, not a claim of qualified acceleration. Optional endpoint declarations may only tighten limits. **Loss trade-off:** at default 1× and a 20 s prefix wall, a 135 s unanswered backlog keeps the newest 20 s and skips 115 s from successor transcription, explicitly metered and retired once. Capture gaps do not count as audio. Slower endpoint limits, repeated failures and residence expiry can cut additional audio. Transport writes are not transcript acknowledgments. Live ingestion stays ordered in a ≤26 s tail; first capture acceptance is retained in a bounded 8,192-entry birth ledger. Tail writes have a 28 s capture-age bound, or are explicitly cut/rejected. The qualified one-handoff 20 ms consumer case measured ≤25.532 s capture-to-wire at 16 kHz including setup (≤26.044 s at 8 kHz), excluding transcript latency. Continuous 1× speech cannot catch up until admitted audio pauses. Conservative recovery-owned PCM allowance: 8,241,152 B/session; 125.75 MiB for 16 sessions at 16 kHz, 375.75 MiB at 48 kHz, excluding Python/VAD/POST/ordinary queues/RSS. 429s remain session-local refusal evidence ON, not account quarantine or a shared long serving bench. Three refusals in 10 s open 2/4/8/10 s process-local backoff. All-cooling cannot alone deny a fresh session: one earliest-expiry otherwise-admissible dial is allowed; an early lease does not extend/escalate cooldown. Account, withdrawal, failed-target, capability, window admission and recovery budgets remain enforced. Historical paid concurrency was supplied by the coordinator; fake surge tests do not establish current paid headroom. No global paid limiter was added. Historical aggregate exhausted events cannot be individually attributed. Reproductions cover stalled send/finalize queues outside replay and already-claimed failures settling after later departure. OFF keeps main semantics; ON departure settles degraded, with exhausted reserved for active bounded recovery exhaustion. PTT stays unpaced and retains its existing large-frame follow-up: independently supervised disconnect, bounded residual cursor, paced pump and EOS barrier are still needed. ## Canary observation and rollout — coordinator-owned, not performed New metrics are not fleet-wide SLIs while defaults are off. Set `${canary_pods:regex}` / `${control_pods:regex}` to escaped exact enabled-canary / flag-off control pod names and refresh after replacement. Current scrape does not carry `track`; do not filter on it. Missing telemetry/exposure is HOLD, not zero-loss proof. Examples, not executed production measurements: ```promql sum by (source,successor) (increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) histogram_quantile(0.95,sum by (le,source,successor) (rate(omi_stt_replay_wall_seconds_bucket{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[5m]))) sum by (source,successor) (increase(omi_stt_replay_skipped_seconds_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum by (provider) (increase(omi_live_session_terminal_after_text_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}"}[15m])) sum(increase(omi_stt_recovery_attempts_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${control_pods:regex}"}[15m])) > 0 ``` Proposed canary alerts (`for: 1m`), scoped rather than mixing inert controls: ```promql sum(increase(omi_fallback_total{job="backend-listen-metrics",namespace="prod-omi-backend",pod=~"${canary_pods:regex}",component="stt_live_session",from_mode=~"soniox|modulate",reason="capacity_full"}[5m])) > 0 sum(increase(omi_live_stt_terminal_failures_total{job="backend-listen-metrics",namespace="prod-omi-backend",phase=~"connection|send"}[25m])) > 3 ``` The latter is the supplied historical fleet 0–3/25 min baseline, not a measured per-canary threshold. Compare same-load controls and retain independent any-text/continuity checks. Two fixed canary pods plus isolated dev soak are the agreed mechanism (#20418), not an action performed here. First 15 min: ≥10 positive replays including both paid families, all canary pods scraped, zero replay-induced terminal/capacity deaths, replay p95 ≤20 s with ≥10 observations, no unexplained fresh skips, no sustained lifecycle residual, ≥50 sockets with ≥95% any-text and ≤2-point decline vs controls. First 60 min: ≥30 positive replays/≥5 per paid family/≥100 sockets, same no-loss/lifecycle gates, first-text p95 <30 s, window POST p95 <2 s, combined pressure/overflow ≤1% with ≥20 admissions. Missing exposure is HOLD; replay-induced terminal loss is ABORT. Approval, paid/public-speech soak, vendor capacity/quality/billing/RSS/backfill and attended rollback remain coordinator gates. Controller/ring/tail state is process/WebSocket memory only. Existing sockets retain their pinned mode through drain; reverting flag false affects new sessions, not in-flight recovery. An older-image rollback is safe for persisted data but restores its known synchronous-overflow defect. Abrupt process death can lose in-memory tails; client offline capture/sync owns cross-process recovery. ## Product invariants affected - **INV-MEM-4 preserved** (`product/invariants/memory-promotion-authority.md`): runtime manifest gains only a false listen STT flag; memory admission, schedules, authority and fences are unchanged. Runtime compose/render/validator checks cover this additive deployment declaration. ## Final publication / CI receipt The inert implementation was published normally at `9ec29a62cba2bffdfe4f2fe5ed81d429f11e54f5`: all hooks passed (41 preflight checks, typecheck 0 errors, selected backend files under the unchanged CPU guard). Receipt: `.pytest-tmp/logs/inert-push-final.log`. Newer main introduced a documentation conflict, preventing full PR CI; main is now integrated locally at `abcadb4bc5b6418d9fe969baa5262e7eda054540`, preserving its queue cleanup and the bounded-replay wording. A merged-head push passed preflight/typecheck/source closure but was blocked when the canonical `.venv` disappeared before unit tests. The documented `scripts/sync-python-deps.sh` route restored Python 3.11.15 from `pylock.macos.toml`, with no tracked dependency or policy edits; environment preflight and 38 flag tests passed (`env-repair-sync.log`, `inert-env-repair.log`). The remover is unknown; no other lane/process was altered. Final local head is `389885f9e7194db42ceae060b52947e0cde5ad77`, adding only the exact ring-assertion/cold-import follow-up to that merge. **Published normally at `389885f9e7194db42ceae060b52947e0cde5ad77`** with all hooks enabled: 41 preflight checks, typecheck 0 errors, selected backend suites passing the unchanged 0.30 s guard, runtime/env/source closure and API contracts. Receipt: `.pytest-tmp/logs/inert-cold-import-fixed-push.log`. GitHub reports this head MERGEABLE and full source CI is running, including all four backend shards. CI on that head passed CodeQL, slow guardrails, hermetic E2E/listen-pusher gauntlet, metadata/hygiene, env and source closure, but its broad unit shards caught five unchanged provider/readiness files calling constructor-bypassing owners without the new pin field, plus a static lifecycle test inspecting the wrapper rather than the serving body. Follow-up `fab2f0754f8ea52d6f828ea022ba80c9019085b8` pins only missing/non-boolean entry fields once (inheriting an already-pinned receiver), leaves fully constructed sessions unchanged, and strengthens the lifecycle guard across `run → _run → finally teardown`. All original provider assertions remain unmodified; six failing suites plus 42 flag cases passed locally (**159 passed, 14 slow deselected**), typecheck 0 errors (`inert-ci-pin-fix.log`, `typecheck-pin-fix.log`). **That follow-up is now published normally at final head `fab2f0754f8ea52d6f828ea022ba80c9019085b8`**. All hooks passed again (41 preflight checks, typecheck 0 errors, selected tests under unchanged 0.30 s CPU guard); receipt `inert-ci-pin-fix-push.log`. GitHub reports it MERGEABLE and exact-head source CI is running; no green unit-CI claim is made yet. PR remains open/draft; do not merge or deploy. #### Test plan - [x] PCM semantic regressions and before/after benchmark; publish prior unpushed fixes normally. - [x] Flag-off original-main false/unset suites; source/body equivalence audit; mode-pinning/metrics/circuit contracts. - [x] Flag-on fast recovery matrix, provider pairs and affected qualification suites; unchanged CPU guard. - [x] Default-off chart/base/overlays/compose and flag registry; typecheck 0 errors. - [ ] Final slow matrix, committed-head preflight, normal inert-head push and complete source CI. - [ ] Independent coordinator approval, paid/public-speech soak, deployment and attended rollout (not performed). Generated with [Devin](https://devin.ai)
Git-on-my-level
added a commit
that referenced
this pull request
Oct 4, 2026
…20567) The prod adapter values omitted five live Parakeet rules. Upgrading with that file would remove metrics used by the prod Parakeet HPA, risking live STT admission. Restore all five exactly as live and retain `nllb_active_requests_total` for the checked-in prod NLLB chart's concurrency HPA. The pinned prometheus-adapter 4.14.2 render preserves all 18 live rules and adds the NLLB rule (19 total). The only allowed config differences versus the 2026-10-04 read-only live capture are the two #20418 `listen_track!="canary"` selectors and that exact NLLB addition. Known NLLB repo-versus-live HPA drift: live `prod-omi-nllb-translation` consumes only `Resource:cpu` (1 replica, maximum 2); repo prod values set `requestsPerPod: 4`, which renders an External `nllb_active_requests_total` metric on the next deploy. An adapter rule with no matching series is harmless; retaining it protects that future deploy. This PR does not change the NLLB chart. Deployment arguments/image and both APIService specs match live after default service port normalization. The render adds two custom-metrics RBAC objects currently absent live: ClusterRole `prometheus-adapter-server-resources` and ClusterRoleBinding `prometheus-adapter-hpa-controller`. Other rendered RBAC content and ServiceAccount match. Deployment differences are the config checksum, historical restart annotation and Kubernetes defaults; Service differences are assigned IPs/defaults. The manually created live custom APIService lacks this release's Helm ownership metadata, so the live comparator fails closed until David inspects and adopts it. No cluster writes were performed. The runbook gives David an explicit sequence: history → capture every existing rendered object's YAML in a local gitignored directory → validate the known-good rollback baseline and reject conflicting owners → adopt unowned APIService/other objects → pinned `helm upgrade --atomic` → listen/Parakeet metric and HPA post-checks → rollback on failed acceptance. It explicitly checks whether both RBAC additions are still new or now exist unowned. The rollback gate requires BOTH APIService specs plus exact live rules and Deployment arguments; a missing APIService blocks adoption/upgrade. Captured APIService and ConfigMap YAML provides a documented emergency recovery alternative for an incomplete historical/atomic rollback, followed by adapter restart and repeated post-checks; this does not waive the baseline gate. The prod-operator tier has no GKE writes, so David uses his authorized human context for the write steps. Agents use ro-prod only. The hermetic contract renders prod Parakeet, listen, pusher, VAD, diarizer, Deepgram engine/API and NLLB HPAs and checks every consumed Pods/External metric against the correct adapter rule list. The selector includes NLLB chart changes. Upgrade comparison permits only the reviewed canary/NLLB changes; rollback comparison remains exact and verifies both APIService specs before live ownership adoption. Why isn't this a shared primitive instead? The prod values remain the shared cluster-wide rule source. This consumer/producer contract catches the observed prod-values/live incident before an incomplete Helm replacement; the comparator operates on captures without a cluster client. Verification: - Local chart 4.14.2 render with the supported APIService v1 capability; fresh ro-prod captures: 18 live → 19 rendered rules, only the canary selectors and exact NLLB addition differ. Matching Deployment arguments and both APIService specs. Comparator exits 1 only for the documented custom APIService ownership HOLD. - `python -m pytest -q backend/tests/unit/test_monitoring_adapter_hpa_contract.py`: 24 passed, including NLLB HPA/selector coverage, exact NLLB query validation, missing APIService rollback rejection, pre-adoption rollback review, and existing negative drift cases. - Focused adapter/telemetry suites: 52 passed; selector-output test: 1 passed. PR-body validation and `make preflight`: 31 checks passed each. All three runbook command blocks pass `bash -n`; capture/adoption/recovery Python was exercised on fresh read-only captures and rejects conflicting owners or APIService service targets. - Helm history is unavailable to ro-prod (release secrets forbidden); David must inspect the deployed known-good manifest before any adoption/upgrade. No upgrade or post-upgrade acceptance was performed. Failure-Class: none Failure-Class-Reason: First observed production adapter rule-inventory drift; no existing class captures this chart/live reconciliation contract. Draft only. Do not merge or deploy from this PR. Repeat the review using the merged revision before David performs the upgrade.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Add a coordinator-owned listen canary Deployment rendered from the existing chart and pinned by image digest, plus an isolated dev live-STT soak using public LibriSpeech audio. The canary joins the existing Service while remaining outside the main Helm release, so routine main upgrades do not remove or overwrite it. Its replicas stay fixed; pod names distinguish existing scrape metrics. Production pod discovery copies track into listen_track; the Prometheus Adapter adds only listen_track!="canary" to the old discovery and averaging queries, preserving the original cross-namespace and per-query job scope while excluding canaries from the main HPA input and retaining canary/fleet telemetry. Production rendering requires a coordinator-captured main Deployment snapshot so live env/resource/scheduling overrides stay identical to controls apart from the image and explicit recovery flag.
Failure-Class: none
Product invariants affected
none
The dev workload uses pod-local Firestore/Redis, UUID synthetic accounts, no customer credentials/runtime identity, and a restricted NetworkPolicy. It exercises the real listen route, window capture/recovery and Soniox/Modulate adapters with a local failing window peer; paid mode uses explicitly supplied existing scoped provider keys. Reports distinguish client termination from diagnostic fallback exhaustion and preserve missing telemetry as HOLD.
The rollout card includes exact coordinator commands, image admission findings, 15/60-minute exposure gates, expansion/removal and rollback. Current workflows cannot build unmerged PR heads. The recommended merge-inert path requires #20391's author to implement a complete default-off recovery flag; this PR does not change that branch or claim that its image already recognizes the proposed flag. Production monitoring values now carry the canary scrape label and exclude it from the main HPA metric. The coordinator must deploy the scrape config through the existing monitoring workflow and upgrade the adapter using its deployed chart version before starting canary. The runbook includes live isolation checks and rollback ordering. No workflows, live production resources or serving startup are changed. Coordinator Claude owns Luna review and all dev/prod rollout actions.
Validation
Luna P2 follow-up: merged origin/main (147f77d) normally. Removed the added namespace restriction from both adapter queries and the added job restriction from discovery. Replaced selector-string assertions with result-equivalence fixtures covering absent/empty/main/control track labels, cross-namespace and namespace-less series, other scrape jobs, unrelated metrics, and idle/busy canaries. Focused rollout, listen Helm defaults and monitoring telemetry suites: 61 passed. Offline promtool evaluated both old and configured new queries over the same three fixtures successfully.
Review fixes: merged origin/main normally; rollout, existing listen Helm defaults and monitoring telemetry suites: 58 passed. Both monitoring Helm charts render; offline Prometheus fixtures verify 30 unlabeled main pods retain the same HPA average with two idle or heavily loaded canaries. All 27 runbook PromQL expressions pass promtool syntax validation. The two fleet watches now define manual for: 1m evaluation semantics (every 15s, five consecutive true samples across 60s).
Focused rollout contract suite: 20 passed (chart render/ownership, immutable images, isolation rejection, public fixture hash, protocol faults and client terminal observation).
Real local listen route with private Firestore/Redis and public audio: two concurrent 35-second sessions, two window-to-Soniox recovered hops, 26 transcript batches per socket, zero client terminal failures, clean 1000 closes. This ran current main source; absent fix(stt): bound live recovery and replay under one session owner #20391 replay metrics correctly produced HOLD. It is harness validation, not vendor or deployed qualification.
Backend typecheck: 0 errors (existing nonblocking warnings).
Combined rollout and existing listen Helm default suites: 29 passed. Shared preflights and normal pre-push run before publication; final receipts recorded in the task report.
The Helm rendering tests cover the requested rollout primitive in the existing pytest selector; no new standalone check/workflow is added. Paid-provider headroom/billing, dev-cluster execution, real GPU/backfill behavior, GKE NEG distribution, graceful production drain and the flag-on #20391 image remain coordinator acceptance gates.