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): kill the multi-second vosk wake spawn delay on a busy CPU

Personal Jarvis Maintainer1da6608275c4
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index be11c351b7..8ccd91b0ba 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -480,6 +480,16 @@ class VoskKwsProvider:
name = "vosk_kws"
+ # Catch-up contract with the pipeline fanout (``_queue_iter``): Kaldi
+ # streams arbitrary buffer sizes, so when this detector falls behind live
+ # audio (busy desktop CPU — live forensic 2026-07-21: the fanout queue sat
+ # pinned at 50 x 100 ms chunks and every wake was heard ~5 s late), the
+ # pipeline may coalesce up to this many backlogged chunks into ONE
+ # AudioChunk. The per-chunk state machine below is byte-based
+ # (``pending_tail``, ring) and decision-identical either way; batches only
+ # ever form while catching up, never on the caught-up hot path.
+ coalesce_catchup_chunks = 10
+
def __init__(
self,
phrase: str,
@@ -1208,7 +1218,22 @@ class VoskKwsProvider:
# decode state stays aligned with the ring.
for r in recs.values():
self._grammar_hit(r, pcm)
- if pending_tail < self._confirm_tail_bytes:
+ # 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
+ # the confirm tail after that verdict is pure dead time on
+ # every early-confirmed wake (~0.3-0.5 s of perceived spawn
+ # latency), so fire as soon as the verdict lands. A pending,
+ # failed, or negative early task changes nothing: the normal
+ # tail wait + full-window verify below still decide.
+ early_positive = (
+ self._early_task is not None
+ and self._early_task.done()
+ and not self._early_task.cancelled()
+ and self._early_task.exception() is None
+ and self._early_task.result() is True
+ )
+ if pending_tail < self._confirm_tail_bytes and not early_positive:
continue
is_final, conf, hit_path = pending
pending = None
@@ -1296,14 +1321,30 @@ class VoskKwsProvider:
# de-spoken garbles on the de model yet verifies on en).
# Fail-CLOSED via _early_check: an opportunistic rescue must
# never fire off a broken sibling (the fail-open contract
- # protects only the primary confirm).
- for other in self._model_paths:
- if other == hit_path or other not in recs:
- continue
- if await asyncio.to_thread(self._early_check, window, other):
- confirmed = True
- fired_path = other
- break
+ # protects only the primary confirm). The siblings verify
+ # CONCURRENTLY — each owns its fresh one-shot recognizers
+ # (AP-24-safe: nothing mutable is shared), and the sequential
+ # form paid the SUM of two full verifies right on the fire
+ # path of exactly the phrases the primary model garbles. The
+ # decision is unchanged: the first sibling in configured
+ # order that verifies still wins.
+ others = [
+ other
+ for other in self._model_paths
+ if other != hit_path and other in recs
+ ]
+ if others:
+ rescues = await asyncio.gather(
+ *(
+ asyncio.to_thread(self._early_check, window, other)
+ for other in others
+ )
+ )
+ for other, rescued in zip(others, rescues, strict=True):
+ if rescued:
+ confirmed = True
+ fired_path = other
+ break
if not confirmed:
self._stat_suppressed_confirm += 1
# Invalidate this generation and defensively retract any stale
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2049f43b16..10384f3426 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1083,12 +1083,51 @@ def _looks_like_complete_smalltalk(text: str) -> bool:
)
-async def _queue_iter(q: asyncio.Queue) -> AsyncIterator[AudioChunk]:
- """Adapt a queue into an async iterator for wake detectors."""
+async def _queue_iter(
+ q: asyncio.Queue, *, coalesce_max_chunks: int = 1
+) -> AsyncIterator[AudioChunk]:
+ """Adapt a queue into an async iterator for wake detectors.
+
+ ``coalesce_max_chunks`` > 1 turns a BACKLOG into catch-up batches: after
+ the blocking get, every chunk already waiting in the queue (up to the cap)
+ is drained non-blocking and concatenated into ONE AudioChunk. A detector
+ that falls behind live audio on a busy desktop CPU (live forensic
+ 2026-07-21: oww_q pinned at 50 → the wake word was heard FIVE SECONDS
+ late) then pays its per-chunk loop/decode overhead once per batch instead
+ of once per 100 ms block and catches back up to the present instead of
+ grinding through stale audio at the same rate it arrives. When the
+ consumer is keeping up the queue is empty and every chunk passes through
+ untouched, so the caught-up hot path is byte-identical to before. Only a
+ detector that declares the capability (``coalesce_catchup_chunks``) gets
+ batches — a provider with fixed frame-size expectations keeps the
+ per-chunk contract.
+ """
while True:
chunk = await q.get()
if chunk is None: # Sentinel
return
+ if coalesce_max_chunks > 1 and not q.empty():
+ parts = [chunk.pcm]
+ ended = False
+ while len(parts) < coalesce_max_chunks:
+ try:
+ nxt = q.get_nowait()
+ except asyncio.QueueEmpty:
+ break
+ if nxt is None: # Sentinel mid-drain: flush, then end
+ ended = True
+ break
+ parts.append(nxt.pcm)
+ if len(parts) > 1:
+ chunk = AudioChunk(
+ pcm=b"".join(parts),
+ sample_rate=chunk.sample_rate,
+ timestamp_ns=chunk.timestamp_ns,
+ channels=chunk.channels,
+ )
+ if ended:
+ yield chunk
+ return
yield chunk
@@ -5374,7 +5413,17 @@ class SpeechPipeline:
return handoff_buffer
async def _run_oww() -> str:
- async for kw in self._wake.detect(_queue_iter(oww_queue)):
+ # Capability-gated catch-up: a detector that can consume variable
+ # chunk sizes (vosk_kws) advertises how many backlogged 100 ms
+ # blocks may be coalesced into one catch-up batch, so a busy CPU
+ # never leaves it grinding through seconds-stale audio (the
+ # inconsistent multi-second wake delay, live 2026-07-21).
+ coalesce = max(
+ 1, int(getattr(self._wake, "coalesce_catchup_chunks", 1) or 1)
+ )
+ async for kw in self._wake.detect(
+ _queue_iter(oww_queue, coalesce_max_chunks=coalesce)
+ ):
return f"oww:{kw}"
return ""
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index 1a59713b41..1691971c7b 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -637,6 +637,108 @@ async def test_immediate_retry_is_latched_during_reject_backpressure(
assert p.stats()["backpressure_windows"] == 1
+# --- spawn latency: early-fire + concurrent sibling rescue ----------------------
+
+
+async def test_positive_early_check_fires_without_waiting_the_full_tail(
+ fake_vosk, monkeypatch
+) -> None:
+ """A positive early check is authoritative — the rest of the confirm tail
+ is dead time (spawn-latency, live 2026-07-21). With a tail far longer than
+ the whole test stream, the old wait-out-the-tail path could never fire;
+ the fire below therefore proves the early verdict alone released it."""
+ p = VoskKwsProvider(
+ "Hey Nova", model_path="fake", keyword="nova", confirm_tail_s=600.0
+ )
+ monkeypatch.setattr(p, "_early_check", lambda window, model_path=None: True)
+
+ fired: list[str] = []
+
+ async def _drive() -> None:
+ async def _iter() -> AsyncIterator[AudioChunk]:
+ for _ in range(12):
+ # Give the early-check worker thread room to land its verdict.
+ await asyncio.sleep(0.02)
+ yield _chunk()
+
+ async for kw in p.detect(_iter()):
+ fired.append(kw)
+
+ await asyncio.wait_for(_drive(), timeout=5.0)
+ assert fired == ["nova"]
+ assert p.stats()["fired"] == 1
+
+
+async def test_negative_early_check_still_waits_for_the_tail(
+ fake_vosk, monkeypatch
+) -> None:
+ """The early-fire fast path must never let a NEGATIVE early check bypass
+ the tail wait: with an over-long tail and a rejecting early check, the
+ stream ends without a fire (the full-window fallback never becomes due)."""
+ p = VoskKwsProvider(
+ "Hey Nova", model_path="fake", keyword="nova", confirm_tail_s=600.0
+ )
+ monkeypatch.setattr(p, "_early_check", lambda window, model_path=None: False)
+
+ fired: list[str] = []
+
+ async def _drive() -> None:
+ async def _iter() -> AsyncIterator[AudioChunk]:
+ for _ in range(12):
+ await asyncio.sleep(0.02)
+ yield _chunk()
+
+ async for kw in p.detect(_iter()):
+ fired.append(kw)
+
+ await asyncio.wait_for(_drive(), timeout=5.0)
+ assert fired == []
+
+
+async def test_sibling_rescue_verifies_siblings_concurrently(
+ fake_vosk, monkeypatch
+) -> None:
+ """Deterministic concurrency proof via a 2-party barrier (same pattern as
+ the grammar/free-decode test): both sibling rescues must be in flight at
+ once. A sequential regression strands the first sibling at the barrier
+ until its timeout breaks the barrier and fails the test hard.
+
+ ``confirm_tail_s=0.0`` disables the early-candidate path so the patched
+ ``_early_check`` is reached ONLY by the rescue calls."""
+ barrier = threading.Barrier(2, timeout=2.0)
+ p = VoskKwsProvider(
+ "Hey Nova",
+ model_path="primary",
+ model_paths=["primary", "sib-a", "sib-b"],
+ keyword="nova",
+ confirm_tail_s=0.0,
+ )
+ for m in ("primary", "sib-a", "sib-b"):
+ p._ensure_model(m)
+ monkeypatch.setattr(
+ p, "_verify_candidate", lambda window, model_path=None: False
+ )
+
+ def _rescue(window, model_path=None): # noqa: ANN001, ARG001
+ barrier.wait()
+ return True
+
+ monkeypatch.setattr(p, "_early_check", _rescue)
+ fired = await _run_detect(p, [_chunk() for _ in range(12)])
+ assert fired == ["nova"]
+ assert barrier.broken is False, (
+ "the barrier never filled — the sibling rescues ran SEQUENTIALLY, "
+ "not concurrently"
+ )
+
+
+def test_provider_advertises_catchup_coalescing() -> None:
+ """The pipeline's ``_queue_iter`` catch-up batching is capability-gated on
+ this attribute — losing it silently reverts the wake path to grinding
+ through seconds-stale audio 100 ms at a time on a busy CPU."""
+ assert VoskKwsProvider.coalesce_catchup_chunks > 1
+
+
# --- prewarmed verify-recognizer stock ------------------------------------------
diff --git a/tests/unit/speech/test_wake_queue_coalesce.py b/tests/unit/speech/test_wake_queue_coalesce.py
new file mode 100644
index 0000000000..fb1383f789
--- /dev/null
+++ b/tests/unit/speech/test_wake_queue_coalesce.py
@@ -0,0 +1,97 @@
+"""Wake fanout catch-up batching (``_queue_iter`` coalescing).
+
+Live forensic 2026-07-21 (macOS test machine under parallel build load): the
+vosk_kws detector consumed its fanout queue slower than real time, the queue
+sat pinned at its 50-chunk cap, and every wake was heard ~5 seconds after it
+was spoken — the "inconsistent huge spawn delay". The fix lets a detector
+that can consume variable buffer sizes (capability attribute
+``coalesce_catchup_chunks``) drain a BACKLOG as one concatenated catch-up
+chunk instead of grinding through it 100 ms at a time. Pinned here:
+
+- backlog is coalesced up to the cap, byte-for-byte in order;
+- an empty/keeping-up queue passes chunks through untouched (hot path is
+ byte-identical to the pre-coalescing behavior);
+- the default (no capability) never coalesces;
+- the end-of-stream sentinel still terminates, even mid-drain.
+"""
+from __future__ import annotations
+
+import asyncio
+
+from jarvis.core.protocols import AudioChunk
+from jarvis.speech.pipeline import _queue_iter
+
+_CHUNK_BYTES = 1600 * 2 # 100 ms of 16 kHz mono int16
+
+
+def _chunk(fill: int, n_bytes: int = _CHUNK_BYTES, ts: int = 0) -> AudioChunk:
+ return AudioChunk(
+ pcm=bytes([fill % 256]) * n_bytes, sample_rate=16000, timestamp_ns=ts
+ )
+
+
+async def _drain(it) -> list[AudioChunk]:
+ return [c async for c in it]
+
+
+async def test_backlog_is_coalesced_into_catchup_batches() -> None:
+ q: asyncio.Queue = asyncio.Queue()
+ chunks = [_chunk(i, ts=i) for i in range(25)]
+ for c in chunks:
+ q.put_nowait(c)
+ q.put_nowait(None) # sentinel
+
+ out = await _drain(_queue_iter(q, coalesce_max_chunks=10))
+
+ # 25 backlogged chunks drain as 10 + 10 + 5.
+ assert [len(c.pcm) // _CHUNK_BYTES for c in out] == [10, 10, 5]
+ # Audio is preserved byte-for-byte and in order.
+ assert b"".join(c.pcm for c in out) == b"".join(c.pcm for c in chunks)
+ # Each batch keeps the timestamp of its FIRST chunk (start of the buffer).
+ assert [c.timestamp_ns for c in out] == [0, 10, 20]
+
+
+async def test_caught_up_stream_passes_chunks_through_untouched() -> None:
+ """One chunk at a time in the queue (the keeping-up case) must yield the
+ exact same objects as the pre-coalescing iterator — no re-wrapping."""
+ q: asyncio.Queue = asyncio.Queue()
+ seen: list[AudioChunk] = []
+
+ async def _consume() -> None:
+ async for c in _queue_iter(q, coalesce_max_chunks=10):
+ seen.append(c)
+
+ task = asyncio.create_task(_consume())
+ sent = []
+ for i in range(3):
+ c = _chunk(i, ts=i)
+ sent.append(c)
+ q.put_nowait(c)
+ # Let the consumer drain before the next chunk arrives.
+ for _ in range(5):
+ await asyncio.sleep(0)
+ q.put_nowait(None)
+ await asyncio.wait_for(task, timeout=2.0)
+ assert seen == sent # identity: untouched pass-through
+
+
+async def test_default_never_coalesces() -> None:
+ q: asyncio.Queue = asyncio.Queue()
+ for i in range(5):
+ q.put_nowait(_chunk(i))
+ q.put_nowait(None)
+ out = await _drain(_queue_iter(q))
+ assert [len(c.pcm) // _CHUNK_BYTES for c in out] == [1, 1, 1, 1, 1]
+
+
+async def test_sentinel_mid_drain_flushes_and_terminates() -> None:
+ q: asyncio.Queue = asyncio.Queue()
+ for i in range(3):
+ q.put_nowait(_chunk(i))
+ q.put_nowait(None) # sentinel lands inside the first drain window
+ q.put_nowait(_chunk(99)) # must never be seen
+
+ out = await _drain(_queue_iter(q, coalesce_max_chunks=10))
+
+ assert len(out) == 1
+ assert len(out[0].pcm) == 3 * _CHUNK_BYTES