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): retain retries during verifier backpressure

Ruben Lütke8c4c50691b8f
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 41fdd2af21..8a6a6bf641 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3364,15 +3364,32 @@ rescue, and recognizer-stock replenishment. The existing five-second cooldown
applied only after a successful wake, so a stream of rejected candidates had no
load bound. Detailed rejection messages at INFO level amplified the burst.
-**Fix.** A rejected candidate now opens a two-second, monotonic backpressure
-window. Audio continues advancing the ring, but stage-one decode, fresh
-recognizer construction, and full verification pause until re-arm. The first
-candidate after quiet remains immediate; only work proven to be a false
-candidate is throttled. The early visual verify completes before the
-authoritative pair starts, replenishment begins only after the decision, and
-rejection details are DEBUG-level. Session stats expose backpressure windows and
-skipped chunks. The mechanism uses only asyncio and monotonic time, so Windows,
-macOS, Linux desktops, and headless Linux share the same behaviour.
+A follow-up regression exposed two recall losses in that otherwise necessary
+hardening. First, the backpressure window paused stage one as well as the costly
+verifier, so rapid human retries were discarded. Second, the structured sound
+confirm rejected real one-token merges and close core spellings produced by the
+free decoder even after a high-confidence grammar re-score.
+
+**Fix.** A rejected candidate opens a two-second, monotonic backpressure window.
+Full verification remains paused until re-arm, but stage one immediately gets
+one fresh recognizer set and may latch one retry. Once latched, stage one also
+pauses while audio continues advancing the ring; the retained candidate is
+verified when the existing deadline expires. This preserves the hard verifier
+and recognizer-rebuild bound without turning backpressure into a deaf period for
+a user's immediate second call. The first candidate after quiet remains
+immediate. The early visual verify completes before the authoritative pair
+starts, replenishment begins only after the decision, and rejection details are
+DEBUG-level. Session stats expose backpressure windows and bounded chunks. The
+mechanism uses only asyncio and monotonic time, so Windows, macOS, Linux desktops,
+and headless Linux share the same behaviour.
+
+The sound confirm also accepts a narrowly calibrated class of generic ASR
+variants: a known prefix followed by a two-thirds-similar core, or a one-token
+merge that independently resembles the configured prefix, core, and complete
+phrase. The merge path cannot accept the bare core. Calibration against 100
+real positive and 500 real negative speech windows improved recall without a
+new negative acceptance; the energy, grammar-confidence, localisation, and
+full-phrase requirements remain intact.
The desktop startup path also logs whether the browser-originated shell-paint
acknowledgment arrived or whether the bounded 12-second fallback released heavy
@@ -3380,9 +3397,13 @@ initialization. A future screenshot can therefore distinguish paint failure
from post-start process starvation without inference.
**Guards.** `tests/unit/plugins/wake/test_vosk_kws_provider.py` proves that 200
-continuous noisy chunks trigger one verification and one recognizer set, not a
-candidate/rebuild storm. The existing wake recall, sibling rescue, early visual
-candidate, cooldown, and AP-24 exclusive-recognizer tests remain green.
+continuous noisy chunks trigger one verification and only one bounded retry
+recognizer set, not a candidate/rebuild storm. It also proves that immediate
+retries for one-word and multi-word arbitrary phrases are retained during the
+window. Sound-confirm guards cover close spellings, merged phrases, bare-core
+rejection, and the production false-wake transcripts. The existing wake recall,
+sibling rescue, early visual candidate, cooldown, and AP-24
+exclusive-recognizer tests remain green.
`tests/unit/ui/web/test_fast_bootstrap.py` and
`tests/unit/ui/test_desktop_backend_start_order.py` retain the cross-platform
paint-before-heavy-start contract.
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 99fe5dd8d2..4f71d92ff8 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -95,7 +95,7 @@ _CONFIRM_RATIO = 0.55
# ("Jarvis" -> "joe avis"), but unrelated words must not be subsidised by the
# matching prefix. A phrase with no prefix has no independent anchor and needs
# the stricter bare-core floor.
-_PREFIXED_CORE_RATIO = 0.70
+_PREFIXED_CORE_RATIO = 2.0 / 3.0
_UNPREFIXED_CORE_RATIO = 0.80
# A free decoder often preserves the wake core while garbling the short
@@ -110,6 +110,20 @@ _UNPREFIXED_CORE_RATIO = 0.80
_GARBLED_PREFIX_CORE_RATIO = 0.80
_GARBLED_PREFIX_PHRASE_RATIO = 0.62
+# Some free decoders merge the complete prefixed phrase into one word. Real
+# captures include "Hey Ruben" -> "herum" / "erhoben"; treating those as a
+# missing prefix would either reject genuine calls or accidentally accept the
+# bare core. The rescue therefore requires independent similarity to the
+# prefix, core, and complete merged phrase, plus a bounded length ratio. A
+# 100-positive / 500-negative real-window calibration on 2026-07-13 lifted
+# recall without adding a negative acceptance. These rules are derived from
+# the configured tokens and apply equally to every supported phrase.
+_MERGED_PREFIX_RATIO = 0.40
+_MERGED_CORE_RATIO = 0.40
+_MERGED_PHRASE_RATIO = 0.53
+_MERGED_MIN_LENGTH_RATIO = 0.55
+_MERGED_MAX_LENGTH_RATIO = 1.20
+
# Word-agnostic energy floor for a candidate window (mirrors the stt_match
# path's RollingWhisperWake._match_min_rms — AP-27: silence is gated on raw
# energy, never on transcript content).
@@ -128,7 +142,9 @@ _COOLDOWN_S = 5.0
# passes in 140 seconds, enough to starve the WebView, overlay, microphone, and
# local HTTP listener in the shared desktop process. A short reject-only
# backoff bounds that work on every OS while leaving the first candidate (and
-# therefore the normal quiet-room wake path) at full speed.
+# therefore the normal quiet-room wake path) at full speed. Stage one keeps
+# 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
# How much audio to let land in the ring AFTER a PARTIAL candidate before the
@@ -218,6 +234,30 @@ def sound_confirm(free_text: str, phrase: str, *, ratio: float = _CONFIRM_RATIO)
and phrase_score >= _GARBLED_PREFIX_PHRASE_RATIO
):
return True
+
+ # The unconstrained decoder may merge the complete spoken phrase into
+ # one token. Require that one token to carry separate prefix AND core
+ # evidence; this keeps a bare core from satisfying a configured full
+ # phrase while recovering generic ASR merges.
+ if len(words) == 1:
+ heard = words[0]
+ target_prefix = "".join(
+ sound_fold(token) for token in phrase_tokens[:prefix_count]
+ )
+ target_merged = "".join(sound_fold(token) for token in phrase_tokens)
+ length_ratio = len(heard) / max(1, len(target_merged))
+ if (
+ _MERGED_MIN_LENGTH_RATIO
+ <= length_ratio
+ <= _MERGED_MAX_LENGTH_RATIO
+ and SequenceMatcher(None, target_prefix, heard).ratio()
+ >= _MERGED_PREFIX_RATIO
+ and SequenceMatcher(None, target_core, heard).ratio()
+ >= _MERGED_CORE_RATIO
+ and SequenceMatcher(None, target_merged, heard).ratio()
+ >= _MERGED_PHRASE_RATIO
+ ):
+ return True
return False
@@ -319,6 +359,10 @@ class VoskKwsProvider:
self._early_active = False
self._early_task: asyncio.Task[None] | None = None
self._pending_gen = 0
+ # Instance-local clock hook keeps reject/backpressure state-machine
+ # tests deterministic without replacing Python's process-global
+ # monotonic clock (which asyncio itself also consumes).
+ self._monotonic = time.monotonic
# Session stats (parity with OpenWakeWordProvider.stats()).
self._stat_chunks = 0
self._stat_candidates = 0
@@ -788,20 +832,26 @@ class VoskKwsProvider:
self._stat_chunks += 1
pcm = chunk.pcm
self._ring_push(pcm)
- # A clean rejection proves that the recall-biased grammar is
- # currently mapping unrelated audio onto the wake phrase. Do not
- # keep decoding/rebuilding recognizers during the bounded reject
- # window: that was the process-wide UI starvation loop behind
- # BUG-045. Ring audio still advances, so the first candidate after
- # re-arm is verified against current sound rather than stale bytes.
- now_mono = time.monotonic()
- if now_mono < verify_not_before:
+ # 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
- continue
if not recs:
recs = self._fresh_recs()
if pending is not None:
pending_tail += len(pcm)
+ if backpressure_active:
+ # The retry is already latched. Advancing the ring is
+ # enough; do not spend stage-one or verifier work yet.
+ continue
# Keep every model's stream fed during the tail wait so their
# decode state stays aligned with the ring.
for r in recs.values():
@@ -827,13 +877,20 @@ class VoskKwsProvider:
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 = (
- time.monotonic() + self._rejected_candidate_backoff_s
+ self._monotonic() + self._rejected_candidate_backoff_s
)
- self._kick_replenish()
- recs = {}
+ recs = self._fresh_recs()
continue
if not is_final and self._confirm_tail_bytes > 0:
pending = (is_final, conf, hit_path)
@@ -895,7 +952,7 @@ class VoskKwsProvider:
await self._notify_early(False)
self._stat_backpressure_windows += 1
verify_not_before = (
- time.monotonic() + self._rejected_candidate_backoff_s
+ self._monotonic() + self._rejected_candidate_backoff_s
)
if (
self._stat_backpressure_windows == 1
@@ -909,11 +966,10 @@ class VoskKwsProvider:
self._stat_backpressure_windows,
self._stat_backpressure_chunks,
)
- # Do not consume/build another streaming recognizer until the
- # backoff expires. Replenishment can finish in the background
- # while detection is intentionally idle.
- self._kick_replenish()
- recs = {}
+ # 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
# Confirmed: let a still-running early check finish first (in
# production it completed long ago — the tail wait dwarfs it) so
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index 6772c69874..00fe376fcd 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -16,7 +16,8 @@ up. What is pinned here:
mission 2026-07-10): they are independent passes over the same audio, so
paying their SUM instead of their MAX is a pure latency regression.
- Rejected-candidate storms are backpressured so recall-biased grammar cannot
- starve the desktop UI, microphone, or local server.
+ starve the desktop UI, microphone, or local server, while one immediate
+ user retry remains latched instead of landing in a deaf period.
"""
from __future__ import annotations
@@ -38,10 +39,27 @@ from jarvis.plugins.wake.vosk_kws_provider import VoskKwsProvider, sound_confirm
def test_sound_confirm_accepts_sound_close_mishearing() -> None:
assert sound_confirm("hey ruben", "Hey Ruben") is True
+ assert sound_confirm("hey oben", "Hey Ruben") is True
assert sound_confirm("hey nowa", "Hey Nova") is True
assert sound_confirm("hey joe avis", "Hey Jarvis") is True
+ ("heard", "phrase"),
+ (
+ ("herum", "Hey Ruben"),
+ ("erhoben", "Hey Ruben"),
+ ("henowa", "Hey Nova"),
+ ("helatlas", "Hello Atlas"),
+ ),
+)
+def test_sound_confirm_accepts_generic_merged_full_phrase(
+ heard: str, phrase: str
+) -> None:
+ """A one-token ASR merge still carries independent prefix/core evidence."""
+ assert sound_confirm(heard, phrase) is True
+
+
@pytest.mark.parametrize(
"heard",
(
@@ -85,6 +103,12 @@ def test_garbled_prefix_rescue_does_not_fish_the_core_from_longer_speech() -> No
assert sound_confirm("we discussed jarvis today", "Hey Jarvis") is False
+def test_merged_phrase_rescue_never_accepts_the_bare_core() -> None:
+ """The configured full phrase remains mandatory after a one-token merge."""
+ assert sound_confirm("ruben", "Hey Ruben") is False
+ assert sound_confirm("atlas", "Hello Atlas") is False
+
+
def test_unprefixed_wake_requires_strong_core_evidence() -> None:
assert sound_confirm("joseph", "Joseph") is True
assert sound_confirm("das ist etwas", "Joseph") is False # i18n-allow: utterance under test
@@ -445,8 +469,9 @@ async def test_rejected_candidate_storm_is_backpressured(
) -> None:
"""Room speech can make recall-biased grammar hit continuously.
- One rejection must pause stage-one decoding as well as the expensive
- verifier. Rebuilding recognizers on every skipped hit would preserve the
+ One rejection may re-arm one cheap recognizer set to retain a user retry,
+ but the first candidate it hears is latched without another expensive
+ verifier call. Rebuilding on every skipped hit would preserve the
process-wide CPU storm even if full verification were rate-limited.
"""
p = VoskKwsProvider(
@@ -481,11 +506,72 @@ async def test_rejected_candidate_storm_is_backpressured(
assert fired == []
assert verify_calls == 1
- assert fresh_rec_calls == 1
+ assert fresh_rec_calls == 2 # initial set + one bounded retry listener
assert p.stats()["backpressure_windows"] == 1
assert p.stats()["backpressure_chunks"] > 100
+ ("phrase", "keyword"),
+ (
+ ("Hey Nova", "nova"),
+ ("Computer", "computer"),
+ ("Good Morning Atlas", "atlas"),
+ ),
+)
+async def test_immediate_retry_is_latched_during_reject_backpressure(
+ fake_vosk, monkeypatch, phrase: str, keyword: str
+) -> None:
+ """A clean false-negative must not make any configured phrase deaf.
+
+ The expensive verifier remains limited to one call per backpressure
+ window. Stage one retains the next complete call and releases it at the
+ deadline, so rapid human retries are not discarded.
+ """
+ p = VoskKwsProvider(
+ phrase,
+ model_path="fake",
+ keyword=keyword,
+ confirm_tail_s=0.0,
+ rejected_candidate_backoff_s=0.5,
+ )
+ p._ensure_model()
+ fake_vosk["model"].phrase = phrase.lower()
+ fake_vosk["model"].free_text = phrase.lower()
+
+ now = 0.0
+ verify_calls = 0
+
+ def _clock() -> float:
+ return now
+
+ def _verify(_window, _model_path=None): # noqa: ANN001
+ nonlocal verify_calls
+ verify_calls += 1
+ return verify_calls > 1
+
+ monkeypatch.setattr(p, "_monotonic", _clock)
+ monkeypatch.setattr(p, "_verify_candidate", _verify)
+
+ async def _iter() -> AsyncIterator[AudioChunk]:
+ nonlocal now
+ # First candidate at t=0.3 rejects. The freshly re-armed recognizer
+ # hears the retry at t=0.6, inside the t=0.8 deadline. On the first
+ # chunk after that deadline the retained retry is verified. The old
+ # deaf-window implementation only begins listening again there and
+ # therefore cannot accumulate the three chunks needed for a wake.
+ for _ in range(9):
+ now += 0.1
+ yield _chunk()
+
+ fired = [wake async for wake in p.detect(_iter())]
+
+ assert fired == [keyword]
+ assert verify_calls == 2
+ assert p.stats()["candidates"] == 2
+ assert p.stats()["backpressure_windows"] == 1
+
+
# --- prewarmed verify-recognizer stock ------------------------------------------