Skip to content

fix(stt): count accepted provider deaths without a speech gate - #20332

Merged
Git-on-my-level merged 3 commits into
mainfrom
fix/stt-router-count-early-provider-deaths
Oct 2, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
fix/stt-router-count-early-provider-deaths

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Accepted live-STT provider deaths were discarded unless the managed leg had at least one second of VAD speech. Modulate can accept and serve audio before sending a Velma error frame, so early deaths and every VAD-disabled death disappeared from the cost router while the receiver still recorded the failover. Count provider deaths without an audio/speech prerequisite, and count actual text as successful evidence without VAD. Plain no-text keeps its speech threshold and remains censored.

Cause and resulting behavior

  • LiveLegSocket._record_cost_outcome used the speech predicate for all outcomes. The production Velma error frames now produce one bounded provider-failure observation before audio, below one second of speech, on VAD-negative audio and with VAD disabled. No-text diagnostics and actual text callbacks do not seal the slot before a later serving death.
  • The same managed leg supplies the immutable reason to both health and the receiver's source-hop telemetry. The real parser/failover reproduction finds no serve-error-to-connection-loss absorption. Settlement delay changes time buckets, not total counts for a settled cohort; before the fix the tests reproduce four settled failovers and zero observations, while >=1s speech controls reconcile.
  • An accepted socket rejected by the connect-time serving check shares its accounting receipt with the leg: one counter increment and one sample per local/Redis scope. Fresh connect evidence reaches a newer gate if the session generation was stale; forward, reverse and concurrent CAS writes cannot duplicate a sample, including when it promotes a trial. Trial share admission remains enforced. A failure before any managed socket exists still contributes one connect observation. Serving selection, local circuits and connect outcomes are unchanged.
  • A terminal Soniox death can have health evidence with no source hop: the receiver returns when it has no replacement candidate. Connect failures also have no mid-session hop. The aggregates cannot identify which path produced the single production Soniox observation. Real Soniox rotation, idle timeout and finished-frame tests remain non-failures; intentional owner close fences later teardown transport symptoms from health.

Reconciliation and state

For accepted managed Modulate legs that produce hops, settled fallback counts and provider-failure observations must match per reason, regardless of speech. The tests drive the real SafeModulateSocket receive/send loops, LiveLegSocket, and ListenReceiver failover/settlement path with four deaths in each of 30 cases (120 deaths total), covering both Velma error shapes and transport loss, recovered/exhausted outcomes and five speech/VAD configurations.

Aggregate health can exceed live-session fallback counts for terminal deaths with no replacement failures before any accepted socket, or an accepted socket that dies during connect-time serving validation before a source hop. Account/window/session causes remain censored. Compare the same surface and endpoints; family fallback labels also cover legacy/PTT paths. Settlement and first-scrape boundaries still matter.

Retain omi:live-stt:cost-v5: stored failure/success meanings, reason vocabulary, gate thresholds and state shape do not change. This adds previously missed failures and successes; it neither reinterprets nor backfills old evidence. Registry, ramps, capacity policy, serving behavior, shadow default and on-percent zero remain unchanged. No kubectl/gcloud, production access, routing-state writes, merge or deploy.

Validation

Recreated the missing worktree-owned Python 3.11 virtualenv with uv and requirements.txt. Direct pytest with worktree TMPDIR, no cacheprovider and --durations=8:

  • 18 focused suites on the review-fixed commit: 1,490 passed, 9 warnings, 111.10s; slowest test 0.73s.
  • Final targeted suite including generation/CAS regressions: 63 passed, 1 warning, 1.61s; slowest test 0.30s.
  • Type check: zero errors, 10,007 warnings.
  • Baseline reproduction before the fix: 28 failed / 10 passed, including the missing-failure cases and >=1s speech passing controls. No real transcript/audio or external services were read; synthetic protocol/audio fixtures only.

Runbook, architecture and pipeline owner document the corrected sample eligibility and expected reconciliation. The follow-up review fix preserves fresh connect-time gate evidence while sharing per-scope accounting across both background writes, with stale-generation and concurrent-CAS tests. Repository preflight and supplied-body preflight each passed all 30 checks. Normal push hooks validate the committed head; CI is the full-suite authority.

Product invariants affected

none — no locked runtime/config paths or client wire models changed.

Failure-Class: none

Review fixes

P1 — Soniox 408 request timeout

  • The real Soniox frame parser now maps 408 request_timeout to bounded soniox_request_timeout. Soniox documents 408 as a request deadline, including slow or missing audio; this is client/stream timing evidence and differs from its 400 idle error, so it stays censored and out of PROVIDER_FAILURE_REASONS. See Soniox STT WebSocket errors.
  • Serving behavior is preserved: this reason remains in _SERVE_FAILURE_REASONS, the same terminal serving classification as the prior connection_lost, so terminal circuit opening and existing failover/close-code behavior are unchanged. Only health classification and bounded reason labels change.
  • Regression coverage sends a raw 408 frame through SafeSonioxSocket and a terminal Korean Soniox LiveLegSocket: one censored observation, zero provider failures. A terminal-path test confirms circuit opening remains active.

P2 — client teardown attribution fence

  • ListenReceiver.receive_data now samples any already-dead managed leg and marks owner teardown before the awaited final force flush. A pre-disconnect provider death still records; a later transport symptom is censored. Managed-leg send closure is now separate from the health fence, so final buffered audio is still sent before drain and close codes are unchanged.
  • Receiver-level regressions cover late raw-socket death during the final flush (normal and app-background disconnect), five no-frame Korean Soniox reconnects with zero provider failures, and a real transport death observed while connected counting exactly once.

Validation

  • Focused backend suite: 276 passed, 1 warning in 4.59s; slowest individual test 0.32s. All six requested test files were present.
  • make preflight: passed all 31 selected checks in 109.65s. The failure-class history ratchet skipped because this checkout is shallow; architecture size notices are advisory.

Line-Count-Exception: backend/routers/listen/receiver.py | 1825 -> 1835 | Fence owner teardown before final audio flush for provider health attribution.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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 6 files

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

Re-trigger cubic

Comment thread backend/utils/stt/live_chain.py Resolved
@Git-on-my-level
Git-on-my-level merged commit 0ba6edb into main Oct 2, 2026
53 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/stt-router-count-early-provider-deaths branch October 2, 2026 12:28
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
Provider health was inferred from socket liveness and teardown
independently of the serving decision. That both censored early Modulate
deaths and invented Soniox failures during client churn. This change
makes a leg's exactly-once terminal settlement emit both the existing
fallback event and router observation, with the original bounded cause
frozen before transport cleanup. Liveness getters are read-only;
accepted deaths need no VAD minimum; terminal-provider exhaustion is
visible too.

`cost-v6` gives each hashed user at most three classified votes per
target/scope/five-minute Redis-time window, enforced by CAS with bounded
state. Raw observations remain uncapped for emission accounting. Healthy
windows have 2,048 ordinary fingerprints plus an eight-distinct-user
outage reserve that resets on every classified success; eight new
failures still bench after saturation without failure-only CUSUM
sampling. Healthy Redis keys expire after 900 idle seconds;
benches/trials persist so expiry cannot bypass staged recovery.
Independent chain-opened / terminal-settled / transport-open lifecycle
metrics and honestly named emission-acknowledgement/error/vote counters
and an intent-to-treat router-canary transcript SLI support the
runbook's 60–120 minute shadow qualification and 5→25→100 ramp. The gate
remains 8%; reproducible synthetic calibration reports zero false
benches in each 400,000-session healthy-floor scenario and p95 detection
at 48/21/8 sessions for 40%/60%/100% failures.

Production remains `STT_ROUTING_MODE=shadow`,
`STT_ROUTING_ON_PERCENT=0`. Deliberate serving changes: configured
fallback order becomes Parakeet window → Soniox → Modulate → Deepgram;
Soniox timing/configuration, local VAD and other censored input causes
no longer accumulate provider circuit failures at connect or terminal
settlement; client teardown transport errors cannot start recovery or
open provider circuits; local queue/loop/input failures retain
non-provider causes; an active router cannot reappend a
registry-withdrawn default endpoint as a legacy tail. No-text remains
censored and diagnostic; the existing transcript-success alert remains
the detector, with no new silent-stream rescue.

