Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(stt): cross to another provider when one fails mid-transcription (AP-22)
Ruben Lütke1f36d8edcbad
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.pyindex 90ea3be193..7772757a9c 100644--- a/jarvis/plugins/stt/__init__.py+++ b/jarvis/plugins/stt/__init__.py@@ -259,6 +259,53 @@ def build_stt_from_config(stt_cfg: Any) -> Any:return _build_local_fallback(stt_cfg, language)+def available_stt_provider_names() -> list[str]:+ """Every provider this host could actually transcribe with, right now.++ "Could" is a CREDENTIAL + INSTALL question, never a config one: the answer+ is the menu the runtime fallback chain picks from when the configured+ provider starts failing (``jarvis.speech.stt_fallback``), so a name in here+ has to be one that would really work. Cloud families come in the+ cross-family order, the key-free local engine last and only when it is+ installed.+ """+ names: list[str] = []+ for name in _STT_CROSS_FAMILY_ORDER:+ if _stt_family_has_key(name) and _load_provider_class(name) is not None:+ names.append(name)+ if _faster_whisper_installed():+ names.append("faster-whisper")+ return names+++def build_named_stt_provider(name: str, stt_cfg: Any) -> Any:+ """Build the provider called ``name`` using ``stt_cfg`` for everything else.++ Language, bias prompt, dictionary vocabulary and the team-proxy handling all+ have to match what the configured provider got — a fallback that quietly+ drops the user's vocabulary would transcribe their words differently the+ moment it took over. So this reuses :func:`build_stt_from_config` on a copy+ of the config rather than re-deriving any of it.+ """+ try:+ patched = stt_cfg.model_copy(update={"provider": name})+ except AttributeError:+ # Not a pydantic model (test doubles); a tiny view is enough.+ patched = _StttConfigView(stt_cfg, name)+ return build_stt_from_config(patched)+++class _StttConfigView:+ """Read-only ``stt_cfg`` with ``provider`` swapped — for non-pydantic doubles."""++ def __init__(self, inner: Any, provider: str) -> None:+ self._inner = inner+ self.provider = provider++ def __getattr__(self, item: str) -> Any:+ return getattr(self._inner, item)++# One-time gate so the "no working STT" hint is logged at most once per process# (the STT provider is rebuilt whenever a key changes; the hint must not repeat)._NO_STT_HINT_EMITTED = False@@ -888,6 +935,8 @@ def start_wake_model_prefetch(__all__ = [+ "available_stt_provider_names",+ "build_named_stt_provider","build_stt_from_config","build_wake_whisper","mark_wake_gpu_bad",diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex b90dd97205..6633469a12 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -1460,6 +1460,22 @@ class SpeechPipeline:"Utterance-STT factory failed (%s); reusing local Whisper for utterances.",exc,)+ # Runtime fallback (AP-22). ``build_stt_from_config`` only crosses to+ # another provider when the configured one has no KEY — a build-time+ # decision. A provider that fails at CALL time (a 429 mid-dictation, an+ # expired key, a 503) had no way out, so one rate limit deleted the+ # user's words while three other keyed providers sat unused. The chain+ # is names-only until something actually fails, so this costs the boot+ # path nothing (AP-26).+ if config is not None and getattr(config, "stt", None) is not None:+ try:+ from jarvis.speech.stt_fallback import wrap_stt_with_fallback++ self._utterance_stt = wrap_stt_with_fallback(+ self._utterance_stt, config.stt+ )+ except Exception as exc: # noqa: BLE001 — never block voice boot+ log.warning("STT fallback chain unavailable: %s", exc)# Live transcript preview uses the cheap local probe when available.# In lightweight mode there is no local Whisper, but the post-wake# utterance STT may still exist (cloud provider). Keep that path alivediff --git a/jarvis/speech/stt_fallback.py b/jarvis/speech/stt_fallback.pynew file mode 100644index 0000000000..28ad9ed154--- /dev/null+++ b/jarvis/speech/stt_fallback.py@@ -0,0 +1,323 @@+"""Runtime STT fallback — cross to another provider family when one fails.++``build_stt_from_config`` already picks a different provider when the configured+one has no usable credential. That is a BUILD-time decision, and it was the only+one there was: once a provider was chosen, a failure at CALL time ended the+transcription. So a Groq rate limit in the middle of a dictation deleted the+user's words even though three other keyed providers were sitting there unused+(live bug 2026-07-29: a 137 s dictation returned 367 characters, the log full of+``429 Too Many Requests``).++That is exactly what AP-22 forbids — "a missing / depleted / 429 / 402 /+unreachable one degrades or crosses to a **different family** with an honest+message, never bricking a core path". This module supplies the missing half.++What it does NOT do, on purpose:++* **It never retries a rejection the audio itself caused.** A 400 means this+ provider understood the request and refused it; sending the same bytes to+ another provider would just burn a second quota for the same answer. Only+ failures another provider could plausibly survive cross over — the quota,+ availability and transport ones enumerated in :func:`_is_crossable`.+* **It never builds an alternate on the boot path** (AP-26). The chain is a+ list of provider NAMES; an instance is constructed the first time it is+ actually needed and then kept.+* **It never reorders the user's choice.** The configured provider is always+ tried first, except while it is in the cooldown a rate limit put it in —+ which is the whole point: hammering a 429 keeps it locked.+"""++from __future__ import annotations++import logging+import time+from collections.abc import AsyncIterator, Sequence+from typing import Any++log = logging.getLogger(__name__)++#: How long a provider stays skipped after it reported a quota failure. Long+#: enough that a per-minute limit has actually rolled over, short enough that a+#: user who fixed their billing is not stuck on the fallback all session.+RATE_LIMIT_COOLDOWN_S = 60.0++#: Cooldown for the failures that are not about quota (5xx, transport). Shorter:+#: these clear on their own and the user's configured provider should come back+#: as soon as it can.+TRANSIENT_COOLDOWN_S = 15.0++#: Substrings identifying a failure ANOTHER provider could survive. Matched+#: against ``"<ExceptionType>: <message>"`` rather than against a status-code+#: attribute, because the providers raise whatever their own HTTP client raises+#: (httpx, aiohttp, google-genai, a bare OSError) and there is no shared type to+#: switch on. Capability, not provider identity (AP-21).+_QUOTA_MARKERS = (+ "429",+ "too many requests",+ "rate limit",+ "ratelimit",+ "quota",+ "insufficient_quota",+ "402",+ "payment required",+ "billing",+ "credit balance",+)++_AVAILABILITY_MARKERS = (+ "500", "502", "503", "504",+ "internal server error",+ "bad gateway",+ "service unavailable",+ "gateway timeout",+ "overloaded",+ "timeout",+ "timed out",+ "connection",+ "connecterror",+ "readerror",+ "remoteprotocolerror",+ "temporarily",+)++#: An expired / missing / rejected credential. Crossing over is the honest move:+#: the user has another key that works, and telling them "dictation is broken"+#: while a working provider sits unused is the single-provider brick AP-22 names.+_CREDENTIAL_MARKERS = (+ "401",+ "403",+ "unauthorized",+ "invalid api key",+ "invalid_api_key",+ "authentication",+ "permission denied",+)+++def _classify(exc: BaseException) -> str:+ """``"quota"`` / ``"transient"`` / ``"credential"`` / ``""`` (do not cross)."""+ blob = f"{type(exc).__name__}: {exc}".lower()+ if any(m in blob for m in _QUOTA_MARKERS):+ return "quota"+ if any(m in blob for m in _CREDENTIAL_MARKERS):+ return "credential"+ if any(m in blob for m in _AVAILABILITY_MARKERS):+ return "transient"+ return ""+++def _is_crossable(exc: BaseException) -> bool:+ """Whether another provider deserves a shot at this same audio."""+ return bool(_classify(exc))+++class FallbackSTT:+ """One STT handle that crosses to another provider on a runtime failure.++ Transparent decorator, same shape as ``DictionaryCorrectingSTT``: every+ attribute that is not a transcribe method delegates to whichever provider is+ currently in front, so duck-typed callers (``recover()``, ``is_warm``, model+ fields) keep working.++ ``alternates`` are provider NAMES, not instances — see the module docstring+ on why nothing here is built until it is needed.+ """++ def __init__(+ self,+ primary: Any,+ alternates: Sequence[str],+ build: Any,+ *,+ primary_name: str = "",+ ) -> None:+ self._primary = primary+ self._primary_name = primary_name or type(primary).__name__+ self._alternate_names = list(alternates)+ self._build = build+ # name -> instance, built on first use and kept for the process.+ self._instances: dict[str, Any] = {}+ # name -> monotonic deadline before which we do not try it again.+ self._cooldown: dict[str, float] = {}+ # The alternate that last worked, tried first among the alternates so a+ # long dictation does not re-walk the whole chain on every segment.+ self._preferred: str | None = None++ # ------------------------------------------------------------------+ # Delegation+ # ------------------------------------------------------------------+ def __getattr__(self, name: str) -> Any:+ return getattr(self._primary, name)++ def __repr__(self) -> str: # pragma: no cover — logging nicety+ return f"FallbackSTT({self._primary_name} -> {self._alternate_names})"++ @property+ def provider_label(self) -> str:+ return self._primary_name++ @property+ def last_used_provider(self) -> str:+ """Which provider produced the most recent transcript."""+ return self._last_used++ _last_used = ""++ # ------------------------------------------------------------------+ # Cooldown bookkeeping+ # ------------------------------------------------------------------+ def _available(self, name: str) -> bool:+ until = self._cooldown.get(name, 0.0)+ return time.monotonic() >= until++ def _penalize(self, name: str, kind: str) -> None:+ seconds = RATE_LIMIT_COOLDOWN_S if kind in ("quota", "credential") else TRANSIENT_COOLDOWN_S+ self._cooldown[name] = time.monotonic() + seconds++ def _instance(self, name: str) -> Any:+ inst = self._instances.get(name)+ if inst is None:+ inst = self._build(name)+ self._instances[name] = inst+ return inst++ def _order(self) -> list[tuple[str, Any]]:+ """(name, provider) pairs to try, best first.++ The configured provider leads unless it is cooling down, in which case+ it moves to the BACK rather than being dropped: if every alternate is+ also exhausted it still gets the last word, which beats returning+ nothing at all.+ """+ alternates = [n for n in self._alternate_names]+ if self._preferred in alternates:+ alternates.remove(self._preferred)+ alternates.insert(0, self._preferred)+ head: list[tuple[str, Any]] = []+ tail: list[tuple[str, Any]] = []+ entry = (self._primary_name, self._primary)+ (head if self._available(self._primary_name) else tail).append(entry)+ for name in alternates:+ (head if self._available(name) else tail).append((name, None))+ return head + tail++ # ------------------------------------------------------------------+ # Transcription+ # ------------------------------------------------------------------+ async def _call(self, method: str, *args: Any, **kwargs: Any) -> Any:+ first_error: BaseException | None = None+ for name, preloaded in self._order():+ try:+ provider = preloaded if preloaded is not None else self._instance(name)+ except Exception as exc: # noqa: BLE001 — an unbuildable alternate is skipped+ log.debug("STT fallback: %s could not be built (%s)", name, exc)+ self._penalize(name, "transient")+ continue+ fn = getattr(provider, method, None)+ if fn is None:+ continue+ try:+ result = await fn(*args, **kwargs)+ except Exception as exc: # noqa: BLE001 — classified below+ kind = _classify(exc)+ if not kind:+ # The provider understood us and refused. Another one would+ # refuse the same bytes; surface it instead of burning quota.+ raise+ if first_error is None:+ first_error = exc+ self._penalize(name, kind)+ log.warning(+ "STT provider %s failed (%s: %s) — crossing to the next "+ "provider so the transcription is not lost.",+ name,+ kind,+ exc,+ )+ continue+ if name != self._primary_name:+ self._preferred = name+ log.info("STT transcribed by fallback provider %s.", name)+ self._last_used = name+ return result+ if first_error is not None:+ raise first_error+ raise RuntimeError("No speech-to-text provider was able to transcribe.")++ async def transcribe_pcm(self, *args: Any, **kwargs: Any) -> Any:+ return await self._call("transcribe_pcm", *args, **kwargs)++ async def transcribe(self, *args: Any, **kwargs: Any) -> Any:+ return await self._call("transcribe", *args, **kwargs)++ async def stream_transcribe(+ self, *args: Any, **kwargs: Any+ ) -> AsyncIterator[Any]:+ # Streaming is NOT re-routed mid-stream: a consumer has already received+ # part of the transcript, and restarting on another provider would+ # duplicate it. The chain protects the one-shot calls, which is where+ # dictation and the final utterance transcription live.+ async for item in self._primary.stream_transcribe(*args, **kwargs):+ yield item+++def alternate_provider_names(configured: str, available: Sequence[str]) -> list[str]:+ """The provider names to fall back to, in order, minus ``configured``.++ Ordered by what a failing provider most likely needs: another CLOUD family+ first (fast, and the user demonstrably has a key for it), then the key-free+ local engine as the floor. Local goes last because it is absent on a base /+ headless install and slow on a machine without a GPU — but when it IS there+ it is the one option no quota can take away.+ """+ ordered = [n for n in available if n != configured and n != "faster-whisper"]+ if "faster-whisper" in available and configured != "faster-whisper":+ ordered.append("faster-whisper")+ return ordered+++def wrap_stt_with_fallback(provider: Any, stt_cfg: Any) -> Any:+ """Wrap ``provider`` in a :class:`FallbackSTT` over the user's other keys.++ Returns ``provider`` unchanged when there is nothing to fall back to (no+ other keyed provider) or it is already wrapped — so a single-key install+ pays nothing for this.+ """+ if provider is None or isinstance(provider, FallbackSTT):+ return provider+ try:+ from jarvis.plugins.stt import (+ available_stt_provider_names,+ build_named_stt_provider,+ )++ configured = (getattr(stt_cfg, "provider", "") or "").strip()+ alternates = alternate_provider_names(+ configured, available_stt_provider_names()+ )+ if not alternates:+ return provider++ def _build(name: str) -> Any:+ return build_named_stt_provider(name, stt_cfg)++ log.info(+ "STT fallback chain armed: %s -> %s",+ configured or type(provider).__name__,+ ", ".join(alternates),+ )+ return FallbackSTT(+ provider, alternates, _build, primary_name=configured+ )+ except Exception as exc: # noqa: BLE001 — a chain that cannot be built is not fatal+ log.warning("STT fallback chain unavailable (%s); using one provider.", exc)+ return provider+++__all__ = [+ "FallbackSTT",+ "RATE_LIMIT_COOLDOWN_S",+ "TRANSIENT_COOLDOWN_S",+ "alternate_provider_names",+ "wrap_stt_with_fallback",+]diff --git a/tests/unit/speech/test_stt_fallback.py b/tests/unit/speech/test_stt_fallback.pynew file mode 100644index 0000000000..06126534f0--- /dev/null+++ b/tests/unit/speech/test_stt_fallback.py@@ -0,0 +1,194 @@+"""Runtime STT fallback — a failing provider must not cost the user their words.++The live bug these lock (2026-07-29): a 137 s dictation came back with 367+characters because Groq answered ``429 Too Many Requests`` partway through and+nothing crossed to any of the three other providers the user had keys for. That+is the single-provider brick AP-22 exists to forbid.+"""++from __future__ import annotations++import pytest++from jarvis.core.protocols import Transcript+from jarvis.speech.stt_fallback import (+ FallbackSTT,+ alternate_provider_names,+ wrap_stt_with_fallback,+)+++class FakeSTT:+ """Minimal STTProvider double: answers, or raises what it was told to."""++ def __init__(self, text: str = "", error: Exception | None = None) -> None:+ self.text = text+ self.error = error+ self.calls = 0++ async def transcribe_pcm(self, pcm, language=None, **kwargs):+ self.calls += 1+ if self.error is not None:+ raise self.error+ return Transcript(text=self.text, language="de", confidence=0.9)+++def _chain(primary: FakeSTT, **alternates: FakeSTT) -> FallbackSTT:+ return FallbackSTT(+ primary,+ list(alternates),+ lambda name: alternates[name],+ primary_name="groq-api",+ )+++# ----------------------------------------------------------------------+# Crossing over+# ----------------------------------------------------------------------+++async def test_rate_limit_crosses_to_the_next_provider():+ """REGRESSION: a 429 mid-dictation must not lose the audio."""+ primary = FakeSTT(error=RuntimeError("Client error '429 Too Many Requests'"))+ backup = FakeSTT(text="die echten Worte") # i18n-allow: German test fixture+ chain = _chain(primary, **{"openai-api": backup})++ result = await chain.transcribe_pcm(b"\x00" * 32000, language="de")++ assert result.text == "die echten Worte"+ assert backup.calls == 1+++ "message",+ [+ "Client error '429 Too Many Requests'",+ "insufficient_quota: You exceeded your current quota",+ "Error code: 402 - payment required",+ "HTTP 503 Service Unavailable",+ "ReadTimeout: The read operation timed out",+ "ConnectError: [Errno 111] Connection refused",+ "Error code: 401 - invalid api key",+ ],+)+async def test_every_failure_another_provider_could_survive_crosses(message):+ primary = FakeSTT(error=RuntimeError(message))+ backup = FakeSTT(text="recovered")+ chain = _chain(primary, **{"openai-api": backup})++ assert (await chain.transcribe_pcm(b"x")).text == "recovered"+++async def test_a_rejection_the_audio_caused_is_not_retried_elsewhere():+ """A 400 means the request itself was refused — another key answers the same.++ Crossing over here would burn a second provider's quota to be told the same+ thing, and hide the real reason from the user.+ """+ primary = FakeSTT(error=ValueError("400 Bad Request: audio file is too short"))+ backup = FakeSTT(text="never reached")+ chain = _chain(primary, **{"openai-api": backup})++ with pytest.raises(ValueError):+ await chain.transcribe_pcm(b"x")+ assert backup.calls == 0+++async def test_the_error_surfaces_when_every_provider_is_exhausted():+ """No silent empty transcript: the user has to learn their keys are spent."""+ primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ backup = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ chain = _chain(primary, **{"openai-api": backup})++ with pytest.raises(RuntimeError, match="429"):+ await chain.transcribe_pcm(b"x")+++# ----------------------------------------------------------------------+# Cooldown — hammering a rate limit is what keeps it locked+# ----------------------------------------------------------------------+++async def test_a_rate_limited_provider_is_skipped_on_the_next_call():+ """The probe fires again 1.2s later; retrying the 429 only extends it."""+ primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ backup = FakeSTT(text="ok")+ chain = _chain(primary, **{"openai-api": backup})++ await chain.transcribe_pcm(b"x")+ calls_after_first = primary.calls+ await chain.transcribe_pcm(b"x")++ assert primary.calls == calls_after_first # not retried while cooling down+ assert backup.calls == 2+++async def test_a_cooling_provider_is_still_the_last_resort():+ """Skipped is not dropped: with every alternate dead it gets the last word."""+ primary = FakeSTT(text="from the configured provider")+ chain = _chain(primary, **{"openai-api": FakeSTT(error=RuntimeError("429"))})+ # Put the primary into cooldown by hand, then starve every alternate.+ chain._penalize("groq-api", "quota")++ result = await chain.transcribe_pcm(b"x")++ assert result.text == "from the configured provider"+++async def test_the_working_alternate_is_preferred_on_later_segments():+ """A long dictation must not re-walk the whole chain on every segment."""+ primary = FakeSTT(error=RuntimeError("429 Too Many Requests"))+ first = FakeSTT(error=RuntimeError("503 Service Unavailable"))+ second = FakeSTT(text="ok")+ chain = FallbackSTT(+ primary,+ ["openai-api", "gemini-api"],+ lambda name: {"openai-api": first, "gemini-api": second}[name],+ primary_name="groq-api",+ )++ await chain.transcribe_pcm(b"x")+ calls_after_first = first.calls+ await chain.transcribe_pcm(b"x")++ assert first.calls == calls_after_first # the dead one is not re-tried+ assert second.calls == 2+++# ----------------------------------------------------------------------+# Chain construction+# ----------------------------------------------------------------------+++def test_local_whisper_is_the_floor_not_the_first_choice():+ """A cloud key is fast and present; local is the option no quota can revoke."""+ order = alternate_provider_names(+ "groq-api", ["groq-api", "openai-api", "faster-whisper", "gemini-api"]+ )+ assert order == ["openai-api", "gemini-api", "faster-whisper"]+ assert "groq-api" not in order # never falls back to the one that just failed+++def test_a_single_key_install_is_not_wrapped():+ """Nothing to fall back to — no wrapper, no cost."""++ class Cfg:+ provider = "groq-api"++ provider = FakeSTT(text="x")+ import jarvis.plugins.stt as stt_mod++ original = stt_mod.available_stt_provider_names+ stt_mod.available_stt_provider_names = lambda: ["groq-api"]+ try:+ assert wrap_stt_with_fallback(provider, Cfg()) is provider+ finally:+ stt_mod.available_stt_provider_names = original+++def test_attributes_delegate_to_the_provider_in_front():+ """Duck-typed callers (recover(), is_warm, model fields) keep working."""+ primary = FakeSTT(text="x")+ primary.is_warm = True+ chain = _chain(primary, **{"openai-api": FakeSTT()})+ assert chain.is_warm is True