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: stop a failed vosk import from filling PATH (WinError 8) (#1080)
Ruben Lütke930168c29abf
diff --git a/dodaios.spec b/dodaios.specindex c3fd8c87b6..af8b686a3d 100644--- a/dodaios.spec+++ b/dodaios.spec@@ -286,6 +286,10 @@ _optional_hidden = ["webview","pystray","PIL",+ # Wake keyword spotting imports vosk through a guarded helper+ # (dodaios/plugins/wake/vosk_native.py), invisible to import analysis; its+ # DLLs come from packaging/pyinstaller_hooks/hook-vosk.py.+ "vosk",]if sys.platform == "win32":_optional_hidden += [diff --git a/dodaios/core/path_augment.py b/dodaios/core/path_augment.pyindex 377f415a79..9ffa484f8b 100644--- a/dodaios/core/path_augment.py+++ b/dodaios/core/path_augment.py@@ -222,6 +222,14 @@ def fit_path_entries(entries: list[str], budget: int) -> list[str]:return existing+def fit_spawn_path(value: str) -> str:+ """``value`` shortened to a PATH a child process can start with."""+ budget = _path_budget()+ if budget is None or len(value) <= budget:+ return value+ return os.pathsep.join(fit_path_entries(value.split(os.pathsep), budget))++def _store_path(current: str, added: list[str]) -> list[str]:"""Write ``current`` plus ``added`` to ``PATH``; return what of ``added`` got in.diff --git a/dodaios/plugins/wake/vosk_kws_provider.py b/dodaios/plugins/wake/vosk_kws_provider.pyindex e90895bb72..a7f5303436 100644--- a/dodaios/plugins/wake/vosk_kws_provider.py+++ b/dodaios/plugins/wake/vosk_kws_provider.py@@ -109,7 +109,7 @@ from typing import Anyimport numpy as npfrom dodaios.core.protocols import AudioChunk-from dodaios.plugins.wake.vosk_native import build_recognizer, native_call+from dodaios.plugins.wake.vosk_native import build_recognizer, import_vosk, native_callfrom dodaios.speech.wake_constants import (WAKE_PREFIXES,normalize_phrase_for_match,@@ -917,6 +917,7 @@ class VoskKwsProvider:# keeps that diagnosable without turning a candidate storm into a log# flood (same shape as the existing backpressure warning).self._suppress_log_count = 0+ self._reported_unusable: set[tuple[str, str]] = set()# -- lifecycle -----------------------------------------------------------@@ -931,11 +932,11 @@ class VoskKwsProvider:model = self._models.get(key)if model is not None:return model- from vosk import Model, SetLogLevel # lazy: keep base import light+ vosk = import_vosk() # lazy: keep base import light- SetLogLevel(-1)+ vosk.SetLogLevel(-1)t0 = time.perf_counter()- model = Model(key)+ model = vosk.Model(key)self._models[key] = modellog.info("vosk-kws: model loaded in %.1f s (%s)",@@ -1055,7 +1056,12 @@ class VoskKwsProvider:try:recs[path] = self._take_verify_rec(path, "grammar")except Exception as exc: # noqa: BLE001 — isolate a broken model- log.warning("vosk-kws: model %s unusable (%s) — skipped.", path, exc)+ # Called after every candidate reset: report each distinct+ # failure once instead of flooding the log (#1045).+ failure = (path, str(exc))+ if failure not in self._reported_unusable:+ self._reported_unusable.add(failure)+ log.warning("vosk-kws: model %s unusable (%s) — skipped.", path, exc)self._kick_replenish()return recs@@ -2326,9 +2332,14 @@ def vosk_model_supports_phrase(model_path: str, phrase: str) -> bool:import tempfiletry:- from vosk import KaldiRecognizer, Model, SetLogLevel+ vosk = import_vosk()except Exception: # noqa: BLE001 — no vosk → cannot disprove supportreturn True+ KaldiRecognizer, Model, SetLogLevel = ( # noqa: N806 — vosk API names+ vosk.KaldiRecognizer,+ vosk.Model,+ vosk.SetLogLevel,+ )tmp = Noneold = Nonetry:diff --git a/dodaios/plugins/wake/vosk_native.py b/dodaios/plugins/wake/vosk_native.pyindex b64641e1a4..62f36b7c39 100644--- a/dodaios/plugins/wake/vosk_native.py+++ b/dodaios/plugins/wake/vosk_native.py@@ -16,12 +16,59 @@ wrapped.from __future__ import annotations+import importlib+import osimport queue+import sysimport threading+import time+from types import ModuleTypefrom typing import Any_LOCK = threading.Lock()+# ``vosk/__init__.py`` prepends its DLL folder to ``os.environ["PATH"]`` before+# it loads ``libvosk.dll``. When that load fails the module is not cached, so+# every retry prepended the folder again: the wake loop retries per candidate+# reset, PATH grew to the 32,767-character limit and every later spawn of the+# process failed with WinError 8 (#1045). A failed import now leaves PATH as it+# was and is not retried until the cooldown has passed.+_IMPORT_LOCK = threading.Lock()+_IMPORT_RETRY_S = 300.0+_import_failure: tuple[float, BaseException] | None = None+++def import_vosk() -> ModuleType:+ """Import ``vosk`` without letting a failed import grow ``PATH``.++ Raises ``ImportError`` while a recent failure is remembered.+ """+ global _import_failure++ cached = sys.modules.get("vosk")+ if cached is not None:+ return cached+ with _IMPORT_LOCK:+ cached = sys.modules.get("vosk")+ if cached is not None:+ return cached+ if _import_failure is not None:+ failed_at, error = _import_failure+ if time.monotonic() - failed_at < _IMPORT_RETRY_S:+ raise ImportError(f"vosk unavailable: {error}") from error+ saved_path = os.environ.get("PATH")+ try:+ module = importlib.import_module("vosk")+ except BaseException as exc:+ if saved_path is not None and os.environ.get("PATH") != saved_path:+ os.environ["PATH"] = saved_path+ if isinstance(exc, Exception):+ _import_failure = (time.monotonic(), exc)+ raise ImportError(f"vosk unavailable: {exc}") from exc+ raise+ _import_failure = None+ return module+# One worker that does nothing but let recognizers die. ``vosk_recognizer_free``# (KaldiRecognizer.__del__) is a native call measured at 15 s on a cold, paging# box (2026-08-30 "Event loop STALLED" stack) — and it runs on WHICHEVER thread@@ -194,7 +241,7 @@ def wrap_recognizer(rec: Any) -> Any:def build_recognizer(model: Any, sample_rate: int, grammar: str | None = None) -> Any:"""Construct a ``KaldiRecognizer``, ``SetWords(True)``, wrap if native."""- from vosk import KaldiRecognizer+ KaldiRecognizer = import_vosk().KaldiRecognizer # noqa: N806 — vosk API namewith _LOCK:rec = (diff --git a/dodaios/society/browser/install.py b/dodaios/society/browser/install.pyindex d094c8f4d1..ffd5ad91c3 100644--- a/dodaios/society/browser/install.py+++ b/dodaios/society/browser/install.py@@ -220,8 +220,14 @@ def snapshot(data_dir: Path | None = None) -> dict[str, Any]:def _run(cmd: list[str], *, env: dict[str, str], timeout: float = 900) -> str:+ from dodaios.core.path_augment import ensure_cli_paths, fit_spawn_pathfrom dodaios.core.process_tree import make_process_tree+ # Windows refuses every spawn while this process's PATH is over its limit,+ # and a child handed such a PATH dies on start-up (#1045). Repair both.+ ensure_cli_paths()+ if env.get("PATH"):+ env = {**env, "PATH": fit_spawn_path(env["PATH"])}tree = make_process_tree("browser-install")process_options: dict[str, Any] = {"start_new_session": True} if os.name != "nt" else {}proc = subprocess.Popen(diff --git a/packaging/pyinstaller_hooks/hook-vosk.py b/packaging/pyinstaller_hooks/hook-vosk.pynew file mode 100644index 0000000000..7867c9b230--- /dev/null+++ b/packaging/pyinstaller_hooks/hook-vosk.py@@ -0,0 +1,13 @@+# Collects vosk's native libraries next to its package in the frozen bundle.+#+# vosk loads ``libvosk.dll`` (and on Windows its MinGW runtime DLLs) with+# ``cffi.dlopen`` from its own package folder, which no import analysis can see.+# Without this hook the frozen app shipped the Python module but no DLL: every+# ``import vosk`` failed after vosk had prepended its folder to PATH, so PATH+# filled up with copies of ``_internal\vosk`` and the app could no longer start+# any program (WinError 8, #1045 / #1071).++from PyInstaller.utils.hooks import collect_dynamic_libs++binaries = collect_dynamic_libs("vosk")+hiddenimports = ["vosk.vosk_cffi"]diff --git a/packaging/windows/build.ps1 b/packaging/windows/build.ps1index 4cb3d17d06..c959110c8d 100644--- a/packaging/windows/build.ps1+++ b/packaging/windows/build.ps1@@ -164,6 +164,19 @@ foreach ($required in @("DodaiosApp.exe", "PersonalJarvis.exe", "dodaios.exe", "}}+# vosk loads libvosk.dll from its own folder at runtime. A bundle without it+# fails every wake-word load and each failed import grew PATH until the app could+# not start programs (#1045 / #1071). Only checked when the build environment+# has vosk (it is not installed on Windows ARM64).+& $Python -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('vosk') else 1)"+if ($LASTEXITCODE -eq 0) {+ $voskDll = Join-Path $BundleDir "_internal\vosk\libvosk.dll"+ if (-not (Test-Path $voskDll)) {+ Stop-WithError "the frozen bundle is missing libvosk.dll (expected at $voskDll)"+ }+}+$global:LASTEXITCODE = 0+# Running the app straight out of dist/Jarvis (the obvious way to smoke-test a# build) leaves runtime state behind in _internal: a jarvis.db, flight-recorder# JSONL, logs. Shipping that would put the builder's own data inside everydiff --git a/tests/unit/plugins/wake/test_vosk_import_path_guard.py b/tests/unit/plugins/wake/test_vosk_import_path_guard.pynew file mode 100644index 0000000000..fd357f92ce--- /dev/null+++ b/tests/unit/plugins/wake/test_vosk_import_path_guard.py@@ -0,0 +1,137 @@+"""A failed vosk import must not grow PATH (#1045, #1071)."""++from __future__ import annotations++import os+import sys+import types++import pytest++from dodaios.core import path_augment+from dodaios.plugins.wake import vosk_native+++def fresh_import_state(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(vosk_native, "_import_failure", None)+ monkeypatch.delitem(sys.modules, "vosk", raising=False)+++def _broken_vosk_import(monkeypatch: pytest.MonkeyPatch) -> list[int]:+ """Mimic vosk/__init__.py: prepend its DLL folder, then fail to load."""+ attempts: list[int] = []+ real_import = vosk_native.importlib.import_module++ def fake_import(name: str, *args, **kwargs):+ if name != "vosk":+ return real_import(name, *args, **kwargs)+ attempts.append(1)+ os.environ["PATH"] = r"C:\app\_internal\vosk" + os.pathsep + os.environ["PATH"]+ raise OSError("cannot load library 'libvosk.dll'")++ monkeypatch.setattr(vosk_native.importlib, "import_module", fake_import)+ return attempts+++def test_repeated_failing_import_leaves_path_unchanged(+ monkeypatch: pytest.MonkeyPatch, fresh_import_state: None+) -> None:+ monkeypatch.setenv("PATH", os.pathsep.join(["/usr/bin", "/bin"]))+ before = os.environ["PATH"]+ attempts = _broken_vosk_import(monkeypatch)++ for _ in range(50):+ with pytest.raises(ImportError):+ vosk_native.import_vosk()++ assert os.environ["PATH"] == before+ # The failure is remembered: the wake loop does not retry the import.+ assert len(attempts) == 1+++def test_failed_import_is_retried_after_the_cooldown(+ monkeypatch: pytest.MonkeyPatch, fresh_import_state: None+) -> None:+ attempts = _broken_vosk_import(monkeypatch)+ with pytest.raises(ImportError):+ vosk_native.import_vosk()+ failed_at, error = vosk_native._import_failure+ monkeypatch.setattr(+ vosk_native, "_import_failure", (failed_at - vosk_native._IMPORT_RETRY_S - 1, error)+ )+ with pytest.raises(ImportError):+ vosk_native.import_vosk()+ assert len(attempts) == 2+++def test_an_imported_vosk_is_returned_as_is(+ monkeypatch: pytest.MonkeyPatch, fresh_import_state: None+) -> None:+ module = types.ModuleType("vosk")+ monkeypatch.setitem(sys.modules, "vosk", module)+ monkeypatch.setattr(vosk_native, "_import_failure", (0.0, OSError("old")))+ assert vosk_native.import_vosk() is module+++def test_trimming_drops_repeated_vosk_folders(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:+ real = tmp_path / "bin"+ real.mkdir()+ vosk_dir = str(tmp_path / "_internal" / "vosk")+ entries = [vosk_dir] * 600 + [str(real)]+ monkeypatch.setattr(path_augment, "_path_budget", lambda: 31_000)+ fitted = path_augment.fit_spawn_path(os.pathsep.join(entries))+ assert fitted.split(os.pathsep) == [vosk_dir, str(real)]+++def test_browser_install_run_repairs_an_over_budget_path(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ from dodaios.society.browser import install++ # A small budget stands in for Windows' limit: os.environ itself refuses+ # a value past 32,767 characters on Windows.+ real = tmp_path / "bin"+ real.mkdir()+ long_path = os.pathsep.join([str(tmp_path / "_internal" / "vosk")] * 200 + [str(real)])+ monkeypatch.setattr(path_augment, "_path_budget", lambda: 4_000)+ monkeypatch.setattr(path_augment, "candidate_dirs", lambda: [])+ monkeypatch.setattr(path_augment, "_settled_overflow", None)+ monkeypatch.setenv("PATH", long_path)+ seen: dict[str, str] = {}++ class FakeProc:+ pid = 4242+ returncode = 0++ def communicate(self, timeout=None):+ return "ok", None++ def poll(self):+ return 0++ def wait(self):+ return 0++ class FakeTree:+ def assign(self, pid):+ pass++ def close(self):+ pass++ def fake_popen(cmd, **kwargs):+ seen["child"] = kwargs["env"]["PATH"]+ seen["parent"] = os.environ["PATH"]+ return FakeProc()++ monkeypatch.setattr(install.subprocess, "Popen", fake_popen)+ monkeypatch.setattr(+ "dodaios.core.process_tree.make_process_tree", lambda name: FakeTree()+ )+ install._run(["python", "-V"], env={"PATH": long_path})++ assert len(seen["parent"]) <= 4_000+ assert len(seen["child"]) <= 4_000+ assert seen["child"].split(os.pathsep)[-1] == str(real)+