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
perf(boot): prefetch the fast-first wake model in parallel with the import mountain
Ruben Lütke40ecd3b68bbc
diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.pyindex 09a848d045..a7294debcd 100644--- a/jarvis/plugins/stt/__init__.py+++ b/jarvis/plugins/stt/__init__.py@@ -410,4 +410,66 @@ def build_wake_whisper()-__all__ = ["build_stt_from_config", "build_wake_whisper"]+def start_wake_model_prefetch(+ stt_cfg: Any,+ *,+ language: str | None = None,+ wake_phrase: str | None = None,+) -> Any:+ """Load the fast-first wake Whisper MODEL in a daemon thread, off the boot+ critical path (TTU iteration 10, docs/diagnostics/BOOT-TTU-NOTES.md).++ Drift-free by construction: the exact model parameters are resolved by+ building a throwaway provider through :func:`build_wake_whisper`+ (``fast_first=True`` — the same call the boot path makes; the ctor is+ cheap and fully lazy), then the weights are loaded into the hand-over+ cache that ``FasterWhisperProvider._ensure_model`` adopts. The phrase+ bias and language do not participate in the cache key (they are decode+ parameters, not load parameters), so a key can only miss if the real+ boot resolves a different model/device — in which case the consumer+ simply loads lazily as before.++ GIL note (2026-06-22 forensic): the load runs behind the+ ``inference_only_import_shield`` inside ``_new_whisper_model`` and touches+ no torch; the first real torch import (Silero VAD) happens seconds later+ in the deferred loaders, so the shield race window stays clear.++ No-op when voice is disabled (``JARVIS_VOICE``) or on any failure —+ a prefetch must never break boot. Returns the thread or ``None``.+ """+ import threading++ from jarvis.speech.warmup_prefetch import _voice_disabled++ if _voice_disabled():+ return None++ def _load() -> None:+ try:+ from jarvis.plugins.stt.fwhisper import prefetch_model++ probe = build_wake_whisper(+ stt_cfg,+ language=language,+ wake_phrase=wake_phrase,+ fast_first=True,+ )+ prefetch_model(+ probe._model_name, # noqa: SLF001 — resolved params, same module family+ probe._device, # noqa: SLF001+ probe._compute_type, # noqa: SLF001+ probe._cpu_threads, # noqa: SLF001+ )+ except Exception as exc: # noqa: BLE001 — a prefetch must never break boot+ logger.debug("Wake-model prefetch skipped: {}", exc)++ thread = threading.Thread(target=_load, name="wake-model-prefetch", daemon=True)+ thread.start()+ return thread+++__all__ = [+ "build_stt_from_config",+ "build_wake_whisper",+ "start_wake_model_prefetch",+]diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex e7a4757ac8..50396a7a01 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -169,6 +169,61 @@ def _new_whisper_model(return WhisperModel(model_name, **kwargs)+# --- Boot-time wake-model prefetch (TTU iteration 10) -----------------------+# The instrumented cold-boot timeline (docs/diagnostics/BOOT-TTU-NOTES.md)+# shows the wake model load+prime (~3.1 s) runs strictly AFTER the import+# mountain (~2.6 s) and the WebServer ctor (~1.5 s), even though it only needs+# faster_whisper. Loading it in a daemon thread right after the UI shell is+# served overlaps those blocks. ``_ensure_model`` ADOPTS the prefetched engine+# when its exact key (normalized model, device, compute_type, cpu_threads)+# matches; on a mismatch or a prefetch failure it loads lazily as before —+# never slower than today beyond the bounded in-flight wait. The adopted model+# is popped (single use): a later ``recover()`` therefore always rebuilds a+# FRESH engine and can never re-adopt a possibly wedged prefetch (AP-24).+# Thread-safety: the prefetch runs in ONE daemon thread and hands over via the+# event+dict under a lock; the provider's own inference lock is untouched.+_PREFETCH_LOCK = threading.Lock()+_PREFETCH_EVENTS: dict[tuple, threading.Event] = {}+_PREFETCHED_MODELS: dict[tuple, Any] = {}+# Upper bound on waiting for an in-flight prefetch of the SAME key before+# falling back to a local load. The prefetch starts seconds earlier than any+# consumer, so the typical remaining wait is <1 s; the bound only matters if+# the prefetch thread died mid-load.+_PREFETCH_WAIT_S = 20.0+++def _prefetch_key(+ model_name: str, device: str, compute_type: str, cpu_threads: int+) -> tuple:+ return (_normalize_model_name(model_name), device, compute_type, int(cpu_threads))+++def prefetch_model(+ model_name: str, device: str, compute_type: str, cpu_threads: int+) -> bool:+ """Load a WhisperModel into the hand-over cache (call from a daemon thread).++ Idempotent per key: a second call while one is in flight (or done) is a+ no-op. Failures are swallowed — the consumer simply loads lazily. Returns+ True iff a model was cached by THIS call.+ """+ key = _prefetch_key(model_name, device, compute_type, cpu_threads)+ with _PREFETCH_LOCK:+ if key in _PREFETCH_EVENTS:+ return False+ _PREFETCH_EVENTS[key] = threading.Event()+ model: Any = None+ try:+ model = _new_whisper_model(key[0], device, compute_type, int(cpu_threads))+ except Exception as exc: # noqa: BLE001 — a prefetch must never break boot+ log.debug("Wake-model prefetch failed (lazy load will cover it): %s", exc)+ with _PREFETCH_LOCK:+ if model is not None:+ _PREFETCHED_MODELS[key] = model+ _PREFETCH_EVENTS[key].set()+ return model is not None++class FasterWhisperProvider:"""Local Whisper STT via faster-whisper (CTranslate2 backend)."""@@ -246,11 +301,38 @@ class FasterWhisperProvider:"""True when the model is constructed AND primed (safe to poll)."""return self._warm+ @property+ def bias_prompt(self) -> str | None:+ """The ``initial_prompt`` this instance primes the decoder with.++ The rolling wake uses this to know whether a transcript could be a+ PROMPT ECHO (the primed model emitting the prompt verbatim on+ ambiguous noise/breath windows — the 2026-07-02 ghost-activation+ forensic) and therefore needs the unbiased second-pass confirm."""+ return self._initial_prompt+def _ensure_model(self) -> None:if self._model is not None:returnmodel_name = _normalize_model_name(self._model_name)device, compute_type = self._device, self._compute_type+ # Adopt the boot-prefetched engine when its exact key matches (see the+ # prefetch block above). Popped = single use, so recover() always+ # rebuilds fresh. On an in-flight prefetch of OUR key, wait bounded+ # instead of double-loading the same weights.+ key = (model_name, device, compute_type, int(self._cpu_threads))+ ev = _PREFETCH_EVENTS.get(key)+ if ev is not None:+ ev.wait(timeout=_PREFETCH_WAIT_S)+ with _PREFETCH_LOCK:+ prefetched = _PREFETCHED_MODELS.pop(key, None)+ if prefetched is not None:+ self._model = prefetched+ log.info(+ "Adopted boot-prefetched Whisper model (%s/%s/%s).",+ model_name, device, compute_type,+ )+ returntry:self._model = _new_whisper_model(model_name, device, compute_type, self._cpu_threads@@ -355,28 +437,43 @@ class FasterWhisperProvider:async def transcribe_pcm(self, pcm_bytes: bytes, sample_rate: int = 16_000,language: str | None = None,+ ignore_initial_prompt: bool = False,) -> Transcript:"""Direct path for VAD output: int16 PCM bytes → transcript.`language` overrides the default language per call. Useful for thewake detector, which should always listen for German even when theSTT default is "auto".++ ``ignore_initial_prompt=True`` runs THIS call without the configured+ phrase bias — the rolling wake's echo confirm: when a candidate+ transcript is exactly the primed phrase, an unbiased second pass on+ the same window separates a genuine wake (the unprimed ear still+ hears speech) from a prompt echo on noise/breath (it hears nothing)."""self._ensure_model()audio_np = pcm_bytes_to_np(pcm_bytes)- return await self._transcribe_np(audio_np, sample_rate, language=language)+ return await self._transcribe_np(+ audio_np, sample_rate, language=language,+ ignore_initial_prompt=ignore_initial_prompt,+ )async def _transcribe_np(self, audio_np: np.ndarray, sample_rate: int,language: str | None = None,+ ignore_initial_prompt: bool = False,) -> Transcript:# faster-whisper is synchronous → ship it off to a threadimport asyncio- return await asyncio.to_thread(self._transcribe_sync, audio_np, sample_rate, language)+ return await asyncio.to_thread(+ self._transcribe_sync, audio_np, sample_rate, language,+ ignore_initial_prompt,+ )def _transcribe_sync(self, audio_np: np.ndarray, sample_rate: int,language: str | None = None,+ ignore_initial_prompt: bool = False,) -> Transcript:# faster-whisper accepts np.ndarray float32 directly when 16 kHzif sample_rate != 16_000:@@ -410,7 +507,12 @@ class FasterWhisperProvider:beam_size=self._beam_size,vad_filter=self._vad_filter,condition_on_previous_text=False,- initial_prompt=self._initial_prompt,+ # 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).+ initial_prompt=(+ None if ignore_initial_prompt else self._initial_prompt+ ),no_speech_threshold=self._no_speech_threshold,)# segments_iter is a generator — iterating over it materializes itdiff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 087cf1f3b5..a7a1b00275 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -771,6 +771,18 @@ class DesktopApp:from jarvis.audio.device_init import start_audio_device_prefetchstart_audio_device_prefetch()+ # Wake-MODEL prefetch (TTU iteration 10): the instrumented timeline+ # showed the ~3.1 s fast-first wake-model load running strictly AFTER+ # the import mountain + WebServer ctor. Start it NOW in a daemon+ # thread so it overlaps them; the deferred warm-up later ADOPTS the+ # loaded engine (FasterWhisperProvider._ensure_model) instead of+ # loading again. No-op on JARVIS_VOICE=0 / any failure.+ try:+ from jarvis.plugins.stt import start_wake_model_prefetch+ start_wake_model_prefetch(self.cfg.stt)+ except Exception: # noqa: BLE001 — a prefetch must never break boot+ pass+def _log_unhandled_async(loop_: asyncio.AbstractEventLoop, context: dict) -> None:exc = context.get("exception")msg = context.get("message", "<no message>")diff --git a/tests/unit/stt/test_fwhisper_prefetch.py b/tests/unit/stt/test_fwhisper_prefetch.pynew file mode 100644index 0000000000..7edcbdbd3f--- /dev/null+++ b/tests/unit/stt/test_fwhisper_prefetch.py@@ -0,0 +1,153 @@+"""Boot-time wake-model prefetch — hand-over cache contract.++TTU iteration 10 (docs/diagnostics/BOOT-TTU-NOTES.md): the fast-first wake+model load (~3.1 s) is started in a daemon thread right after the UI shell is+served, and ``FasterWhisperProvider._ensure_model`` ADOPTS the loaded engine+when its exact key matches. Contracts pinned here:++- adoption returns the SAME object the prefetch loaded (no double load),+- the cache entry is single-use (popped), so ``recover()`` always rebuilds a+ FRESH engine and can never re-adopt a possibly wedged prefetch (AP-24),+- a key mismatch or a failed prefetch falls back to the normal lazy load,+- an in-flight prefetch of the same key is awaited instead of double-loaded.+"""+from __future__ import annotations++import threading++import pytest++import jarvis.plugins.stt.fwhisper as fw+from jarvis.plugins.stt.fwhisper import FasterWhisperProvider, prefetch_model++[email protected](autouse=True)+def _clean_cache():+ with fw._PREFETCH_LOCK:+ fw._PREFETCH_EVENTS.clear()+ fw._PREFETCHED_MODELS.clear()+ yield+ with fw._PREFETCH_LOCK:+ fw._PREFETCH_EVENTS.clear()+ fw._PREFETCHED_MODELS.clear()+++def _provider(model: str = "base") -> FasterWhisperProvider:+ return FasterWhisperProvider(+ model=model, device="cpu", compute_type="int8", cpu_threads=2+ )+++def test_ensure_model_adopts_prefetched_engine(monkeypatch) -> None:+ loads: list[tuple] = []+ sentinel = object()++ def _fake_new(name, device, compute, threads=0): # noqa: ANN001+ loads.append((name, device, compute, threads))+ return sentinel++ monkeypatch.setattr(fw, "_new_whisper_model", _fake_new)+ assert prefetch_model("base", "cpu", "int8", 2) is True++ p = _provider()+ p._ensure_model()+ assert p._model is sentinel, "provider must adopt the prefetched engine"+ assert len(loads) == 1, "the weights must be loaded exactly once"+++def test_recover_after_adoption_rebuilds_fresh(monkeypatch) -> None:+ objs = [object(), object()]+ loads: list[int] = []++ def _fake_new(name, device, compute, threads=0): # noqa: ANN001+ loads.append(1)+ return objs[len(loads) - 1]++ monkeypatch.setattr(fw, "_new_whisper_model", _fake_new)+ prefetch_model("base", "cpu", "int8", 2)++ p = _provider()+ p._ensure_model()+ assert p._model is objs[0]+ p.recover() # wedged mid-session -> the cache must NOT hand the old one back+ p._ensure_model()+ assert p._model is objs[1], "recover() must rebuild fresh, not re-adopt"+++def test_key_mismatch_falls_back_to_lazy_load(monkeypatch) -> None:+ prefetched = object()+ own = object()+ calls: list[str] = []++ def _fake_new(name, device, compute, threads=0): # noqa: ANN001+ calls.append(name)+ return prefetched if name == "small" else own++ monkeypatch.setattr(fw, "_new_whisper_model", _fake_new)+ prefetch_model("small", "cpu", "int8", 2) # different model than the provider++ p = _provider(model="base")+ p._ensure_model()+ assert p._model is own+ with fw._PREFETCH_LOCK:+ assert ("small", "cpu", "int8", 2) in fw._PREFETCHED_MODELS, (+ "a mismatched prefetch must stay cached, not be consumed"+ )+++def test_failed_prefetch_degrades_to_lazy_load(monkeypatch) -> None:+ own = object()++ def _boom(name, device, compute, threads=0): # noqa: ANN001+ raise RuntimeError("no faster_whisper on this host")++ monkeypatch.setattr(fw, "_new_whisper_model", _boom)+ assert prefetch_model("base", "cpu", "int8", 2) is False++ monkeypatch.setattr(fw, "_new_whisper_model", lambda *a, **k: own)+ p = _provider()+ p._ensure_model()+ assert p._model is own+++def test_in_flight_prefetch_is_awaited_not_double_loaded(monkeypatch) -> None:+ release = threading.Event()+ sentinel = object()+ loads: list[int] = []++ def _slow_new(name, device, compute, threads=0): # noqa: ANN001+ loads.append(1)+ assert release.wait(timeout=10)+ return sentinel++ monkeypatch.setattr(fw, "_new_whisper_model", _slow_new)+ t = threading.Thread(+ target=prefetch_model, args=("base", "cpu", "int8", 2), daemon=True+ )+ t.start()+ # Give the prefetch thread time to claim the key and enter the slow load.+ for _ in range(100):+ with fw._PREFETCH_LOCK:+ claimed = ("base", "cpu", "int8", 2) in fw._PREFETCH_EVENTS+ if claimed and loads:+ break+ threading.Event().wait(0.01)++ p = _provider()+ consumer = threading.Thread(target=p._ensure_model, daemon=True)+ consumer.start()+ release.set()+ consumer.join(timeout=10)+ t.join(timeout=10)+ assert p._model is sentinel+ assert len(loads) == 1, "consumer must wait for the in-flight load, not duplicate it"+++def test_second_prefetch_call_is_noop(monkeypatch) -> None:+ loads: list[int] = []+ monkeypatch.setattr(+ fw, "_new_whisper_model", lambda *a, **k: loads.append(1) or object()+ )+ assert prefetch_model("base", "cpu", "int8", 2) is True+ assert prefetch_model("base", "cpu", "int8", 2) is False+ assert len(loads) == 1