#20332 merged while this lane was in progress. This branch merges that
main revision and supersedes its parallel receipt writers, retaining and
extending its real parser/receiver tests and preserving the new
`soniox_request_timeout` label. No merge or deployment is performed by
this lane. Merged origin/main again at 81a51d0 after #20340 landed.
Its Parakeet allocation/capacity values are preserved exactly at 100/16;
#20344 slow marks remain intact.

## Validation

- Real `LiveLegSocket` + provider parser + receiver tests reconcile 120
accepted deaths, before-audio/subsecond/no-VAD paths, typed terminal
causes, connect rejection, exhaustion, cancellation, and client
teardown.
- Fleet CAS tests cover 46 reconnects across pods, concurrent budget
admission, bounded fingerprint storage and generation fencing.
- Initial STT/provider/runtime regression run before the final review:
**2,268 tests passed across 50 isolated files**, with
`BACKEND_FAST_UNIT_FAIL_SECONDS=1.0`; two real listen-runtime parity
tests also passed under the same guard with an external `--basetemp`
(their capture validator intentionally rejects checkout-local roots).
Type checking: zero errors. `make preflight`: all 38 selected checks
passed with this PR body; normal push hooks passed.
- Test command: `cd backend && BACKEND_UNIT_TEST_FILE_LIST=<selected
file list> BACKEND_FAST_UNIT_FAIL_SECONDS=1.0 BACKEND_PYTEST_WORKERS=3
TMPDIR=$PWD/../.pytest-tmp bash test.sh`. Focused real-object cases also
used `.venv/bin/python -m pytest -q -p no:cacheprovider <files>
--durations=8`.
- The separate slow lane also passed all 668 calibration tests and both
files are registered in the existing slow-guardrail CI manifest; main's
slow marks are retained; the fast baseline sample uses 20k sessions per
rate and the full separate calibration retains 400k per scenario. Full
realistic-floor calibration was run separately. Exact qualification
PromQL and canary/abort conditions:
`backend/docs/runbooks/live-stt-routing.md`.

- Synthetic calibration: `cd backend && .venv/bin/python
scripts/stt/calibrate_live_gate.py`; no user transcript/audio access or
production-state writes. Production acceptance is pending coordinator
deployment/shadow checks.

## Product invariants affected

- INV-MEM-4: generated runtime env is touched only for the live STT
order; canonical memory promotion authority and its flags are unchanged.

Failure-Class: FC-decoded-outcome-discarded-before-canonical-record

Line-Count-Exception: backend/routers/listen/receiver.py | 1835 -> 1844
| Wire the shared settlement and teardown fence at existing
serving-owner boundaries; extracting unrelated receiver/provider logic
would widen this incident fix.

Line-Count-Exception: backend/utils/stt/streaming.py | 2186 -> 2188 |
Wire the shared settlement and teardown fence at existing serving-owner
boundaries; extracting unrelated receiver/provider logic would widen
this incident fix.


## Review decisions

The 30-second pending-hop bound is intentional: `degraded` means
recovery was unproven by the deadline. Late successor text remains
visible in leg/session and router-canary transcript SLIs; it does not
emit a second fallback or change the source provider-failure vote.
Waiting indefinitely for successor speech would again make outage
detection depend on user audio.

Review corrections include invalid-percent telemetry fail-open, a
teardown recheck after awaited recovery, settlement on engine-mismatch
recursion and cancelled replacement retries, aligned prod
ConfigMap/inline order, and explicit censored local circuit causes. The
long calibration files are now registered in the existing slow-guardrail
CI manifest, while the fast lane stays below its per-test CPU budget.


## Serving behaviour changes

