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): make the subscription voice recognizer survive past the first turn

rubenluetke10-beepc456e8d63cef
diff --git a/jarvis/realtime/input_transcription.py b/jarvis/realtime/input_transcription.py
index 98e32a265f..e32e4a7b5c 100644
--- a/jarvis/realtime/input_transcription.py
+++ b/jarvis/realtime/input_transcription.py
@@ -15,6 +15,14 @@ what was said, so none of the integrations fire.
So Jarvis transcribes the microphone audio it already owns, with the
recognizer the user already configured, and emits the same events every
other provider emits. "It is just another provider" then holds.
+
+On such a transport this class is also the GROUNDING evidence: the adapter
+authorizes a provider response only when a fresh local ``speech_started``
+proves a human spoke, and otherwise rejects AND interrupts that response. So
+every way this class can go quiet — a wedged engine, a mis-sampled buffer, a
+mic below a hardcoded gate, a dropped control event — is indistinguishable
+from "the assistant never answers again". Everything below is written for that
+consequence, not merely for a missing transcript.
"""
from __future__ import annotations
@@ -22,6 +30,7 @@ from __future__ import annotations
import asyncio
import logging
import time
+from collections import deque
from dataclasses import dataclass
from typing import Any
@@ -30,8 +39,15 @@ log = logging.getLogger(__name__)
# Endpointing: deliberately simple and dependency-free. The far end runs its
# own turn detection for the model's benefit; this endpointer only has to
# decide when to hand one utterance to the recognizer.
+#
+# These are the CONFIGURED ceilings. The gate actually applied is calibrated
+# down against the session's own noise floor — see ``_NoiseFloor``.
_SPEECH_RMS = 700.0
_SILENCE_RMS = 500.0
+# The hysteresis between "speech" and "silence" is a RATIO, not two independent
+# numbers, so a calibrated speech gate carries the silence gate down with it and
+# the two can never cross.
+_SILENCE_RATIO = _SILENCE_RMS / _SPEECH_RMS
_SPEECH_START_MS = 120
_SILENCE_END_MS = 700
_PREROLL_MS = 300
@@ -42,6 +58,30 @@ _MAX_UTTERANCE_MS = 20_000
# that Jarvis would treat as something the user said.
_MIN_VOICED_MS = 300
+# Session-relative noise-floor calibration (AP-23; the same defect and the same
+# fix already shipped one layer up for the wake gates —
+# ``jarvis.speech.rolling_whisper_wake.SessionNoiseFloor``). The absolute gates
+# above were chosen on one machine. On a quieter input path real speech lands
+# below them, so ``_begin_utterance`` never fires — and because a missing
+# ``speech_started`` is missing GROUNDING, the adapter then rejects and
+# interrupts every provider response: the user talks and is cut off forever.
+#
+# effective = min(configured_absolute, max(K * floor, absolute_minimum))
+#
+# Strictly LOWER-ONLY. ``_FLOOR_INIT`` is deliberately pessimistic so a session
+# STARTS at the legacy absolutes (K * init >= _SPEECH_RMS) and relaxes only once
+# measured silence proves the mic is quieter — every historical measurement and
+# pin therefore still holds on a normal mic.
+#
+# The word-agnostic discriminator (AP-27) survives BY CONSTRUCTION: silence and
+# speaker echo sit AT the floor while the gate sits at ``_SPEECH_GATE_K`` x the
+# floor, at ANY mic gain. Nothing here looks at what was said — only at energy.
+_FLOOR_INIT = 600.0
+_FLOOR_ABS_MIN = 7.0 # a muted mic's numeric noise must never define a floor
+_FLOOR_ALPHA = 0.05 # EMA weight per quiet chunk
+_FLOOR_QUIET_BAND = 1.5 # a chunk this close to the floor counts as quiet
+_SPEECH_GATE_K = 1.2
+_SPEECH_GATE_ABS_MIN = 50.0
# How long after the microphone last carried real speech a server-side user
# transcript is still plausible. The far end transcribes with its own latency,
@@ -49,14 +89,63 @@ _MIN_VOICED_MS = 300
# the user is silent or while the assistant itself is talking.
_SERVER_TRANSCRIPT_GRACE_MS = 2_000
+# Recognizer input rate. Providers that pin one declare it; the in-tree ones all
+# expect 16 kHz (the local Whisper provider REJECTS anything else outright, the
+# local Nemotron decoder silently mis-reads it, and the cloud providers wrap
+# whatever rate they are handed into a WAV header), so 16 kHz is the documented
+# fallback and the capture rate is resampled to it rather than passed through.
+_RECOGNIZER_RATE_FALLBACK = 16_000
+_RECOGNIZER_RATE_ATTRS = ("native_sample_rate", "input_sample_rate", "sample_rate")
+
+# A recognizer call is bounded, and the bound scales with the audio handed in:
+# a flat ceiling either aborts a legitimate long segment or lets a wedged engine
+# hold the path for as long as the longest legitimate one (AP-24).
+_RECOGNITION_TIMEOUT_BASE_S = 6.0
+_RECOGNITION_TIMEOUT_PER_AUDIO_S = 1.5
+_RECOGNITION_TIMEOUT_MAX_S = 90.0
+# A timed-out call leaves an UNCANCELLABLE worker thread inside the native
+# engine, so the next call finds it occupied. Rebuilding after this many
+# consecutive hard failures is the only way back (AP-24 / BUG-036); a
+# slow-but-alive engine that merely reports "busy" gets a longer leash, exactly
+# as the wake poll loop gives it.
+_RECOVER_AFTER_FAILURES = 2
+_RECOVER_AFTER_BUSY = 3
+
+# 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
+# event, never by refusing whatever arrived last.
+_EVENT_QUEUE_MAX = 256
+
+SPEECH_STARTED = "speech_started"
+TRANSCRIPT = "transcript"
+TRANSCRIPT_FAILED = "transcript_failed"
+#: An utterance the endpointer opened but then discarded as too short to be
+#: speech. It carries no text and must never become a turn — but it must not
+#: vanish either: ``speech_started`` already told the transport a human spoke,
+#: and a boundary that never arrives is a turn that hangs.
+SPEECH_DISCARDED = "speech_discarded"
+
+
+class RecognizerBusy(RuntimeError):
+ """A recognition was skipped because this recognizer is already in use.
+
+ Deliberately a SKIP rather than a wait (AP-24): the configured STT may own a
+ native engine that a second concurrent entry wedges permanently, and queueing
+ behind a call that has already hung would make every later utterance hang too.
+ """
+
@dataclass(frozen=True, slots=True)
class InputTranscriptEvent:
"""One normalized user-speech event for the provider event stream."""
- kind: str # "speech_started" | "transcript" | "transcript_failed"
+ kind: str # see the module-level kind constants
text: str = ""
is_final: bool = False
+ # Voiced milliseconds behind this event. Diagnosis only — no decision hangs
+ # on it, but a discarded utterance is unreadable without it.
+ voiced_ms: int = 0
def _rms(pcm: bytes) -> float:
@@ -70,16 +159,71 @@ def _rms(pcm: bytes) -> float:
return float(np.sqrt(np.mean(samples.astype(np.float32) ** 2)))
+class _NoiseFloor:
+ """EMA estimate of this session's noise floor over per-chunk RMS values.
+
+ Ported from ``jarvis.speech.rolling_whisper_wake.SessionNoiseFloor`` rather
+ than imported: that module imports the faster-whisper provider at module
+ level, and the realtime path must stay usable on a base install without the
+ local-voice extra.
+
+ Only chunks in the quiet band (below ``quiet_band`` x the current floor)
+ update the estimate, so speech never drags the floor up; the floor may drift
+ up slowly when the ROOM gets noisier (each step is bounded by the band) and
+ is clamped to ``abs_min`` so a muted mic cannot zero it.
+ """
+
+ def __init__(
+ self,
+ initial: float = _FLOOR_INIT,
+ abs_min: float = _FLOOR_ABS_MIN,
+ alpha: float = _FLOOR_ALPHA,
+ quiet_band: float = _FLOOR_QUIET_BAND,
+ ) -> None:
+ self._floor = float(initial)
+ self._abs_min = float(abs_min)
+ self._alpha = float(alpha)
+ self._quiet_band = float(quiet_band)
+
+ @property
+ def floor(self) -> float:
+ return self._floor
+
+ def update(self, rms: float) -> None:
+ if rms < self._floor * self._quiet_band:
+ floor = (1.0 - self._alpha) * self._floor + self._alpha * rms
+ self._floor = max(floor, self._abs_min)
+
+ def gate(self, configured: float, k: float, abs_min: float) -> float:
+ """Lower-only effective gate: never above ``configured``."""
+ if configured <= 0.0:
+ return configured
+ return min(configured, max(k * self._floor, abs_min))
+
+
class LocalInputTranscriber:
"""Turn microphone PCM into ``input_transcript`` events."""
- def __init__(self, *, sample_rate: int = 24_000, stt_factory: Any = None) -> None:
+ def __init__(
+ self,
+ *,
+ sample_rate: int = 24_000,
+ stt_factory: Any = None,
+ recognizer_sample_rate: int | None = None,
+ ) -> None:
self._sample_rate = sample_rate
self._stt_factory = stt_factory
- self._stt: Any = None
- self._events: asyncio.Queue[InputTranscriptEvent | None] = asyncio.Queue(
- maxsize=64
+ self._recognizer_rate_override = (
+ int(recognizer_sample_rate) if recognizer_sample_rate else None
)
+ self._recognizer_rate: int | None = None
+ self._stt: Any = None
+ # Control events must survive a stalled consumer, so this is a deque
+ # evicted by policy rather than an asyncio.Queue that refuses whatever
+ # arrives last (see ``_emit``). Everything here runs on one event loop,
+ # so no cross-thread synchronization is required.
+ self._events: deque[InputTranscriptEvent | None] = deque()
+ self._event_ready = asyncio.Event()
self._preroll: list[bytes] = []
self._preroll_ms = 0
self._utterance: list[bytes] = []
@@ -89,13 +233,24 @@ class LocalInputTranscriber:
self._silence_ms = 0
self._in_speech = False
self._last_speech_end = 0.0
+ self._floor = _NoiseFloor()
self._tasks: set[asyncio.Task[None]] = set()
# A configured recognizer may wrap a native inference engine. Those
# engines are not safe to enter concurrently (AP-24), and output
- # transcript recovery can overlap the tail of input recognition.
- self._recognition_lock = asyncio.Lock()
+ # transcript recovery can overlap the tail of input recognition. The
+ # guard is a non-blocking flag, NOT a lock: a second caller skips, so a
+ # call that has hung can never make every later call hang behind it.
+ self._recognition_busy = False
+ # 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
+ # output-transcript recovery time out by construction.
+ self._build_lock = asyncio.Lock()
+ self._consecutive_failures = 0
+ self._consecutive_busy = 0
self._closed = False
self._unavailable_logged = False
+ self._rate_mismatch_logged = False
# -- voice activity ------------------------------------------------
def speech_recently(self, grace_ms: int = _SERVER_TRANSCRIPT_GRACE_MS) -> bool:
@@ -114,26 +269,46 @@ class LocalInputTranscriber:
return False
return (time.monotonic() - self._last_speech_end) * 1000.0 <= grace_ms
+ @property
+ def noise_floor(self) -> float:
+ """The session's measured noise floor (int16 RMS). Diagnosis only."""
+ return self._floor.floor
+
+ def _speech_gate(self) -> float:
+ return self._floor.gate(_SPEECH_RMS, _SPEECH_GATE_K, _SPEECH_GATE_ABS_MIN)
+
# -- feeding -------------------------------------------------------
def feed(self, pcm: bytes, sample_rate: int) -> None:
"""Accept one microphone chunk; never blocks the audio path."""
if self._closed or not pcm:
return
if sample_rate != self._sample_rate:
- # The pipeline is fixed at one rate per session; a mismatch means
- # a caller bug, and guessing would corrupt every duration below.
- log.debug(
- "Local input transcription ignoring a %d Hz chunk (session is %d Hz)",
- sample_rate,
- self._sample_rate,
- )
+ # The pipeline is fixed at one rate per session; a mismatch means a
+ # caller bug that silences this recognizer COMPLETELY — and with it
+ # the grounding evidence the transport needs to answer at all. Say
+ # so once, at a level that is actually visible (AP-30): a per-chunk
+ # debug line is indistinguishable from working.
+ if not self._rate_mismatch_logged:
+ self._rate_mismatch_logged = True
+ log.warning(
+ "Local input transcription is dropping every microphone "
+ "chunk: the session sends %d Hz but this recognizer was "
+ "opened for %d Hz. No user transcript can be produced "
+ "until the two rates agree.",
+ sample_rate,
+ self._sample_rate,
+ )
return
duration_ms = int(len(pcm) / 2 / self._sample_rate * 1000)
if duration_ms <= 0:
return
level = _rms(pcm)
+ speech_gate = self._speech_gate()
if not self._in_speech:
+ # Only non-speech chunks may define the floor, and the quiet band
+ # inside ``update`` rejects the rest.
+ self._floor.update(level)
self._preroll.append(pcm)
self._preroll_ms += duration_ms
while self._preroll_ms > _PREROLL_MS and len(self._preroll) > 1:
@@ -141,7 +316,7 @@ class LocalInputTranscriber:
self._preroll_ms -= int(
len(dropped) / 2 / self._sample_rate * 1000
)
- if level >= _SPEECH_RMS:
+ if level >= speech_gate:
self._speech_ms += duration_ms
if self._speech_ms >= _SPEECH_START_MS:
self._begin_utterance()
@@ -151,9 +326,9 @@ class LocalInputTranscriber:
self._utterance.append(pcm)
self._utterance_ms += duration_ms
- if level >= _SPEECH_RMS:
+ if level >= speech_gate:
self._voiced_ms += duration_ms
- if level < _SILENCE_RMS:
+ if level < speech_gate * _SILENCE_RATIO:
self._silence_ms += duration_ms
else:
self._silence_ms = 0
@@ -173,7 +348,7 @@ class LocalInputTranscriber:
self._utterance_ms = self._preroll_ms
self._preroll = []
self._preroll_ms = 0
- self._emit(InputTranscriptEvent(kind="speech_started"))
+ self._emit(InputTranscriptEvent(kind=SPEECH_STARTED))
def _finish_utterance(self) -> None:
pcm = b"".join(self._utterance)
@@ -185,63 +360,236 @@ class LocalInputTranscriber:
self._silence_ms = 0
self._speech_ms = 0
if voiced_ms < _MIN_VOICED_MS or not pcm:
+ # Too short to be speech. It still needs a boundary: the matching
+ # ``speech_started`` already told the transport a human spoke, and a
+ # turn that opens without ever closing hangs (AP-30 — a discard that
+ # neither logs nor signals is how a turn disappears silently).
+ log.debug(
+ "Local input transcription discarded a %d ms utterance "
+ "(minimum %d ms voiced, gate %.0f, floor %.0f)",
+ voiced_ms,
+ _MIN_VOICED_MS,
+ self._speech_gate(),
+ self._floor.floor,
+ )
+ self._emit(
+ InputTranscriptEvent(kind=SPEECH_DISCARDED, voiced_ms=voiced_ms)
+ )
return
# Only a qualifying utterance vouches for a server-side transcript; a
# cough must not open the door that the energy gate just closed.
self._last_speech_end = time.monotonic()
task = asyncio.create_task(
- self._transcribe(pcm), name="realtime-local-input-transcribe"
+ self._transcribe(pcm, voiced_ms), name="realtime-local-input-transcribe"
)
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
# -- recognition ---------------------------------------------------
+ async def warm(self) -> bool:
+ """Build (and prime) the recognizer off the first utterance's path.
+
+ A local engine costs seconds to construct and prime. Paying that inside
+ the first utterance delays the first transcript past its own turn AND
+ guarantees that a concurrent output-transcript recovery times out —
+ which is what abandons a worker thread inside the native engine in the
+ first place (AP-24). Call this once when the session opens; it is
+ idempotent, never raises, and reports whether a recognizer is available.
+ """
+ try:
+ await self._ensure_stt()
+ except Exception: # noqa: BLE001 - a deaf bar must not stop a call opening
+ self._log_unavailable()
+ return False
+ prime = getattr(self._stt, "warm_up", None)
+ if callable(prime):
+ try:
+ await asyncio.to_thread(prime)
+ except Exception: # noqa: BLE001 - priming is best-effort by contract
+ log.debug(
+ "Local input recognizer could not be primed; the first "
+ "utterance pays the cold cost instead",
+ exc_info=True,
+ )
+ return True
+
+ def _log_unavailable(self) -> None:
+ if self._unavailable_logged:
+ return
+ self._unavailable_logged = True
+ log.warning(
+ "Local input transcription is unavailable; this provider's voice "
+ "still answers, but Jarvis-side features that need the user's "
+ "words stay idle",
+ exc_info=True,
+ )
+
async def _ensure_stt(self) -> Any:
if self._stt is not None:
return self._stt
- factory = self._stt_factory
- if factory is None:
+ async with self._build_lock:
+ if self._stt is not None:
+ return self._stt
+ factory = self._stt_factory
+ if factory is None:
+
+ def factory() -> Any: # noqa: ANN202 - local default wiring
+ from jarvis.core.config import load_config # noqa: PLC0415
+ from jarvis.plugins.stt import ( # noqa: PLC0415
+ build_stt_from_config,
+ )
+
+ return build_stt_from_config(load_config().stt)
+
+ stt = await asyncio.to_thread(factory)
+ self._recognizer_rate = self._resolve_recognizer_rate(stt)
+ self._stt = stt
+ return self._stt
- def factory() -> Any: # noqa: ANN202 - local default wiring
- from jarvis.core.config import load_config # noqa: PLC0415
- from jarvis.plugins.stt import build_stt_from_config # noqa: PLC0415
+ def _resolve_recognizer_rate(self, stt: Any) -> int:
+ """The rate this recognizer wants its PCM in.
- return build_stt_from_config(load_config().stt)
+ Derived from the provider when it declares one, so a future 8 kHz or
+ 48 kHz engine is served correctly without touching this file; 16 kHz
+ otherwise, which is what every in-tree provider expects.
+ """
+ if self._recognizer_rate_override:
+ return self._recognizer_rate_override
+ for attribute in _RECOGNIZER_RATE_ATTRS:
+ try:
+ declared = int(getattr(stt, attribute, 0) or 0)
+ except (TypeError, ValueError):
+ continue
+ if declared > 0:
+ return declared
+ return _RECOGNIZER_RATE_FALLBACK
+
+ def _recognition_timeout_s(self, pcm: bytes, sample_rate: int) -> float:
+ seconds = len(pcm) / 2 / max(1, sample_rate)
+ return min(
+ _RECOGNITION_TIMEOUT_MAX_S,
+ _RECOGNITION_TIMEOUT_BASE_S + seconds * _RECOGNITION_TIMEOUT_PER_AUDIO_S,
+ )
- self._stt = await asyncio.to_thread(factory)
- return self._stt
+ def _note_success(self) -> None:
+ 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."""
+ self._consecutive_busy += 1
+ if self._consecutive_busy >= _RECOVER_AFTER_BUSY:
+ await self._recover_recognizer(
+ f"{self._consecutive_busy} consecutive skipped recognitions"
+ )
+
+ async def _note_failure(self, detail: str) -> None:
+ self._consecutive_failures += 1
+ if self._consecutive_failures >= _RECOVER_AFTER_FAILURES:
+ await self._recover_recognizer(
+ f"{self._consecutive_failures} consecutive failures ({detail})"
+ )
+
+ async def _recover_recognizer(self, reason: str) -> None:
+ """Rebuild a wedged engine instead of re-polling it forever (AP-24).
+
+ A timed-out recognition leaves a worker thread inside the native engine
+ that nothing can cancel, so the engine stays occupied and every later
+ utterance fails the same way — the "works once, then deaf for the rest
+ 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.
+ """
+ stt = self._stt
+ self._stt = None
+ self._recognizer_rate = None
+ self._consecutive_failures = 0
+ self._consecutive_busy = 0
+ log.warning(
+ "Rebuilding the local input recognizer after %s; the next "
+ "utterance loads a fresh engine",
+ reason,
+ )
+ recover = getattr(stt, "recover", None)
+ if not callable(recover):
+ return
+ try:
+ await asyncio.to_thread(recover)
+ except Exception: # noqa: BLE001 - the dropped reference is the real fix
+ log.warning(
+ "Local input recognizer recover() failed; continuing with a "
+ "freshly constructed engine anyway",
+ exc_info=True,
+ )
- async def _transcribe(self, pcm: bytes) -> None:
+ async def _transcribe(self, pcm: bytes, voiced_ms: int) -> None:
started = time.monotonic()
try:
text = await self.transcribe_audio(pcm, sample_rate=self._sample_rate)
- except Exception: # noqa: BLE001 - one failed utterance is not fatal
- if self._stt is None and not self._unavailable_logged:
- self._unavailable_logged = True
- log.warning(
- "Local input transcription is unavailable; this provider's "
- "voice still answers, but Jarvis-side features that need "
- "the user's words stay idle",
- exc_info=True,
- )
- elif self._stt is not None:
+ except RecognizerBusy:
+ # The recognizer is still inside an earlier call. Skipping keeps the
+ # engine intact (AP-24), but the turn must still learn it got nothing.
+ log.warning(
+ "Local input transcription skipped a %d ms utterance: the "
+ "recognizer is still busy with an earlier segment",
+ voiced_ms,
+ )
+ await self._note_busy()
+ self._emit(
+ InputTranscriptEvent(kind=TRANSCRIPT_FAILED, voiced_ms=voiced_ms)
+ )
+ return
+ except TimeoutError:
+ log.warning(
+ "Local input transcription timed out on a %d ms utterance; "
+ "the recognizer is treated as wedged",
+ voiced_ms,
+ )
+ await self._note_failure("timeout")
+ self._emit(
+ InputTranscriptEvent(kind=TRANSCRIPT_FAILED, voiced_ms=voiced_ms)
+ )
+ return
+ except Exception as exc: # noqa: BLE001 - one failed utterance is not fatal
+ if self._stt is None:
+ self._log_unavailable()
+ else:
log.warning(
"Local input transcription failed for one utterance",
exc_info=True,
)
- self._emit(InputTranscriptEvent(kind="transcript_failed"))
+ # A provider reporting its OWN engine as busy (the non-blocking
+ # in-flight guard the local Whisper provider raises) is the same
+ # "slow but alive" signal as our own skip, not an independent
+ # failure. Recognized by shape, never by importing the provider —
+ # the realtime path must stay importable without the local-voice
+ # extra installed.
+ if type(exc).__name__ == "TranscribeBusy":
+ await self._note_busy()
+ else:
+ await self._note_failure(type(exc).__name__)
+ self._emit(
+ InputTranscriptEvent(kind=TRANSCRIPT_FAILED, voiced_ms=voiced_ms)
+ )
return
+ self._note_success()
if not text:
# Real speech that produced no words: the far end's own transcript
# of the same audio is now the best thing Jarvis has.
- self._emit(InputTranscriptEvent(kind="transcript_failed"))
+ self._emit(
+ InputTranscriptEvent(kind=TRANSCRIPT_FAILED, voiced_ms=voiced_ms)
+ )
return
log.info(
"realtime local input transcript (%.0f ms): %r",
(time.monotonic() - started) * 1000,
text[:120],
)
- self._emit(InputTranscriptEvent(kind="transcript", text=text, is_final=True))
+ self._emit(
+ InputTranscriptEvent(
+ kind=TRANSCRIPT, text=text, is_final=True, voiced_ms=voiced_ms
+ )
+ )
async def transcribe_audio(self, pcm: bytes, *, sample_rate: int) -> str:
"""Recognize one bounded PCM segment without emitting input events.
@@ -249,8 +597,12 @@ class LocalInputTranscriber:
The Codex subscription transport uses this only when ChatGPT-Live
supplied assistant audio but omitted its matching transcript. The
recovered text still passes through the ordinary output scrub gate;
- this method merely supplies the missing evidence. Calls are serialized
- because the configured STT may own a native, non-thread-safe engine.
+ this method merely supplies the missing evidence.
+
+ Raises ``RecognizerBusy`` when the recognizer is already in use, and
+ ``TimeoutError`` when a call outlives a bound scaled to the audio handed
+ in. Both are deliberate: waiting behind a hung native engine is what
+ turned one bad recovery into a permanently deaf call (AP-24).
"""
if sample_rate != self._sample_rate:
raise ValueError(
@@ -259,31 +611,98 @@ class LocalInputTranscriber:
if not pcm:
return ""
- from jarvis.core.protocols import AudioChunk # noqa: PLC0415
+ # Build BEFORE taking the inference guard: a model load is not an
+ # inference, and holding the guard across it blocks the input path for
+ # the entire load.
+ stt = await self._ensure_stt()
+ target_rate = self._recognizer_rate or _RECOGNIZER_RATE_FALLBACK
+ payload = self._to_recognizer_rate(pcm, target_rate)
+ if not payload:
+ return ""
- async with self._recognition_lock:
- stt = await self._ensure_stt()
+ if self._recognition_busy:
+ raise RecognizerBusy(
+ "the local recognizer is already transcribing another segment"
+ )
+ self._recognition_busy = True
+ try:
+ from jarvis.core.protocols import AudioChunk # noqa: PLC0415
async def chunks(): # noqa: ANN202 - one-shot adapter
yield AudioChunk(
- pcm=pcm,
- sample_rate=self._sample_rate,
+ pcm=payload,
+ sample_rate=target_rate,
timestamp_ns=0,
channels=1,
)
- result = await stt.transcribe(chunks())
+ result = await asyncio.wait_for(
+ stt.transcribe(chunks()),
+ timeout=self._recognition_timeout_s(payload, target_rate),
+ )
+ finally:
+ self._recognition_busy = False
return str(getattr(result, "text", "") or "").strip()
+ def _to_recognizer_rate(self, pcm: bytes, target_rate: int) -> bytes:
+ """Convert captured PCM to the rate the recognizer actually accepts.
+
+ The realtime capture rate is the PROVIDER's (ChatGPT-Live runs at
+ 24 kHz) while recognizers pin their own: the local Whisper provider
+ raises ``ValueError("Expected 16 kHz, ...")`` on anything else and the
+ local Nemotron decoder mis-reads it without any error at all, so passing
+ the capture rate through means every local-STT user gets zero
+ transcripts on every turn. Converting here keeps that a detail of this
+ bridge instead of a constraint on the transport.
+ """
+ if target_rate == self._sample_rate:
+ return pcm
+ from jarvis.realtime.audio import StreamingPcm16Resampler # noqa: PLC0415
+
+ # One-shot: a fresh resampler per segment, because segments are not
+ # contiguous audio and carrying a tail across them would splice the end
+ # of one utterance onto the start of the next.
+ return StreamingPcm16Resampler(self._sample_rate, target_rate).process(pcm)
+
def _emit(self, event: InputTranscriptEvent) -> None:
- try:
- self._events.put_nowait(event)
- except asyncio.QueueFull: # noqa: S110 - a backed-up consumer already has plenty
- log.debug("Local input transcript queue is full; dropping one event")
+ if len(self._events) >= _EVENT_QUEUE_MAX:
+ self._evict_one()
+ self._events.append(event)
+ self._event_ready.set()
+
+ def _evict_one(self) -> None:
+ """Make room without ever discarding grounding evidence.
+
+ A dropped ``speech_started`` does not merely lose a bar update: the
+ adapter counts it as the proof that a human spoke, so losing one makes
+ the next genuine answer look like a self-echo and get interrupted.
+ Transcript events are the droppable ones.
+ """
+ for index, queued in enumerate(self._events):
+ if queued is not None and queued.kind != SPEECH_STARTED:
+ del self._events[index]
+ log.warning(
+ "Local input transcript queue is full; dropped one %s "
+ "event to keep the speech boundaries intact",
+ queued.kind,
+ )
+ return
+ dropped = self._events.popleft()
+ log.warning(
+ "Local input transcript queue is full of unread speech boundaries; "
+ "dropping the oldest (%s). The event consumer is not draining.",
+ getattr(dropped, "kind", "end-of-stream"),
+ )
# -- consuming -----------------------------------------------------
async def next_event(self) -> InputTranscriptEvent | None:
- return await self._events.get()
+ while not self._events:
+ self._event_ready.clear()
+ await self._event_ready.wait()
+ event = self._events.popleft()
+ if not self._events:
+ self._event_ready.clear()
+ return event
async def close(self) -> None:
if self._closed:
@@ -294,10 +713,16 @@ class LocalInputTranscriber:
task.cancel()
if self._tasks:
await asyncio.gather(*tuple(self._tasks), return_exceptions=True)
- try:
- self._events.put_nowait(None)
- except asyncio.QueueFull: # noqa: S110 - the consumer will drain and see the end
- pass
-
-
-__all__ = ["InputTranscriptEvent", "LocalInputTranscriber"]
+ self._events.append(None)
+ self._event_ready.set()
+
+
+__all__ = [
+ "SPEECH_DISCARDED",
+ "SPEECH_STARTED",
+ "TRANSCRIPT",
+ "TRANSCRIPT_FAILED",
+ "InputTranscriptEvent",
+ "LocalInputTranscriber",
+ "RecognizerBusy",
+]
diff --git a/tests/unit/realtime/test_input_transcription.py b/tests/unit/realtime/test_input_transcription.py
index 7580fff6e1..8d2377315b 100644
--- a/tests/unit/realtime/test_input_transcription.py
+++ b/tests/unit/realtime/test_input_transcription.py
@@ -4,6 +4,12 @@ ChatGPT-Live sends assistant transcripts only, so without these events the
provider is deaf to Jarvis: the bar stays blank, the indicators never move,
and every transcript-driven integration (delegate, wiki, project files,
hang-up phrase) sits idle while the model happily talks.
+
+On that transport these events are also the GROUNDING evidence — the adapter
+answers only when a fresh local ``speech_started`` proves a human spoke — so
+the tests below pin the SECOND and THIRD utterance of one call, not just the
+first: every historical "works once, then only listens" report is a turn-2
+failure that a single-utterance test cannot see.
"""
from __future__ import annotations
@@ -15,38 +21,73 @@ from types import SimpleNamespace
import pytest
-from jarvis.realtime.input_transcription import LocalInputTranscriber
+from jarvis.realtime import input_transcription as module
+from jarvis.realtime.input_transcription import (
+ LocalInputTranscriber,
+ RecognizerBusy,
+)
RATE = 24_000
CHUNK_SAMPLES = 480 # 20 ms
+RECOGNIZER_RATE = 16_000
-def _loud(samples: int = CHUNK_SAMPLES) -> bytes:
+def _tone(amplitude: int, samples: int = CHUNK_SAMPLES) -> bytes:
return b"".join(
- struct.pack("<h", int(9000 * math.sin(2 * math.pi * 180 * n / RATE)))
+ struct.pack("<h", int(amplitude * math.sin(2 * math.pi * 180 * n / RATE)))
for n in range(samples)
)
+def _loud(samples: int = CHUNK_SAMPLES) -> bytes:
+ return _tone(9000, samples)
+
+
def _quiet(samples: int = CHUNK_SAMPLES) -> bytes:
return b"\x00\x00" * samples
+class TranscribeBusy(RuntimeError):
+ """The class NAME the local Whisper provider raises when its engine is busy.
+
+ The transcriber recognizes it by shape, never by importing the provider, so
+ the realtime path stays importable on a base install without the
+ local-voice extra. The name is therefore load-bearing here.
+ """
+
+
class _FakeSTT:
def __init__(self, text: str = "hallo welt") -> None:
self.text = text
self.calls = 0
self.seconds: list[float] = []
+ self.rates: list[int] = []
async def transcribe(self, audio): # noqa: ANN001 - protocol shape
self.calls += 1
total = 0
+ rate = RECOGNIZER_RATE
async for chunk in audio:
total += len(chunk.pcm)
- self.seconds.append(total / 2 / RATE)
+ rate = chunk.sample_rate
+ self.rates.append(rate)
+ self.seconds.append(total / 2 / rate)
return SimpleNamespace(text=self.text)
+class _CountingSTT:
+ """Returns a distinct transcript per call, so turn N is identifiable."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def transcribe(self, audio): # noqa: ANN001 - protocol shape
+ self.calls += 1
+ async for _ in audio:
+ pass
+ return SimpleNamespace(text=f"utterance {self.calls}")
+
+
_EVENT_WAIT_S = 5.0
@@ -59,40 +100,74 @@ async def _drain(transcriber: LocalInputTranscriber, expected: int):
return events
+def _speak(
+ transcriber: LocalInputTranscriber,
+ *,
+ chunk: bytes | None = None,
+ speech_chunks: int = 40,
+ silence_chunks: int = 40,
+) -> None:
+ """Feed one complete utterance: speech, then the silence that closes it."""
+ voice = _loud() if chunk is None else chunk
+ for _ in range(speech_chunks):
+ transcriber.feed(voice, RATE)
+ for _ in range(silence_chunks):
+ transcriber.feed(_quiet(), RATE)
+
+
@pytest.mark.asyncio
async def test_speech_then_silence_yields_speech_start_and_transcript() -> None:
stt = _FakeSTT("Ben, durchsuche mein Wiki.")
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
- for _ in range(40): # 800 ms of speech
- transcriber.feed(_loud(), RATE)
- for _ in range(40): # 800 ms of silence closes the utterance
- transcriber.feed(_quiet(), RATE)
-
+ _speak(transcriber)
events = await _drain(transcriber, 2)
- assert events[0].kind == "speech_started"
- assert events[1].kind == "transcript"
+
+ assert events[0].kind == module.SPEECH_STARTED
+ assert events[1].kind == module.TRANSCRIPT
assert events[1].text == "Ben, durchsuche mein Wiki."
assert events[1].is_final is True
- assert stt.calls == 1
+ await transcriber.close()
+
+
+async def test_every_utterance_of_one_call_produces_its_own_transcript() -> None:
+ """Turn 2 and turn 3 are the whole bug class.
+
+ Every "it works once and then only listens" report is this: a recognizer
+ wedged by turn 1, a one-shot task, or a flag latched on the first final
+ transcript. A single-utterance test cannot see any of them.
+ """
+ stt = _CountingSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ transcripts = []
+ for _ in range(3):
+ _speak(transcriber)
+ started, result = await _drain(transcriber, 2)
+ assert started.kind == module.SPEECH_STARTED
+ assert result.kind == module.TRANSCRIPT, result
+ transcripts.append(result.text)
+
+ assert transcripts == ["utterance 1", "utterance 2", "utterance 3"]
+ assert stt.calls == 3
await transcriber.close()
@pytest.mark.asyncio
async def test_a_blip_of_noise_never_becomes_a_transcript() -> None:
- """A cough must not cost a recognizer call — or worse, become something
- Jarvis believes the user said. The guard measures VOICED audio, because
- the buffer also holds pre-roll and the silence that closed it: judging by
- buffer length, 160 ms of noise looks like a whole sentence."""
stt = _FakeSTT()
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
- for _ in range(8): # 160 ms of noise — real, but far too short to be speech
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
- transcriber.feed(_quiet(), RATE)
- await asyncio.sleep(0.1)
+ _speak(transcriber, speech_chunks=8) # 160 ms - too short to be speech
+ events = await _drain(transcriber, 2)
+ assert events[0].kind == module.SPEECH_STARTED
+ # It must not become a turn - but it must not vanish either: the boundary
+ # tells the transport that the turn opened by ``speech_started`` is over.
+ assert events[1].kind == module.SPEECH_DISCARDED
+ assert events[1].text == ""
+ assert events[1].voiced_ms < module._MIN_VOICED_MS # noqa: SLF001
assert stt.calls == 0
await transcriber.close()
@@ -104,10 +179,7 @@ async def test_the_utterance_carries_its_own_onset() -> None:
stt = _FakeSTT()
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
- for _ in range(50): # 1.0 s of speech
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
- transcriber.feed(_quiet(), RATE)
+ _speak(transcriber, speech_chunks=50) # 1.0 s of speech
await _drain(transcriber, 2)
# Speech + pre-roll + the trailing silence that closed it.
@@ -126,19 +198,18 @@ async def test_a_failing_recognizer_never_kills_the_call() -> None:
transcriber = LocalInputTranscriber(
sample_rate=RATE, stt_factory=lambda: _Broken()
)
- for _ in range(40):
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
- transcriber.feed(_quiet(), RATE)
+ _speak(transcriber)
- first = await asyncio.wait_for(transcriber.next_event(), timeout=5.0)
- assert first.kind == "speech_started"
+ first = await asyncio.wait_for(transcriber.next_event(), timeout=_EVENT_WAIT_S)
+ assert first.kind == module.SPEECH_STARTED
# The provider receives one explicit failure boundary so it can promote
# its own energy-gated preview; closing still completes cleanly.
- failed = await asyncio.wait_for(transcriber.next_event(), timeout=5.0)
- assert failed.kind == "transcript_failed"
+ failed = await asyncio.wait_for(transcriber.next_event(), timeout=_EVENT_WAIT_S)
+ assert failed.kind == module.TRANSCRIPT_FAILED
await transcriber.close()
- assert await asyncio.wait_for(transcriber.next_event(), timeout=5.0) is None
+ assert (
+ await asyncio.wait_for(transcriber.next_event(), timeout=_EVENT_WAIT_S) is None
+ )
@pytest.mark.asyncio
@@ -179,10 +250,7 @@ async def test_real_speech_vouches_for_a_server_transcript() -> None:
async def test_a_cough_does_not_vouch_for_a_server_transcript() -> None:
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())
- for _ in range(8): # 160 ms — too short to be an utterance
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
- transcriber.feed(_quiet(), RATE)
+ _speak(transcriber, speech_chunks=8) # 160 ms - too short to be an utterance
assert transcriber.speech_recently() is False
await transcriber.close()
@@ -199,14 +267,11 @@ async def test_a_failed_recognizer_announces_itself() -> None:
raise RuntimeError("recognizer exploded")
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _Broken())
- for _ in range(40):
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
- transcriber.feed(_quiet(), RATE)
+ _speak(transcriber)
events = await _drain(transcriber, 2)
- assert events[0].kind == "speech_started"
- assert events[1].kind == "transcript_failed"
+ assert events[0].kind == module.SPEECH_STARTED
+ assert events[1].kind == module.TRANSCRIPT_FAILED
await transcriber.close()
@@ -214,11 +279,360 @@ async def test_a_failed_recognizer_announces_itself() -> None:
async def test_an_empty_result_also_announces_itself() -> None:
stt = _FakeSTT(" ")
transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
- for _ in range(40):
- transcriber.feed(_loud(), RATE)
- for _ in range(40):
+ _speak(transcriber)
+
+ events = await _drain(transcriber, 2)
+ assert events[1].kind == module.TRANSCRIPT_FAILED
+ await transcriber.close()
+
+
+# -- sample rate ------------------------------------------------------------
+
+
+class _StrictRateSTT:
+ """A recognizer that rejects any rate but its own.
+
+ Not a contrived fake: the local Whisper provider raises
+ ``ValueError("Expected 16 kHz, got 24000 Hz")`` for exactly this, so before
+ the conversion below every local-STT user got zero transcripts on every
+ single turn while cloud users saw nothing wrong.
+ """
+
+ def __init__(self, native_rate: int = RECOGNIZER_RATE) -> None:
+ self.native_sample_rate = native_rate
+ self.seen_rates: list[int] = []
+
+ async def transcribe(self, audio): # noqa: ANN001 - protocol shape
+ async for chunk in audio:
+ self.seen_rates.append(chunk.sample_rate)
+ if chunk.sample_rate != self.native_sample_rate:
+ raise ValueError(
+ f"Expected {self.native_sample_rate} Hz, "
+ f"got {chunk.sample_rate} Hz"
+ )
+ return SimpleNamespace(text="resampled fine")
+
+
+async def test_capture_audio_is_converted_to_the_recognizer_rate() -> None:
+ stt = _StrictRateSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ _speak(transcriber)
+ events = await _drain(transcriber, 2)
+
+ assert events[1].kind == module.TRANSCRIPT, events[1]
+ assert events[1].text == "resampled fine"
+ assert stt.seen_rates == [RECOGNIZER_RATE]
+ await transcriber.close()
+
+
+async def test_a_provider_declaring_its_own_rate_is_honoured() -> None:
+ """16 kHz is the documented fallback, not an assumption baked into the path."""
+ stt = _StrictRateSTT(native_rate=8_000)
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ _speak(transcriber)
+ events = await _drain(transcriber, 2)
+
+ assert events[1].kind == module.TRANSCRIPT, events[1]
+ assert stt.seen_rates == [8_000]
+ await transcriber.close()
+
+
+async def test_output_recovery_is_converted_to_the_recognizer_rate_too() -> None:
+ stt = _StrictRateSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ text = await transcriber.transcribe_audio(_loud() * 40, sample_rate=RATE)
+
+ assert text == "resampled fine"
+ assert stt.seen_rates == [RECOGNIZER_RATE]
+ await transcriber.close()
+
+
+# -- AP-24: a wedged engine must be rebuilt, never re-polled forever ---------
+
+
+class _WedgingSTT:
+ """Models a native engine whose worker thread cannot be cancelled.
+
+ The first call enters the engine and never returns. When the caller's
+ timeout cancels the await, the ENGINE stays occupied — that is the whole
+ AP-24 trap: a timeout bounds the wait, it does not recover the engine. Every
+ later call therefore reports itself busy until ``recover()`` rebuilds it.
+ """
+
+ def __init__(self) -> None:
+ self.busy = False
+ self.wedged = True
+ self.recover_calls = 0
+ self.transcribe_calls = 0
+
+ async def transcribe(self, audio): # noqa: ANN001 - protocol shape
+ self.transcribe_calls += 1
+ async for _ in audio:
+ pass
+ if self.busy:
+ raise TranscribeBusy("a transcription is already in flight on this model")
+ self.busy = True
+ if self.wedged:
+ # Cancelling this await leaves ``busy`` set, exactly as an abandoned
+ # ctranslate2 worker thread leaves the real engine occupied.
+ await asyncio.sleep(3600)
+ self.busy = False
+ return SimpleNamespace(text="recovered engine works")
+
+ def recover(self) -> None:
+ self.recover_calls += 1
+ self.busy = False
+ self.wedged = False
+
+
+async def test_a_cancelled_recovery_does_not_deafen_the_rest_of_the_call() -> None:
+ """The headline regression: works once, then only listens.
+
+ A missing assistant transcript sends the adapter into ``transcribe_audio``
+ under its own timeout. When that timeout cancels the await, the native
+ engine keeps running — so every later USER utterance used to fail,
+ permanently, with no attempt to rebuild.
+ """
+ stt = _WedgingSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+ assert await transcriber.warm() is True
+
+ # The adapter's bounded output-transcript recovery, cancelled mid-flight.
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(
+ transcriber.transcribe_audio(_loud() * 40, sample_rate=RATE),
+ timeout=0.05,
+ )
+ assert stt.busy is True # the engine is still occupied
+
+ # The engine reports itself busy for a bounded streak, and is then rebuilt
+ # instead of being re-polled forever.
+ kinds: list[str] = []
+ for _ in range(module._RECOVER_AFTER_BUSY): # noqa: SLF001
+ _speak(transcriber)
+ started, result = await _drain(transcriber, 2)
+ assert started.kind == module.SPEECH_STARTED
+ kinds.append(result.kind)
+
+ assert kinds == [module.TRANSCRIPT_FAILED] * module._RECOVER_AFTER_BUSY # noqa: SLF001
+ assert stt.recover_calls == 1
+
+ # ...and the very next utterance is heard again.
+ _speak(transcriber)
+ started, result = await _drain(transcriber, 2)
+ assert started.kind == module.SPEECH_STARTED
+ assert result.kind == module.TRANSCRIPT, result
+ assert result.text == "recovered engine works"
+ await transcriber.close()
+
+
+async def test_a_second_caller_skips_instead_of_queueing_behind_a_hung_engine() -> None:
+ stt = _WedgingSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+ await transcriber.warm()
+
+ first = asyncio.create_task(
+ transcriber.transcribe_audio(_loud() * 40, sample_rate=RATE)
+ )
+ await asyncio.sleep(0.05) # let it enter the engine
+
+ with pytest.raises(RecognizerBusy):
+ await transcriber.transcribe_audio(_loud() * 40, sample_rate=RATE)
+
+ first.cancel()
+ await asyncio.gather(first, return_exceptions=True)
+ await transcriber.close()
+
+
+async def test_a_recognizer_timeout_is_bounded_by_the_audio_it_was_given(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(module, "_RECOGNITION_TIMEOUT_BASE_S", 0.05)
+ monkeypatch.setattr(module, "_RECOGNITION_TIMEOUT_PER_AUDIO_S", 0.0)
+ stt = _WedgingSTT()
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+ await transcriber.warm()
+
+ _speak(transcriber)
+ events = await _drain(transcriber, 2)
+
+ # The hung call is abandoned by OUR bound, and reported rather than hidden.
+ assert events[1].kind == module.TRANSCRIPT_FAILED
+ await transcriber.close()
+
+
+def test_the_recognition_bound_scales_with_the_segment() -> None:
+ """A flat ceiling either aborts long legitimate audio or shelters a wedge."""
+ transcriber = LocalInputTranscriber(sample_rate=RATE)
+ short = transcriber._recognition_timeout_s( # noqa: SLF001
+ b"\x00\x00" * RECOGNIZER_RATE, RECOGNIZER_RATE
+ )
+ long = transcriber._recognition_timeout_s( # noqa: SLF001
+ b"\x00\x00" * RECOGNIZER_RATE * 60, RECOGNIZER_RATE
+ )
+ assert long > short
+ assert long <= module._RECOGNITION_TIMEOUT_MAX_S # noqa: SLF001
+
+
+# -- AP-23: the gate must not be a property of the maintainer's mic ----------
+
+
+async def test_a_quiet_microphone_still_endpoints_after_calibration() -> None:
+ """Speech below the legacy absolute gate still opens an utterance.
+
+ On a quieter input path real speech lands under the hardcoded threshold, so
+ the endpointer never fired — and because a missing ``speech_started`` is
+ missing GROUNDING, the adapter then rejected and interrupted every provider
+ response. The user talked and was cut off, on every turn.
+ """
+ stt = _FakeSTT("quiet but audible")
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: stt)
+
+ hiss = _tone(45)
+ speech = _tone(280)
+ assert module._rms(speech) < module._SPEECH_RMS # noqa: SLF001
+
+ for _ in range(150): # 3 s of room tone teaches the session its floor
+ transcriber.feed(hiss, RATE)
+ assert transcriber.noise_floor < module._SPEECH_RMS # noqa: SLF001
+
+ _speak(transcriber, chunk=speech)
+ events = await _drain(transcriber, 2)
+
+ assert events[0].kind == module.SPEECH_STARTED
+ assert events[1].kind == module.TRANSCRIPT, events[1]
+ await transcriber.close()
+
+
+async def test_calibration_is_lower_only_so_a_loud_microphone_is_unchanged() -> None:
+ """Every historical measurement and pin still holds on a normal mic."""
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())
+
+ assert transcriber._speech_gate() == module._SPEECH_RMS # noqa: SLF001
+ for _ in range(200): # a genuinely noisy room cannot RAISE the gate
+ transcriber.feed(_tone(2000), RATE)
+ assert transcriber._speech_gate() <= module._SPEECH_RMS # noqa: SLF001
+ await transcriber.close()
+
+
+async def test_digital_silence_never_becomes_speech_at_any_calibration() -> None:
+ """AP-27 by construction: a hallucination sits AT the floor, speech above it."""
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())
+
+ for _ in range(400): # a muted mic drives the floor to its absolute minimum
transcriber.feed(_quiet(), RATE)
+ assert transcriber.speech_recently() is False
+ assert transcriber._speech_gate() >= module._SPEECH_GATE_ABS_MIN # noqa: SLF001
+ await transcriber.close()
+
+
+# -- grounding evidence must survive a stalled consumer ---------------------
+
+
+async def test_a_full_queue_never_drops_a_speech_boundary() -> None:
+ """A dropped ``speech_started`` is what makes a genuine answer get cut off.
+
+ The adapter counts it as the proof that a human spoke, so losing one to
+ queue pressure turns the model's next real response into a rejected
+ self-echo.
+ """
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())
+
+ total = module._EVENT_QUEUE_MAX + 50 # noqa: SLF001
+ for index in range(total):
+ transcriber._emit( # noqa: SLF001
+ module.InputTranscriptEvent(
+ kind=module.SPEECH_STARTED
+ if index % 2 == 0
+ else module.TRANSCRIPT_FAILED
+ )
+ )
+
+ queued = list(transcriber._events) # noqa: SLF001
+ assert len(queued) <= module._EVENT_QUEUE_MAX # noqa: SLF001
+ boundaries = sum(1 for event in queued if event.kind == module.SPEECH_STARTED)
+ assert boundaries == (total + 1) // 2
+ await transcriber.close()
+
+
+async def test_a_rate_mismatch_is_reported_once_and_loudly(caplog) -> None:
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=lambda: _FakeSTT())
+
+ with caplog.at_level("WARNING"):
+ for _ in range(20):
+ transcriber.feed(_loud(), 16_000)
+
+ warnings = [
+ record
+ for record in caplog.records
+ if "dropping every microphone" in record.getMessage()
+ ]
+ assert len(warnings) == 1
+ assert "16000" in warnings[0].getMessage()
+ assert "24000" in warnings[0].getMessage()
+ await transcriber.close()
+
+
+# -- warm path --------------------------------------------------------------
+
+
+async def test_warm_builds_and_primes_the_recognizer_before_the_first_utterance() -> (
+ None
+):
+ """A model load inside the first utterance delays that turn's transcript AND
+ guarantees a concurrent output-transcript recovery times out (AP-24)."""
+ builds = 0
+ primed = 0
+
+ class _Primed(_FakeSTT):
+ def warm_up(self) -> None:
+ nonlocal primed
+ primed += 1
+
+ def factory(): # noqa: ANN202 - test wiring
+ nonlocal builds
+ builds += 1
+ return _Primed("warmed")
+
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=factory)
+
+ assert await transcriber.warm() is True
+ assert builds == 1
+ assert primed == 1
+
+ _speak(transcriber)
+ events = await _drain(transcriber, 2)
+ assert events[1].kind == module.TRANSCRIPT
+ assert builds == 1 # the utterance reused the warmed engine
+ await transcriber.close()
+
+
+async def test_warm_never_raises_when_no_recognizer_can_be_built() -> None:
+ def factory(): # noqa: ANN202 - test wiring
+ raise RuntimeError("no STT configured")
+
+ transcriber = LocalInputTranscriber(sample_rate=RATE, stt_factory=factory)
+
+ assert await transcriber.warm() is False
+ # The call still runs; the turn just learns it got no words.
+ _speak(transcriber)
events = await _drain(transcriber, 2)
- assert events[1].kind == "transcript_failed"
+ assert events[1].kind == module.TRANSCRIPT_FAILED
await transcriber.close()