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(dictation): harden local preview and faster-whisper CUDA library resolution
Ruben Lütkeea9bbc9a2893
diff --git a/jarvis/dictation/local_preview.py b/jarvis/dictation/local_preview.pyindex c719d2b4cb..c436f7ea42 100644--- a/jarvis/dictation/local_preview.py+++ b/jarvis/dictation/local_preview.py@@ -106,29 +106,71 @@ class LocalPreviewTranscriber:def _load_model(self) -> None:"""Build the engine. Runs OFF the transcribe path — see ``transcribe``."""try:- from faster_whisper import WhisperModel-- device, compute = self._pick_device()- model = WhisperModel(- self._model_name, device=device, compute_type=compute- )- with self._lock:- self._model = model- log.info(- "Dictation preview engine ready: %s on %s (%s).",- self._model_name,- device,- compute,- )- except Exception as exc: # noqa: BLE001 — a preview must never break dictation- self._load_failed = True- self._unavailable = True- log.info(- "Local dictation preview unavailable (%s: %s) — the transcript "- "is unaffected; the live line falls back to the provider.",- type(exc).__name__,- exc,- )+ from jarvis.plugins.stt.fwhisper import _new_whisper_model++ preferred = self._pick_device()+ attempts = [preferred]+ if preferred[0] != "cpu":+ attempts.append(("cpu", "int8"))+ last_error: Exception | None = None+ for device, compute in attempts:+ try:+ model = _new_whisper_model(self._model_name, device, compute)+ except Exception as exc: # noqa: BLE001 — try the portable floor+ last_error = exc+ log.info(+ "Dictation preview engine could not use %s (%s: %s).",+ device,+ type(exc).__name__,+ exc,+ )+ continue+ try:+ # Constructing the model does not pay CUDA's first-decode+ # setup cost. Prime one throwaway greedy decode here, while+ # the preview is still advertised as unavailable, so the+ # first visible preview keeps the steady-state latency.+ import numpy as np++ rng = np.random.default_rng(0)+ warm_audio = (+ rng.standard_normal(16_000).astype(np.float32) * 0.001+ )+ segments, _info = model.transcribe(+ warm_audio,+ beam_size=1,+ temperature=0.0,+ condition_on_previous_text=False,+ )+ list(segments)+ except Exception as exc: # noqa: BLE001 — try the portable floor+ last_error = exc+ log.info(+ "Dictation preview rejected %s after its first "+ "decode failed (%s: %s).",+ device,+ type(exc).__name__,+ exc,+ )+ continue+ with self._lock:+ self._model = model+ log.info(+ "Dictation preview engine ready: %s on %s (%s).",+ self._model_name,+ device,+ compute,+ )+ break+ else:+ self._load_failed = True+ self._unavailable = True+ log.info(+ "Local dictation preview unavailable (%s: %s) — the transcript "+ "is unaffected; the live line falls back to the provider.",+ type(last_error).__name__ if last_error is not None else "Error",+ last_error or "no usable local inference device",+ )finally:self._loading = False@@ -136,15 +178,25 @@ class LocalPreviewTranscriber:def _pick_device() -> tuple[str, str]:"""``(device, compute_type)`` — CUDA when it is genuinely usable.- Capability probe, never a hardware name (AP-21/AP-25 territory): CUDA- being importable and CUDA working are different questions, and the- answer here only decides how FAST the preview is. Anything uncertain- picks CPU, which always works.+ Ask the inference runtime that will actually execute the model. Importing+ torch here was both indirect and racy: the faster-whisper import shield+ can temporarily hide torch from another loader thread, which made a+ CUDA-capable desktop silently choose the CPU for the rest of the process.+ Anything uncertain picks CPU, and ``_load_model`` still proves the choice+ with a real model build before accepting it."""try:- import torch+ from jarvis.plugins.stt.fwhisper import (+ ensure_cuda_libraries_findable,+ inference_only_import_shield,+ )++ ensure_cuda_libraries_findable()+ with inference_only_import_shield():+ import ctranslate2- if torch.cuda.is_available():+ supported = ctranslate2.get_supported_compute_types("cuda")+ if "int8_float16" in supported:return "cuda", "int8_float16"except Exception as exc: # noqa: BLE001 — a probe must never decide by raisinglog.debug("Preview CUDA probe failed (%s); using CPU.", exc)@@ -170,6 +222,10 @@ class LocalPreviewTranscriber:samples,language=language,beam_size=1, # greedy: the preview trades a little accuracy for latency+ # A tuple/default enables Whisper's temperature fallback ladder and+ # may decode the same stale preview repeatedly. One fixed greedy+ # pass keeps the measured path in the tens-of-milliseconds range.+ temperature=0.0,condition_on_previous_text=False,)text = " ".join(seg.text for seg in segments).strip()@@ -205,18 +261,29 @@ class LocalPreviewTranscriber:# first couple of seconds is not a failure of anything.self._start_loading()return None- if not self._busy.acquire(blocking=False):+ guard = self._busy+ if not guard.acquire(blocking=False):# A previous preview is still running. Skipping is correct: a queued- # call on a native engine is how it wedges (AP-24).+ # call on a native engine is how it wedges (AP-24). This can only+ # persist after a timed-out/cancelled waiter, so count it toward+ # recovery; otherwise one truly wedged worker owns the guard forever.+ self._note_failure("still busy after its waiter ended")return None+ work: asyncio.Task[tuple[str, str, float]] | None = None+ release_here = Truetry:- text, detected, probability = await asyncio.wait_for(+ work = asyncio.create_task(asyncio.to_thread(self._transcribe_sync, pcm, language),+ name="dictation-local-preview",+ )+ text, detected, probability = await asyncio.wait_for(+ asyncio.shield(work),timeout=PREVIEW_TIMEOUT_S,)if detected:self.last_language = detectedself.last_language_probability = probability+ self._failures = 0return textexcept TimeoutError:# Not silent: _note_failure logs the attempt and drops the engine once@@ -229,7 +296,25 @@ class LocalPreviewTranscriber:self._note_failure(f"{type(exc).__name__}: {exc}")return Nonefinally:- self._busy.release()+ if work is not None and not work.done():+ # Cancelling or timing out the asyncio waiter does not stop the+ # native thread. Keep the non-blocking guard held until that+ # thread really exits, or the next preview would enter the same+ # ctranslate2 session concurrently (AP-24).+ release_here = False++ def _release_finished_worker(done: asyncio.Task) -> None:+ guard.release()+ try:+ done.result()+ except asyncio.CancelledError:+ pass+ except Exception as exc: # noqa: BLE001 — detached worker is contained+ log.debug("Detached dictation preview failed: %s", exc)++ work.add_done_callback(_release_finished_worker)+ if release_here:+ guard.release()def _start_loading(self) -> None:"""Kick off a one-shot background load. Cheap and idempotent."""@@ -260,7 +345,11 @@ class LocalPreviewTranscriber:if self._failures < _MAX_FAILURES:returnwith self._lock:+ # The old native worker keeps its captured model and guard. Rotate+ # both references atomically so the next tick builds a genuinely+ # fresh session rather than re-polling a wedged engine (AP-24).self._model = None+ self._busy = threading.Lock()self._failures = 0log.info("Dictation preview engine dropped (%s); rebuilding on the next tick.", why)diff --git a/jarvis/plugins/stt/fwhisper.py b/jarvis/plugins/stt/fwhisper.pyindex 32dc897458..6b377d27b6 100644--- a/jarvis/plugins/stt/fwhisper.py+++ b/jarvis/plugins/stt/fwhisper.py@@ -197,10 +197,10 @@ def _cpu_safe_compute_type(compute_type: str) -> str:#: (``cublas64_12.dll``, ``cudnn64_9.dll``, ...) and the standalone#: ``nvidia-*-cu12`` wheels carry them one subdirectory deeper, so a host with#: either is covered without depending on either.-_CUDA_DLL_PACKAGE_DIRS: Final[tuple[tuple[str, ...], ...]] = (- ("torch", "lib"),- ("nvidia", "cublas", "bin"),- ("nvidia", "cudnn", "bin"),+_CUDA_DLL_PACKAGE_DIRS: Final[tuple[tuple[str, tuple[str, ...]], ...]] = (+ ("torch", ("lib",)),+ ("nvidia.cublas", ("bin",)),+ ("nvidia.cudnn", ("bin",)),)#: Loaded explicitly, in dependency order, once a directory holding them is@@ -218,6 +218,11 @@ _CUDA_DLL_PRELOAD: Final[tuple[str, ...]] = (#: Set once the libraries are actually in the process, so repeated model builds#: do not re-walk site-packages._cuda_dll_path_prepared = False+# ``os.add_dll_directory`` removes the search entry when its return object is+# closed/collected. ctypes may likewise unload an explicitly opened DLL when+# its wrapper dies. Retain both for the process lifetime once CUDA is usable.+_cuda_dll_directory_handles: list[Any] = []+_cuda_dll_library_handles: list[Any] = []def ensure_cuda_libraries_findable() -> None:@@ -257,42 +262,59 @@ def ensure_cuda_libraries_findable() -> None:if _cuda_dll_path_prepared:returnadd_dll_directory = getattr(os, "add_dll_directory", None)- if add_dll_directory is None:+ if os.name != "nt" and add_dll_directory is None:# POSIX resolves shared libraries through the loader's own search path,# where a pip-installed CUDA runtime already lands. Nothing to do._cuda_dll_path_prepared = Truereturn- import ctypes- import importlib.util+ if add_dll_directory is None:+ return+ import ctypes # noqa: PLC0415 — Windows-only, off every non-CUDA path+ import importlib.util # noqa: PLC0415 — lazy path must stay cheap- for parts in _CUDA_DLL_PACKAGE_DIRS:+ for module_name, relative_parts in _CUDA_DLL_PACKAGE_DIRS:try:- spec = importlib.util.find_spec(parts[0])+ spec = importlib.util.find_spec(module_name)except (ImportError, ValueError):# ValueError is what find_spec raises for a module stubbed as None# in sys.modules — exactly what the import shield does to torch.# Leaving the flag unset means a later build tries again.continue- origin = getattr(spec, "origin", None) if spec is not None else None- if not origin:+ if spec is None:continue- directory = Path(origin).parent.joinpath(*parts[1:])- if not directory.is_dir() or not any(directory.glob("cublas64_*.dll")):+ roots: list[Path] = []+ origin = getattr(spec, "origin", None)+ if origin:+ roots.append(Path(origin).parent)+ for location in getattr(spec, "submodule_search_locations", ()) or ():+ root = Path(location)+ if root not in roots:+ roots.append(root)+ for root in roots:+ directory = root.joinpath(*relative_parts)+ if directory.is_dir() and any(directory.glob("cublas64_*.dll")):+ break+ else:continue- with contextlib.suppress(OSError):+ directory_handle: Any = None+ try:# Lets the loaded libraries find their own dependencies by name.- add_dll_directory(str(directory))- loaded = []+ directory_handle = add_dll_directory(str(directory))+ except OSError:+ pass+ loaded: list[str] = []+ library_handles: list[Any] = []for name in _CUDA_DLL_PRELOAD:library = directory / nameif not library.is_file():continuetry:- ctypes.WinDLL(str(library))+ handle = ctypes.WinDLL(str(library))except OSError as exc:log.debug("could not load %s: %s", library, exc)continueloaded.append(name)+ library_handles.append(handle)if not any(name.startswith("cublas64") for name in loaded):continue # the one that actually blocks ctranslate2 is still missinglog.info(@@ -301,6 +323,9 @@ def ensure_cuda_libraries_findable() -> None:directory,", ".join(loaded),)+ if directory_handle is not None:+ _cuda_dll_directory_handles.append(directory_handle)+ _cuda_dll_library_handles.extend(library_handles)_cuda_dll_path_prepared = Truereturndiff --git a/tests/unit/dictation/test_local_preview.py b/tests/unit/dictation/test_local_preview.pyindex dcb2fdcdf3..062ae75952 100644--- a/tests/unit/dictation/test_local_preview.py+++ b/tests/unit/dictation/test_local_preview.py@@ -166,17 +166,120 @@ async def test_loading_the_engine_never_counts_as_a_failure():def test_the_device_probe_falls_back_to_cpu_when_cuda_is_not_usable(monkeypatch):"""CUDA present and CUDA usable are different questions (AP-21/AP-25)."""- import builtins+ import sys+ from types import SimpleNamespace++ monkeypatch.setitem(+ sys.modules,+ "ctranslate2",+ SimpleNamespace(+ get_supported_compute_types=lambda _device: (_ for _ in ()).throw(+ RuntimeError("no CUDA here")+ )+ ),+ )+ assert LocalPreviewTranscriber._pick_device() == ("cpu", "int8")- real_import = builtins.__import__- def _no_torch(name, *args, **kwargs):- if name == "torch":- raise ImportError("no torch here")- return real_import(name, *args, **kwargs)+def test_the_device_probe_asks_ctranslate2_not_torch(monkeypatch):+ """The executing runtime decides; another loader may temporarily hide torch."""+ import sys+ from types import SimpleNamespace- monkeypatch.setattr(builtins, "__import__", _no_torch)- assert LocalPreviewTranscriber._pick_device() == ("cpu", "int8")+ monkeypatch.setitem(+ sys.modules,+ "ctranslate2",+ SimpleNamespace(+ get_supported_compute_types=lambda device: (+ {"int8", "int8_float16"} if device == "cuda" else {"int8"}+ )+ ),+ )++ assert LocalPreviewTranscriber._pick_device() == ("cuda", "int8_float16")+++def test_a_cuda_model_that_cannot_decode_falls_back_to_cpu(monkeypatch):+ """A successful constructor is not proof that CUDA inference is usable."""+ import jarvis.plugins.stt.fwhisper as fwhisper++ calls: list[tuple[str, str]] = []+ cpu_model = object()++ class _Model:+ def __init__(self, device: str) -> None:+ self.device = device++ def transcribe(self, _audio, **_kwargs):+ if self.device == "cuda":+ raise RuntimeError("CUDA decode failed")+ return [], object()++ def _build(_name: str, device: str, compute: str):+ calls.append((device, compute))+ if device == "cpu":+ model = _Model(device)+ model.marker = cpu_model+ return model+ return _Model(device)++ monkeypatch.setattr(fwhisper, "_new_whisper_model", _build)+ engine = LocalPreviewTranscriber()+ engine._pick_device = lambda: ("cuda", "int8_float16") # type: ignore[method-assign]++ engine._load_model()++ assert calls == [("cuda", "int8_float16"), ("cpu", "int8")]+ assert getattr(engine._model, "marker", None) is cpu_model+++async def test_a_timed_out_native_call_keeps_the_engine_busy_until_it_really_ends():+ """AP-24: the timeout bounds the wait; it does not stop the native thread."""+ import jarvis.dictation.local_preview as mod++ engine = _Engine(delay=0.15)+ original = mod.PREVIEW_TIMEOUT_S+ mod.PREVIEW_TIMEOUT_S = 0.02+ try:+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert engine.calls == 1, "the still-running native call must own the engine"+ await asyncio.sleep(0.2)+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert engine.calls == 2+ finally:+ mod.PREVIEW_TIMEOUT_S = original+++async def test_a_wedged_native_preview_rotates_to_a_fresh_model_and_guard():+ """BUG-036: busy ticks must eventually orphan a never-returning engine."""+ import threading++ import jarvis.dictation.local_preview as mod++ release = threading.Event()+ engine = _Engine()++ def _wedge(_pcm, _language):+ engine.calls += 1+ release.wait(timeout=5.0)+ return "", "", 0.0++ engine._transcribe_sync = _wedge # type: ignore[method-assign]+ old_guard = engine._busy+ original = mod.PREVIEW_TIMEOUT_S+ mod.PREVIEW_TIMEOUT_S = 0.02+ try:+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert await engine.transcribe(b"\x00" * 32000) is None+ assert engine.ready is False+ assert engine._busy is not old_guard+ assert engine.available is True+ finally:+ release.set()+ await asyncio.sleep(0.05)+ mod.PREVIEW_TIMEOUT_S = originalasync def test_the_audio_language_reading_is_kept_not_discarded():@@ -212,9 +315,11 @@ class _NativeModel:def __init__(self, text, language, probability):self._answer = (text, language, probability)self.asked_for: list[str | None] = []+ self.options: list[dict[str, object]] = []def transcribe(self, samples, language=None, **kwargs):self.asked_for.append(language)+ self.options.append(kwargs)text, detected, probability = self._answerreturn [_Segment(text)], _Info(detected, probability)@@ -246,3 +351,4 @@ def test_an_unpinned_decode_reports_the_language_it_found():assert (detected, probability) == ("de", 0.98)assert text == "Hallo Welt" # i18n-allow: German test fixture+ assert engine._model.options[-1]["temperature"] == 0.0diff --git a/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py b/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.pyindex 2e6a1bf3a4..f62a961314 100644--- a/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py+++ b/tests/unit/plugins/stt/test_fwhisper_cuda_libraries.py@@ -24,11 +24,14 @@ from jarvis.plugins.stt import fwhisperdef _reset_module_flag(monkeypatch):"""Each test starts with the helper un-run."""monkeypatch.setattr(fwhisper, "_cuda_dll_path_prepared", False)+ monkeypatch.setattr(fwhisper, "_cuda_dll_directory_handles", [])+ monkeypatch.setattr(fwhisper, "_cuda_dll_library_handles", [])class TestItNeverCostsAnything:def test_it_is_a_no_op_where_there_is_no_dll_search_path(self, monkeypatch):"""POSIX has no ``os.add_dll_directory`` — and needs none."""+ monkeypatch.setattr(fwhisper.os, "name", "posix")monkeypatch.delattr(fwhisper.os, "add_dll_directory", raising=False)fwhisper.ensure_cuda_libraries_findable()@@ -129,8 +132,14 @@ class TestItOnlyClaimsSuccessWhenItLoadedTheOne:added: list[str] = []loaded: list[str] = []+ directory_token = object()++ def _add(path: str):+ added.append(path)+ return directory_token+monkeypatch.setattr(- fwhisper.os, "add_dll_directory", added.append, raising=False+ fwhisper.os, "add_dll_directory", _add, raising=False)monkeypatch.setattr("importlib.util.find_spec",@@ -155,6 +164,47 @@ class TestItOnlyClaimsSuccessWhenItLoadedTheOne:"cublas64_12.dll",], "cublasLt must load before the cublas that depends on it"assert fwhisper._cuda_dll_path_prepared is True+ assert fwhisper._cuda_dll_directory_handles == [directory_token]+ assert len(fwhisper._cuda_dll_library_handles) == 2++ def test_namespace_nvidia_package_is_searched_by_full_submodule(+ self, tmp_path, monkeypatch+ ):+ """PEP-420 ``nvidia`` has no origin; its cublas child owns ``bin``."""+ package = tmp_path / "nvidia" / "cublas"+ lib = package / "bin"+ lib.mkdir(parents=True)+ (lib / "cublas64_12.dll").write_bytes(b"")++ searched: list[str] = []++ def _find_spec(name: str):+ searched.append(name)+ if name == "nvidia.cublas":+ return type(+ "S",+ (),+ {+ "origin": None,+ "submodule_search_locations": [str(package)],+ },+ )()+ return None++ monkeypatch.setattr("importlib.util.find_spec", _find_spec)+ monkeypatch.setattr(+ fwhisper.os, "add_dll_directory", lambda _path: object(), raising=False+ )+ monkeypatch.setitem(+ sys.modules,+ "ctypes",+ type("C", (), {"WinDLL": staticmethod(lambda _path: object())}),+ )++ fwhisper.ensure_cuda_libraries_findable()++ assert "nvidia.cublas" in searched+ assert fwhisper._cuda_dll_path_prepared is Truedef test_a_library_that_will_not_load_is_survived(self, tmp_path, monkeypatch):"""A present-but-broken DLL falls through to the cuda->cpu self-heal."""