| Location (under backend/) | Before → after; intent and accepted risk |
| --- | --- |
| charts/backend-listen/prod_omi_backend_listen_values.yaml:457;
deploy/runtime_env/prod.overlay.yaml:39,295; regenerated
deploy/runtime_env.yaml | Parakeet → Modulate → Soniox becomes Parakeet
→ Soniox → Modulate. Sessions unable to use Parakeet now start on
Soniox: cost up, reliability up. Modulate remains in the static chain
and registry, with the separate new-endpoint ramp supported. |
| routers/listen/receiver.py:1741; utils/stt/live_session.py:843;
utils/stt/live_failure.py:550; utils/stt/resilient_stream.py:266 | Owner
teardown fences later transport symptoms before tail sends. A published
death already latched before that fence is now settled as a failure even
without a monitor claim; a death beginning during/after teardown is
censored. Connected streaming deaths still invoke recovery. |
| utils/stt/live_outcome.py:61; utils/stt/live_session.py:529 | Accepted
provider deaths no longer require >=1s VAD speech; actual text counts
success without VAD. This removes early-death undercounting; normal
no-text stays censored. #20332 independently merged that early-death
policy while this PR was in progress. |
| utils/stt/live_session.py:854; utils/stt/live_failure.py:170,255 |
Health settles at the serving owner, not a liveness read or transport
close. Close of an already-claimed failed leg defers settlement to its
hop; a 30s timer bounds that deferral and reports degraded if recovery
is unproven. Terminal-provider exhaustion now emits a fallback. These
change telemetry, not audio/transport actions. |
| utils/stt/live_chain.py:372; utils/stt/live_failure.py:108 | Censored
connect reasons release admission without accumulating circuit failures.
Terminal transport reasons shrink to connection_lost/send_failed,
removing vad_failed and soniox_request_timeout; separate typed
account/serve-error protection stays. Repeated Soniox 408 connect
rejections can therefore be retried across sessions: accepted because
408 alone cannot distinguish outage from input timing, while the same
connect still falls through. Reason counters and latency/transcript SLIs
support manual withdrawal if an outage is demonstrated. |
| utils/stt/soniox.py:212,238; utils/stt/streaming.py:1323,1456 | Soniox
publishes cause before death. Queue-full/loop misuse/invalid input
retain bounded censored causes instead of connection_lost; accepted-dead
connects retain their normalized cause instead of collapsing to
provider_5xx. Same-session fallback remains. |
| utils/stt/live_chain.py:161 | Active selection cannot reappend a
registry-withdrawn/excluded default endpoint as a legacy tail;
configured-order error fail-open remains. Shadow/0 does not activate
this selection branch. |

## Luna final review corrections

- Saturated-window + eight new-failure regression; existing UID budgets
never refill. Normal capacity exceeds 10x the stated 1,800
sessions/hour; any saturation still stops rollout because normal
brownout evidence is sampled; the independent outage reserve resets on
successes and cannot be filled by one reconnecting user.
- Death-before-teardown now counts, including the real receive_data
path; errors arising during its final flush remain censored.
- `omi_stt_cost_routing_emission_ack_errors_total` replaces the
misleading reconciliation name. It does not prove classification,
settlement coverage or Redis persistence.
- Independent `omi_stt_managed_legs_opened_total -
omi_stt_managed_legs_settled_total - omi_stt_managed_legs_open` is
exported by target/pod. A regression deliberately suppresses settlement
and verifies that this gap grows while acknowledgement errors need not
change. Go/no-go rejects a nonzero gap persisting two minutes (30s
deferred settlement is allowed).
- Healthy fairness keys get a 900s TTL. Benches and recovery trials
deliberately do not expire into healthy state; they contain no
healthy-window fingerprint list.


Final review-round validation: **1,614 fast tests across 50 isolated
files passed with the stricter 0.30s CPU guard**, followed by **139
focused tests** covering the final overflow/CAS and lifecycle-oracle
changes. Re-ran the six 400,000-session calibration scenarios: zero
false benches in each; detection median/p95 remains 20/48, 13/21, 8/8 at
40/60/100%. The earlier 2,268 count predates main's additional slow
split; it is not the new fast-lane count. Generated runtime env
regeneration and `--check` pass. PR metadata preflight passed all 38
checks.

Final type check: zero errors. The final main merge includes #20340,
with 100% allocation / cap 16 retained and runtime env regenerated and
checked.
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
#20348)

## Summary

Fix static/shadow live STT recovery after a local full/open window:
continue to an eligible non-account rescue provider, and latch terminal
recovery failure so audio/monitor races cannot repeat rebuilds. No
cost-router implementation or rollout defaults change.

Failure-Class: none

## Product invariants affected

none

## Evidence and mechanism

- The supplied 35-event burst is not a count of distinct sessions.
Read-only Prometheus samples on the affected pod show chain exhaustion 0
→ 35 but terminal-session failures only 2 → 4 over 13:46:30–13:49Z. A
deterministic test reproduces 35 competing rebuild calls against one
receiver before the fix; distinct failed-provider cardinality is not an
attempt budget.
- Timestamp-only logging queries find all 35 rebuild errors within 0.64s
(13:47:35.490–13:47:36.131Z), immediately after a pending
Soniox→Modulate connection_lost hop settles degraded. Soniox's local
selection/account gauges are both zero and its connect-success count
stays 30: it was not dialed during the burst. Its permanent session
exclusion after that earlier transport loss explains the absence of
Soniox skip/attempt events; the aggregate evidence does not require 35
independent sessions. Add one bounded re-entry of that already-used
Soniox leg when the circuit is closed, never after account/connect
rejection, and keep untried configured Deepgram ahead of re-entry.
- A separate reproduced corner (not the production Soniox circuit
state): Soniox selection benches are not proof it cannot accept a new
stream. The old last-resort suffix required every callback's circuit to
be benched, including an already-excluded Modulate callback. A closed
circuit for that failed source suppressed rescue. A window capacity
refusal also set `attempted`, suppressing the same suffix. The
historical configured-chain functions on 6a26acc, afa7800 and 0ba6edb
all exhaust the same open-window/open-Soniox/failed-Modulate input. This
is not introduced by #20304 or #20332.
- `reason=capacity_full` on a source Modulate hop is the latched source
cause, not evidence the proposed Parakeet successor was dialed. Managed
replacement replay-ring pressure can produce that cause; the selection
event with circuit_open is consistent with no actual connection in that
rebuild.
- The affected live-session exhausted counter first appears at 35, then
stays 35: Prometheus increase cannot recover increments before its first
sample. The helper increments and logs identical labels. Initialize
bounded exhausted STT children at zero to make subsequent first bursts
observable.

## Changes

- Exclude already-failed providers from the local all-benched decision.
- Check actual local window admission before socket/VAD construction,
counting these refused selections in the existing admission-overflow
metric; respect existing five-second target capacity cooldown in shadow
serving, without enabling the cost router.
- Try each remaining non-TDT rescue provider once after an open/refused
window; never bypass account cooldown, failed providers, known capacity
or TDT shedding. Preserve the half-open probe count; competing rescue
handshakes wait at most twelve seconds in total for a slot instead of
failing immediately. At 300ms liveness grace, 35 otherwise healthy
serialized handshakes take about 10.5s, excluding actual provider
connect latency.
- Count actual rebuild attempts, at most three on managed sessions and
two on legacy sessions. A single healthy Soniox re-entry consumes that
same budget; the failed window never re-arms.
- Latch failed rebuilds under the receiver lock, and send unrecoverable
ring pressure through the ordinary idempotent terminal-close path.
- Preserve source numeric/capacity diagnostics when settling a failed
hop. Replay snapshots and timestamp fencing remain on the existing path.

## Verification

Direct focused pytest suites (TMPDIR inside the worktree): new
capacity/failover suite, configured-chain suite, session-failover suite,
Parakeet replacement/replay suite, cost-router suite and
resilient-stream suite. Tests include 35 concurrent deaths with a real
full eight-slot admission and an in-flight recovery handshake, exact
replay of a pending window-origin span, terminal ring-pressure closure
once, shadow capacity cooldown, occupied/account probe limits,
historical reproductions and zero-baseline telemetry. Each test is below
0.5s. Final run after merging current main: 236 passed in 5.52s; slowest
test 0.32s. Exact command (from backend): `TMPDIR=$PWD/../.pytest-tmp
.venv/bin/python -m pytest -q -p no:cacheprovider
tests/unit/test_modulate_capacity_failover.py
tests/unit/test_live_stt_chain.py
tests/unit/test_stt_session_failover.py
tests/unit/test_parakeet_failover_exhausted.py
tests/unit/test_live_cost_router.py
tests/unit/test_live_stt_resilient_stream.py --durations=8`.

