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(desktop): bound rejected wake verification load

Ruben Lütkebdf8903517a1
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 413cd6b917..caf05bcbd4 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3338,3 +3338,56 @@ shows a WebView before heavy process initialization must wait for a signal from
an actually rendered browser frame, never a server-side response, asset-read,
or fixed sleep. The wait must remain bounded so a broken GUI cannot deadlock a
headless or degraded backend.
+
+## BUG-045: Rejected Vosk wake candidates starve the desktop process (HIGH, 2026-07-13)
+
+**Symptom.** The desktop client became a featureless dark surface and Windows
+labelled the native window as not responding. Closing and reopening appeared to
+fix it, which made the failure look like a rare WebView startup race. The same
+failure mode can affect the GTK and Cocoa pywebview backends because the native
+window, local HTTP server, overlay, microphone, and wake detector share one
+Python process.
+
+**Forensic timeline.** The affected process started at 08:22:04 and served its
+health endpoint at 08:22:19. The screenshot was created at 08:29:32, so this was
+not the initial paint race from BUG-044. During the 140 seconds surrounding the
+capture, the log recorded 99 full Vosk verification-pass results. The later
+watchdogs independently reported a 2.5-second JarvisBar frame stall, 6.6 seconds
+without a microphone frame, and a local-listener recovery. Those simultaneous
+failures identify process-wide starvation rather than a React-only crash.
+
+**Root cause.** Vosk grammar mode intentionally favours recall and can map room
+speech onto the configured wake phrase. A clean rejection reset every streaming
+recognizer and immediately admitted another candidate. Each candidate could run
+an early visual verify, an authoritative grammar/free-decode pair, sibling-model
+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.
+
+The desktop startup path also logs whether the browser-originated shell-paint
+acknowledgment arrived or whether the bounded 12-second fallback released heavy
+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.
+`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.
+
+**Class rule.** A recall-biased candidate source needs rejection backpressure,
+not only a post-success cooldown. The suppressed interval must stop both the
+expensive verifier and the candidate/recognizer producer; rate-limiting only the
+last stage leaves the same resource storm alive one layer earlier.
diff --git a/jarvis/plugins/wake/vosk_kws_provider.py b/jarvis/plugins/wake/vosk_kws_provider.py
index 97f8539c52..99fe5dd8d2 100644
--- a/jarvis/plugins/wake/vosk_kws_provider.py
+++ b/jarvis/plugins/wake/vosk_kws_provider.py
@@ -122,6 +122,15 @@ _RING_SECONDS = 3.0
# Refractory period after a fired wake.
_COOLDOWN_S = 5.0
+# A rejected stage-one candidate is expected occasionally because grammar mode
+# deliberately favours recall. It must not immediately launch another pair of
+# full-window decoders: production forensics on 2026-07-13 captured 99 verify
+# 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.
+_REJECTED_CANDIDATE_BACKOFF_S = 2.0
+
# How much audio to let land in the ring AFTER a PARTIAL candidate before the
# confirm pass runs. A partial fires DURING the phrase (that is its virtue),
# but confirming at that instant hands the free decoder a truncated utterance
@@ -240,6 +249,7 @@ class VoskKwsProvider:
confirm_ratio: float = _CONFIRM_RATIO,
match_min_rms: float = _MATCH_MIN_RMS,
cooldown_s: float = _COOLDOWN_S,
+ rejected_candidate_backoff_s: float = _REJECTED_CANDIDATE_BACKOFF_S,
confirm_tail_s: float = _CONFIRM_TAIL_S,
# Production poll-loop parity: peak-normalize the confirm window to
# -3 dBFS (gain capped at 40 dB) exactly like the other wake paths.
@@ -269,6 +279,9 @@ class VoskKwsProvider:
self._confirm_ratio = max(float(confirm_ratio), structural_floor)
self._match_min_rms = float(match_min_rms)
self._cooldown_s = float(cooldown_s)
+ self._rejected_candidate_backoff_s = max(
+ 0.0, float(rejected_candidate_backoff_s)
+ )
self._confirm_tail_bytes = int(float(confirm_tail_s) * sample_rate) * 2
self._target_peak = float(target_peak)
self._max_gain = float(max_gain)
@@ -312,6 +325,8 @@ class VoskKwsProvider:
self._stat_gated_rms = 0
self._stat_suppressed_confirm = 0
self._stat_suppressed_cooldown = 0
+ self._stat_backpressure_windows = 0
+ self._stat_backpressure_chunks = 0
self._stat_fired = 0
self._stat_early_shown = 0
self._stat_early_retracted = 0
@@ -474,6 +489,8 @@ class VoskKwsProvider:
"gated_rms": self._stat_gated_rms,
"suppressed_confirm": self._stat_suppressed_confirm,
"suppressed_cooldown": self._stat_suppressed_cooldown,
+ "backpressure_windows": self._stat_backpressure_windows,
+ "backpressure_chunks": self._stat_backpressure_chunks,
"fired": self._stat_fired,
"early_shown": self._stat_early_shown,
"early_retracted": self._stat_early_retracted,
@@ -678,7 +695,7 @@ class VoskKwsProvider:
if w.get("word") in self._grammar_words
]
if self._phrase.lower() not in gres.get("text", "") or not gwords:
- log.info(
+ log.debug(
"vosk-kws: verify SUPPRESSED — re-score did not re-hear "
"%r (heard %r)",
self._phrase, gres.get("text", "")[:60],
@@ -686,7 +703,7 @@ class VoskKwsProvider:
return False
conf = min(w.get("conf", 0.0) for w in gwords)
if conf < self._min_final_conf:
- log.info(
+ log.debug(
"vosk-kws: verify SUPPRESSED — re-score conf %.2f < %.2f "
"for %r", conf, self._min_final_conf, self._phrase,
)
@@ -703,7 +720,7 @@ class VoskKwsProvider:
rms = float(np.sqrt(np.mean(segment * segment) + 1e-12)) if len(segment) else 0.0
if rms < self._match_min_rms:
self._stat_gated_rms += 1
- log.info(
+ log.debug(
"vosk-kws: verify SUPPRESSED — span rms %.4f < %.4f "
"(silence can never fire)", rms, self._match_min_rms,
)
@@ -723,7 +740,8 @@ class VoskKwsProvider:
)
return fail_open
ok = sound_confirm(free_local, self._phrase, ratio=self._confirm_ratio)
- log.info(
+ log_method = log.info if ok else log.debug
+ log_method(
"vosk-kws: verify %s — free ear heard %r at the candidate span "
"(conf=%.2f) vs phrase %r",
"OK" if ok else "SUPPRESSED",
@@ -757,6 +775,7 @@ class VoskKwsProvider:
# (union recall measured +38% on the fixture corpus, 2026-07-11).
recs = self._fresh_recs()
last_fire_t = 0.0
+ verify_not_before = 0.0
# Pending candidate: a PARTIAL hit waits for ``confirm_tail_s`` more
# audio before the confirm pass so the free decoder sees the WHOLE
# phrase, not a truncated one (E2E-measured recall trap). Finals skip
@@ -769,6 +788,18 @@ 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:
+ self._stat_backpressure_chunks += 1
+ continue
+ 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 wait so their
@@ -797,7 +828,12 @@ class VoskKwsProvider:
continue
self._stat_candidates += 1
if is_final and conf < self._min_final_conf:
- recs = self._fresh_recs()
+ self._stat_backpressure_windows += 1
+ verify_not_before = (
+ time.monotonic() + self._rejected_candidate_backoff_s
+ )
+ self._kick_replenish()
+ recs = {}
continue
if not is_final and self._confirm_tail_bytes > 0:
pending = (is_final, conf, hit_path)
@@ -813,11 +849,15 @@ class VoskKwsProvider:
self._ring_window(), self._pending_gen, hit_path
)
)
- # The early check just consumed prewarmed recognizers;
- # top the stock back up before the authoritative
- # verify needs its own pair (~0.6s from now).
- self._kick_replenish()
continue
+ # The early visual check and authoritative decision must not fan
+ # out two decoder pairs at once on a weak CPU. The 0.6 s tail
+ # normally lets the early check finish already, so this is a
+ # no-cost ordering guard in the common path.
+ if self._early_task is not None:
+ with contextlib.suppress(Exception):
+ await self._early_task
+ self._early_task = None
now = time.time()
window = self._ring_window()
confirmed = await asyncio.to_thread(
@@ -853,7 +893,27 @@ class VoskKwsProvider:
self._early_task = None
self._pending_gen += 1
await self._notify_early(False)
- recs = self._fresh_recs()
+ self._stat_backpressure_windows += 1
+ verify_not_before = (
+ time.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,
+ )
+ # 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 = {}
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/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 9fc973e9de..2ac981ac9d 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -754,7 +754,7 @@ class DesktopApp:
# WebServer → fastapi + every route schema, etc.) are DELIBERATELY NOT
# done here. They hold the GIL in long C-level blocks, which would
# starve the bootstrap loop and delay the UI shell. They are imported
- # AFTER ``wait_shell_served`` below — i.e. once the window has painted —
+ # AFTER ``wait_shell_painted`` below — i.e. once the window has painted —
# so the visible boot is never blocked by the import storm.
if prebound is not None:
# Fast-boot launcher path: the loop already exists and the bootstrap
@@ -848,7 +848,20 @@ class DesktopApp:
# as the visible shell paints, while a broken GUI can never deadlock the
# backend forever.
if self._bootstrap is not None:
- loop.run_until_complete(self._bootstrap.wait_shell_painted(timeout=12.0))
+ shell_painted = loop.run_until_complete(
+ self._bootstrap.wait_shell_painted(timeout=12.0)
+ )
+ from loguru import logger as _boot_logger
+
+ if shell_painted:
+ _boot_logger.info(
+ "Desktop boot shell painted; heavy initialization released."
+ )
+ else:
+ _boot_logger.warning(
+ "Desktop boot shell paint was not acknowledged within 12s; "
+ "releasing heavy initialization through the bounded fallback."
+ )
# Fire the heavy OpenWakeWord/onnxruntime import now, in a daemon thread,
# before the WebServer + brain build + subsystem boot storm grab the
@@ -896,7 +909,7 @@ class DesktopApp:
from jarvis.mcp.registry import MCPRegistry
from jarvis.state.chat_store import ChatStore, default_chats_db_path
from jarvis.state.supervisor import Supervisor
- from jarvis.ui.web.server import WebServer # lazy, vermeidet Circular
+ from jarvis.ui.web.server import WebServer # lazy to avoid a circular import
_db_mark("pre_webserver")
# Build the FastAPI app + all routes (~1 s, CPU-bound) in a worker thread
@@ -3547,7 +3560,7 @@ class DesktopApp:
asyncio.run_coroutine_threadsafe(_pty_cleanup(), loop).result(timeout=2.0)
except Exception: # noqa: BLE001
pass
- # Phase 9.8: Overlay-Subprocess stoppen BEVOR server.stop().
+ # Phase 9.8: stop the overlay subprocess BEFORE server.stop().
try:
from jarvis.overlay.integration import stop_overlay
asyncio.run_coroutine_threadsafe(stop_overlay(), loop).result(timeout=2.0)
@@ -3566,7 +3579,7 @@ class DesktopApp:
try:
fut.result(timeout=3.0)
except Exception: # noqa: BLE001
- # Server-stop darf haengen — wir stoppen den Loop hart.
+ # Server shutdown may hang; the event loop still stops forcibly.
pass
except Exception: # noqa: BLE001
pass
diff --git a/tests/unit/plugins/wake/test_vosk_kws_provider.py b/tests/unit/plugins/wake/test_vosk_kws_provider.py
index fa785fb6d8..6772c69874 100644
--- a/tests/unit/plugins/wake/test_vosk_kws_provider.py
+++ b/tests/unit/plugins/wake/test_vosk_kws_provider.py
@@ -15,6 +15,8 @@ up. What is pinned here:
- The grammar re-score and the free decode run CONCURRENTLY (spawn-latency
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.
"""
from __future__ import annotations
@@ -438,6 +440,52 @@ async def test_cooldown_suppresses_immediate_refire(fake_vosk) -> None:
assert p.stats()["suppressed_cooldown"] >= 1
+async def test_rejected_candidate_storm_is_backpressured(
+ fake_vosk, monkeypatch
+) -> 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
+ process-wide CPU storm even if full verification were rate-limited.
+ """
+ p = VoskKwsProvider(
+ "Hey Nova",
+ model_path="fake",
+ keyword="nova",
+ confirm_tail_s=0.0,
+ rejected_candidate_backoff_s=60.0,
+ )
+ p._ensure_model()
+ fake_vosk["model"].free_text = "unrelated room speech"
+
+ verify_calls = 0
+ fresh_rec_calls = 0
+ original_verify = p._verify_candidate
+ original_fresh_recs = p._fresh_recs
+
+ def _counted_verify(window, model_path=None): # noqa: ANN001
+ nonlocal verify_calls
+ verify_calls += 1
+ return original_verify(window, model_path)
+
+ def _counted_fresh_recs():
+ nonlocal fresh_rec_calls
+ fresh_rec_calls += 1
+ return original_fresh_recs()
+
+ monkeypatch.setattr(p, "_verify_candidate", _counted_verify)
+ monkeypatch.setattr(p, "_fresh_recs", _counted_fresh_recs)
+
+ fired = await _run_detect(p, [_chunk() for _ in range(200)])
+
+ assert fired == []
+ assert verify_calls == 1
+ assert fresh_rec_calls == 1
+ assert p.stats()["backpressure_windows"] == 1
+ assert p.stats()["backpressure_chunks"] > 100
+
+
# --- prewarmed verify-recognizer stock ------------------------------------------