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(realtime): never tear down a shared recognizer under live inference

rubenluetke10-beepbc1831e3c13a
diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.py
index 8e7a810aff..53e46c493b 100644
--- a/jarvis/realtime/input_transcription.py
+++ b/jarvis/realtime/input_transcription.py
@@ -138,6 +138,23 @@ _RECOGNITION_TIMEOUT_MAX_S = 90.0
_RECOVER_AFTER_FAILURES = 2
_RECOVER_AFTER_BUSY = 3
+# A SET busy flag is not evidence of a wedge. Since one engine is shared
+# process-wide, the ordinary meaning of "busy" is that ANOTHER session is inside
+# a perfectly healthy recognition — the cache doing exactly its job. Counting
+# those skips toward a rebuild made routine contention indistinguishable from a
+# wedge: the second session evicted the shared engine and tore the backend down
+# while the first was still inside an inference, so that utterance was lost, both
+# sessions re-paid a multi-second model load, and the weights were briefly
+# resident twice.
+#
+# What DOES prove a wedge is wall-clock. Every recognition runs under its own
+# ``asyncio.wait_for`` bound and every exit path — success, timeout, error,
+# cancellation — clears the flag, so a busy span that outlives the holder's own
+# bound by this margin cannot still be running: the holder is gone (its loop went
+# away mid-flight, or a native worker was abandoned) and the flag will never
+# clear by itself. Only that span may rebuild the engine.
+_BUSY_WEDGE_GRACE_S = 10.0
+
# Control events (``speech_started``) are grounding evidence, not telemetry: a
# dropped one makes the adapter treat the next genuine answer as a self-echo and
# interrupt it. The queue is therefore bounded by EVICTING the oldest droppable
@@ -258,10 +275,19 @@ class _SharedRecognizer:
once two sessions can share one cached backend, a per-object flag cannot see
the other caller, and entering a native engine twice at once is what wedges
it permanently (AP-24).
+
+ ``busy_since`` / ``busy_bound_s`` travel with the flag for the same reason:
+ the transcriber that has to decide whether a busy engine is merely serving
+ someone else or is genuinely wedged is a DIFFERENT object from the one that
+ took the guard, so the evidence cannot live on the holder.
"""
backend: Any
busy: bool = False
+ #: Monotonic instant the in-flight recognition took the guard, and the
+ #: timeout it runs under. Both are meaningless while ``busy`` is False.
+ busy_since: float = 0.0
+ busy_bound_s: float = 0.0
# Building the recognizer is the expensive half of opening a realtime call — a
@@ -395,6 +421,9 @@ class LocalInputTranscriber:
# Held here only while this transcriber owns its engine alone; a cached
# engine carries the flag itself (see ``_recognition_busy``).
self._local_recognition_busy = False
+ # The unshared mirror of the shared record's busy timestamps.
+ self._local_busy_since = 0.0
+ self._local_busy_bound_s = 0.0
# Serializes only the CONSTRUCTION of the recognizer, so two utterances
# racing at session start cannot load the model twice. Never held across
# an inference: a model load inside the inference guard made the first
@@ -591,11 +620,48 @@ class LocalInputTranscriber:
@_recognition_busy.setter
def _recognition_busy(self, value: bool) -> None:
+ # Without a caller-supplied bound the only honest assumption is the
+ # widest one a recognition can legitimately run under.
+ self._set_recognition_busy(bool(value), bound_s=_RECOGNITION_TIMEOUT_MAX_S)
+
+ def _set_recognition_busy(self, busy: bool, *, bound_s: float) -> None:
+ """Flip the in-flight guard and stamp what the holder is bounded by.
+
+ Written onto the shared cache entry whenever there is one, because the
+ reader of these fields is the OTHER transcriber on the same engine.
+ """
+ since = time.monotonic() if busy else 0.0
+ bound = float(bound_s) if busy else 0.0
+ shared = self._shared
+ if shared is not None:
+ shared.busy = busy
+ shared.busy_since = since
+ shared.busy_bound_s = bound
+ else:
+ self._local_recognition_busy = busy
+ self._local_busy_since = since
+ self._local_busy_bound_s = bound
+
+ def _busy_wedge_state(self) -> tuple[float, bool]:
+ """How long the guard has been held, and whether that proves a wedge.
+
+ Returns ``(0.0, False)`` when nothing is in flight. A span still inside
+ the holder's own bound (plus ``_BUSY_WEDGE_GRACE_S``) is ordinary
+ sharing, never a reason to tear an engine down underneath its user.
+ """
shared = self._shared
if shared is not None:
- shared.busy = bool(value)
+ busy = shared.busy
+ since = shared.busy_since
+ bound = shared.busy_bound_s
else:
- self._local_recognition_busy = bool(value)
+ busy = self._local_recognition_busy
+ since = self._local_busy_since
+ bound = self._local_busy_bound_s
+ if not busy or since <= 0.0:
+ return 0.0, False
+ span = max(0.0, time.monotonic() - since)
+ return span, span >= bound + _BUSY_WEDGE_GRACE_S
async def warm(self) -> bool:
"""Build (and prime) the recognizer off the first utterance's path.
@@ -705,8 +771,26 @@ class LocalInputTranscriber:
self._consecutive_failures = 0
self._consecutive_busy = 0
- async def _note_busy(self) -> None:
- """A skipped call is not proof the engine is broken — a streak is."""
+ async def _note_busy(self, *, in_flight: bool = False) -> None:
+ """A skipped call is not proof the engine is broken — a streak is.
+
+ ``in_flight`` marks the skip THIS transcriber's own guard produced, i.e.
+ "the engine is inside a recognition right now". On a shared engine that
+ is usually another session's healthy call, so such a skip only counts
+ toward a rebuild once the busy span outlives the holder's own bound. A
+ provider reporting its own engine busy while our guard is clear needs no
+ such proof: nobody legitimate is inside it.
+ """
+ if in_flight:
+ span, wedged = self._busy_wedge_state()
+ if not wedged:
+ log.debug(
+ "Local input transcription skipped a segment: the shared "
+ "recognizer has been serving another holder for %.1f s, "
+ "which is normal sharing rather than a wedged engine",
+ span,
+ )
+ return
self._consecutive_busy += 1
if self._consecutive_busy >= _RECOVER_AFTER_BUSY:
await self._recover_recognizer(
@@ -729,9 +813,16 @@ class LocalInputTranscriber:
of the call" signature. Providers that own such an engine expose
``recover()``; the reference is dropped either way, so the next
utterance constructs a fresh one.
+
+ Dropping the reference is safe for everyone. ``recover()`` is not: it
+ tears the model down under whoever is inside it, so it is withheld while
+ a holder is still within its own bound — this transcriber cannot see the
+ other session, only the guard it left behind.
"""
stt = self._stt
shared = self._shared
+ in_flight = self._recognition_busy
+ busy_span, wedged = self._busy_wedge_state()
if shared is not None:
# Dropping only this reference would leave the wedged engine in the
# process-wide cache, and the next session would be handed it as if
@@ -751,6 +842,16 @@ class LocalInputTranscriber:
recover = getattr(stt, "recover", None)
if not callable(recover):
return
+ if in_flight and not wedged:
+ log.warning(
+ "Not tearing down the local input recognizer after %s: it is "
+ "%.1f s into a recognition for another holder and still inside "
+ "its own bound. The cache entry was retired, so the next "
+ "utterance builds a fresh engine instead.",
+ reason,
+ busy_span,
+ )
+ return
try:
await asyncio.to_thread(recover)
except Exception: # noqa: BLE001 - the dropped reference is the real fix
@@ -866,7 +967,7 @@ class LocalInputTranscriber:
return ""
if self._recognition_busy:
- await self._note_busy()
+ await self._note_busy(in_flight=True)
raise RecognizerBusy(
"the local recognizer is already transcribing another segment"
)
@@ -886,12 +987,14 @@ class LocalInputTranscriber:
# output-transcript recovery. Counting it only in the caller above left
# a wedge first hit by recovery invisible to the leash, so the self-heal
# needed four lost utterances instead of two.
- self._recognition_busy = True
+ #
+ # The guard is taken WITH this call's own timeout, so a second session
+ # that finds the engine busy can tell "still inside its bound" from
+ # "long past every bound it had", instead of reading the flag alone.
+ bound_s = self._recognition_timeout_s(payload, target_rate)
+ self._set_recognition_busy(True, bound_s=bound_s)
try:
- result = await asyncio.wait_for(
- stt.transcribe(chunks()),
- timeout=self._recognition_timeout_s(payload, target_rate),
- )
+ result = await asyncio.wait_for(stt.transcribe(chunks()), timeout=bound_s)
except TimeoutError:
self._recognition_busy = False
await self._note_failure("timeout")
diff --git a/tests/unit/realtime/test_input_transcription_shared_wedge.py b/tests/unit/realtime/test_input_transcription_shared_wedge.py
new file mode 100644
index 0000000000..44b8a40874
--- /dev/null
+++ b/tests/unit/realtime/test_input_transcription_shared_wedge.py
@@ -0,0 +1,279 @@
+"""Sharing one recognizer must not be mistaken for a wedged one.
+
+The recognizer cache is process-wide, so "the engine is busy" has two very
+different meanings. Usually it means ANOTHER session is inside a perfectly
+healthy recognition — the cache doing its job. Rarely it means the guard was
+left set by a holder that is never coming back, which is the AP-24 wedge the
+self-heal exists for.
+
+Reading the flag alone conflated them: the second session counted three skips,
+evicted the shared engine and called ``recover()`` on the backend WHILE the
+first session was still inside an inference. That aborted a live recognition,
+made both sessions re-pay a multi-second model load, and left the weights
+briefly resident twice — a GPU-sized bill for a cache hit.
+
+So the tests below pin the discriminator: wall-clock against the holder's own
+timeout bound, never the flag on its own.
+"""
+
+from __future__ import annotations
+
+import math
+import struct
+import time
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.core.config import STTConfig
+from jarvis.realtime import input_transcription as module
+from jarvis.realtime.input_transcription import LocalInputTranscriber, RecognizerBusy
+
+RATE = 24_000
+CHUNK_SAMPLES = 480 # 20 ms
+
+
+def _loud(samples: int = CHUNK_SAMPLES) -> bytes:
+ return b"".join(
+ struct.pack("<h", int(9000 * math.sin(2 * math.pi * 180 * n / RATE)))
+ for n in range(samples)
+ )
+
+
+SEGMENT = _loud() * 40
+
+
+class TranscribeBusy(RuntimeError):
+ """The class NAME the local Whisper provider raises for its own guard.
+
+ Recognized by shape, never by import, so the realtime path stays importable
+ without the local-voice extra. The name is load-bearing here.
+ """
+
+
+class _SharedEngine:
+ """A recognizer stand-in that counts every teardown it is put through."""
+
+ native_sample_rate = 16_000
+
+ def __init__(self) -> None:
+ self.recover_calls = 0
+ self.transcribe_calls = 0
+
+ async def transcribe(self, chunks: Any) -> Any:
+ self.transcribe_calls += 1
+ async for _ in chunks:
+ pass
+ return SimpleNamespace(text="heard it")
+
+ def recover(self) -> None:
+ self.recover_calls += 1
+
+
[email protected](autouse=True)
+def _clean_recognizer_cache():
+ module._reset_for_tests()
+ yield
+ module._reset_for_tests()
+
+
+def engine(monkeypatch: pytest.MonkeyPatch) -> _SharedEngine:
+ """One engine behind the configured STT, so both sessions share it."""
+ built = _SharedEngine()
+ config = type("_Config", (), {"stt": STTConfig(provider="groq-api", language="en")})
+
+ monkeypatch.setattr(
+ "jarvis.core.config.load_config", lambda *a, **k: config, raising=True
+ )
+ monkeypatch.setattr(
+ "jarvis.plugins.stt.build_stt_from_config",
+ lambda *a, **k: built,
+ raising=True,
+ )
+ return built
+
+
+async def _two_sessions_on_one_engine() -> tuple[
+ LocalInputTranscriber, LocalInputTranscriber
+]:
+ first = LocalInputTranscriber(sample_rate=RATE, language="de")
+ second = LocalInputTranscriber(sample_rate=RATE, language="de")
+ assert await first.warm() is True
+ assert await second.warm() is True
+ assert first._shared is second._shared is not None
+ return first, second
+
+
+# -- (a) contention is not a wedge -------------------------------------
+
+
+async def test_a_busy_shared_engine_is_never_torn_down_under_its_user(
+ engine: _SharedEngine,
+) -> None:
+ """The headline regression: one session's cache hit killed the other's turn."""
+ holder, other = await _two_sessions_on_one_engine()
+ shared = holder._shared
+ assert shared is not None
+
+ # Session A is two seconds into a recognition bounded well above that.
+ holder._set_recognition_busy(True, bound_s=30.0)
+ shared.busy_since = time.monotonic() - 2.0
+
+ # Session B keeps arriving and keeps being skipped — far past the streak
+ # that used to trigger a rebuild.
+ for _ in range(module._RECOVER_AFTER_BUSY + 2):
+ with pytest.raises(RecognizerBusy):
+ await other.transcribe_audio(SEGMENT, sample_rate=RATE)
+
+ assert engine.recover_calls == 0
+ assert other._consecutive_busy == 0
+ # The healthy engine stays cached and stays attached to both sessions.
+ assert len(module._stt_cache) == 1
+ assert other._shared is shared
+ assert other._stt is engine
+ assert shared.busy is True # A's in-flight call was left alone
+
+ await holder.close()
+ await other.close()
+
+
+async def test_the_other_session_is_heard_again_once_the_holder_returns(
+ engine: _SharedEngine,
+) -> None:
+ """Skipping is a pause, not a deafness: no rebuild, so no cold start."""
+ holder, other = await _two_sessions_on_one_engine()
+
+ holder._set_recognition_busy(True, bound_s=30.0)
+ for _ in range(module._RECOVER_AFTER_BUSY):
+ with pytest.raises(RecognizerBusy):
+ await other.transcribe_audio(SEGMENT, sample_rate=RATE)
+ holder._set_recognition_busy(False, bound_s=0.0)
+
+ assert await other.transcribe_audio(SEGMENT, sample_rate=RATE) == "heard it"
+ assert engine.recover_calls == 0
+ assert engine.transcribe_calls == 1
+
+ await holder.close()
+ await other.close()
+
+
+# -- (b) an overdue guard IS a wedge -----------------------------------
+
+
+async def test_a_guard_held_past_every_bound_rebuilds_the_engine(
+ engine: _SharedEngine,
+) -> None:
+ """A holder that will never clear the flag must not deafen the process."""
+ holder, other = await _two_sessions_on_one_engine()
+ shared = holder._shared
+ assert shared is not None
+
+ holder._set_recognition_busy(True, bound_s=5.0)
+ shared.busy_since = time.monotonic() - (5.0 + module._BUSY_WEDGE_GRACE_S + 1.0)
+
+ for _ in range(module._RECOVER_AFTER_BUSY):
+ with pytest.raises(RecognizerBusy):
+ await other.transcribe_audio(SEGMENT, sample_rate=RATE)
+
+ assert engine.recover_calls == 1
+ assert not module._stt_cache
+ assert other._stt is None
+ assert other._shared is None
+
+ await holder.close()
+ await other.close()
+
+
+async def test_the_wedge_threshold_scales_with_the_holders_own_timeout(
+ engine: _SharedEngine,
+) -> None:
+ """A long segment's recognition is allowed to take long — nothing else is."""
+ holder, other = await _two_sessions_on_one_engine()
+ shared = holder._shared
+ assert shared is not None
+
+ # Exactly the span of a wedge under a five-second bound, but this holder
+ # runs under a sixty-second one, so it is still healthy.
+ holder._set_recognition_busy(True, bound_s=60.0)
+ shared.busy_since = time.monotonic() - (5.0 + module._BUSY_WEDGE_GRACE_S + 1.0)
+
+ for _ in range(module._RECOVER_AFTER_BUSY):
+ with pytest.raises(RecognizerBusy):
+ await other.transcribe_audio(SEGMENT, sample_rate=RATE)
+
+ assert engine.recover_calls == 0
+ assert len(module._stt_cache) == 1
+
+ await holder.close()
+ await other.close()
+
+
+async def test_a_recovery_from_another_cause_still_spares_a_live_inference(
+ engine: _SharedEngine,
+) -> None:
+ """Eviction is safe for everyone; ``recover()`` is not.
+
+ A rebuild triggered by this session's OWN failures must still not tear the
+ model down under a holder it cannot see. Retiring the cache entry is enough:
+ the next utterance builds a fresh engine either way.
+ """
+ holder, other = await _two_sessions_on_one_engine()
+
+ holder._set_recognition_busy(True, bound_s=30.0)
+ await other._recover_recognizer("2 consecutive failures (ValueError)")
+
+ assert engine.recover_calls == 0
+ assert not module._stt_cache # nobody is handed the suspect engine again
+ assert other._stt is None
+
+ await holder.close()
+ await other.close()
+
+
+# -- (c) the single-session wedge path is unchanged --------------------
+
+
+class _StuckEngine:
+ """One session's own engine with an abandoned worker thread inside it.
+
+ It reports itself busy — our guard is clear, so nobody legitimate is in
+ there — until ``recover()`` rebuilds it. That report needs no wall-clock
+ proof and must keep healing after the historical streak.
+ """
+
+ native_sample_rate = 16_000
+
+ def __init__(self) -> None:
+ self.wedged = True
+ self.recover_calls = 0
+
+ async def transcribe(self, chunks: Any) -> Any:
+ async for _ in chunks:
+ pass
+ if self.wedged:
+ raise TranscribeBusy("a transcription is already in flight on this model")
+ return SimpleNamespace(text="recovered engine works")
+
+ def recover(self) -> None:
+ self.recover_calls += 1
+ self.wedged = False
+
+
+async def test_a_providers_own_busy_report_still_rebuilds_after_the_streak() -> None:
+ stuck = _StuckEngine()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stuck)
+ assert await transcriber.warm() is True
+
+ for _ in range(module._RECOVER_AFTER_BUSY):
+ with pytest.raises(TranscribeBusy):
+ await transcriber.transcribe_audio(SEGMENT, sample_rate=RATE)
+
+ assert stuck.recover_calls == 1
+ # ...and the next utterance is heard again.
+ assert (
+ await transcriber.transcribe_audio(SEGMENT, sample_rate=RATE)
+ == "recovered engine works"
+ )
+ await transcriber.close()