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(wake): run the Vosk grammar decode off the voice event loop
Ruben Lütke3eb25cd9e6b0
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.pyindex 8ccd91b0ba..02beaf9ec6 100644--- a/jarvis/plugins/wake/vosk_kws_provider.py+++ b/jarvis/plugins/wake/vosk_kws_provider.py@@ -555,6 +555,12 @@ class VoskKwsProvider:self._target_peak = float(target_peak)self._max_gain = float(max_gain)self._models: dict[str, Any] = {}+ # Guards the model CACHE, never an inference (AP-24 is about sharing a+ # live engine; this only serialises the one-time load). Two verify+ # threads can reach _ensure_model for the same not-yet-loaded sibling+ # model concurrently and both build it — 68-92 MB and ~0.7-0.9 s each,+ # one of which is then dropped on the floor.+ self._model_load_lock = threading.Lock()# Set once ``start()`` has attempted every model load — the honest# "warm" floor even when a broken model directory never loads.self._load_attempted = False@@ -613,7 +619,14 @@ class VoskKwsProvider:def _ensure_model(self, path: str | None = None) -> Any:key = path or self._model_pathmodel = self._models.get(key)- if model is None:+ if model is not None:+ return model+ # Double-checked: the fast path above stays lock-free (it runs on every+ # verify recognizer build), and only the rare actual load serialises.+ with self._model_load_lock:+ model = self._models.get(key)+ if model is not None:+ return modelfrom vosk import Model, SetLogLevel # lazy: keep base import lightSetLogLevel(-1)@@ -913,6 +926,30 @@ class VoskKwsProvider:return (False, 1.0) # partials carry no conf; the confirm decidesreturn None+ def _grammar_hit_all(+ self, recs: dict[str, Any], pcm: bytes+ ) -> tuple[bool, float, str] | None:+ """Feed one chunk to EVERY model's grammar; the first hit wins.++ Exists so ``detect()`` can pay ONE thread hop per chunk instead of+ running N native decodes inline on the voice event loop. The iteration+ order and the first-hit-wins rule are identical to the previous inline+ loops, so the decision is unchanged; only where it executes moves.++ AP-24-safe: the caller awaits this hop, so each recognizer still has+ exactly one caller at a time — this is serialised work moved off the+ loop, never a shared engine called concurrently.+ """+ hit: tuple[bool, float] | None = None+ hit_path = ""+ for path, rec in recs.items():+ found = self._grammar_hit(rec, pcm)+ if found is not None and hit is None:+ hit, hit_path = found, path+ if hit is None:+ return None+ return (hit[0], hit[1], hit_path)+def _verify_candidate(self, window: np.ndarray, model_path: str | None = None) -> bool:@@ -1171,9 +1208,39 @@ class VoskKwsProvider:Only the keyword yielded after the full verify pass may cross into thepipeline or become visible in the overlay."""+ # The always-on ear gets RESERVED capacity. asyncio's default executor+ # is shared with every other to_thread call site in the app (mission+ # workers, wiki indexing, git worktrees, TTS); when those saturate it,+ # wake inference queues behind them, the detector drifts behind real+ # time and the fan-out's drop-oldest policy then destroys audio.+ #+ # Sized 2, never 1: a single worker owned by a wedged native inference+ # would deafen the ear permanently (AP-24 — a timeout bounds a hang, it+ # never recovers it). The pool lives exactly as long as this detect()+ # session, so a wake-plan reload rebuilds it.+ infer_pool = ThreadPoolExecutor(+ max_workers=2, thread_name_prefix="vosk-wake-infer"+ )+ loop = asyncio.get_running_loop()++ async def _in_pool(fn: Callable[..., Any], *args: Any) -> Any:+ return await loop.run_in_executor(infer_pool, fn, *args)++ try:+ async for keyword in self._detect_inner(chunks, _in_pool):+ yield keyword+ finally:+ infer_pool.shutdown(wait=False)++ async def _detect_inner(+ self,+ chunks: AsyncIterator[AudioChunk],+ _in_pool: Callable[..., Awaitable[Any]],+ ) -> AsyncIterator[str]:+ """The detection loop proper; ``_in_pool`` runs native decode work."""for path in self._model_paths:try:- await asyncio.to_thread(self._ensure_model, path)+ await _in_pool(self._ensure_model, path)except Exception as exc: # noqa: BLE001 — skip a broken modellog.warning("vosk-kws: model %s failed to load (%s).", path, exc)# One streaming grammar per installed model — a phrase whose language@@ -1215,9 +1282,9 @@ class VoskKwsProvider:# enough; do not spend stage-one or verifier work yet.continue# Keep every model's stream fed during the tail wait so their- # decode state stays aligned with the ring.- for r in recs.values():- self._grammar_hit(r, pcm)+ # decode state stays aligned with the ring. The verdict is+ # irrelevant here — the latched candidate already won the slot.+ await _in_pool(self._grammar_hit_all, recs, pcm)# A POSITIVE early check is already authoritative for this# candidate (later audio belongs to the session and cannot# revoke it — see _run_early_check). Waiting out the rest of@@ -1238,16 +1305,13 @@ class VoskKwsProvider:is_final, conf, hit_path = pendingpending = Noneelse:- # Feed EVERY model; first hit wins the candidate slot.- hit: tuple[bool, float] | None = None- hit_path = ""- for path, r in recs.items():- h = self._grammar_hit(r, pcm)- if h is not None and hit is None:- hit, hit_path = h, path- if hit is None:+ # Feed EVERY model; first hit wins the candidate slot. One+ # thread hop for all N models keeps the loop free to drain the+ # microphone fan-out (see _grammar_hit_all).+ found = await _in_pool(self._grammar_hit_all, recs, pcm)+ if found is None:continue- is_final, conf = hit+ is_final, conf, hit_path = foundnow = time.time()if now - last_fire_t < self._cooldown_s:self._stat_suppressed_cooldown += 1