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.

fix(wake): stream the vosk confirm during the tail, keep intake flowing, budget stage-1 CPU (BUG-150)

Haralde3e44f7e3c5b
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 9a59d05ce5..606a8e141b 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -10433,3 +10433,149 @@ window is the bound; a single discarded event is not.
`test_finishing_a_drop_keeps_the_watch_armed`; the original
`test_second_generation_after_readback_is_discarded_whole` now asserts the
watch stays armed).
+
+## BUG-150: on a weak CPU the wake bar appears 1-3 s after "Hey Nova" and the phrase has to be repeated — the confirm re-decoded the whole ring after the tail, stalled its own intake until the fanout dropped audio, and three language models streamed stage 1 on every chunk (HIGH, FIXED 2026-08-19)
+
+**Symptom.** Maintainer report from a second machine (i7-10510U, 4 cores /
+15 W, Windows 11): "the wake word spawns delayed, maybe a second", "on the
+main machine it never does". Live log of that box: `early_shown=0` in every
+heartbeat, `oww_q=19` (the 0.6 s fanout queue FULL) at every candidate, five
+"verify SUPPRESSED — re-score did not re-hear 'Hey Nova' (heard '')" inside
+two minutes while the user was repeating the phrase, and an accepted wake
+whose bar arrived ~1 s after the phrase.
+
+**Measured on that box** (synthetic "Hey Nova", real de/en/es small models,
+scratch timeline bench, idle CPU): stage-1 partial at −0.2 s before speech
+end (fine); fixed 0.6 s confirm tail; then the from-scratch confirm
+(grammar re-score + free decode over the 3 s ring) took **0.4-0.9 s** —
+free decode alone 300-700 ms (0.14-0.2x realtime) — so the bar came at
+**+1.0-1.6 s** after speech end, **+2.9 s** with four busy threads (the
+box runs OBS, WebView, Discord, the dictation preview Whisper). Three
+models' stage 1 cost 25-30 ms per 32 ms chunk during speech (~0.8x of one
+core; p95 75 ms = 2.3x under load, i.e. the detector fell behind). During
+the confirm the detect loop consumed nothing, so the 19-chunk queue filled
+and dropped the OLDEST frames — holes inside the very audio the re-score
+then judged ("heard ''"). On a desktop CPU the same path costs ~0.1-0.2 s
+and is perceived as instant.
+
+**Fixes (`jarvis/plugins/wake/vosk_kws_provider.py`, `jarvis/speech/pipeline.py`).**
+
+1. *Streamed confirm.* A partial candidate's authoritative confirm now takes
+ its grammar + free recognizers at PARTIAL time, feeds them the ring
+ immediately and every tail chunk as it lands (`_StreamingVerify`: one
+ single-worker executor per recognizer for the feeds — AP-24, never two
+ callers on one native recognizer — and the two finals sequentially on
+ the finishing thread, see BUG-151); at tail end only `FinalResult` + the
+ unchanged judgement run (`_finish_streaming_verify` → `_judge_decoded`). Same
+ audio, same recognizers, same thresholds — Kaldi's `AcceptWaveform`
+ already slices any buffer into 0.2 s steps internally, so the chunking
+ cannot change the decode. The from-scratch path remains for finals,
+ latched retries, the sibling rescue and the early check, and is the
+ fallback when streaming errors (never a blind accept). Bench
+ (`scripts/vosk_wake_bench.py`, 64 files × 2 phrases): decision-identical
+ to the baseline, file by file. Timeline on the weak box (quiet): bar at
+ **+0.40-0.48 s** after speech end (idle and busy ×4), finish 20-70 ms;
+ on the same box at 100 % load from other apps the finish still took
+ only 0.2-0.3 s where the from-scratch confirm took 1.3 s.
+2. *Intake budget as time, honoured only with batching.* The detector
+ declares `coalesce_catchup_s = 1.0` and `intake_backlog_s = 3.0` (the
+ ring length); `_wake_catchup_budget` turns both into capture blocks
+ (the old `coalesce_catchup_chunks = 10` was chosen for 100 ms blocks and
+ silently became 320 ms when the block shrank to 32 ms). A detector that
+ cannot catch up keeps the generic 0.6 s queue — a deeper queue without
+ batching is just a later wake.
+3. *Stage-1 CPU budget.* Stage 1 demotes the LAST secondary model when its
+ own decode cost proves it cannot keep up (`_STAGE1_SLOW_RT` = 2.0x on 4
+ of the last 8 calls); the demoted model stays loaded for the verify and
+ the sibling rescue; the primary is never demoted; the set is restored on
+ the next `detect()` session so a transient load costs nothing lasting.
+ Silence decodes (~0.03x) and a desktop CPU (~0.1x per model) never trip
+ it.
+
+**Not changed (checked).** The recognizer-stock replenish after a fire does
+NOT collide with the realtime session build: the pipeline closes the
+detector generator on the first yield, so the post-fire `_fresh_recs()`
+never runs; the replenish happens at the start of the next wake session.
+The analysis note claiming a burst during session assembly was wrong.
+
+**Frontier.** A wake spoken in one breath with the command still loses the
+~0.4 s between phrase end and the fire unless the early candidate armed the
+preroll — the pipeline's confirmed-wake handoff seeds from the candidate
+preroll only. The `es` model on a `de` box with an English-looking name is
+pure cost until demotion; a vocabulary-aware model set is the cleaner fix.
+
+**Class rule.** An always-on ear must never pay a multi-hundred-ms native
+decode on the fire path that it could have paid during the wait it is
+already sitting out — and it must never stop consuming its own intake
+while it deliberates; bound the work, not the listening.
+
+**Guards.** `tests/unit/plugins/wake/test_vosk_kws_provider.py`
+(`test_partial_candidate_confirm_is_streamed_during_the_tail`,
+`test_final_candidates_confirm_from_scratch`,
+`test_streamed_confirm_error_falls_back_to_from_scratch`,
+`test_positive_early_check_discards_the_streamed_confirm`,
+`test_stage1_budget_demotes_the_last_secondary_and_never_the_primary`,
+`test_detect_demotes_a_slow_secondary_but_keeps_it_for_the_rescue`,
+`test_stage1_demotion_is_reset_per_detect_session`,
+`test_provider_advertises_catchup_coalescing`);
+`tests/unit/speech/test_wake_queue_coalesce.py`
+(`test_catchup_budget_resolves_seconds_to_capture_blocks`,
+`test_catchup_budget_defaults_without_the_capability`,
+`test_catchup_budget_ignores_garbage_values`,
+`test_vosk_provider_declares_both_budgets`).
+
+## BUG-151: libvosk crashes the whole process under concurrent recognizer churn — the wake engine's parallel verify design hits it (HIGH, OPEN 2026-08-19)
+
+**Symptom.** `scripts/vosk_wake_bench.py --phrase "Hey Jarvis" --language de`
+dies with exit 139 ("Windows fatal exception: access violation", via
+`python -X faulthandler`) part-way through the corpus — at HEAD before the
+BUG-150 change 3 of 3 runs on the 4-core laptop that afternoon, 2 of 4 runs
+after it (one baseline run in the morning passed). The crash thread is
+always inside a native recognizer call: stage-1 `AcceptWaveform`
+(`_grammar_hit`) or the stock prewarm's `FinalResult` (`_build_verify_rec`
+in the replenish thread), with other threads decoding concurrently. The
+same libvosk runs inside the desktop process, so in production this is an
+app crash, not a log line. Plausibly the same memory-corruption class as
+the macOS "malformed JSON from `Result()`" glitch already guarded by
+`_parse_recognizer_json`.
+
+**Minimal repro (`scripts/vosk_native_stress.py`, vosk 0.3.44, Windows
+11, Python 3.13, one shared `Model`).** Five threads each looping
+`KaldiRecognizer(model) → AcceptWaveform(0.1-0.3 s) → FinalResult() →
+drop`, plus one thread streaming 3 s of noise through its own recognizer:
+access violation after 5-50 s. Variants that SURVIVED 60-180 s: six
+long-lived recognizers decoding + `FinalResult`/`Reset` concurrently (no
+churn); create/free churn WITHOUT decoding (280 k recognizers) next to a
+decoder; churn with `AcceptWaveform` only or `AcceptWaveform + PartialResult`
+(~80 k); `FinalResult` without audio (165 k); every native call behind ONE
+global lock. Variants that CRASHED: churn with `AcceptWaveform +
+FinalResult` on 0.1 s silence / 0.3 s silence / 0.3 s noise; the same with
+finals serialised among themselves; finals exclusive vs decodes (RW); finals
++ constructions exclusive (1 of 2 runs). So: many concurrent short
+decode-and-finalise cycles are unsafe in this build, and no cheap partial
+lock protocol found so far is reliably sufficient.
+
+**Why the engine hits it.** Every candidate runs the early check
+(grammar + free decode in two threads), the authoritative confirm (two
+more), optionally N sibling rescues (two each, concurrently), the
+competition pass, AND the replenish thread's prewarm
+(`AcceptWaveform(0.3 s silence) + FinalResult + Reset`) — all short
+decode-and-finalise cycles, exactly the repro pattern, on top of stage 1.
+BUG-150 deliberately adds only ONE native thread (single-worker
+`_StreamingVerify`), but does not reduce the pre-existing churn.
+
+**Mitigation options (not done here).** (a) Serialise every native
+recognizer call process-wide behind one lock — proven safe, but it
+re-serialises the grammar/free pair and the sibling rescues (the 2026-07-10
+spawn-latency win) and stalls stage 1 during every verify; with the
+BUG-150 streamed confirm the fire-path cost of that is small, the early
+check and rescues pay it. (b) Drop the prewarm's `FinalResult` (keep
+`AcceptWaveform(silence) + Reset` — measure that the lazy-init saving
+survives and decisions stay identical, per the 2026-07-11 parity method).
+(c) Move all Vosk work into ONE dedicated native thread with a queue. (d)
+Upgrade/patch libvosk. Whichever is chosen must be re-measured with the
+repro script AND the bench (3/3 clean runs on the laptop) before it counts.
+
+**Guards.** None in CI — a crash test cannot run without the native model;
+`scripts/vosk_native_stress.py churn 180` (3 x clean) plus 3/3 clean bench
+runs on the weak laptop are the acceptance test until a fix lands.
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index f7abd22366..9dddaadbf4 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -55,6 +55,46 @@ mini-verify leaks 0/2500 ("hey jarvis") and 1-2/2500 (worst-case single
word) while early-confirming ~a third of eventual fires. Infrastructure errors
fail CLOSED in the prefix check — the opposite polarity of the fallback
full-window confirm, which fails open so it can never eat a real wake.
+
+**Weak-CPU spawn latency (measured 2026-08-19 on a 4-core 15 W laptop).**
+Three costs made the bar arrive 1-3 s after the phrase there where a desktop
+CPU shows it ~0.5 s after:
+
+* The authoritative confirm re-decoded the whole 3 s ring from scratch AFTER
+ the confirm tail (0.4-0.9 s on that CPU vs ~0.1-0.2 s on a fast one). The
+ confirm is now STREAMED: its grammar + free recognizers are taken at
+ PARTIAL time, fed the ring immediately and then every tail chunk as it
+ lands, so at tail end only ``FinalResult`` remains (~0.1 s). Same audio,
+ same recognizers, same judgement — only *when* the decode runs moved
+ (``_StreamingVerify``). The from-scratch path stays for finals, latched
+ retries and the sibling rescue, and is the fallback when streaming errors.
+* While the loop awaited that confirm it consumed no audio; the fanout
+ queue (0.6 s) overflowed and DROPPED the oldest frames (live: ``oww_q=19``
+ at every candidate) — the ring then had holes and the re-score heard ''
+ ("say it twice"). The detector now declares a deeper intake budget
+ (``intake_backlog_s``) and a 1 s catch-up batch (``coalesce_catchup_s``);
+ the pipeline honours both only for detectors that can catch up in batches.
+* Every installed language model streamed stage 1 on every chunk (three
+ models ~0.8x realtime of one core during speech on that CPU; >2x under
+ desktop load — the detector fell seconds behind). Stage 1 now DEMOTES the
+ last secondary model when its own decode cost proves it cannot keep up
+ (``_STAGE1_SLOW_RT`` on several recent calls); demoted models stay
+ loaded for verify/rescue and return on the next ``detect()`` session. The
+ primary model is never demoted.
+
+**Native concurrency limit (found 2026-08-19, PRE-EXISTING, open).** libvosk
+0.3.44 is safe for many recognizers DECODING concurrently on one Model, but
+under a high rate of concurrent recognizer construction + short decode +
+``FinalResult`` it crashes the process with an access violation (Windows,
+reproduced in ~5-50 s with five threads; the real-model bench
+``scripts/vosk_wake_bench.py`` hit it 3/3 at HEAD before this change and
+2/4 after). No partial lock protocol tried (finals only; finals exclusive
+vs decodes; finals + constructions exclusive) was reliably enough; full
+serialisation of every native call survives. This module therefore adds no
+new concurrent decode-and-finalise cycle (the streamed confirm decodes in
+parallel but finalises sequentially on one thread) and keeps the rest of
+the pre-existing design; the fix proper is tracked in docs/BUGS.md
+(BUG-151).
"""
from __future__ import annotations
@@ -336,6 +376,23 @@ _REJECTED_CANDIDATE_BACKOFF_S = 2.0
# passed).
_CONFIRM_TAIL_S = 0.6
+# --- stage-1 CPU budget (weak-CPU forensic 2026-08-19) -----------------------
+# Stage 1 runs one streaming grammar per installed model on EVERY chunk. Its
+# cost is the acoustic model's forward pass per model (~0.3x realtime per small
+# model on a 15 W laptop core, ~0.1x on a desktop core); three models plus a
+# busy desktop pushed that above realtime, the fanout backlog grew and every
+# wake was heard late. A call whose decode took longer than this multiple of
+# the audio it covered is "losing ground"; when that happens on
+# ``_STAGE1_SLOW_CALLS`` of the last ``_STAGE1_RT_WINDOW`` calls the LAST
+# secondary model is demoted from stage 1 (it stays loaded for the verify and
+# sibling rescue). 2.0 separates the regimes measured on that laptop: three
+# models keeping up sat at ~0.8x (p95) during speech, the overloaded box at
+# 2.3x and above. Silence decodes are cheap (~0.03x), so a quiet room never
+# trips it, and a desktop CPU never reaches it at all.
+_STAGE1_SLOW_RT = 2.0
+_STAGE1_SLOW_CALLS = 4
+_STAGE1_RT_WINDOW = 8
+
def _folded(text: str) -> str:
return " ".join(sound_fold(t) for t in normalize_phrase_for_match(text))
@@ -571,6 +628,108 @@ def candidate_shape_ok(
) == SHAPE_WAKE
+class _StreamingVerify:
+ """The authoritative confirm's decode, paid DURING the confirm tail.
+
+ Why: the confirm used to run only after the tail had landed, re-decoding
+ the whole 3 s ring from scratch — 0.4-0.9 s on a 15 W laptop core, i.e.
+ most of the spawn latency there. Kaldi recognizers are streaming decoders,
+ so the SAME two one-shot recognizers (grammar re-score + free ear) can
+ start on the ring the moment the partial fires and then eat each tail
+ chunk as it arrives; at tail end only ``FinalResult`` is left. Audio,
+ recognizers and every downstream threshold are unchanged — only the moment
+ the decode runs moved, which is why this is a latency change and not a
+ decision change. (``AcceptWaveform`` slices any buffer into 0.2 s steps
+ internally, so feeding the ring and then 32 ms chunks decodes exactly what
+ one 3.6 s buffer would.)
+
+ Threading, chosen against the libvosk limits measured 2026-08-19 (module
+ note, BUG-151): FEEDS run on one single-worker executor per recognizer —
+ ordered, never overlapping on one native recognizer (AP-24), and the two
+ recognizers decode concurrently, which is the proven-safe pattern (many
+ recognizers decoding at once on one Model). The two FINALS run
+ sequentially on the finishing thread after every feed has landed — the
+ concurrent short-decode-and-finalise cycle is the one that crashes that
+ build, so this class never adds one. The window and the normalised pcm are
+ accumulated here so the judgement sees exactly what the recognizers
+ decoded. Peak normalisation uses the gain measured over the ring at
+ partial time; the tail keeps that gain (clipped), which is the one place
+ this differs from the from-scratch path — the phrase itself, the part the
+ re-score and the span RMS judge, is the ring.
+ """
+
+ def __init__(
+ self,
+ model_path: str | None,
+ grammar_rec: Any,
+ free_rec: Any,
+ ring: np.ndarray,
+ *,
+ target_peak: float,
+ max_gain: float,
+ ) -> None:
+ self.model_path = model_path
+ self._grammar = grammar_rec
+ self._free = free_rec
+ peak = float(np.max(np.abs(ring))) if len(ring) else 0.0
+ self._gain = min(target_peak / peak, max_gain) if peak > 1e-6 else 1.0
+ self._parts: list[np.ndarray] = []
+ self._pcm_parts: list[bytes] = []
+ self._g_pool = ThreadPoolExecutor(
+ max_workers=1, thread_name_prefix="vosk-verify-grammar"
+ )
+ self._f_pool = ThreadPoolExecutor(
+ max_workers=1, thread_name_prefix="vosk-verify-free"
+ )
+ self._pending: list[Any] = []
+ self.feed(ring)
+
+ def _normalise(self, audio: np.ndarray) -> tuple[np.ndarray, bytes]:
+ window = np.clip(audio * self._gain, -1.0, 1.0)
+ return window, (window * 32767.0).astype(np.int16).tobytes()
+
+ def feed(self, audio: np.ndarray) -> None:
+ """Queue more audio (float32 [-1, 1]) for both recognizers, in order."""
+ if not len(audio):
+ return
+ window, pcm = self._normalise(audio)
+ self._parts.append(window)
+ self._pcm_parts.append(pcm)
+ # A failed feed is surfaced by finish() through the stored futures,
+ # never raised into the detect loop.
+ self._pending.append(self._g_pool.submit(self._grammar.AcceptWaveform, pcm))
+ self._pending.append(self._f_pool.submit(self._free.AcceptWaveform, pcm))
+
+ def finish(self) -> tuple[np.ndarray, bytes, dict, dict]:
+ """Finalize both decodes; returns (window, pcm, grammar_json, free_json).
+
+ Blocking (worker thread). Raises if any feed or final failed — the
+ caller then falls back to the from-scratch confirm. Both finals run
+ HERE, one after the other, once every queued feed has completed (so
+ no executor thread touches either recognizer any more).
+ """
+ try:
+ for fut in self._pending:
+ fut.result()
+ self._g_pool.shutdown(wait=True)
+ self._f_pool.shutdown(wait=True)
+ gres = _parse_recognizer_json(
+ self._grammar.FinalResult(), where="verify.grammar_final"
+ )
+ fres = _parse_recognizer_json(
+ self._free.FinalResult(), where="verify.free_final"
+ )
+ finally:
+ self.close()
+ 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:
+ """Discard (early fire, superseded candidate, teardown)."""
+ self._g_pool.shutdown(wait=False, cancel_futures=True)
+ self._f_pool.shutdown(wait=False, cancel_futures=True)
+
+
class VoskKwsProvider:
"""Any-word wake detector — structurally compatible with `WakeWordProvider`.
@@ -585,11 +744,25 @@ class VoskKwsProvider:
# 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
+ # pipeline may coalesce the backlog into ONE AudioChunk covering up to this
+ # much audio. A TIME budget, not a chunk count: the capture block shrank
+ # from 100 ms to 32 ms after the count was chosen and silently turned "1 s
+ # per batch" into 320 ms (queue bounds are time budgets — capture.py). 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_s = 1.0
+ # How far behind live audio the fanout may let this detector fall before
+ # it drops the OLDEST frames. The generic detector budget is 0.6 s (a
+ # detector that cannot catch up must stay near-present); this one catches
+ # up in batches, so its budget is the ring length: anything older could
+ # not reach a verify anyway, and a frame dropped INSIDE the ring leaves
+ # a hole the re-score hears as '' (live 2026-08-19: every candidate's
+ # 0.4-0.9 s confirm overflowed the 0.6 s queue on a 4-core laptop and
+ # genuine retries were eaten). Honoured by the pipeline ONLY together with
+ # the catch-up capability above — a deeper queue without batching would
+ # just be a later wake.
+ intake_backlog_s = _RING_SECONDS
def __init__(
self,
@@ -714,6 +887,19 @@ class VoskKwsProvider:
self._stat_early_shown = 0
self._stat_early_retracted = 0
self._stat_suppressed_shape_competition = 0
+ # Verify path accounting: how many confirms ran streamed (decode paid
+ # during the tail) vs from scratch (finals, latched retries, fallback).
+ self._stat_verify_streamed = 0
+ self._stat_verify_scratch = 0
+ self._stat_verify_stream_fallback = 0
+ # Stage-1 CPU budget: the model paths currently streaming stage 1
+ # (primary first; secondaries are demoted from the END when the
+ # decode proves it cannot keep up) and the recent per-call realtime
+ # factors the rule reads. Reset per detect() session.
+ self._stage1_paths: list[str] = list(self._model_paths)
+ self._stage1_rt: deque[float] = deque(maxlen=_STAGE1_RT_WINDOW)
+ self._last_stage1_cost: tuple[float, float] = (0.0, 0.0)
+ self._stat_stage1_demoted = 0
# Rate limiter for the verify-suppression log. Every rejection used to
# be DEBUG-only, so a dropped GENUINE wake left no production trace at
# all: the log could not tell "never heard" from "heard, verified,
@@ -847,17 +1033,19 @@ class VoskKwsProvider:
)
def _fresh_recs(self) -> dict[str, Any]:
- """One streaming grammar recognizer per LOADABLE model path.
+ """One streaming grammar recognizer per ACTIVE stage-1 model path.
Taken from the prewarmed stock when available: a rebuilt streaming
recognizer otherwise pays Kaldi's ~400ms lazy first-decode init
INLINE in the detect loop (it decodes chunks on the event loop) —
after every candidate reset, per model. A corrupt/missing model dir
must never brick the working ones — it is skipped with a warning and
- detection continues on the rest.
+ detection continues on the rest. A model demoted by the stage-1 CPU
+ budget (``_note_stage1_cost``) gets no streaming recognizer; it is
+ still loaded for the verify and the sibling rescue.
"""
recs: dict[str, Any] = {}
- for path in self._model_paths:
+ for path in self._stage1_paths:
try:
recs[path] = self._take_verify_rec(path, "grammar")
except Exception as exc: # noqa: BLE001 — isolate a broken model
@@ -951,8 +1139,53 @@ class VoskKwsProvider:
"suppressed_shape_competition": (
self._stat_suppressed_shape_competition
),
+ "verify_streamed": self._stat_verify_streamed,
+ "verify_scratch": self._stat_verify_scratch,
+ "verify_stream_fallback": self._stat_verify_stream_fallback,
+ "stage1_models": len(self._stage1_paths),
+ "stage1_demoted": self._stat_stage1_demoted,
}
+ # -- stage-1 CPU budget ----------------------------------------------------
+
+ def _note_stage1_cost(self, decode_s: float, audio_s: float) -> bool:
+ """Record one stage-1 call's realtime factor; True when a model was demoted.
+
+ The rule reads only the detector's OWN decode time against the audio
+ it covered — never wall-clock queue depth (which the provider cannot
+ see) and never transcript content (AP-27). Demotion removes the LAST
+ active secondary (plan order puts the speaker-language model first);
+ the primary is never demoted, so a phrase's own language keeps
+ listening even on the weakest box. Reset per ``detect()`` session, so
+ a transient load (a build, a dictation) does not cost the box a model
+ for the rest of the process.
+ """
+ if audio_s <= 0.0:
+ return False
+ self._stage1_rt.append(decode_s / audio_s)
+ if len(self._stage1_paths) <= 1:
+ return False
+ if len(self._stage1_rt) < _STAGE1_RT_WINDOW:
+ return False
+ slow = sum(1 for rt in self._stage1_rt if rt > _STAGE1_SLOW_RT)
+ if slow < _STAGE1_SLOW_CALLS:
+ return False
+ demoted = self._stage1_paths.pop()
+ self._stage1_rt.clear()
+ self._stat_stage1_demoted += 1
+ log.warning(
+ "vosk-kws: stage-1 cannot keep up on this CPU (%d of the last %d "
+ "decodes ran slower than %.1fx realtime) — demoting %s from the "
+ "streaming stage; %d model(s) keep listening, the demoted one "
+ "stays available for verify. Restored on the next wake session.",
+ slow,
+ _STAGE1_RT_WINDOW,
+ _STAGE1_SLOW_RT,
+ demoted,
+ len(self._stage1_paths),
+ )
+ return True
+
# -- early candidate (visual-only) ----------------------------------------
def set_early_candidate_listener(
@@ -1077,17 +1310,43 @@ class VoskKwsProvider:
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.
+
+ Records the call's decode cost in ``_last_stage1_cost`` (decode
+ seconds, audio seconds) for the stage-1 CPU budget; the loop turns
+ that into a demotion decision on its own thread.
"""
+ t0 = time.perf_counter()
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
+ self._last_stage1_cost = (
+ time.perf_counter() - t0,
+ len(pcm) / (2.0 * self._sample_rate),
+ )
if hit is None:
return None
return (hit[0], hit[1], hit_path)
+ async def _stage1(
+ self,
+ recs: dict[str, Any],
+ pcm: bytes,
+ _in_pool: Callable[..., Awaitable[Any]],
+ ) -> tuple[tuple[bool, float, str] | None, dict[str, Any]]:
+ """Feed one chunk to stage 1 off the loop and apply the CPU budget.
+
+ Returns the hit (if any) and the recognizer set to continue with —
+ rebuilt without the demoted model when the budget rule fired.
+ """
+ self._last_stage1_cost = (0.0, 0.0)
+ found = await _in_pool(self._grammar_hit_all, recs, pcm)
+ if self._note_stage1_cost(*self._last_stage1_cost):
+ recs = self._fresh_recs()
+ return found, recs
+
def _verify_candidate(
self, window: np.ndarray, model_path: str | None = None
) -> bool:
@@ -1096,6 +1355,7 @@ class VoskKwsProvider:
``model_path`` selects the model that HEARD the candidate; the verify
must use the same acoustics that produced the hit, never a sibling.
"""
+ self._stat_verify_scratch += 1
return self._verify_window(window, fail_open=True, model_path=model_path)
def _early_check(
@@ -1113,6 +1373,58 @@ class VoskKwsProvider:
except Exception: # noqa: BLE001 — belt and braces for the UI path
return False
+ def _start_streaming_verify(
+ self, ring: np.ndarray, model_path: str | None
+ ) -> _StreamingVerify | None:
+ """Begin the authoritative confirm's decode at PARTIAL time.
+
+ Takes this candidate's grammar + free recognizers (prewarmed stock,
+ cold build otherwise) and starts them on the ring; the loop then
+ feeds every tail chunk. None when the recognizers cannot be built —
+ the loop falls back to the from-scratch confirm at tail end, exactly
+ the pre-streaming behaviour.
+ """
+ try:
+ grammar = self._take_verify_rec(model_path, "grammar")
+ free = self._take_verify_rec(model_path, "free")
+ return _StreamingVerify(
+ model_path,
+ grammar,
+ free,
+ ring,
+ target_peak=self._target_peak,
+ max_gain=self._max_gain,
+ )
+ except Exception as exc: # noqa: BLE001 — fall back to from-scratch
+ log.debug("vosk-kws: streaming verify unavailable (%s)", exc)
+ return None
+
+ def _finish_streaming_verify(
+ self, streaming: _StreamingVerify, fallback_window: np.ndarray
+ ) -> bool:
+ """Authoritative confirm over the streamed decode — fails OPEN.
+
+ Blocking (worker thread). A streaming infrastructure error (a failed
+ feed, a broken final) does NOT accept blindly: it re-runs the
+ from-scratch confirm over ``fallback_window`` (the ring as it stands),
+ which carries the usual fail-open polarity — so a broken extra
+ optimisation degrades to yesterday's path, never to a blind yes.
+ """
+ try:
+ decoded = streaming.finish()
+ except Exception as exc: # noqa: BLE001 — degrade to from-scratch
+ self._stat_verify_stream_fallback += 1
+ log.warning(
+ "vosk-kws: streamed confirm failed (%s) — re-running the "
+ "from-scratch confirm.",
+ exc,
+ )
+ return self._verify_candidate(fallback_window, streaming.model_path)
+ self._stat_verify_streamed += 1
+ return self._judge_decoded(
+ decoded, fail_open=True, model_path=streaming.model_path
+ )
+
def _verify_window(
self,
window: np.ndarray,
@@ -1171,42 +1483,77 @@ class VoskKwsProvider:
recognizer). This changes only wall-clock time, never the decision:
both passes decode the identical ``pcm`` and every downstream
threshold/comparison is untouched.
+
+ Two entry shapes share the judgement below (``_judge_decoded``): this
+ from-scratch decode (finals, latched retries, sibling rescue, early
+ check) and the STREAMED decode a partial candidate pays during its
+ confirm tail (``_StreamingVerify`` → ``_finish_streaming_verify``).
"""
try:
- peak = float(np.max(np.abs(window))) if len(window) else 0.0
- if peak > 1e-6:
- window = np.clip(
- window * min(self._target_peak / peak, self._max_gain), -1.0, 1.0
- )
- pcm = (window * 32767.0).astype(np.int16).tobytes()
-
- # 1) grammar re-score (real confidence + time span) and
- # 3) free decode (unconstrained) run CONCURRENTLY — see the
- # latency note above. One attempt each over the full ring,
- # deliberately: a second grammar try over a shorter cut
- # measurably HELPED room speech more than genuine calls (FA
- # matrix 3 -> 7 with a last-1.8 s retry), because the grammar
- # happily forces any short speech snippet onto the phrase.
- def _grammar_pass() -> dict:
- g = self._take_verify_rec(model_path, "grammar")
- g.AcceptWaveform(pcm)
- return _parse_recognizer_json(
- g.FinalResult(), where="verify.grammar_final"
- )
+ decoded = self._decode_window(window, model_path)
+ except Exception as exc: # noqa: BLE001 — polarity via fail_open
+ log.warning(
+ "vosk-kws: verify failed (%s) — %s.",
+ exc,
+ "accepting" if fail_open else "rejecting (visual-only)",
+ )
+ return fail_open
+ return self._judge_decoded(decoded, fail_open=fail_open, model_path=model_path)
- def _free_pass() -> dict:
- f = self._take_verify_rec(model_path, "free")
- f.AcceptWaveform(pcm)
- return _parse_recognizer_json(
- f.FinalResult(), where="verify.free_final"
- )
+ def _decode_window(
+ self, window: np.ndarray, model_path: str | None
+ ) -> tuple[np.ndarray, bytes, dict, dict]:
+ """Peak-normalise ``window`` and run the grammar + free passes over it.
- with ThreadPoolExecutor(max_workers=2) as pool:
- grammar_future = pool.submit(_grammar_pass)
- free_future = pool.submit(_free_pass)
- gres = grammar_future.result()
- fres = free_future.result()
+ Returns ``(window, pcm, grammar_json, free_json)`` — the normalised
+ float window, its int16 bytes, and the two decodes. Raises on
+ infrastructure errors; the caller picks the fail polarity.
+ """
+ peak = float(np.max(np.abs(window))) if len(window) else 0.0
+ if peak > 1e-6:
+ window = np.clip(
+ window * min(self._target_peak / peak, self._max_gain), -1.0, 1.0
+ )
+ pcm = (window * 32767.0).astype(np.int16).tobytes()
+
+ # 1) grammar re-score (real confidence + time span) and
+ # 3) free decode (unconstrained) run CONCURRENTLY — see the
+ # latency note above. One attempt each over the full ring,
+ # deliberately: a second grammar try over a shorter cut
+ # measurably HELPED room speech more than genuine calls (FA
+ # matrix 3 -> 7 with a last-1.8 s retry), because the grammar
+ # happily forces any short speech snippet onto the phrase.
+ def _grammar_pass() -> dict:
+ g = self._take_verify_rec(model_path, "grammar")
+ g.AcceptWaveform(pcm)
+ return _parse_recognizer_json(
+ g.FinalResult(), where="verify.grammar_final"
+ )
+
+ def _free_pass() -> dict:
+ f = self._take_verify_rec(model_path, "free")
+ f.AcceptWaveform(pcm)
+ return _parse_recognizer_json(
+ f.FinalResult(), where="verify.free_final"
+ )
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ grammar_future = pool.submit(_grammar_pass)
+ free_future = pool.submit(_free_pass)
+ gres = grammar_future.result()
+ fres = free_future.result()
+ return window, pcm, gres, fres
+ def _judge_decoded(
+ self,
+ decoded: tuple[np.ndarray, bytes, dict, dict],
+ *,
+ fail_open: bool,
+ model_path: str | None,
+ ) -> bool:
+ """Checks 1-4 of ``_verify_window`` over an already-decoded window."""
+ window, pcm, gres, fres = decoded
+ try:
def _rescored(res: dict, offset_s: float) -> tuple[list[dict], float] | None:
"""The best CONSECUTIVE phrase-token run in a grammar decode.
@@ -1557,7 +1904,11 @@ class VoskKwsProvider:
log.warning("vosk-kws: model %s failed to load (%s).", path, exc)
# One streaming grammar per installed model — a phrase whose language
# differs from the speaker's still has a model that can spell it
- # (union recall measured +38% on the fixture corpus, 2026-07-11).
+ # (union recall measured +38% on the fixture corpus, 2026-07-11). The
+ # stage-1 CPU budget starts every session with the full set; a model
+ # demoted in an earlier session gets its chance again here.
+ self._stage1_paths = list(self._model_paths)
+ self._stage1_rt.clear()
recs = self._fresh_recs()
last_fire_t = 0.0
verify_not_before = 0.0
@@ -1569,210 +1920,253 @@ class VoskKwsProvider:
# same acoustics, never a sibling model.
pending: tuple[bool, float, str] | None = None
pending_tail = 0
- async for chunk in chunks:
- self._stat_chunks += 1
- pcm = chunk.pcm
- self._ring_push(pcm)
- # Full verification remains rate-limited after a clean rejection,
- # but the cheap streaming grammar must keep listening. Completely
- # pausing stage one made this a deaf period: a genuine immediate
- # retry was discarded before it could ever reach the verifier.
- # During the window we latch at most one candidate, stop stage-one
- # work once latched, and verify it only when the same deadline
- # expires. This preserves the BUG-045 load bound without dropping
- # a user's retry.
- now_mono = self._monotonic()
- backpressure_active = now_mono < verify_not_before
- if backpressure_active:
- self._stat_backpressure_chunks += 1
- if not recs:
- recs = self._fresh_recs()
- if pending is not None:
- pending_tail += len(pcm)
- # Keep every model's stream fed during the tail/backoff wait so
- # their decode state stays aligned with the ring.
- found = await _in_pool(self._grammar_hit_all, recs, pcm)
+ # The authoritative confirm of the pending PARTIAL, decoding during
+ # the tail (see _StreamingVerify). None for finals and for candidates
+ # latched under backpressure — those run the from-scratch confirm.
+ streaming: _StreamingVerify | None = None
+
+ def _drop_streaming() -> None:
+ nonlocal streaming
+ if streaming is not None:
+ streaming.close()
+ streaming = None
+
+ try:
+ async for chunk in chunks:
+ self._stat_chunks += 1
+ pcm = chunk.pcm
+ self._ring_push(pcm)
+ # Full verification remains rate-limited after a clean rejection,
+ # but the cheap streaming grammar must keep listening. Completely
+ # pausing stage one made this a deaf period: a genuine immediate
+ # retry was discarded before it could ever reach the verifier.
+ # During the window we latch at most one candidate, stop stage-one
+ # work once latched, and verify it only when the same deadline
+ # expires. This preserves the BUG-045 load bound without dropping
+ # a user's retry.
+ now_mono = self._monotonic()
+ backpressure_active = now_mono < verify_not_before
if backpressure_active:
- if found is not None:
- # A NEWER hit refreshes the latch. The old behaviour
- # kept the first latched candidate and went deaf for
- # anything after it, so room speech rejected moments
- # earlier could hold the slot while the user's real
- # wake landed in it unheard ("say it twice"). Still
- # exactly ONE verify runs, at the same deadline — the
- # BUG-045 load bound is untouched.
- is_final_new, _conf_new, _path_new = found
- pending = found
- pending_tail = (
- self._confirm_tail_bytes if is_final_new else 0
+ self._stat_backpressure_chunks += 1
+ if not recs:
+ recs = self._fresh_recs()
+ if pending is not None:
+ pending_tail += len(pcm)
+ if streaming is not None:
+ # The tail belongs to the candidate's confirm: hand it
+ # to the streaming decoders NOW instead of re-decoding
+ # the whole ring at tail end.
+ streaming.feed(
+ np.frombuffer(pcm, dtype=np.int16).astype(np.float32)
+ / 32768.0
)
- continue
- # 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
- else:
- # 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_path = found
+ # Keep every model's stream fed during the tail/backoff wait so
+ # their decode state stays aligned with the ring.
+ found, recs = await self._stage1(recs, pcm, _in_pool)
+ if backpressure_active:
+ if found is not None:
+ # A NEWER hit refreshes the latch. The old behaviour
+ # kept the first latched candidate and went deaf for
+ # anything after it, so room speech rejected moments
+ # earlier could hold the slot while the user's real
+ # wake landed in it unheard ("say it twice"). Still
+ # exactly ONE verify runs, at the same deadline — the
+ # BUG-045 load bound is untouched.
+ is_final_new, _conf_new, _path_new = found
+ pending = found
+ pending_tail = (
+ self._confirm_tail_bytes if is_final_new else 0
+ )
+ _drop_streaming() # belonged to the superseded one
+ continue
+ # 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
+ else:
+ # Feed EVERY active 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, recs = await self._stage1(recs, pcm, _in_pool)
+ if found is None:
+ continue
+ is_final, conf, hit_path = found
+ now = time.time()
+ if now - last_fire_t < self._cooldown_s:
+ self._stat_suppressed_cooldown += 1
+ recs = self._fresh_recs()
+ continue
+ self._stat_candidates += 1
+ if backpressure_active:
+ # One user retry (or one more room-speech candidate) is
+ # retained without launching any expensive decode. A
+ # final already includes its endpoint; a partial keeps
+ # accumulating the normal confirmation tail in the ring.
+ pending = (is_final, conf, hit_path)
+ pending_tail = self._confirm_tail_bytes if is_final else 0
+ continue
+ if is_final and conf < self._min_final_conf:
+ self._stat_backpressure_windows += 1
+ verify_not_before = (
+ self._monotonic() + self._rejected_candidate_backoff_s
+ )
+ recs = self._fresh_recs()
+ continue
+ if not is_final and self._confirm_tail_bytes > 0:
+ pending = (is_final, conf, hit_path)
+ pending_tail = 0
+ ring_now = self._ring_window()
+ # Start the authoritative confirm's decode on the ring
+ # right away — it takes its (prewarmed) recognizers
+ # BEFORE the visual-only early check so the path that
+ # decides is the warm one when stock is short. Built off
+ # the loop: a cold free recognizer costs ~0.3 s.
+ streaming = await _in_pool(
+ self._start_streaming_verify, ring_now, hit_path
+ )
+ # Strictly verify the audio heard SO FAR in a worker thread
+ # while the confirm tail keeps accumulating. A positive is
+ # enough to confirm this candidate and may reveal the bar;
+ # 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)
+ )
+ continue
+ # The candidate-prefix check and fallback decision must not fan out
+ # two decoder pairs at once on a weak CPU. The 0.6 s tail normally
+ # lets the prefix check finish already, so this is a no-cost
+ # ordering guard in the common path. Most importantly, a positive
+ # prefix verdict is monotonic: the newly captured tail belongs to
+ # the user's command and cannot turn a verified wake back off.
+ early_confirmed = False
+ if self._early_task is not None:
+ try:
+ early_confirmed = bool(await self._early_task)
+ except Exception as exc: # noqa: BLE001 — fallback verify remains
+ log.debug(
+ "candidate-prefix task failed; using full-window fallback: %s",
+ exc,
+ )
+ finally:
+ self._early_task = None
now = time.time()
- if now - last_fire_t < self._cooldown_s:
- self._stat_suppressed_cooldown += 1
- recs = self._fresh_recs()
- continue
- self._stat_candidates += 1
- if backpressure_active:
- # One user retry (or one more room-speech candidate) is
- # retained without launching any expensive decode. A
- # final already includes its endpoint; a partial keeps
- # accumulating the normal confirmation tail in the ring.
- pending = (is_final, conf, hit_path)
- pending_tail = self._confirm_tail_bytes if is_final else 0
- continue
- if is_final and conf < self._min_final_conf:
+ window = self._ring_window()
+ fired_path = hit_path
+ if early_confirmed:
+ confirmed = True
+ _drop_streaming()
+ log.info(
+ "vosk-kws: retaining verified candidate prefix for %r; "
+ "following audio belongs to the voice session",
+ self._phrase,
+ )
+ elif streaming is not None:
+ # 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(
+ self._finish_streaming_verify, finishing, window
+ )
+ else:
+ confirmed = await asyncio.to_thread(
+ self._verify_candidate, window, hit_path
+ )
+ if not confirmed:
+ # Sibling rescue: the model that HEARD the candidate could not
+ # verify it, but the ring still holds the phrase — let every
+ # other model try (union recall, measured +38%: 'Hey Jarvis'
+ # 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). 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. Every LOADED sibling takes
+ # part — including one the stage-1 CPU budget demoted, whose
+ # ear is exactly as good for this one-off as before.
+ others = [
+ other
+ for other in self._model_paths
+ if other != hit_path and other in self._models
+ ]
+ 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
+ # visual state. A positive prefix task cannot reach this branch;
+ # it was consumed as the monotonic verdict above.
+ self._pending_gen += 1
+ await self._notify_early(False)
self._stat_backpressure_windows += 1
verify_not_before = (
self._monotonic() + self._rejected_candidate_backoff_s
)
- recs = self._fresh_recs()
- continue
- if not is_final and self._confirm_tail_bytes > 0:
- pending = (is_final, conf, hit_path)
- pending_tail = 0
- # Strictly verify the audio heard SO FAR in a worker thread
- # while the confirm tail keeps accumulating. A positive is
- # enough to confirm this candidate and may reveal the bar;
- # a negative still falls through to the later full window.
- self._pending_gen += 1
- self._early_task = asyncio.create_task(
- self._run_early_check(
- self._ring_window(), self._pending_gen, hit_path
+ if (
+ self._stat_backpressure_windows == 1
+ or self._stat_backpressure_windows % 25 == 0
+ ):
+ log.warning(
+ "vosk-kws: rejected-candidate backpressure active "
+ "(pause %.1fs, windows=%d, skipped_chunks=%d) — "
+ "protecting desktop responsiveness.",
+ self._rejected_candidate_backoff_s,
+ self._stat_backpressure_windows,
+ self._stat_backpressure_chunks,
)
- )
+ # Re-arm one cheap streaming recognizer set now. It may latch
+ # one retry during backpressure, but no second full verify can
+ # run before the deadline above.
+ recs = self._fresh_recs()
continue
- # The candidate-prefix check and fallback decision must not fan out
- # two decoder pairs at once on a weak CPU. The 0.6 s tail normally
- # lets the prefix check finish already, so this is a no-cost
- # ordering guard in the common path. Most importantly, a positive
- # prefix verdict is monotonic: the newly captured tail belongs to
- # the user's command and cannot turn a verified wake back off.
- early_confirmed = False
- if self._early_task is not None:
- try:
- early_confirmed = bool(await self._early_task)
- except Exception as exc: # noqa: BLE001 — fallback verify remains
- log.debug(
- "candidate-prefix task failed; using full-window fallback: %s",
- exc,
- )
- finally:
- self._early_task = None
- now = time.time()
- window = self._ring_window()
- fired_path = hit_path
- if early_confirmed:
- confirmed = True
+ # The shown flag stays set for the pipeline to CONSUME: it must know
+ # the bar is visible when it silently drops this wake (echo lock)
+ # and retract it.
+ self._pending_gen += 1
+ self._stat_fired += 1
+ last_fire_t = now
log.info(
- "vosk-kws: retaining verified candidate prefix for %r; "
- "following audio belongs to the voice session",
+ "vosk-kws: WAKE fired for %r (%s candidate, model %s)",
self._phrase,
+ "final" if is_final else "partial",
+ fired_path,
)
- else:
- confirmed = await asyncio.to_thread(
- self._verify_candidate, window, hit_path
- )
- if not confirmed:
- # Sibling rescue: the model that HEARD the candidate could not
- # verify it, but the ring still holds the phrase — let every
- # other model try (union recall, measured +38%: 'Hey Jarvis'
- # 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). 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
- # visual state. A positive prefix task cannot reach this branch;
- # it was consumed as the monotonic verdict above.
- self._pending_gen += 1
- await self._notify_early(False)
- self._stat_backpressure_windows += 1
- verify_not_before = (
- self._monotonic() + self._rejected_candidate_backoff_s
- )
- if (
- self._stat_backpressure_windows == 1
- or self._stat_backpressure_windows % 25 == 0
- ):
- log.warning(
- "vosk-kws: rejected-candidate backpressure active "
- "(pause %.1fs, windows=%d, skipped_chunks=%d) — "
- "protecting desktop responsiveness.",
- self._rejected_candidate_backoff_s,
- self._stat_backpressure_windows,
- self._stat_backpressure_chunks,
- )
- # Re-arm one cheap streaming recognizer set now. It may latch
- # one retry during backpressure, but no second full verify can
- # run before the deadline above.
+ yield self._keyword
recs = self._fresh_recs()
- continue
- # The shown flag stays set for the pipeline to CONSUME: it must know
- # the bar is visible when it silently drops this wake (echo lock)
- # and retract it.
- self._pending_gen += 1
- self._stat_fired += 1
- last_fire_t = now
- log.info(
- "vosk-kws: WAKE fired for %r (%s candidate, model %s)",
- self._phrase,
- "final" if is_final else "partial",
- fired_path,
- )
- yield self._keyword
- recs = self._fresh_recs()
+ finally:
+ # A confirm still decoding at teardown (stream ended mid-tail, the
+ # pipeline closed the generator on a fire) must not keep its
+ # worker threads or recognizers alive.
+ _drop_streaming()
def vosk_model_supports_phrase(model_path: str, phrase: str) -> bool:
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 41d01490c9..1274ac57e1 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1842,6 +1842,42 @@ def _looks_like_complete_smalltalk(text: str) -> bool:
)
+def _wake_catchup_budget(detector: Any) -> tuple[int, int]:
+ """Resolve a wake detector's fanout budgets: (coalesce chunks, queue depth).
+
+ Both are TIME budgets the detector declares in seconds and this turns into
+ capture blocks — ``capture_chunks_for_duration`` is the one place that
+ knows the block size, so a block-size change can never silently shrink a
+ "1 s batch" to 320 ms again (that is exactly what happened when the block
+ went from 100 ms to 32 ms under a chunk-count attribute).
+
+ * ``coalesce_catchup_s`` > 0: the detector can consume variable buffer
+ sizes, so a backlog may be drained as ONE batch covering that much
+ audio (see ``_queue_iter``). Absent/0 → no coalescing (1).
+ * ``intake_backlog_s``: how far behind live audio the detector may fall
+ before the fanout drops its oldest frame. Honoured ONLY for a detector
+ that coalesces — one that cannot catch up must stay near-present on the
+ generic ``REALTIME_QUEUE_CHUNKS`` budget, or a deeper queue would only
+ mean a later wake. Floored at the generic budget.
+ """
+ coalesce = 1
+ try:
+ coalesce_s = float(getattr(detector, "coalesce_catchup_s", 0.0) or 0.0)
+ except (TypeError, ValueError):
+ coalesce_s = 0.0
+ if coalesce_s > 0.0:
+ coalesce = max(2, capture_chunks_for_duration(coalesce_s))
+ depth = REALTIME_QUEUE_CHUNKS
+ if coalesce > 1:
+ try:
+ backlog_s = float(getattr(detector, "intake_backlog_s", 0.0) or 0.0)
+ except (TypeError, ValueError):
+ backlog_s = 0.0
+ if backlog_s > 0.0:
+ depth = max(REALTIME_QUEUE_CHUNKS, capture_chunks_for_duration(backlog_s))
+ return coalesce, depth
+
+
async def _queue_iter(
q: asyncio.Queue, *, coalesce_max_chunks: int = 1
) -> AsyncIterator[AudioChunk]:
@@ -1857,9 +1893,9 @@ async def _queue_iter(
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.
+ detector that declares the capability (``coalesce_catchup_s``, resolved by
+ ``_wake_catchup_budget``) gets batches — a provider with fixed frame-size
+ expectations keeps the per-chunk contract.
"""
while True:
chunk = await q.get()
@@ -7479,7 +7515,19 @@ class SpeechPipeline:
# Keep OWW within ~0.6 s and the slower Whisper consumer within ~1.2 s;
# both queues drop oldest on overflow, so an overloaded host evaluates
# recent audio instead of a wake word heard several seconds ago.
- oww_queue: asyncio.Queue = asyncio.Queue(maxsize=REALTIME_QUEUE_CHUNKS)
+ #
+ # A detector that can CATCH UP in batches (``coalesce_catchup_s``, see
+ # ``_wake_catchup_budget``) may declare a deeper ``intake_backlog_s``:
+ # its confirm pass blocks its own consumption for 0.4-0.9 s on a weak
+ # CPU, which overflowed the 0.6 s queue at every candidate (live
+ # 2026-08-19, ``oww_q=19``) and dropped frames INSIDE the audio it
+ # was about to verify — the re-score then heard '' and the user had to
+ # repeat. With batching it drains a deeper backlog in one or two
+ # decodes, so nothing it could still use is ever dropped; a detector
+ # without batching keeps the shallow budget, because for it a deeper
+ # queue would only mean a later wake.
+ coalesce, intake_chunks = _wake_catchup_budget(self._wake)
+ oww_queue: asyncio.Queue = asyncio.Queue(maxsize=intake_chunks)
whisper_queue: asyncio.Queue = asyncio.Queue(
maxsize=REALTIME_QUEUE_CHUNKS * 2
)
@@ -7597,13 +7645,11 @@ class SpeechPipeline:
async def _run_oww() -> str:
# Capability-gated catch-up: a detector that can consume variable
- # chunk sizes (vosk_kws) advertises how many backlogged capture
- # 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)
- )
+ # chunk sizes (vosk_kws) advertises how much backlogged audio 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`` comes
+ # from the same resolver that sized the queue above.
async for kw in self._wake.detect(
_queue_iter(oww_queue, coalesce_max_chunks=coalesce)
):
diff --git a/scripts/vosk_native_stress.py b/scripts/vosk_native_stress.py
new file mode 100644
index 0000000000..7c4e03aae1
--- /dev/null
+++ b/scripts/vosk_native_stress.py
@@ -0,0 +1,141 @@
+"""Native-concurrency stress for libvosk — the BUG-151 repro and acceptance test.
+
+Exercises ONE shared ``vosk.Model`` from several threads the way the wake
+engine does (``jarvis/plugins/wake/vosk_kws_provider.py``): short-lived
+recognizers that are built, fed a little audio, finalised and dropped, next
+to a long-running streaming decoder. On vosk 0.3.44 / Windows 11 (2026-08-19)
+the ``churn`` mode dies with an access violation within 5-50 s; ``steady``
+(long-lived recognizers decoding concurrently) and ``churn-nodecode``
+(construction/destruction only) survive. Run with ``-X faulthandler`` to see
+the native call each thread was in.
+
+Modes (first argument; second = seconds, default 90):
+ churn build -> AcceptWaveform(short) -> FinalResult -> drop, x5 threads + decoder
+ churn-nodecode build -> drop only (no decode), x5 + decoder
+ churn-nofinal build -> AcceptWaveform -> drop (no finalise), x5 + decoder
+ steady five long-lived recognizers decode + FinalResult/Reset forever + decoder
+ churn-serial ``churn`` with EVERY native call behind one global lock (survives)
+
+A fix for BUG-151 counts only when ``churn`` survives 3 x 180 s here AND
+``scripts/vosk_wake_bench.py`` passes 3/3 on the weak laptop.
+
+ python -X faulthandler scripts/vosk_native_stress.py churn 120
+"""
+from __future__ import annotations
+
+import json
+import sys
+import threading
+import time
+from pathlib import Path
+
+import numpy as np
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO_ROOT))
+
+import vosk # noqa: E402
+
+from jarvis.speech.wake_constants import resolve_vosk_model_paths # noqa: E402
+
+SR = 16_000
+MODE = sys.argv[1] if len(sys.argv) > 1 else "churn"
+DURATION_S = float(sys.argv[2]) if len(sys.argv) > 2 else 90.0
+
+vosk.SetLogLevel(-1)
+_paths = resolve_vosk_model_paths(None)
+if not _paths:
+ raise SystemExit("no Vosk model under data/wake_models/vosk/ — install one first")
+MODEL = vosk.Model(_paths[0])
+GRAMMAR = json.dumps(["hey nova", "[unk]"])
+SILENCE_300MS = np.zeros(4800, dtype=np.int16).tobytes()
+NOISE_3S = (np.random.default_rng(0).standard_normal(SR * 3) * 2000).astype(np.int16).tobytes()
+
+stop = threading.Event()
+counts = {"built": 0, "decoded": 0}
+counts_lock = threading.Lock()
+GLOBAL = threading.Lock() # churn-serial only
+
+
+def _native(fn, *args):
+ """Run one native call — behind the global lock in ``churn-serial``."""
+ if MODE == "churn-serial":
+ with GLOBAL:
+ return fn(*args)
+ return fn(*args)
+
+
+def _new(kind: str):
+ if kind == "grammar":
+ rec = _native(vosk.KaldiRecognizer, MODEL, SR, GRAMMAR)
+ else:
+ rec = _native(vosk.KaldiRecognizer, MODEL, SR)
+ rec.SetWords(True)
+ return rec
+
+
+def churn(kind: str) -> None:
+ while not stop.is_set():
+ holder = [_new(kind)]
+ if MODE != "churn-nodecode":
+ _native(holder[0].AcceptWaveform, SILENCE_300MS)
+ if MODE != "churn-nofinal":
+ _native(holder[0].FinalResult)
+ holder.clear() # drop = vosk_recognizer_free
+ with counts_lock:
+ counts["built"] += 1
+
+
+def steady(kind: str) -> None:
+ rec = _new(kind)
+ pcm = NOISE_3S[: SR * 2]
+ while not stop.is_set():
+ for i in range(0, len(pcm), 1024):
+ if _native(rec.AcceptWaveform, pcm[i : i + 1024]):
+ _native(rec.Result)
+ _native(rec.FinalResult)
+ rec.Reset()
+ with counts_lock:
+ counts["built"] += 1
+
+
+def decoder() -> None:
+ """The long-running streaming ear next to the churn (stage 1 in the engine)."""
+ while not stop.is_set():
+ rec = _new("grammar")
+ for i in range(0, len(NOISE_3S), 1024):
+ if _native(rec.AcceptWaveform, NOISE_3S[i : i + 1024]):
+ _native(rec.Result)
+ else:
+ rec.PartialResult()
+ _native(rec.FinalResult)
+ del rec
+ with counts_lock:
+ counts["decoded"] += 1
+
+
+def main() -> int:
+ worker = steady if MODE == "steady" else churn
+ threads = [threading.Thread(target=decoder, daemon=True)]
+ threads += [threading.Thread(target=worker, args=("grammar",), daemon=True) for _ in range(3)]
+ threads += [threading.Thread(target=worker, args=("free",), daemon=True) for _ in range(2)]
+ for t in threads:
+ t.start()
+ t0 = time.time()
+ while time.time() - t0 < DURATION_S:
+ time.sleep(5)
+ with counts_lock:
+ print(
+ f"[{MODE}] t={time.time() - t0:5.0f}s built={counts['built']} "
+ f"decoded={counts['decoded']}",
+ flush=True,
+ )
+ stop.set()
+ for t in threads:
+ t.join(timeout=15)
+ print(f"[{MODE}] survived {DURATION_S:.0f}s: {counts}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index d95beb7f8c..d9fc5a5415 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -215,16 +215,22 @@ class _FakeModel:
def fake_vosk(monkeypatch):
mod = types.ModuleType("vosk")
# "model" = the most recently built model (single-model tests);
- # "models" = every model by path (multi-model tests).
- state = {"model": None, "models": {}}
+ # "models" = every model by path (multi-model tests);
+ # "recs" = every recognizer built, in order (streaming-confirm tests).
+ state = {"model": None, "models": {}, "recs": []}
def _model_factory(path): # noqa: ANN001
state["model"] = _FakeModel(path)
state["models"][path] = state["model"]
return state["model"]
+ def _rec_factory(model, rate, grammar=None): # noqa: ANN001
+ rec = _FakeRecognizer(model, rate, grammar)
+ state["recs"].append(rec)
+ return rec
+
mod.Model = _model_factory
- mod.KaldiRecognizer = _FakeRecognizer
+ mod.KaldiRecognizer = _rec_factory
mod.SetLogLevel = lambda *_a: None
monkeypatch.setitem(sys.modules, "vosk", mod)
return state
@@ -426,7 +432,12 @@ async def test_verified_candidate_prefix_cannot_be_revoked_by_following_speech(
async def test_rejected_truncated_prefix_still_uses_full_window_fallback(
fake_vosk, monkeypatch
) -> None:
- """A too-early negative never eats a wake completed during the tail."""
+ """A too-early negative never eats a wake completed during the tail.
+
+ The tail-end confirm is the STREAMED one (its decode ran during the tail,
+ ``_finish_streaming_verify``); the from-scratch ``_verify_candidate`` is
+ only its error fallback. Exactly one tail-end confirm must run and it
+ must decide — never the early negative."""
events: list[bool] = []
fallback_calls = 0
@@ -449,7 +460,9 @@ async def test_rejected_truncated_prefix_still_uses_full_window_fallback(
assert fired == ["nova"]
assert events == []
- assert fallback_calls == 1
+ assert p.stats()["verify_streamed"] == 1
+ assert fallback_calls == 0 # the streamed confirm decided; no re-decode
+ assert p.stats()["verify_stream_fallback"] == 0
def test_early_check_fails_closed_on_infra_error(fake_vosk, monkeypatch) -> None:
@@ -763,8 +776,14 @@ async def test_sibling_rescue_verifies_siblings_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
+ through seconds-stale audio one block at a time on a busy CPU. It is a
+ TIME budget (seconds), resolved to capture blocks by the pipeline, so a
+ capture block-size change can never shrink the batch again."""
+ assert VoskKwsProvider.coalesce_catchup_s >= 0.5
+ # The deeper intake budget is only meaningful together with batching and
+ # must cover the confirm ring — a frame dropped inside the ring is a hole
+ # the re-score hears as ''.
+ assert VoskKwsProvider.intake_backlog_s >= 2.0
# --- prewarmed verify-recognizer stock ------------------------------------------
@@ -865,3 +884,223 @@ def test_verify_candidate_runs_grammar_and_free_decode_concurrently(monkeypatch)
"SEQUENTIALLY, not concurrently"
)
assert result is True
+
+
+# --- weak-CPU spawn latency: streamed confirm ---------------------------------
+# Live forensic 2026-08-19 (4-core 15 W laptop): the authoritative confirm
+# re-decoded the whole 3 s ring AFTER the tail (0.4-0.9 s there). A partial
+# candidate's confirm now decodes DURING the tail — same recognizers, same
+# audio, same judgement; only its timing moved. These pin that contract.
+
+
+async def test_partial_candidate_confirm_is_streamed_during_the_tail(
+ fake_vosk, monkeypatch
+) -> None:
+ """The confirm's grammar + free recognizers are taken at PARTIAL time and
+ fed the ring plus every tail chunk; at tail end only the finalize runs.
+ Observable: the fire is a STREAMED verify, no from-scratch decode ran,
+ and the free recognizer that decided saw more than one feed (the ring,
+ then the tail chunks one by one). The early check is held negative so
+ the tail-end confirm — not the early verdict — is what fires."""
+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")
+ monkeypatch.setattr(p, "_early_check", lambda window, model_path=None: False)
+ fired = await _run_detect(p, [_chunk() for _ in range(12)])
+ assert fired == ["nova"]
+ assert p.stats()["verify_streamed"] == 1
+ assert p.stats()["verify_scratch"] == 0
+ assert p.stats()["verify_stream_fallback"] == 0
+ # The early check also builds a free recognizer (one feed: the truncated
+ # ring); the streamed confirm's free recognizer is the one fed repeatedly.
+ free_feeds = sorted(
+ r._chunks for r in fake_vosk["recs"] if r._grammar is None # noqa: SLF001
+ )
+ assert free_feeds, "no free recognizer was built"
+ # partial at chunk 3 + 0.6 s tail = 6 tail chunks -> ring + 6 feeds
+ assert free_feeds[-1] >= 1 + 6
+
+
+async def test_final_candidates_confirm_from_scratch(fake_vosk) -> None:
+ """No tail, nothing to stream: ``confirm_tail_s=0`` verifies the ring at
+ once with the from-scratch decode (the path finals and latched retries
+ take)."""
+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova", confirm_tail_s=0.0)
+ fired = await _run_detect(p, [_chunk() for _ in range(12)])
+ assert fired == ["nova"]
+ assert p.stats()["verify_scratch"] == 1
+ assert p.stats()["verify_streamed"] == 0
+
+
+async def test_streamed_confirm_error_falls_back_to_from_scratch(
+ fake_vosk, monkeypatch
+) -> None:
+ """A broken streamed decode must not accept blindly NOR eat the wake: it
+ re-runs yesterday's from-scratch confirm over the ring (which keeps the
+ usual fail-open polarity)."""
+ from jarvis.plugins.wake import vosk_kws_provider as mod
+
+ def _broken_finish(self): # noqa: ANN001
+ raise RuntimeError("native finalize glitch")
+
+ monkeypatch.setattr(mod._StreamingVerify, "finish", _broken_finish) # noqa: SLF001
+ scratch_calls = 0
+ p = VoskKwsProvider("Hey Nova", model_path="fake", keyword="nova")
+ # Hold the early check negative so the tail-end confirm is what decides.
+ monkeypatch.setattr(p, "_early_check", lambda window, model_path=None: False)
+ original = p._verify_candidate # noqa: SLF001
+
+ def _counting(window, model_path=None): # noqa: ANN001
+ nonlocal scratch_calls
+ scratch_calls += 1
+ return original(window, model_path)
+
+ monkeypatch.setattr(p, "_verify_candidate", _counting)
+ fired = await _run_detect(p, [_chunk() for _ in range(12)])
+ assert fired == ["nova"]
+ assert scratch_calls == 1
+ assert p.stats()["verify_stream_fallback"] == 1
+ assert p.stats()["verify_streamed"] == 0
+
+
+async def test_positive_early_check_discards_the_streamed_confirm(
+ fake_vosk, monkeypatch
+) -> None:
+ """An early-confirmed wake fires on the early verdict alone; the streamed
+ confirm it no longer needs is dropped, never finalized (no duplicate
+ decode, no second judgement that could contradict the verdict)."""
+ 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):
+ 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()["verify_streamed"] == 0
+ assert p.stats()["verify_scratch"] == 0
+
+
+# --- weak-CPU spawn latency: stage-1 CPU budget -------------------------------
+# Three language models streamed stage 1 on every chunk; on the same laptop
+# that was ~0.8x realtime of a core during speech and >2x under desktop load,
+# so the detector fell seconds behind. The provider now demotes the LAST
+# secondary model when its own decode cost proves it cannot keep up.
+
+
+def test_stage1_budget_demotes_the_last_secondary_and_never_the_primary() -> None:
+ from jarvis.plugins.wake import vosk_kws_provider as mod
+
+ p = VoskKwsProvider(
+ "Hey Nova",
+ model_path="primary",
+ model_paths=["primary", "sib-a", "sib-b"],
+ keyword="nova",
+ )
+ # Keeping up (0.8x) never demotes, however long it lasts.
+ for _ in range(3 * mod._STAGE1_RT_WINDOW): # noqa: SLF001
+ assert p._note_stage1_cost(0.8 * 0.032, 0.032) is False # noqa: SLF001
+ assert p._stage1_paths == ["primary", "sib-a", "sib-b"] # noqa: SLF001
+ # A few slow calls alone do not trip it (one GC pause, one scheduler hiccup).
+ for _ in range(mod._STAGE1_SLOW_CALLS - 1): # noqa: SLF001
+ assert p._note_stage1_cost(3.0 * 0.032, 0.032) is False # noqa: SLF001
+ # ...but a sustained run does: last secondary goes first.
+ demoted = False
+ for _ in range(mod._STAGE1_RT_WINDOW): # noqa: SLF001
+ demoted = demoted or p._note_stage1_cost(3.0 * 0.032, 0.032) # noqa: SLF001
+ assert demoted is True
+ assert p._stage1_paths == ["primary", "sib-a"] # noqa: SLF001
+ assert p.stats()["stage1_demoted"] == 1
+ assert p.stats()["stage1_models"] == 2
+ # The window restarts after a demotion — the next one needs fresh evidence.
+ for _ in range(mod._STAGE1_RT_WINDOW): # noqa: SLF001
+ p._note_stage1_cost(3.0 * 0.032, 0.032) # noqa: SLF001
+ assert p._stage1_paths == ["primary"] # noqa: SLF001
+ # The primary is never demoted, no matter how slow the box is.
+ for _ in range(3 * mod._STAGE1_RT_WINDOW): # noqa: SLF001
+ assert p._note_stage1_cost(10.0 * 0.032, 0.032) is False # noqa: SLF001
+ assert p._stage1_paths == ["primary"] # noqa: SLF001
+ assert p.stats()["stage1_demoted"] == 2
+ # Zero-length audio (a patched/skipped stage 1) is not evidence.
+ assert p._note_stage1_cost(1.0, 0.0) is False # noqa: SLF001
+
+
+def _force_slow_stage1(p: VoskKwsProvider, monkeypatch, rt: float) -> None:
+ """Make every stage-1 call report ``rt`` x realtime (decision input only)."""
+ original = p._grammar_hit_all # noqa: SLF001
+
+ def _slow(recs, pcm): # noqa: ANN001
+ found = original(recs, pcm)
+ audio_s = len(pcm) / (2.0 * 16000)
+ p._last_stage1_cost = (rt * audio_s, audio_s) # noqa: SLF001
+ return found
+
+ monkeypatch.setattr(p, "_grammar_hit_all", _slow)
+
+
+async def test_detect_demotes_a_slow_secondary_but_keeps_it_for_the_rescue(
+ fake_vosk, monkeypatch
+) -> None:
+ """In the loop: a sustained over-budget stage 1 drops the sibling from the
+ streaming set (its recognizer set is rebuilt without it), yet the sibling
+ still rescues a candidate the primary cannot verify — demotion trades
+ stage-1 CPU, never the union's verify ear."""
+ from jarvis.plugins.wake import vosk_kws_provider as mod
+
+ p = VoskKwsProvider(
+ "Hey Nova",
+ model_path="primary",
+ model_paths=["primary", "sibling"],
+ keyword="nova",
+ confirm_tail_s=0.0,
+ )
+ p._ensure_model("primary") # noqa: SLF001
+ p._ensure_model("sibling") # noqa: SLF001
+ # The primary hears the candidate but its free ear contradicts it; the
+ # sibling's free ear confirms. The sibling never stage-1-hits itself.
+ fake_vosk["models"]["primary"].free_text = "das ist ganz anders" # i18n-allow: test utterance
+ # The demotion (after _STAGE1_RT_WINDOW slow calls) rebuilds the primary's
+ # streaming recognizer, whose hit counter restarts — so the first hit lands
+ # AFTER the sibling was demoted, which is the case under test.
+ fake_vosk["models"]["primary"].fire_after = mod._STAGE1_RT_WINDOW + 1 # noqa: SLF001
+ fake_vosk["models"]["sibling"].fire_after = 10**9
+ _force_slow_stage1(p, monkeypatch, rt=3.0)
+
+ fired = await _run_detect(p, [_chunk() for _ in range(2 * mod._STAGE1_RT_WINDOW + 4)]) # noqa: SLF001
+
+ assert p.stats()["stage1_demoted"] == 1
+ assert p.stats()["stage1_models"] == 1
+ assert fired == ["nova"] # primary rejected -> demoted sibling rescued
+ assert p.stats()["suppressed_confirm"] == 0
+
+
+async def test_stage1_demotion_is_reset_per_detect_session(fake_vosk, monkeypatch) -> None:
+ """A transient load (a build, a dictation) must not cost the box a model
+ for the rest of the process: every ``detect()`` session starts with the
+ full set again and re-measures."""
+ from jarvis.plugins.wake import vosk_kws_provider as mod
+
+ p = VoskKwsProvider(
+ "Hey Nova",
+ model_path="primary",
+ model_paths=["primary", "sibling"],
+ keyword="nova",
+ )
+ p._ensure_model("primary") # noqa: SLF001
+ p._ensure_model("sibling") # noqa: SLF001
+ for m in fake_vosk["models"].values():
+ m.fire_after = 10**9 # silence: nothing ever hits
+ _force_slow_stage1(p, monkeypatch, rt=3.0)
+ await _run_detect(p, [_silent_chunk() for _ in range(mod._STAGE1_RT_WINDOW + 2)]) # noqa: SLF001
+ assert p.stats()["stage1_models"] == 1
+ # Second session on a box that keeps up now: full set, no demotion.
+ _force_slow_stage1(p, monkeypatch, rt=0.3)
+ await _run_detect(p, [_silent_chunk() for _ in range(mod._STAGE1_RT_WINDOW + 2)]) # noqa: SLF001
+ assert p.stats()["stage1_models"] == 2
+ assert p.stats()["stage1_demoted"] == 1 # the earlier one, unchanged
diff --git a/tests/unit/speech/test_wake_queue_coalesce.py b/tests/unit/speech/test_wake_queue_coalesce.py
index fb1383f789..a0346509ee 100644
--- a/tests/unit/speech/test_wake_queue_coalesce.py
+++ b/tests/unit/speech/test_wake_queue_coalesce.py
@@ -5,8 +5,9 @@ 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:
+``coalesce_catchup_s``, resolved by ``_wake_catchup_budget``) drain a BACKLOG
+as one concatenated catch-up chunk instead of grinding through it one block
+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
@@ -95,3 +96,74 @@ async def test_sentinel_mid_drain_flushes_and_terminates() -> None:
assert len(out) == 1
assert len(out[0].pcm) == 3 * _CHUNK_BYTES
+
+
+# --- capability resolver: time budgets -> capture blocks ------------------------
+# The batch cap used to be a CHUNK COUNT on the detector; when the capture
+# block shrank from 100 ms to 32 ms it silently turned "1 s per batch" into
+# 320 ms. Both budgets are seconds now and only the pipeline (which knows the
+# block size) turns them into blocks. The deeper intake budget is honoured
+# only together with batching (live 2026-08-19: the vosk confirm blocked its
+# own consumption for 0.4-0.9 s on a weak CPU, the 0.6 s queue overflowed and
+# frames inside the audio about to be verified were dropped).
+
+
+class _Detector:
+ def __init__(self, **attrs): # noqa: ANN003
+ self.__dict__.update(attrs)
+
+
+def test_catchup_budget_resolves_seconds_to_capture_blocks() -> None:
+ from jarvis.audio.capture import capture_chunks_for_duration
+ from jarvis.speech.pipeline import _wake_catchup_budget
+
+ coalesce, depth = _wake_catchup_budget(
+ _Detector(coalesce_catchup_s=1.0, intake_backlog_s=3.0)
+ )
+ assert coalesce == capture_chunks_for_duration(1.0)
+ assert coalesce > 10 # the old 100 ms-era count would under-batch 32 ms blocks
+ assert depth == capture_chunks_for_duration(3.0)
+
+
+def test_catchup_budget_defaults_without_the_capability() -> None:
+ from jarvis.audio.capture import REALTIME_QUEUE_CHUNKS
+ from jarvis.speech.pipeline import _wake_catchup_budget
+
+ assert _wake_catchup_budget(_Detector()) == (1, REALTIME_QUEUE_CHUNKS)
+ # A deeper backlog WITHOUT batching is refused: a detector that cannot
+ # catch up must stay near-present, or a deeper queue is just a later wake.
+ assert _wake_catchup_budget(_Detector(intake_backlog_s=5.0)) == (
+ 1,
+ REALTIME_QUEUE_CHUNKS,
+ )
+ # The intake budget never drops below the generic one.
+ coalesce, depth = _wake_catchup_budget(
+ _Detector(coalesce_catchup_s=1.0, intake_backlog_s=0.1)
+ )
+ assert coalesce > 1
+ assert depth == REALTIME_QUEUE_CHUNKS
+
+
+def test_catchup_budget_ignores_garbage_values() -> None:
+ from jarvis.audio.capture import REALTIME_QUEUE_CHUNKS
+ from jarvis.speech.pipeline import _wake_catchup_budget
+
+ assert _wake_catchup_budget(
+ _Detector(coalesce_catchup_s="soon", intake_backlog_s=None)
+ ) == (1, REALTIME_QUEUE_CHUNKS)
+ coalesce, depth = _wake_catchup_budget(
+ _Detector(coalesce_catchup_s=1.0, intake_backlog_s="lots")
+ )
+ assert coalesce > 1
+ assert depth == REALTIME_QUEUE_CHUNKS
+
+
+def test_vosk_provider_declares_both_budgets() -> None:
+ """The live detector is the reason the resolver exists; pin the wiring."""
+ from jarvis.audio.capture import REALTIME_QUEUE_CHUNKS
+ from jarvis.plugins.wake.vosk_kws_provider import VoskKwsProvider
+ from jarvis.speech.pipeline import _wake_catchup_budget
+
+ coalesce, depth = _wake_catchup_budget(VoskKwsProvider)
+ assert coalesce > 1
+ assert depth > REALTIME_QUEUE_CHUNKS