Skip to content

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.

fix(wake): gate the GPU turbo wake on a verified out-of-process inference probe

Ruben Lütke684a770c4540
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index e1eb0f0c2e..9397e0e604 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -269,20 +269,25 @@ class STTConfig(BaseModel):
wake_model: str = "base"
wake_device: str = "cpu"
wake_compute_type: str = "int8"
- # When True AND a CUDA GPU is present, a CUSTOM wake phrase (the
- # transcription-based ``stt_match`` path) runs the strong ``large-v3-turbo``
- # model on the GPU instead of the small ``base`` model on the CPU.
- # DEFAULT False (2026-06-30, live-log evidence): on the maintainer's Blackwell
- # GPU (RTX 5070 Ti / sm_120) CTranslate2's ``model.transcribe`` HANGS on every
- # live inference (an 8 s timeout every time -> the wake self-heal drops and
- # rebuilds the model -> a fresh cold inference hangs again -> a vicious cycle
- # that leaves the wake permanently deaf). Enabling GPU turbo there made the
- # wake WORSE, not better. It is kept as an opt-in for GPUs where CTranslate2
- # inference is stable (RTX 30xx/40xx), but the transcription wake fundamentally
- # cannot reach "Hey Google" reliability — that needs a trained neural
- # keyword-spotting model (the ``custom_onnx`` engine). Set True only on a GPU
- # you have verified does not hang on repeated faster-whisper inference.
- wake_high_accuracy: bool = False
+ # When True AND a real turbo/cuda inference has been VERIFIED on this host,
+ # a CUSTOM wake phrase (the transcription-based ``stt_match`` path) runs the
+ # strong ``large-v3-turbo`` model on the GPU instead of the small ``base``
+ # model on the CPU — far better proper-noun recall and ~120 ms/window vs
+ # ~700 ms. History: the default was flipped to False on 2026-06-30 because
+ # on the maintainer's Blackwell GPU (RTX 5070 Ti / sm_120) CTranslate2's
+ # ``model.transcribe`` hung on every live inference under the then-current
+ # runtime (AP-25). Re-measured 2026-07-05 on the same GPU (ctranslate2
+ # 4.7.1 + torch 2.11-cu128): 40/40 inferences under in-process torch-OpenMP
+ # load, zero hangs, p50 117 ms — the hang was constellation-specific, not
+ # "Blackwell forever". The gate is therefore no longer this blind flag but
+ # an automated out-of-process inference probe (one killable subprocess run,
+ # cached per ctranslate2 version — ``jarvis.plugins.stt.
+ # _wake_gpu_inference_verified``), plus a live backstop that drops back to
+ # base/cpu and persists the bad verdict if the swapped-in GPU model ever
+ # wedges. False remains the hard opt-out (never try the GPU). The
+ # transcription wake still cannot reach "Hey Google" reliability — that
+ # needs a trained neural keyword-spotting model (the ``custom_onnx`` engine).
+ wake_high_accuracy: bool = True
language: str = "auto"
# Vocabulary biasing passed to Whisper's ``prompt`` field — the same
# mechanism dictation tools like a dictation app use to keep proper nouns and
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 1bd740dd58..dd18d11952 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -341,6 +341,177 @@ def _wake_cuda_available() -> bool:
return available
+def _wake_gpu_probe_cache_path() -> Path:
+ """Location of the persisted GPU wake-inference probe result.
+
+ Separate from ``wake_cuda_probe.json`` (mere CUDA *presence*): this file
+ records whether a real ``large-v3-turbo`` CUDA *inference* completed on this
+ host — presence and usability diverged in AP-25 (a Blackwell sm_120 box HAD
+ CUDA but every CTranslate2 inference hung under the then-current runtime).
+ Delete the file to force a re-probe after a GPU/driver change.
+ """
+ base = os.environ.get("JARVIS__MEMORY__DATA_DIR") or "data"
+ return Path(base) / "wake_gpu_probe.json"
+
+
+# Success marker the probe subprocess prints AFTER its real CUDA inferences.
+# The probe verdict is this marker in stdout, NEVER the exit code: a CUDA
+# process can die in native teardown (observed exit 127 on 2026-07-05) after
+# doing all its work correctly.
+_WAKE_GPU_PROBE_MARKER = "WAKE_GPU_PROBE_OK"
+
+# Generous ceiling for ONE probe run: a cold Blackwell kernel-JIT model load
+# was measured at ~71 s; a healthy warm load + two inferences is < 15 s. A
+# probe that cannot finish inside this window is exactly the AP-25 hang the
+# probe exists to catch.
+_WAKE_GPU_PROBE_TIMEOUT_S = 180.0
+
+# The probe exercises the SAME model the CUDA upgrade branches below swap in.
+_WAKE_GPU_PROBE_SCRIPT = r"""
+import numpy as np
+from faster_whisper import WhisperModel
+m = WhisperModel("large-v3-turbo", device="cuda", compute_type="int8_float16")
+pcm = (np.random.default_rng(0).standard_normal(19200) * 0.05).astype("float32")
+for _ in range(2):
+ segments, _info = m.transcribe(pcm, language="de", beam_size=1)
+ list(segments) # consume the generator — this is what runs the inference
+print("WAKE_GPU_PROBE_OK", flush=True)
+"""
+
+
+def _ctranslate2_version() -> str:
+ """Installed ctranslate2 version (metadata only — no heavy import)."""
+ try:
+ return importlib_metadata.version("ctranslate2")
+ except Exception: # noqa: BLE001 — absent/broken install means "unknown"
+ return "unknown"
+
+
+def _run_wake_gpu_probe_subprocess() -> bool:
+ """Run one real turbo/cuda inference in a KILLABLE child process.
+
+ Out-of-process on purpose (BUG-036/AP-24): a hung native inference thread
+ inside THIS process could never be cancelled and would poison the app; a
+ child process is killed on timeout and leaves no residue. Blocking — only
+ ever called from the background hot-swap thread, never the boot path.
+ """
+ import subprocess
+ import sys
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ try:
+ proc = subprocess.run( # noqa: S603 — fixed argv, our own interpreter
+ [sys.executable, "-c", _WAKE_GPU_PROBE_SCRIPT],
+ capture_output=True,
+ text=True,
+ timeout=_WAKE_GPU_PROBE_TIMEOUT_S,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except subprocess.TimeoutExpired:
+ logger.warning(
+ "Wake-GPU probe: inference did not finish within {:.0f} s — the "
+ "AP-25 hang signature. GPU wake upgrade stays OFF on this host.",
+ _WAKE_GPU_PROBE_TIMEOUT_S,
+ )
+ return False
+ except Exception as exc: # noqa: BLE001 — a probe must never break the caller
+ logger.warning("Wake-GPU probe: could not launch ({}).", exc)
+ return False
+ ok = _WAKE_GPU_PROBE_MARKER in (proc.stdout or "")
+ if not ok:
+ tail = ((proc.stderr or proc.stdout or "").strip())[-300:]
+ logger.warning(
+ "Wake-GPU probe: no success marker (exit={}). Tail: {}",
+ proc.returncode,
+ tail or "<empty>",
+ )
+ return ok
+
+
+@lru_cache(maxsize=1)
+def _wake_gpu_inference_verified() -> bool:
+ """True iff a real turbo/cuda wake inference VERIFIABLY completes here.
+
+ This is the capability gate (AP-21) that replaced the blanket AP-25
+ "GPU turbo off by default": CUDA presence alone is not enough — on one
+ Blackwell host every CTranslate2 inference hung under the then-current
+ runtime while ``get_cuda_device_count()`` was happily > 0. The verdict is
+ cached on disk keyed by the ctranslate2 version (a runtime upgrade that
+ may fix — or break — the hang triggers exactly one re-probe).
+
+ BLOCKING (up to ``_WAKE_GPU_PROBE_TIMEOUT_S`` on a cache miss): call it
+ only from the background hot-swap (``fast_first=False`` builds), never on
+ the boot / hear-ready path (AP-26).
+ """
+ ct2_version = _ctranslate2_version()
+ cache_path = _wake_gpu_probe_cache_path()
+ try:
+ cached = json.loads(cache_path.read_text(encoding="utf-8"))
+ if (
+ isinstance(cached, dict)
+ and isinstance(cached.get("ok"), bool)
+ and cached.get("ctranslate2") == ct2_version
+ ):
+ logger.info(
+ "Wake-GPU probe: cache HIT ({}, ctranslate2 {}) — probe skipped.",
+ "verified" if cached["ok"] else "unusable",
+ ct2_version,
+ )
+ return cached["ok"]
+ except FileNotFoundError:
+ pass
+ except Exception as exc: # noqa: BLE001 — a corrupt cache must never break the swap
+ logger.debug("Wake-GPU probe cache unreadable ({}); re-probing.", exc)
+
+ t0 = time.perf_counter()
+ ok = _run_wake_gpu_probe_subprocess()
+ logger.info(
+ "Wake-GPU probe: real turbo/cuda inference {} in {:.1f} s "
+ "(ctranslate2 {}).",
+ "VERIFIED" if ok else "FAILED",
+ time.perf_counter() - t0,
+ ct2_version,
+ )
+ _persist_wake_gpu_probe(ok, ct2_version)
+ return ok
+
+
+def _persist_wake_gpu_probe(ok: bool, ct2_version: str | None = None) -> None:
+ """Best-effort write of the probe verdict (shared by probe + bad-mark)."""
+ cache_path = _wake_gpu_probe_cache_path()
+ try:
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ cache_path.write_text(
+ json.dumps(
+ {
+ "ok": ok,
+ "ctranslate2": ct2_version or _ctranslate2_version(),
+ "model": "large-v3-turbo",
+ }
+ ),
+ encoding="utf-8",
+ )
+ except Exception as exc: # noqa: BLE001 — caching is best-effort
+ logger.debug("Wake-GPU probe cache write failed ({}).", exc)
+
+
+def mark_wake_gpu_bad() -> None:
+ """Record that the LIVE GPU wake model wedged — future builds stay on CPU.
+
+ Runtime backstop for a hang the one-off probe missed: the rolling wake's
+ self-heal calls this right before swapping back to its base/cpu fallback,
+ so the very next build (and every restart) skips the GPU upgrade until the
+ ctranslate2 version changes (which re-keys the cache and re-probes).
+ """
+ _persist_wake_gpu_probe(False)
+ _wake_gpu_inference_verified.cache_clear()
+ logger.warning(
+ "Wake-GPU probe: marked UNUSABLE after a live wedge — wake stays on "
+ "the base/cpu model until the ctranslate2 runtime changes."
+ )
+
+
def build_wake_whisper(
stt_cfg: Any,
*,
@@ -419,18 +590,27 @@ def build_wake_whisper(
# above). The caller then hot-swaps in the turbo/cuda model in the background
# for faster steady-state inference, so the 2026-06-24 accuracy upgrade is
# preserved — only its load is moved off the hear-ready path.
+ # Both CUDA branches additionally require the one-time out-of-process
+ # INFERENCE probe (``_wake_gpu_inference_verified``): CUDA presence alone
+ # proved insufficient in AP-25 (a Blackwell box had CUDA but every
+ # CTranslate2 inference hung under the then-current runtime). The probe is
+ # blocking on its first run, which is safe here: ``fast_first`` builds
+ # (the boot path) never reach it, so it only ever runs inside the
+ # background hot-swap. Short-circuit order keeps it last — a CPU-only or
+ # opted-out host never pays for it.
if (
not fast_first
and not bias
and model == "base"
and device == "cpu"
and cuda_available
+ and _wake_gpu_inference_verified()
):
model, device, compute = "large-v3-turbo", "cuda", "int8_float16"
bias = None # strong model needs no bias; the bias is what hallucinates
logger.info(
- "Wake-Whisper: CUDA present -> GPU turbo (large-v3-turbo/cuda), "
- "bias OFF (fast + no silence hallucination)."
+ "Wake-Whisper: CUDA inference verified -> GPU turbo "
+ "(large-v3-turbo/cuda), bias OFF (fast + no silence hallucination)."
)
elif (
not fast_first
@@ -439,6 +619,7 @@ def build_wake_whisper(
and device == "cpu"
and cuda_available
and bool(getattr(stt_cfg, "wake_high_accuracy", True))
+ and _wake_gpu_inference_verified()
):
# CUSTOM WAKE PHRASE on a CUDA box: upgrade to the strong turbo model on
# the GPU BUT KEEP the phrase bias. Mission 2026-06-30, live-log evidence
@@ -459,9 +640,9 @@ def build_wake_whisper(
# contend with it. Reversible: wake_high_accuracy=False forces base/cpu.
model, device, compute = "large-v3-turbo", "cuda", "int8_float16"
logger.info(
- "Wake-Whisper: custom phrase on CUDA -> GPU turbo (large-v3-turbo/cuda) "
- "WITH bias — fast (~150 ms, no wedge) + accurate. Set "
- "[stt].wake_high_accuracy=false to force base/cpu."
+ "Wake-Whisper: custom phrase, CUDA inference verified -> GPU turbo "
+ "(large-v3-turbo/cuda) WITH bias — fast (~150 ms, no wedge) + "
+ "accurate. Set [stt].wake_high_accuracy=false to force base/cpu."
)
elif fast_first and model == "base" and device == "cpu" and cuda_available:
logger.info(
@@ -563,5 +744,6 @@ def start_wake_model_prefetch(
__all__ = [
"build_stt_from_config",
"build_wake_whisper",
+ "mark_wake_gpu_bad",
"start_wake_model_prefetch",
]
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 822e6a552b..ec45041617 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1713,8 +1713,18 @@ class SpeechPipeline:
# is ~71 s; base/cpu ~0.45 s, measured). Seed the prompt with the
# custom phrase so the small model transcribes the (proper-noun)
# wake name instead of a common word — forensic 2026-06-22.
+ # fast_first: this runs on a live settings switch (often from
+ # the FastAPI handler), so it must stay non-blocking. The
+ # non-fast build now runs the one-time GPU inference probe
+ # (blocking up to minutes on a cache miss) — that belongs to
+ # the boot hot-swap only. Trade-off: after a LIVE wake-word
+ # switch the stt_match wake runs on base/cpu until the next
+ # app start, whose background hot-swap restores turbo/cuda.
self._stt = build_wake_whisper(
- stt_cfg, language=lang, wake_phrase=getattr(plan, "phrase", None)
+ stt_cfg,
+ language=lang,
+ wake_phrase=getattr(plan, "phrase", None),
+ fast_first=True,
)
if self._probe_stt is None:
try:
diff --git a/jarvis/speech/rolling_whisper_wake.py b/jarvis/speech/rolling_whisper_wake.py
index 4f51ba964a..221a06b780 100644
--- a/jarvis/speech/rolling_whisper_wake.py
+++ b/jarvis/speech/rolling_whisper_wake.py
@@ -533,6 +533,35 @@ class RollingWhisperWake:
def _recover_wedged(reason: str) -> None:
nonlocal busy_since, consecutive_fail, rewarm_owed
+ # GPU-upgrade backstop: the background hot-swap attaches the proven
+ # base/cpu provider to the turbo instance (``_wake_gpu_fallback``).
+ # A wedge on THAT model means the one-off GPU inference probe was
+ # wrong for this host, so rebuilding the same CUDA model would just
+ # wedge again (the AP-25 deaf cycle). Swap straight back to the
+ # still-warm base model and persist the bad verdict so every later
+ # build (and restart) stays on CPU until the ctranslate2 runtime
+ # changes. No re-warm owed — the fallback kept its loaded model.
+ fallback = getattr(self._stt, "_wake_gpu_fallback", None)
+ if fallback is not None:
+ log.error(
+ "rolling-whisper: %s on the GPU wake model — swapping back "
+ "to the base/cpu fallback and marking the GPU probe bad "
+ "(self-heal, no restart).",
+ reason,
+ )
+ try:
+ from jarvis.plugins.stt import mark_wake_gpu_bad
+
+ mark_wake_gpu_bad()
+ except Exception as exc: # noqa: BLE001 — heal must never crash
+ log.warning(
+ "rolling-whisper: could not persist the bad GPU "
+ "verdict: %s", exc,
+ )
+ self._stt = fallback
+ busy_since = None
+ consecutive_fail = 0
+ return
recover = getattr(self._stt, "recover", None)
if callable(recover):
log.error(
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 454faf09c4..49264a4b73 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -2589,6 +2589,15 @@ class DesktopApp:
else turbo._ensure_model
)
if ww is not None:
+ # Runtime backstop: keep the proven base/cpu model
+ # reachable from the turbo instance. If the GPU
+ # model ever wedges live (a hang the one-off probe
+ # missed), the rolling wake's self-heal swaps back
+ # to this fallback and persists the bad verdict
+ # (mark_wake_gpu_bad) instead of rebuilding the
+ # same hung CUDA model — bounded-time recovery to
+ # the pre-upgrade state. ~80 MB RAM held on purpose.
+ turbo._wake_gpu_fallback = ww._stt
# Atomic ref swap (GIL); the next transcribe uses turbo.
ww._stt = turbo
logger.info(
diff --git a/tests/unit/plugins/stt/test_wake_gpu_probe.py b/tests/unit/plugins/stt/test_wake_gpu_probe.py
new file mode 100644
index 0000000000..8d333c72ed
--- /dev/null
+++ b/tests/unit/plugins/stt/test_wake_gpu_probe.py
@@ -0,0 +1,161 @@
+"""The GPU wake-inference probe: verdicts, caching, and the marker contract.
+
+Why this exists (AP-25, re-measured 2026-07-05): CUDA *presence* and CUDA
+*usability* diverged on a Blackwell host — ``get_cuda_device_count() > 0``
+while every CTranslate2 inference hung under the then-current runtime. The
+probe runs ONE real turbo/cuda inference in a killable subprocess and caches
+the verdict per ctranslate2 version, so a runtime upgrade (which may fix or
+re-introduce the hang) triggers exactly one re-probe.
+
+Two hard contracts pinned here:
+- Success is the stdout MARKER, never the exit code — a CUDA process can die
+ in native teardown (observed exit 127 on 2026-07-05) after doing all its
+ work correctly.
+- A hang (subprocess timeout) persists ``ok: false`` so no later build ever
+ re-runs the hanging inference in-process.
+"""
+from __future__ import annotations
+
+import json
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+import jarvis.plugins.stt as stt_pkg
+from jarvis.plugins.stt import (
+ _run_wake_gpu_probe_subprocess,
+ _wake_gpu_inference_verified,
+ _wake_gpu_probe_cache_path,
+ mark_wake_gpu_bad,
+)
+
+
[email protected](autouse=True)
+def _isolated_cache(tmp_path, monkeypatch):
+ """Point the probe cache at a temp dir and clear the in-process memo."""
+ monkeypatch.setenv("JARVIS__MEMORY__DATA_DIR", str(tmp_path))
+ _wake_gpu_inference_verified.cache_clear()
+ yield tmp_path
+ _wake_gpu_inference_verified.cache_clear()
+
+
+def _write_cache(tmp_path, *, ok: bool, ct2: str) -> None:
+ (tmp_path / "wake_gpu_probe.json").write_text(
+ json.dumps({"ok": ok, "ctranslate2": ct2}), encoding="utf-8"
+ )
+
+
+def _pin_version(monkeypatch, version: str) -> None:
+ monkeypatch.setattr(stt_pkg, "_ctranslate2_version", lambda: version)
+
+
+def _forbid_subprocess(monkeypatch) -> None:
+ def _boom() -> bool:
+ raise AssertionError("cache hit must not launch the probe subprocess")
+
+ monkeypatch.setattr(stt_pkg, "_run_wake_gpu_probe_subprocess", _boom)
+
+
+def test_cache_path_honours_data_dir_env(tmp_path) -> None:
+ assert _wake_gpu_probe_cache_path() == tmp_path / "wake_gpu_probe.json"
+
+
+def test_cache_hit_ok_true_skips_the_subprocess(tmp_path, monkeypatch) -> None:
+ _pin_version(monkeypatch, "4.7.1")
+ _write_cache(tmp_path, ok=True, ct2="4.7.1")
+ _forbid_subprocess(monkeypatch)
+ assert _wake_gpu_inference_verified() is True
+
+
+def test_cache_hit_ok_false_skips_the_subprocess(tmp_path, monkeypatch) -> None:
+ _pin_version(monkeypatch, "4.7.1")
+ _write_cache(tmp_path, ok=False, ct2="4.7.1")
+ _forbid_subprocess(monkeypatch)
+ assert _wake_gpu_inference_verified() is False
+
+
+def test_version_mismatch_reprobes_and_rewrites_the_cache(
+ tmp_path, monkeypatch
+) -> None:
+ # A cached "unusable" verdict from an OLD runtime must not outlive a
+ # ctranslate2 upgrade — exactly the AP-25 situation this session resolved.
+ _pin_version(monkeypatch, "4.8.0")
+ _write_cache(tmp_path, ok=False, ct2="4.7.1")
+ monkeypatch.setattr(stt_pkg, "_run_wake_gpu_probe_subprocess", lambda: True)
+
+ assert _wake_gpu_inference_verified() is True
+ cached = json.loads(
+ (tmp_path / "wake_gpu_probe.json").read_text(encoding="utf-8")
+ )
+ assert cached == {"ok": True, "ctranslate2": "4.8.0", "model": "large-v3-turbo"}
+
+
+def test_corrupt_cache_reprobes(tmp_path, monkeypatch) -> None:
+ _pin_version(monkeypatch, "4.7.1")
+ (tmp_path / "wake_gpu_probe.json").write_text("{not json", encoding="utf-8")
+ monkeypatch.setattr(stt_pkg, "_run_wake_gpu_probe_subprocess", lambda: False)
+
+ assert _wake_gpu_inference_verified() is False
+ cached = json.loads(
+ (tmp_path / "wake_gpu_probe.json").read_text(encoding="utf-8")
+ )
+ assert cached["ok"] is False
+
+
+def test_failed_probe_persists_ok_false(tmp_path, monkeypatch) -> None:
+ # A hang/failure verdict must survive restarts: the next build reads the
+ # cache and never re-runs the hanging inference.
+ _pin_version(monkeypatch, "4.7.1")
+ monkeypatch.setattr(stt_pkg, "_run_wake_gpu_probe_subprocess", lambda: False)
+
+ assert _wake_gpu_inference_verified() is False
+ cached = json.loads(
+ (tmp_path / "wake_gpu_probe.json").read_text(encoding="utf-8")
+ )
+ assert cached["ok"] is False and cached["ctranslate2"] == "4.7.1"
+
+
+def test_mark_wake_gpu_bad_overrides_a_verified_cache(tmp_path, monkeypatch) -> None:
+ # The live backstop: a wedge on the swapped-in GPU model demotes the host
+ # even though the one-off probe once said OK.
+ _pin_version(monkeypatch, "4.7.1")
+ _write_cache(tmp_path, ok=True, ct2="4.7.1")
+ assert _wake_gpu_inference_verified() is True
+
+ mark_wake_gpu_bad()
+
+ _forbid_subprocess(monkeypatch) # verdict must come from the rewritten cache
+ assert _wake_gpu_inference_verified() is False
+
+
+# --- the subprocess wrapper's marker contract --------------------------------
+
+
+def _fake_run(stdout: str, returncode: int):
+ def _run(*_a, **_k):
+ return SimpleNamespace(stdout=stdout, stderr="", returncode=returncode)
+
+ return _run
+
+
+def test_probe_success_is_the_marker_not_the_exit_code(monkeypatch) -> None:
+ # Observed 2026-07-05: the probe printed its marker, then the CUDA teardown
+ # killed the process with exit 127. That is a PASS.
+ monkeypatch.setattr(
+ subprocess, "run", _fake_run("WAKE_GPU_PROBE_OK\n", returncode=127)
+ )
+ assert _run_wake_gpu_probe_subprocess() is True
+
+
+def test_probe_clean_exit_without_marker_fails(monkeypatch) -> None:
+ monkeypatch.setattr(subprocess, "run", _fake_run("", returncode=0))
+ assert _run_wake_gpu_probe_subprocess() is False
+
+
+def test_probe_timeout_fails(monkeypatch) -> None:
+ def _hang(*_a, **_k):
+ raise subprocess.TimeoutExpired(cmd="python", timeout=180.0)
+
+ monkeypatch.setattr(subprocess, "run", _hang)
+ assert _run_wake_gpu_probe_subprocess() is False
diff --git a/tests/unit/plugins/stt/test_wake_whisper_build.py b/tests/unit/plugins/stt/test_wake_whisper_build.py
index adf4bbf9ed..f8df4cfc67 100644
--- a/tests/unit/plugins/stt/test_wake_whisper_build.py
+++ b/tests/unit/plugins/stt/test_wake_whisper_build.py
@@ -11,11 +11,22 @@ to a few seconds.
"""
from __future__ import annotations
+import pytest
+
+import jarvis.plugins.stt as stt_pkg
from jarvis.core.config import STTConfig
from jarvis.plugins.stt import build_wake_whisper
from jarvis.plugins.stt.fwhisper import FasterWhisperProvider
[email protected](autouse=True)
+def _gpu_probe_verified(monkeypatch):
+ """Default the GPU inference probe to VERIFIED without touching a real
+ subprocess or the on-disk cache (both belong to integration, not here).
+ Tests for the probe-fail path override with ``lambda: False``."""
+ monkeypatch.setattr(stt_pkg, "_wake_gpu_inference_verified", lambda: True)
+
+
def test_stt_config_wake_defaults_small_and_cpu() -> None:
cfg = STTConfig()
assert cfg.wake_model == "base"
@@ -42,30 +53,57 @@ def test_build_wake_whisper_uses_wake_fields_not_utterance_model() -> None:
assert p._compute_type == "int8"
-def test_build_wake_whisper_custom_phrase_default_stays_base_cpu_on_cuda() -> None:
- # DEFAULT is base/cpu even on a CUDA box (wake_high_accuracy defaults False).
- # Live-log evidence 2026-06-30: on the maintainer's Blackwell GPU (sm_120)
- # CTranslate2 ``model.transcribe`` HANGS on every live large-v3-turbo/cuda
- # inference (8 s timeout -> self-heal drops the model -> cold rebuild hangs
- # again -> vicious cycle, wake permanently deaf). So GPU turbo is OFF by
- # default; the validated base/cpu + phrase-bias config is the default.
+def test_build_wake_whisper_custom_phrase_default_gets_turbo_when_probe_verifies() -> None:
+ # DEFAULT (wake_high_accuracy=True) + CUDA + a VERIFIED real inference probe
+ # -> a custom phrase upgrades to large-v3-turbo/cuda WITH bias. History: the
+ # default was False after the AP-25 Blackwell hang; re-measured 2026-07-05
+ # (ctranslate2 4.7.1, same GPU: 40/40 inferences, 0 hangs) the hang was
+ # constellation-specific, so the blind flag became the automated probe.
+ p = build_wake_whisper(STTConfig(), wake_phrase="Hey Ruben", cuda_available=True)
+ assert p._model_name == "large-v3-turbo"
+ assert p._device == "cuda"
+ assert p._initial_prompt == "Hey Ruben" # bias KEPT — needed to hear the name
+
+
+def test_build_wake_whisper_custom_phrase_stays_base_cpu_when_probe_fails(
+ monkeypatch,
+) -> None:
+ # An UNVERIFIED GPU (probe hang/failure — the AP-25 class) must keep the
+ # validated base/cpu + phrase-bias config even though CUDA is present.
+ monkeypatch.setattr(stt_pkg, "_wake_gpu_inference_verified", lambda: False)
p = build_wake_whisper(STTConfig(), wake_phrase="Hey Ruben", cuda_available=True)
assert p._model_name == "base"
assert p._device == "cpu"
- assert p._initial_prompt == "Hey Ruben" # bias KEPT — needed to hear the name
+ assert p._initial_prompt == "Hey Ruben"
-def test_build_wake_whisper_custom_phrase_gpu_turbo_is_opt_in() -> None:
- # wake_high_accuracy = True opts a custom phrase into large-v3-turbo/cuda WITH
- # bias — for GPUs where CTranslate2 inference is stable (RTX 30xx/40xx). Kept
- # as an escape hatch, NOT the default (it hangs on Blackwell).
- cfg = STTConfig(wake_high_accuracy=True)
+def test_build_wake_whisper_high_accuracy_false_is_a_hard_opt_out() -> None:
+ # wake_high_accuracy=False must force base/cpu even when the probe verifies
+ # the GPU — the user's explicit kill switch always wins.
+ cfg = STTConfig(wake_high_accuracy=False)
p = build_wake_whisper(cfg, wake_phrase="Hey Ruben", cuda_available=True)
- assert p._model_name == "large-v3-turbo"
- assert p._device == "cuda"
+ assert p._model_name == "base"
+ assert p._device == "cpu"
assert p._initial_prompt == "Hey Ruben"
+def test_build_wake_whisper_fast_first_never_runs_the_gpu_probe(
+ monkeypatch,
+) -> None:
+ # The probe BLOCKS (subprocess, up to minutes on a cache miss). fast_first
+ # builds run on the boot / hear-ready path (AP-26) and on live settings
+ # switches, so they must never reach it.
+ def _boom() -> bool:
+ raise AssertionError("fast_first build must not run the GPU probe")
+
+ monkeypatch.setattr(stt_pkg, "_wake_gpu_inference_verified", _boom)
+ p = build_wake_whisper(
+ STTConfig(), wake_phrase="Hey Ruben", cuda_available=True, fast_first=True
+ )
+ assert p._model_name == "base"
+ assert p._device == "cpu"
+
+
def test_build_wake_whisper_custom_phrase_fast_first_stays_base_for_quick_boot() -> None:
# The boot path builds fast-first (base/cpu, ~3 s, no CUDA JIT) so the wake is
# hear-ready immediately; the GPU turbo swaps in via the background hot-swap.
diff --git a/tests/unit/speech/test_rolling_whisper_wake_gpu_backstop.py b/tests/unit/speech/test_rolling_whisper_wake_gpu_backstop.py
new file mode 100644
index 0000000000..80a3e852f0
--- /dev/null
+++ b/tests/unit/speech/test_rolling_whisper_wake_gpu_backstop.py
@@ -0,0 +1,120 @@
+"""A wedged GPU wake model must fall BACK to base/cpu, not rebuild itself.
+
+The background hot-swap attaches the proven base/cpu provider to the turbo
+instance as ``_wake_gpu_fallback`` before the ref swap. If the GPU model later
+wedges live (a hang the one-off inference probe missed), rebuilding the same
+CUDA model would just wedge again — the AP-25 deaf cycle. The self-heal must
+instead swap straight back to the still-warm fallback and persist the bad
+verdict (``mark_wake_gpu_bad``) so every later build stays on CPU.
+"""
+from __future__ import annotations
+
+import asyncio
+import re
+
+import numpy as np
+
+import jarvis.plugins.stt as stt_pkg
+from jarvis.core.protocols import AudioChunk
+from jarvis.speech.rolling_whisper_wake import RollingWhisperWake
+
+
+def _loud_chunk(marker: int, n: int = 1600) -> AudioChunk:
+ val = 12000 + (marker % 80) * 100
+ arr = np.full(n, val, dtype=np.int16)
+ return AudioChunk(pcm=arr.tobytes(), sample_rate=16000, timestamp_ns=0)
+
+
+class _BaseFallbackSTT:
+ """The pre-upgrade base/cpu provider — healthy, transcribes instantly."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm, sample_rate=16000, language=None): # noqa: ANN001
+ self.calls += 1
+
+ class _T:
+ text = ""
+ confidence = 1.0
+ segments = ()
+
+ return _T()
+
+
+class _HangingTurboSTT:
+ """The swapped-in GPU model — every transcribe hangs (probe was wrong)."""
+
+ def __init__(self, fallback: _BaseFallbackSTT) -> None:
+ self._wake_gpu_fallback = fallback
+ self.recovered = 0
+
+ async def transcribe_pcm(self, pcm, sample_rate=16000, language=None): # noqa: ANN001
+ await asyncio.Event().wait()
+
+ def recover(self) -> None: # must NOT be used — rebuilding re-wedges
+ self.recovered += 1
+
+
+async def test_wedged_gpu_model_swaps_back_to_fallback_and_marks_bad(
+ monkeypatch,
+) -> None:
+ marked = []
+ monkeypatch.setattr(stt_pkg, "mark_wake_gpu_bad", lambda: marked.append(True))
+
+ fallback = _BaseFallbackSTT()
+ turbo = _HangingTurboSTT(fallback)
+ wake = RollingWhisperWake(
+ turbo,
+ pattern=re.compile(r"nova", re.IGNORECASE),
+ poll_interval_s=0.01,
+ cooldown_s=0.0,
+ min_rms=0.0,
+ min_peak=0.0,
+ transcribe_timeout_s=0.02, # fast so the wedge is detected quickly
+ )
+ src: asyncio.Queue = asyncio.Queue()
+ stop = asyncio.Event()
+
+ async def _iter():
+ while True:
+ chunk = await src.get()
+ if chunk is None:
+ return
+ yield chunk
+
+ async def _feed() -> None:
+ i = 0
+ while not stop.is_set():
+ await src.put(_loud_chunk(i))
+ i += 1
+ await asyncio.sleep(0.002)
+
+ async def _drive() -> None:
+ async for _kw in wake.detect(_iter()):
+ pass
+
+ feeder = asyncio.create_task(_feed())
+ drive = asyncio.create_task(_drive())
+ try:
+ for _ in range(300):
+ if fallback.calls >= 1:
+ break
+ await asyncio.sleep(0.02)
+ # The heal swapped back: the fallback is transcribing again...
+ assert fallback.calls >= 1, "the base/cpu fallback never took over"
+ assert wake._stt is fallback
+ # ...the bad verdict was persisted for every later build...
+ assert marked, "mark_wake_gpu_bad was never called"
+ # ...and the hung CUDA model was NOT rebuilt (the AP-25 deaf cycle).
+ assert turbo.recovered == 0
+ finally:
+ stop.set()
+ await src.put(None)
+ drive.cancel()
+ feeder.cancel()
+ for t in (drive, feeder):
+ try:
+ await t
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass