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.

perf(wake): stop the always-on ear paying for boot, polling and a decode ladder

Ruben Lütke5164ecc0b8ca
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index b61cb4b642..788888448c 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -466,6 +466,20 @@ def _invalidate_resolve_cache() -> None:
_RESOLVE_CACHE.clear()
+def _request_topology_probe() -> None:
+ """Nudge the topology watcher to re-probe now (best-effort, never raises).
+
+ Imported lazily: ``topology`` imports this module, so a top-level import
+ would be circular.
+ """
+ try:
+ from jarvis.audio.topology import request_topology_probe
+
+ request_topology_probe()
+ except Exception: # noqa: BLE001 — a diagnostics nudge must never propagate
+ _log.debug("topology probe request skipped", exc_info=True)
+
+
def _cached_resolve(
device_spec: int | str | None, priority: tuple[str, ...]
) -> Any | None:
@@ -882,8 +896,11 @@ class MicrophoneCapture:
close_exc,
)
# A failed open means the cached/resolved device may be gone —
- # force the next construction through a fresh full resolve.
+ # force the next construction through a fresh full resolve, and
+ # ask the topology watcher to look NOW rather than at its next
+ # poll (that is why the poll interval can stay cheap).
_invalidate_resolve_cache()
+ _request_topology_probe()
_log.warning(
"Mic-Open on device={} at {}Hz failed ({}); trying next "
"fallback.",
@@ -937,6 +954,7 @@ class MicrophoneCapture:
continue
# Stalled: whatever we knew about the device landscape is suspect.
_invalidate_resolve_cache()
+ _request_topology_probe()
self._restart_count += 1
_log.warning(
"Mic stall detected ({:.1f}s without a frame) — restart #{} (device={}).",
diff --git a/jarvis/audio/topology.py b/jarvis/audio/topology.py
index 3f3f1fc30d..c33c393f5b 100644
--- a/jarvis/audio/topology.py
+++ b/jarvis/audio/topology.py
@@ -54,13 +54,40 @@ _OPEN_LOCK = threading.RLock()
_captures_lock = threading.Lock()
_captures: weakref.WeakSet[Any] = weakref.WeakSet()
-DEFAULT_POLL_S = 5.0
+# Steady-state cadence. Each probe spawns a full Python + PortAudio subprocess,
+# so the former 5 s poll cost 12 interpreter cold starts per MINUTE for the
+# entire life of the app — ~4-6 % of a core on the fastest supported machine and
+# 20-50 % of one core on the hardware the project actually targets (an
+# Intel-2019 Mac, a dual-core VPS), competing directly with wake inference.
+# Hot-plug reaction does not suffer: ``request_topology_probe`` fires an
+# immediate probe from the signals that really mean "a device vanished".
+DEFAULT_POLL_S = 30.0
# One burst of CoreAudio/WASAPI events accompanies a single physical plug;
# wait this long after the first divergent signature so the refresh runs once
# against the settled topology instead of once per event.
_SETTLE_S = 1.5
+# Set while a watcher runs, so a device-loss signal can skip the poll wait.
+_probe_request: asyncio.Event | None = None
+_probe_loop: asyncio.AbstractEventLoop | None = None
+
+
+def request_topology_probe() -> None:
+ """Ask the watcher to probe NOW instead of at the next poll.
+
+ Call this from the signals that actually mean "a device may have vanished"
+ — a mic stall and a failed stream open — so raising the steady-state poll
+ interval costs nothing in hot-plug responsiveness. Safe from any thread,
+ and a silent no-op when no watcher is running (tests, headless).
+ """
+ event, loop = _probe_request, _probe_loop
+ if event is None or loop is None or loop.is_closed():
+ return
+ with contextlib.suppress(RuntimeError): # loop shutting down
+ loop.call_soon_threadsafe(event.set)
+
+
def stream_open_guard() -> threading.RLock:
"""Lock every native PortAudio stream open must hold (``with ...():``)."""
return _OPEN_LOCK
@@ -184,11 +211,17 @@ async def watch_topology(
injectable for tests; the defaults use the out-of-process device probe
and :func:`refresh_audio_backend`.
"""
+ global _probe_request, _probe_loop
probe = probe or _fresh_signature
refresh = refresh or (lambda: refresh_audio_backend(player, output_device))
+ _probe_request = asyncio.Event()
+ _probe_loop = asyncio.get_running_loop()
last: str | None = None
while True:
- await asyncio.sleep(poll_s)
+ # Wake early when a device-loss signal fires, otherwise poll.
+ with contextlib.suppress(TimeoutError):
+ await asyncio.wait_for(_probe_request.wait(), timeout=poll_s)
+ _probe_request.clear()
signature = await asyncio.to_thread(probe)
if signature is None:
# Probe unavailable (headless, worker timeout) — no judgment.
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.py
index 955fc5c0e0..90ea3be193 100644
--- a/jarvis/plugins/stt/__init__.py
+++ b/jarvis/plugins/stt/__init__.py
@@ -812,6 +812,20 @@ def build_wake_whisper(
# stream). NOTE: transcription wake still cannot reach KWS-instant
# latency — the definitive fix remains a neural KWS model (AP-25).
cpu_threads=2,
+ # ONE greedy pass per wake window — drop Whisper's 6-step temperature
+ # fallback ladder here. The ladder only re-decodes transcripts that
+ # already look degenerate, which the phrase matcher and the
+ # ``no_speech_prob``/RMS gates reject anyway, while a genuine wake is
+ # decided on the first pass. Unbounded it made a single window cost up
+ # to 7.7 s on a FAST box (measured) — past the 8 s abandon cap on weaker
+ # hardware, where the timeout drops the model and forces a cold rebuild,
+ # extending the deaf gap. Bounding the work changes no gate and no
+ # transcript rule, so AP-27 is untouched. ``without_timestamps`` is
+ # deliberately NOT set alongside it: collapsing the window to a single
+ # segment would change what ``_reliable_wake_transcript``'s per-segment
+ # ``no_speech_prob`` check sees, i.e. shift the ghost/recall coupling on
+ # the very engine AP-27 was written for.
+ temperature=0.0,
)
diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.py
index 546b855b4a..fbff920e83 100644
--- a/jarvis/plugins/stt/fwhisper.py
+++ b/jarvis/plugins/stt/fwhisper.py
@@ -294,6 +294,19 @@ class FasterWhisperProvider:
# OpenMP deadlock that hung the always-on wake transcribe (see
# ``_new_whisper_model``); set only on the wake model.
cpu_threads: int = 0,
+ # Whisper's temperature-fallback LADDER. The default re-decodes a window
+ # up to 6 times when a transcript looks degenerate, which is right for
+ # an utterance but ruinous for the ALWAYS-ON wake ear: one window
+ # measured 7.7 s on a fast box — inside the 8 s abandon cap, and past it
+ # on weaker hardware, where the timeout drops the model and forces a
+ # cold rebuild (extended deafness, the "I have to say it three times"
+ # mechanism). A single float pins one greedy pass.
+ #
+ # Deliberately a CONSTRUCTOR option, never a ``transcribe_pcm`` kwarg:
+ # the wake poll's call site has no ``TypeError`` escape, so an unknown
+ # kwarg would become ``recover()`` on every second poll — permanent
+ # deafness on any third-party STT provider.
+ temperature: float | list[float] | tuple[float, ...] | None = None,
) -> None:
self._model_name = model
self._device = device
@@ -339,6 +352,7 @@ class FasterWhisperProvider:
self._initial_prompt = initial_prompt
self._no_speech_threshold = no_speech_threshold
self._cpu_threads = int(cpu_threads)
+ self._temperature = temperature
self._model: Any = None # lazy
# Serialize the actual ctranslate2 inference. ``transcribe_pcm`` runs
# ``model.transcribe`` in a worker thread (asyncio.to_thread), and the
@@ -591,12 +605,18 @@ class FasterWhisperProvider:
self._ensure_model() # rebuild a fresh model if recover() cleared it
model = self._model
assert model is not None
+ # Only pass ``temperature`` when pinned, so the default keeps
+ # faster-whisper's own ladder for utterance transcription.
+ decode_opts: dict[str, Any] = {}
+ if self._temperature is not None:
+ decode_opts["temperature"] = self._temperature
segments_iter, info = model.transcribe(
audio_np,
language=effective_lang,
beam_size=self._beam_size,
vad_filter=self._vad_filter,
condition_on_previous_text=False,
+ **decode_opts,
# Echo-confirm support: the caller may run one UNPRIMED pass
# over the same audio to tell a genuine wake from the prompt
# echoing back on noise (2026-07-02 ghost activations).
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 02beaf9ec6..fe8286928c 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -697,8 +697,13 @@ class VoskKwsProvider:
return stack.pop()
return self._build_verify_rec(path, kind, prewarm=False)
- def _replenish_stock(self) -> None:
- """Top the prewarmed stock back up to target (worker thread only)."""
+ def _replenish_stock(self, target: int | None = None) -> None:
+ """Top the prewarmed stock back up to target (worker thread only).
+
+ ``target`` bounds the depth for THIS pass; boot uses depth 1 so it does
+ not await the full stock (see ``start``).
+ """
+ limit = self._stock_target if target is None else target
kinds = ("grammar", "free") if self._competition_grammar is None else (
"grammar", "free", _COMPETITION_KIND,
)
@@ -707,7 +712,7 @@ class VoskKwsProvider:
key = (path, kind)
while True:
with self._stock_lock:
- if len(self._rec_stock.setdefault(key, [])) >= self._stock_target:
+ if len(self._rec_stock.setdefault(key, [])) >= limit:
break
try:
rec = self._build_verify_rec(path, kind, prewarm=True)
@@ -794,7 +799,15 @@ class VoskKwsProvider:
await asyncio.gather(*(_load_one(path) for path in self._model_paths))
self._load_attempted = True
- await asyncio.to_thread(self._replenish_stock)
+ # Await DEPTH ONE per (model, kind) — enough for the first wake's verify
+ # pair to run warm — then top the rest up in the background. Awaiting
+ # the full stock meant boot paid 2 models x 3 kinds x 2 = 12 recognizer
+ # builds, each with its own 0.3 s prewarm decode, before voice became
+ # usable (AP-26: nothing heavier than necessary on the way to
+ # voice-usable). A taker that finds the stock dry already degrades
+ # gracefully to a cold build, so the background remainder is free.
+ await asyncio.to_thread(self._replenish_stock, 1)
+ self._kick_replenish()
async def stop(self) -> None:
# Invalidate any in-flight early check and retract a shown candidate
diff --git a/tests/unit/audio/test_topology.py b/tests/unit/audio/test_topology.py
index 02c3e48741..36ec3c32f1 100644
--- a/tests/unit/audio/test_topology.py
+++ b/tests/unit/audio/test_topology.py
@@ -66,6 +66,53 @@ async def test_watcher_refreshes_once_per_settled_change(monkeypatch) -> None:
assert len(refreshes) == 1
+async def test_a_device_loss_signal_probes_without_waiting_for_the_poll() -> None:
+ """The steady-state poll is deliberately slow, so the signals that mean
+ "a device may be gone" (a mic stall, a failed stream open) must be able to
+ skip the wait. Without this, raising the interval would simply make
+ hot-plug recovery that much slower — each probe is a full Python +
+ PortAudio subprocess, which is why the interval has to stay cheap.
+ """
+ probes: list[float] = []
+ task = asyncio.create_task(
+ topology.watch_topology(
+ player=None,
+ poll_s=60.0, # would never fire inside this test on its own
+ probe=lambda: probes.append(time.monotonic()) or "sig",
+ refresh=lambda: True,
+ )
+ )
+ try:
+ await asyncio.sleep(0.05)
+ assert probes == [], "the slow poll must not have fired yet"
+
+ topology.request_topology_probe()
+ await asyncio.sleep(0.05)
+ assert len(probes) == 1, (
+ "a device-loss signal must trigger an immediate probe instead of "
+ "waiting out the poll interval"
+ )
+
+ # The request is consumed, not sticky — otherwise the watcher would
+ # spin at full speed forever after one stall.
+ await asyncio.sleep(0.05)
+ assert len(probes) == 1, "the request must be one-shot"
+ finally:
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_request_probe_is_a_noop_with_no_watcher_running() -> None:
+ """Called from capture's error paths, which run in tests and headless
+ installs where no watcher exists. It must never raise there."""
+ topology._probe_request = None
+ topology._probe_loop = None
+ topology.request_topology_probe() # must not raise
+
+
@pytest.mark.asyncio
async def test_watcher_fails_open_when_probe_returns_none(monkeypatch) -> None:
monkeypatch.setattr(topology, "_SETTLE_S", 0.0)
diff --git a/tests/unit/plugins/stt/test_wake_whisper_build.py b/tests/unit/plugins/stt/test_wake_whisper_build.py
index 560698e6c5..9b03689edf 100644
--- a/tests/unit/plugins/stt/test_wake_whisper_build.py
+++ b/tests/unit/plugins/stt/test_wake_whisper_build.py
@@ -259,3 +259,39 @@ def test_wake_cuda_available_survives_corrupt_cache(tmp_path, monkeypatch) -> No
assert isinstance(value, bool)
assert json.loads(cache_file.read_text(encoding="utf-8"))["cuda"] == value
_wake_cuda_available.cache_clear()
+
+
+def test_wake_decode_pins_one_greedy_pass() -> None:
+ """The always-on wake ear must not carry Whisper's temperature-fallback
+ ladder.
+
+ Unbounded, the ladder silently pays up to 6 sequential decodes for one
+ window: measured at 7.7 s on a FAST box, i.e. inside the 8 s abandon cap and
+ past it on weaker hardware — where the timeout drops the model and forces a
+ cold rebuild, extending the deaf gap ("I have to say it three times").
+
+ Pinning it changes no gate and no transcript rule, so AP-27 is untouched:
+ the ladder only re-decodes transcripts that already look degenerate, which
+ the phrase matcher and the no_speech/RMS gates reject anyway.
+ """
+ provider = build_wake_whisper(STTConfig(), cuda_available=False)
+ assert provider._temperature == 0.0
+
+
+def test_wake_decode_does_not_collapse_segments() -> None:
+ """``without_timestamps`` must NOT ride along with the temperature pin.
+
+ Collapsing a window into a single segment changes what
+ ``_reliable_wake_transcript``'s per-segment ``no_speech_prob`` check sees,
+ which shifts the ghost/recall coupling on the very engine AP-27 was written
+ for. Bounding decode WORK is safe; changing the token stream is not.
+ """
+ provider = build_wake_whisper(STTConfig(), cuda_available=False)
+ assert getattr(provider, "_without_timestamps", None) in (None, False)
+
+
+def test_utterance_stt_keeps_the_fallback_ladder() -> None:
+ """The pin is wake-scoped. A bare provider (utterance transcription) must
+ keep faster-whisper's own ladder, where a re-decode buys accuracy on a long,
+ ambiguous utterance and no always-on poll cap is at stake."""
+ assert FasterWhisperProvider()._temperature is None