CI found and this revision fixes a helper policy mismatch: replacement
selection now consumes the receiver's managed-chain decision, preserving
the partial-replay retry budget. The other failed shard is an unrelated
main regression:
`test_rate_limiting::TestRouterWiring::test_sensitive_read_page_caps`
still expects the old developer conversation-list limit after #13955
raised it. Those source and test files are unchanged by this PR.

Terminal CI at `b9d6eace43f4ca293fef4f5cb7e1092af572817e`: 29 passed, 23
skipped, two failed checks (backend shard 3 and its aggregate). The only
failed test is the unchanged main regression
`test_rate_limiting::TestRouterWiring::test_sensitive_read_page_caps`.
Listen/Pusher Stack Gauntlet, Hermetic Backend E2E, static checks and
the other three shards passed.

`make preflight` passes all 31 selected gates. Backend type checking
reports zero errors (existing warning inventory remains).

No provider/network/content is used by tests. Production reads were
bounded aggregate metric samples and timestamp-only logging queries; no
uid, transcript or audio was read.

## Not covered

The aggregate evidence cannot identify the exact number of WebSocket
sessions without session identifiers; no identifiers were retrieved. A
session that never entered the window replay path still lacks a
cross-provider replay ring; this fixes chain continuation for it but
does not add capture retention. Genuine account exhaustion, no eligible
provider, confirmed fleet outage, and an occupied rescue slot lasting
beyond the bound remain terminal. No merge or deploy is included.

## After deploy

Watch chain-exhausted vs terminal-session counters, recovered
Modulate→Soniox hops, local window admission overflow, fallback
exhausted series and Soniox connect error/first-text latency. Check that
exhaustion bursts no longer multiply a single terminal incident; compare
headline transcript success across window/control.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Oct 2, 2026
A managed provider death could be claimed during cleanup after the
client had already left, creating router failures with no real serving
handoff. Fence the first serving claim by explicit client/application
disconnect, inactive state and shutdown; preserve claims already made
while connected. Excluded legs retain actual text as success or settle
censored no-text, and emit no provider-failure fallback.

## Resulting behavior

- One accepted physical socket/leg has one serving-owned settlement.
Repeated Velma error frames, death/send/finish observers and connect
validation cannot count it again. New replay/reconnect sockets are
distinct legs.
- `LiveLegOutcome.claim` receives the leg's client lifecycle and
prior-text callbacks. A first claim after departure or owner teardown is
excluded once; a prior connected claim keeps its cause even after
departure. Existing text success remains in the denominator.
- `omi_stt_cost_routing_ignored_deaths_total{target,reason,boundary}`
exposes excluded claims. Registered targets <=16, bounded reason
vocabulary, two boundaries; labels are preinitialized, with no
UID/socket/content dimensions. This diagnoses exclusions, not all raw
close symptoms.
- Fresh state is `omi:live-stt:cost-v7`: v5 and v6 can contain
post-client failures/backoff strikes. Do not migrate or backfill them.
Gate thresholds, vote budgets, provider registry, ramp cohorts and
serving policy are unchanged relative to current main. Raw
connect-attempt diagnostics and per-process circuits remain a separate,
unchanged scope; this PR fences managed serving-health settlements and
their paired fallback emissions.
- Production remains shadow / on-percent zero. No runtime-env, chart,
provider client, transport/recovery/circuit or workflow changes in the
PR diff. No production access or routing-state writes; no merge/deploy.

## Current main integration

Merged origin/main including #20343 (`6e1ce64f5c`), which landed during
validation. Its serving-owned settlement implementation supersedes this
branch's earlier getter/receipt writers: keep read-only liveness and the
single settlement seam. Main now preserves accepted connect-validation
causes and source reasons across rejected successors, and terminal
managed deaths emit fallback to unavailable. This PR adds the missing
actual-client fence to that seam rather than reinstating parallel
writers. Main's deliberate static-order and other serving changes are
preserved without alteration.

## Reproduction and reconciliation

The initial pre-#20343 base had 17 failures / 6 passes in the initial
23-case regression file. After integration, the 26-case socket file
against current main's runtime had **15 failures / 11 passes**. The
fixed tree passes all 26, plus three disabled-mode diagnostic cases.

Three distinct real Modulate sockets (one connected serving failure, two
first claimed after client departure) reproduce the 3:1 excess: **three
failures / one nonterminal hop before; one failure / one hop plus two
ignored claims after**. Reproduces for serve-error and transport loss.
The real Velma parser receives multiple error frames and each leg is
polled/sent/finished repeatedly; this did not reproduce three writes for
one socket.

A five-socket cohort has **three failures = two settled nonterminal hops
(selection + live) + one connected terminal death**, with two departed
sockets excluded. Same equality is asserted per reason. ko/ja/zh
terminal Soniox deaths have a connected client, stt_failed/1011,
terminal metric +1 and connect-chain exhaustion unchanged. That counter
measures construction exhaustion, not serving terminal decisions. Main
now includes terminal deaths in fallback to unavailable: do not add
terminal session counters to the complete fallback total again.

On the deployed #20332 path, accepted warm serve errors were labelled
modulate_serve_error in health but provider_5xx in selection fallback.
Therefore comparing health only to live-session serve-error hops can
produce a large apparent excess without repeated observations; the
connect-validation test demonstrates it. Main #20343 fixes that
attribution, which is retained here.

The supplied production aggregates cannot allocate all 56 excess
serve-error observations or all 11 Soniox observations among paths.
Selection provider_5xx and terminal totals were omitted. The tests
establish false teardown feed and preserve legitimate terminal evidence;
the runbook explains the exact cohort,
terminal/family/legacy/time-boundary qualifications, and the new
ignored-claim query. Paired settlement/observation counts alone can
agree while both classify client churn wrongly.

## Validation

Direct pytest with worktree TMPDIR, `-p no:cacheprovider`,
`--durations=8`: **688 passed across eleven focused suites**, slowest
**0.32s**; all cases below 0.5s locally. New socket cases are below
0.1s. Synthetic protocol/audio and MemoryRedis only.

Suites: test_live_death_socket_accounting,
test_live_early_provider_deaths, test_live_health_reason_reconciliation,
test_live_cost_router, test_live_stt_chain, test_live_stt_failure,
test_modulate_serve_error_deaths, test_soniox_typed_rejections,
test_fallback_observability, test_live_evidence_settlement,
test_parakeet_window_live.

CI exposed an unchanged window-deadline test comparing
12.000000000000028 to exactly 12. Its one assertion now uses
pytest.approx, consistent with the adjacent test; the full 151-case
window file passes. Production window code is unchanged.

Type check: zero errors (10,029 warnings). Final make preflight: 30/30
checks passed on the integrated head. Runbook, STT architecture and
pipeline owner document client eligibility and state v7.

## Product invariants affected

none — no locked runtime/config paths or client wire models changed
relative to main.

Failure-Class: none


## Review fixes

- Snapshot client/owner eligibility and the bounded provider-death cause
on the managed leg's first death observation. A death observed while
connected remains provider-failure evidence through a later client
departure; a death first observed after departure or owner teardown
remains excluded.
- Added both death/departure/claim orderings and a #20348 bounded
rebuild-exhaustion regression. Repeated exhaustion handling settles that
leg and fallback exactly once under the same eligibility fence.
- Merged current `origin/main`, including #20348 (`live_recovery.py` and
bounded rebuild tests); retained both intents.

Validation: the requested six-suite combined run passed **383 tests**
(7.21s total; slowest case 0.32s). `make preflight` passed **30/30
checks** (96.18s); the shallow-clone 90-day failure-class guard skipped
its enforcement window.
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