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(voice): isolate realtime startup from worker starvation

Ruben Lütkea1c1531593be
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 12d6e9e414..896699e62c 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -3240,3 +3240,52 @@ usage/rate cap needs a process-local, self-expiring cooldown its factory
consults (mirror pair: `claude_quota_state` / `codex_quota_state`), and a
cross-WORKER fallback must probe the target's viability before spawning it —
never jump to a provider by name (AP-22).
+
+## BUG-043: Realtime bar appears but cannot accept speech while session assembly waits for the shared thread pool (HIGH, 2026-07-12)
+
+**Symptom.** Immediately after a confirmed wake, the desktop Jarvis Bar enters
+its listening state, but its microphone meter appears inert and the user gets
+no response when speaking naturally without a pause. Waiting several seconds
+before speaking can make the same session work. The delay varies with machine
+load and therefore looks provider-specific even though it affects every
+realtime provider.
+
+**Forensics.** In the live incident, wake confirmation and the listening bar
+arrived at 10:40:34. The voice session entered LISTENING at 10:40:35, but the
+first log line from `RealtimeVoiceSession` did not appear until 10:40:44. The
+user closed the still-unready session before any provider handshake began.
+The same session retained an open microphone throughout. A fresh-process
+benchmark assembled the wrapper in about 0.6 seconds, ruling out the provider
+handshake and normal credential resolution as the eight-to-nine-second gap.
+
+**Root cause.** `_active_realtime_session` queued the synchronous session
+wrapper build through `asyncio.to_thread`, which uses the process-wide default
+executor. Wake detectors and local STT also use that executor for native
+inference and recognizer replenishment. Under load, voice startup queued behind
+those workers. Capture-first buffering correctly preserved audio, but no
+realtime consumer could accept it until the unrelated shared-pool backlog
+cleared. This repeated the executor-starvation half of BUG-036 on a different
+voice-critical control path.
+
+**Fix.** `jarvis/speech/pipeline.py::_run_voice_critical_thread` runs realtime
+session assembly and desktop barge-in warmup on fresh daemon threads, outside
+the shared default executor. The existing ordering remains unchanged:
+microphone capture starts first, `VoiceSessionStarted` reveals the bar only
+after capture is armed, startup audio stays in `_SessionInputBuffer`, and the
+selected provider receives the preserved prefix as soon as its handshake
+completes. Provider selection and cross-family fallback remain capability- and
+credential-driven.
+
+**Guards.** `tests/unit/speech/test_realtime_mode.py` contains
+`test_realtime_builder_survives_exhausted_default_thread_pool`, which fills the
+default executor beyond its platform maximum and proves that realtime assembly
+still starts and completes. The existing
+`test_shared_input_keeps_meter_live_while_realtime_build_is_blocked` and
+`test_capture_precedes_listening_signal_and_preserves_startup_audio` retain the
+metering, ordering, and zero-loss guarantees.
+
+**Class rule.** A voice-critical recovery or startup control path must never
+depend on the same executor used by un-cancellable native inference. Opening
+the microphone early is necessary but not sufficient: every prerequisite for
+the eventual audio consumer must also remain schedulable while the default
+pool is exhausted.
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index c443d1f58e..3a88b791d9 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -135,6 +135,48 @@ if TYPE_CHECKING:
log = logging.getLogger("jarvis.speech.pipeline")
+async def _run_voice_critical_thread(fn: Callable[[], Any]) -> Any:
+ """Run blocking voice startup work outside the shared default executor.
+
+ Wake and local-STT implementations legitimately use ``asyncio.to_thread``
+ for native inference. A slow or un-cancellable inference can occupy every
+ default-pool worker, so queueing realtime session assembly there creates a
+ false LISTENING state: the microphone is buffered, but the provider cannot
+ begin accepting that audio until a worker becomes free. A fresh daemon
+ thread keeps this voice-critical control path independent and cannot hold
+ process shutdown open if a platform credential backend itself wedges.
+ """
+ loop = asyncio.get_running_loop()
+ future: asyncio.Future[Any] = loop.create_future()
+
+ def _resolve(setter: Callable[[Any], None], value: Any) -> None:
+ if not future.done():
+ setter(value)
+
+ def _runner() -> None:
+ try:
+ result = fn()
+ except BaseException as exc: # noqa: BLE001 - relay to async caller
+ callback = future.set_exception
+ value: Any = exc
+ else:
+ callback = future.set_result
+ value = result
+ try:
+ loop.call_soon_threadsafe(_resolve, callback, value)
+ except RuntimeError:
+ # The owning loop may close while an un-cancellable native call is
+ # still unwinding. The daemon thread can then finish silently.
+ pass
+
+ threading.Thread(
+ target=_runner,
+ name="jarvis-voice-critical",
+ daemon=True,
+ ).start()
+ return await future
+
+
async def _gather_timed(
named_thunks: list[tuple[str, Callable[[], Awaitable[Any]]]],
) -> tuple[dict[str, float], list[Any]]:
@@ -5869,7 +5911,7 @@ class SpeechPipeline:
async def _warm_barge_detector() -> None:
try:
- await asyncio.to_thread(barge_detector.warmup)
+ await _run_voice_critical_thread(barge_detector.warmup)
except Exception as exc: # noqa: BLE001 -- voice still works without local VAD
log.warning(
"Realtime desktop barge-in detector unavailable; "
@@ -6016,17 +6058,19 @@ class SpeechPipeline:
self._hangup_event.wait(), name=f"rt-hangup-{session_id}"
)
wait_tasks.add(hangup_task)
+ build_started_at = time.monotonic()
build_task = asyncio.create_task(
- asyncio.to_thread(
- build_realtime_session,
- cfg=self._config,
- bus=self._bus,
- session_id=session_id,
- send_binary=_send_binary,
- send_json=_send_json,
- half_duplex=True,
- surface="desktop",
- brain=getattr(self, "_brain", None),
+ _run_voice_critical_thread(
+ lambda: build_realtime_session(
+ cfg=self._config,
+ bus=self._bus,
+ session_id=session_id,
+ send_binary=_send_binary,
+ send_json=_send_json,
+ half_duplex=True,
+ surface="desktop",
+ brain=getattr(self, "_brain", None),
+ )
),
name=f"rt-build-{session_id}",
)
@@ -6039,8 +6083,11 @@ class SpeechPipeline:
build_task.cancel()
return HANGUP_HOTKEY
session = build_task.result()
+ build_ms = (time.monotonic() - build_started_at) * 1000.0
+ log.info("Realtime desktop session assembled in %.0f ms.", build_ms)
if session is None:
return None
+ handshake_started_at = time.monotonic()
handshake_task = asyncio.create_task(
session.handle_control(
{"type": "audio_start", "sample_rate": 16_000}
@@ -6057,6 +6104,12 @@ class SpeechPipeline:
handshake_task.cancel()
return HANGUP_HOTKEY
handshake_task.result()
+ log.info(
+ "Realtime desktop provider handshake completed in %.0f ms "
+ "(%.0f ms total startup).",
+ (time.monotonic() - handshake_started_at) * 1000.0,
+ (time.monotonic() - build_started_at) * 1000.0,
+ )
# Completed startup tasks must not remain in the live-session
# FIRST_COMPLETED set; either would make a healthy realtime
# session unwind into classic voice immediately.
diff --git a/tests/unit/speech/test_realtime_mode.py b/tests/unit/speech/test_realtime_mode.py
index a754071907..777a556d77 100644
--- a/tests/unit/speech/test_realtime_mode.py
+++ b/tests/unit/speech/test_realtime_mode.py
@@ -669,6 +669,38 @@ async def test_shared_input_keeps_meter_live_while_realtime_build_is_blocked(
mic_level.reset_for_tests()
+async def test_realtime_builder_survives_exhausted_default_thread_pool(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Wake/STT workers must never queue the realtime control path behind them."""
+ pipe = _pipe()
+ loop = asyncio.get_running_loop()
+ release_pool = threading.Event()
+ blockers = [loop.run_in_executor(None, release_pool.wait) for _ in range(64)]
+ await asyncio.sleep(0.1)
+
+ build_called = threading.Event()
+
+ def _build(**kwargs):
+ build_called.set()
+ return _FakeRealtimeSession(kwargs["send_binary"], kwargs["send_json"])
+
+ monkeypatch.setattr("jarvis.realtime.factory.build_realtime_session", _build)
+ buffer = pipeline_mod._SessionInputBuffer() # noqa: SLF001
+ try:
+ reason = await asyncio.wait_for(
+ pipe._active_realtime_session(input_buffer=buffer),
+ timeout=1.0,
+ )
+ finally:
+ release_pool.set()
+ await asyncio.gather(*blockers, return_exceptions=True)
+
+ assert reason == HANGUP_TURN_COMPLETE
+ assert build_called.is_set()
+
+
@pytest.mark.asyncio
async def test_hangup_cancels_realtime_start_while_builder_is_blocked(
monkeypatch: pytest.MonkeyPatch,