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): isolate confirmation from background executor contention (#488)

Ruben Lütke7841f6a7c825
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 49e769bcbf..bb5ce09d68 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -363,6 +363,7 @@ _COOLDOWN_S = 5.0
# listening during this window and latches one retry; otherwise a user's
# immediate second call would land in a two-second deaf period.
_REJECTED_CANDIDATE_BACKOFF_S = 2.0
+_INFERENCE_SHUTDOWN_BUDGET_S = 0.02
# How much audio to let land in the ring AFTER a PARTIAL candidate before the
# confirm pass runs. A partial fires DURING the phrase (that is its virtue),
@@ -678,6 +679,7 @@ class _StreamingVerify:
max_workers=1, thread_name_prefix="vosk-verify-free"
)
self._pending: list[Any] = []
+ self._closed = False
self.feed(ring)
def _normalise(self, audio: np.ndarray) -> tuple[np.ndarray, bytes]:
@@ -720,10 +722,16 @@ class _StreamingVerify:
window = np.concatenate(self._parts) if self._parts else np.zeros(0, np.float32)
return window, b"".join(self._pcm_parts), gres, fres
- def close(self) -> None:
+ def close(self, *, wait: bool = False) -> None:
"""Discard (early fire, superseded candidate, teardown)."""
- self._g_pool.shutdown(wait=False, cancel_futures=True)
- self._f_pool.shutdown(wait=False, cancel_futures=True)
+ self._closed = True
+ self._g_pool.shutdown(wait=wait, cancel_futures=True)
+ self._f_pool.shutdown(wait=wait, cancel_futures=True)
+
+ @property
+ def ready_to_reap(self) -> bool:
+ """A closed decoder with no running feeds can be joined off-loop."""
+ return self._closed and all(future.done() for future in self._pending)
class VoskKwsProvider:
@@ -870,6 +878,9 @@ class VoskKwsProvider:
self._early_active = False
self._early_task: asyncio.Task[bool] | None = None
self._pending_gen = 0
+ self._detect_guard = threading.Lock()
+ self._inference_reaper: threading.Thread | None = None
+ self._inference_cleanup: asyncio.Task[None] | None = None
# Instance-local clock hook keeps reject/backpressure state-machine
# tests deterministic without replacing Python's process-global
# monotonic clock (which asyncio itself also consumes).
@@ -1222,7 +1233,8 @@ class VoskKwsProvider:
log.debug("early-candidate listener failed: %s", exc)
async def _run_early_check(
- self, window: np.ndarray, gen: int, model_path: str | None = None
+ self, window: np.ndarray, gen: int, model_path: str | None,
+ run_verify: Callable[..., Awaitable[Any]],
) -> bool:
"""Strictly verify the candidate prefix and optionally show the bar.
@@ -1231,7 +1243,7 @@ class VoskKwsProvider:
it must not overwrite a clean verdict over the candidate audio itself.
"""
try:
- ok = await asyncio.to_thread(self._early_check, window, model_path)
+ ok = await run_verify(self._early_check, window, model_path)
except Exception as exc: # noqa: BLE001 — fallback verify remains
log.debug("early-candidate check errored: %s", exc)
return False
@@ -1892,24 +1904,130 @@ class VoskKwsProvider:
# 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.
+ if not self._detect_guard.acquire(blocking=False):
+ raise RuntimeError("The previous wake detector is still running or retiring")
infer_pool = ThreadPoolExecutor(
max_workers=2, thread_name_prefix="vosk-wake-infer"
)
+ # Verification must not queue behind unrelated application workers or
+ # take either of stage one's reserved slots. Sibling rescues still run
+ # concurrently, each with its own one-shot recognizers.
+ verify_pool = ThreadPoolExecutor(
+ max_workers=2, thread_name_prefix="vosk-wake-confirm"
+ )
loop = asyncio.get_running_loop()
+ streams: set[_StreamingVerify] = set()
+ stream_lock = threading.Lock()
+
+ def invoke(fn: Callable[..., Any], args: tuple[Any, ...]) -> Any:
+ # A long-lived detector may reject many candidates. Release finished
+ # decoder pairs on a worker instead of retaining all of them until
+ # the next wake, and never join a native worker on the audio loop.
+ with stream_lock:
+ finished = [stream for stream in streams if stream.ready_to_reap]
+ streams.difference_update(finished)
+ for stream in finished:
+ stream.close(wait=True)
+ result = fn(*args)
+ if isinstance(result, _StreamingVerify):
+ # Register before the future publishes its result: cancellation
+ # cannot hide a successfully constructed decoder pair.
+ with stream_lock:
+ streams.add(result)
+ return result
+
+ async def _run(pool: ThreadPoolExecutor, fn: Callable[..., Any], *args: Any) -> Any:
+ future = pool.submit(invoke, fn, args)
+ wrapped = asyncio.wrap_future(future)
+ try:
+ return await wrapped
+ except asyncio.CancelledError:
+ # Pending obsolete work must never occupy a verifier slot.
+ # Running native work remains owned by the retirement thread.
+ future.cancel()
+
+ def consume_late(done: Any) -> None:
+ if done.cancelled():
+ return
+ exc = done.exception()
+ if exc is not None:
+ log.debug("Cancelled wake inference finished with %s", type(exc).__name__)
+ future.add_done_callback(consume_late)
+ raise
async def _in_pool(fn: Callable[..., Any], *args: Any) -> Any:
- return await loop.run_in_executor(infer_pool, fn, *args)
+ return await _run(infer_pool, fn, *args)
+ async def _verify_pool(fn: Callable[..., Any], *args: Any) -> Any:
+ return await _run(verify_pool, fn, *args)
+
+ inner = self._detect_inner(chunks, _in_pool, _verify_pool)
try:
- async for keyword in self._detect_inner(chunks, _in_pool):
+ async for keyword in inner:
yield keyword
finally:
- infer_pool.shutdown(wait=False)
+ try:
+ await inner.aclose()
+ finally:
+ self._pending_gen += 1
+ early, self._early_task = self._early_task, None
+ if early is not None:
+ early.cancel()
+ retired = loop.create_future()
+
+ def notify_retired() -> None:
+ if not retired.done():
+ retired.set_result(None)
+
+ def reap() -> None:
+ try:
+ infer_pool.shutdown(wait=True, cancel_futures=True)
+ verify_pool.shutdown(wait=True, cancel_futures=True)
+ # Both owning pools have joined. No constructor can add
+ # another stream or prune this set after this point.
+ for streaming in streams:
+ streaming.close(wait=True)
+ except Exception:
+ # Retain the guard when retirement cannot be confirmed.
+ log.exception("Wake inference retirement failed")
+ else:
+ self._detect_guard.release()
+ finally:
+ try:
+ loop.call_soon_threadsafe(notify_retired)
+ except RuntimeError:
+ # The loop may close first; this thread still joined
+ # the native workers and owns their last references.
+ pass
+
+ async def retire() -> None:
+ # Finish coroutine cancellation before joining its workers;
+ # the shielded coordinator survives repeated caller cancels.
+ try:
+ if early is not None:
+ await asyncio.gather(early, return_exceptions=True)
+ finally:
+ reaper = threading.Thread(
+ target=reap, name="vosk-wake-retire", daemon=True,
+ )
+ self._inference_reaper = reaper
+ reaper.start()
+ await retired
+
+ cleanup = asyncio.create_task(retire(), name="vosk-wake-retirement")
+ self._inference_cleanup = cleanup
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(cleanup), timeout=_INFERENCE_SHUTDOWN_BUDGET_S,
+ )
+ except TimeoutError:
+ log.warning("Wake inference is still retiring; detector re-entry is blocked")
async def _detect_inner(
self,
chunks: AsyncIterator[AudioChunk],
_in_pool: Callable[..., Awaitable[Any]],
+ _verify_pool: Callable[..., Awaitable[Any]],
) -> AsyncIterator[str]:
"""The detection loop proper; ``_in_pool`` runs native decode work."""
for path in self._model_paths:
@@ -2060,7 +2178,9 @@ class VoskKwsProvider:
# a negative still falls through to the later full window.
self._pending_gen += 1
self._early_task = asyncio.create_task(
- self._run_early_check(ring_now, self._pending_gen, hit_path)
+ self._run_early_check(
+ ring_now, self._pending_gen, hit_path, _verify_pool,
+ )
)
continue
# The candidate-prefix check and fallback decision must not fan out
@@ -2095,11 +2215,11 @@ class VoskKwsProvider:
# The decode already ran during the tail; this is the
# finalize + judgement (~0.1 s) — the spawn-latency win.
finishing, streaming = streaming, None
- confirmed = await asyncio.to_thread(
+ confirmed = await _verify_pool(
self._finish_streaming_verify, finishing, window
)
else:
- confirmed = await asyncio.to_thread(
+ confirmed = await _verify_pool(
self._verify_candidate, window, hit_path
)
if not confirmed:
@@ -2126,7 +2246,7 @@ class VoskKwsProvider:
if others:
rescues = await asyncio.gather(
*(
- asyncio.to_thread(self._early_check, window, other)
+ _verify_pool(self._early_check, window, other)
for other in others
)
)
diff --git a/tests/unit/plugins/wake/test_vosk_executor_isolation.py b/tests/unit/plugins/wake/test_vosk_executor_isolation.py
new file mode 100644
index 0000000000..e1def63b30
--- /dev/null
+++ b/tests/unit/plugins/wake/test_vosk_executor_isolation.py
@@ -0,0 +1,292 @@
+"""Wake confirmation stays independent of busy application workers and owns teardown."""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.plugins.wake import vosk_kws_provider as module
+
+
+class FakeStreamingVerify:
+ def __init__(self):
+ self.closed = False
+
+ def feed(self, audio):
+ pass # No native recognizer belongs to this scheduler-only fake.
+
+ def close(self, *, wait=False):
+ self.closed = True
+
+ @property
+ def ready_to_reap(self):
+ return self.closed
+
+
+def detector(monkeypatch, *, final=False, siblings=False):
+ paths = ("fake-primary", "fake-sibling") if siblings else ("fake-primary",)
+ monkeypatch.setattr(module, "_StreamingVerify", FakeStreamingVerify)
+ provider = module.VoskKwsProvider("Hey Nova", model_path=paths[0], model_paths=paths)
+ monkeypatch.setattr(provider, "_ensure_model", lambda path: None)
+ monkeypatch.setattr(provider, "_fresh_recs", lambda: {path: object() for path in paths})
+ monkeypatch.setattr(provider, "_models", {path: object() for path in paths})
+ monkeypatch.setattr(provider, "_start_streaming_verify", lambda *args: FakeStreamingVerify())
+ state = {"chunks": 0, "workers": []}
+
+ def grammar(recs, pcm):
+ state["chunks"] += 1
+ return ((final, 1.0, paths[0]) if state["chunks"] == 1 else None), recs
+
+ async def stage1(recs, pcm, run):
+ return await run(grammar, recs, pcm)
+
+ monkeypatch.setattr(provider, "_stage1", stage1)
+ return provider, state
+
+
+async def chunks(count=35):
+ for index in range(count):
+ await asyncio.sleep(0.005)
+ yield AudioChunk(
+ pcm=b"\x10\x00" * 512, sample_rate=16000,
+ timestamp_ns=(index + 1) * 32_000_000,
+ )
+
+
+async def until(predicate):
+ async with asyncio.timeout(2):
+ while not predicate(): # noqa: ASYNC110 - observe worker threads without the shared pool.
+ await asyncio.sleep(0.002)
+
+
+async def retired(provider):
+ await until(lambda: provider._inference_reaper is not None
+ and not provider._inference_reaper.is_alive())
+ await asyncio.wait_for(asyncio.shield(provider._inference_cleanup), 2)
+ assert not provider._detect_guard.locked()
+
+
[email protected]("path", ["early", "stream_final", "final", "sibling"])
+async def test_confirmation_uses_reserved_workers_when_default_executor_is_full(monkeypatch, path):
+ provider, state = detector(monkeypatch, final=path in {"final", "sibling"},
+ siblings=path == "sibling")
+
+ def verdict(*args):
+ state["workers"].append(threading.current_thread().name)
+ return True
+
+ monkeypatch.setattr(provider, "_early_check",
+ verdict if path != "stream_final" else lambda *a: False)
+ monkeypatch.setattr(provider, "_verify_candidate",
+ verdict if path != "sibling" else lambda *a: False)
+ monkeypatch.setattr(provider, "_finish_streaming_verify", verdict)
+ loop = asyncio.get_running_loop()
+ previous = loop._default_executor
+ default = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-busy-default")
+ loop.set_default_executor(default)
+ release, busy = threading.Event(), threading.Event()
+
+ def unrelated_work():
+ busy.set()
+ release.wait(5)
+
+ blocker = loop.run_in_executor(None, unrelated_work)
+ stream = provider.detect(chunks())
+ try:
+ await until(busy.is_set)
+ assert await asyncio.wait_for(anext(stream), 1) == "hey_nova"
+ assert not release.is_set(), "Verification must finish while unrelated work remains blocked"
+ assert state["workers"]
+ assert all(name.startswith("vosk-wake-confirm") for name in state["workers"])
+ finally:
+ release.set()
+ await stream.aclose()
+ await retired(provider)
+ await blocker
+ loop._default_executor = previous
+ default.shutdown(wait=True)
+
+
[email protected]("termination", ["cancel", "stream_end"])
+async def test_blocked_confirmation_preserves_stage1_and_retires_before_reentry(
+ monkeypatch, termination,
+):
+ provider, state = detector(monkeypatch)
+ entered, release, finished = threading.Event(), threading.Event(), threading.Event()
+
+ def blocked_verify(*args):
+ entered.set()
+ try:
+ release.wait(5)
+ return True
+ finally:
+ finished.set()
+
+ monkeypatch.setattr(provider, "_early_check", blocked_verify)
+ stream = provider.detect(chunks(5 if termination == "stream_end" else 100))
+ pending = asyncio.create_task(anext(stream))
+ try:
+ await until(entered.is_set)
+ await until(lambda: state["chunks"] >= 3)
+ started = time.perf_counter()
+ if termination == "cancel":
+ pending.cancel()
+ outcome = asyncio.CancelledError if termination == "cancel" else StopAsyncIteration
+ with pytest.raises(outcome):
+ await asyncio.wait_for(pending, 0.3)
+ assert time.perf_counter() - started < 0.2
+ assert not finished.is_set(), "Close must not wait for native inference on the wake path"
+ assert provider._early_task is None
+ assert provider._detect_guard.locked()
+ newer = provider.detect(chunks())
+ with pytest.raises(RuntimeError, match="retiring"):
+ await anext(newer)
+ await newer.aclose()
+ release.set()
+ await retired(provider)
+ assert finished.is_set()
+ newer = provider.detect(chunks(0))
+ with pytest.raises(StopAsyncIteration):
+ await anext(newer)
+ await retired(provider)
+ finally:
+ release.set()
+ if not pending.done():
+ pending.cancel()
+ await asyncio.gather(pending, return_exceptions=True)
+ await stream.aclose()
+ await retired(provider)
+
+
+async def test_cancelled_stream_constructor_joins_its_late_decoder_pools(monkeypatch):
+ provider, state = detector(monkeypatch)
+ entered, release = threading.Event(), threading.Event()
+ joined = threading.Event()
+
+ class LateStream(FakeStreamingVerify):
+ def close(self, *, wait=False):
+ super().close(wait=wait)
+ if wait:
+ joined.set()
+
+ monkeypatch.setattr(module, "_StreamingVerify", LateStream)
+
+ def build(*args):
+ entered.set()
+ release.wait(5)
+ return LateStream()
+
+ monkeypatch.setattr(provider, "_start_streaming_verify", build)
+ stream = provider.detect(chunks())
+ pending = asyncio.create_task(anext(stream))
+ try:
+ await until(entered.is_set)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(pending, 0.3)
+ assert provider._detect_guard.locked()
+ release.set()
+ await retired(provider)
+ assert joined.is_set()
+ finally:
+ release.set()
+ await asyncio.gather(pending, return_exceptions=True)
+ await stream.aclose()
+ await retired(provider)
+
+
+async def test_early_fire_retains_acquired_decoder_workers_until_they_join(monkeypatch):
+ provider, state = detector(monkeypatch)
+ release = threading.Event()
+ entered = [threading.Event(), threading.Event()]
+ owned = []
+
+ class HeldStream(FakeStreamingVerify):
+ def __init__(self):
+ super().__init__()
+ self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="test-owned-decode")
+
+ def decode(index):
+ entered[index].set()
+ release.wait(5)
+
+ self.jobs = [self.pool.submit(decode, index) for index in range(2)]
+ assert all(event.wait(2) for event in entered)
+ owned.append(self)
+
+ def close(self, *, wait=False):
+ super().close(wait=wait)
+ self.pool.shutdown(wait=wait, cancel_futures=True)
+
+ @property
+ def ready_to_reap(self):
+ return self.closed and all(job.done() for job in self.jobs)
+
+ monkeypatch.setattr(module, "_StreamingVerify", HeldStream)
+ monkeypatch.setattr(provider, "_start_streaming_verify", lambda *args: HeldStream())
+ monkeypatch.setattr(provider, "_early_check", lambda *args: True)
+ stream = provider.detect(chunks())
+ try:
+ assert await asyncio.wait_for(anext(stream), 1) == "hey_nova"
+ started = time.perf_counter()
+ await asyncio.wait_for(stream.aclose(), 0.3)
+ assert time.perf_counter() - started < 0.2
+ assert provider._detect_guard.locked()
+ assert any(thread.is_alive() for thread in owned[0].pool._threads)
+ newer = provider.detect(chunks())
+ with pytest.raises(RuntimeError, match="retiring"):
+ await anext(newer)
+ await newer.aclose()
+ release.set()
+ await retired(provider)
+ assert all(not thread.is_alive() for thread in owned[0].pool._threads)
+ finally:
+ release.set()
+ await stream.aclose()
+ await retired(provider)
+
+
+async def test_cancelled_rescue_drops_queued_jobs_and_observes_late_exceptions(monkeypatch):
+ provider, state = detector(monkeypatch, final=True, siblings=True)
+ paths = ("fake-primary", "fake-one", "fake-two", "fake-queued")
+ provider._model_paths = list(paths)
+ provider._models = {path: object() for path in paths}
+ entered = [threading.Event(), threading.Event()]
+ release, queued_ran = threading.Event(), threading.Event()
+ monkeypatch.setattr(provider, "_verify_candidate", lambda *args: False)
+
+ def verify(window, path):
+ if path == "fake-queued":
+ queued_ran.set()
+ return True
+ entered[0 if path == "fake-one" else 1].set()
+ release.wait(5)
+ raise RuntimeError("Expected late fake verification failure")
+
+ monkeypatch.setattr(provider, "_early_check", verify)
+ loop = asyncio.get_running_loop()
+ previous_handler = loop.get_exception_handler()
+ unobserved = []
+ loop.set_exception_handler(lambda owner, context: unobserved.append(context))
+ stream = provider.detect(chunks())
+ pending = asyncio.create_task(anext(stream))
+ try:
+ await until(lambda: all(event.is_set() for event in entered))
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(pending, 0.3)
+ release.set()
+ await retired(provider)
+ assert not queued_ran.is_set()
+ assert not unobserved
+ finally:
+ release.set()
+ await asyncio.gather(pending, return_exceptions=True)
+ await stream.aclose()
+ await retired(provider)
+ loop.set_exception_handler(previous_handler)