voice: tolerate the wake-tail pause; harden the front end

Endpointing fix. The wake detector usually fires inside the wake phrase,
so the first speech captured after it is the phrase's tail (plus the cue
beep echoing back through the mic), not the command. A fixed 500 ms
trailing-silence endpoint then ended the capture during the natural pause
before the command: the utterance held 240-400 ms of speech and STT
returned empty. In a recorded session 18 of 30 wakes dropped the command
that way (only 10 transcribed).

The endpoint now uses a longer silence tolerance (vad.initial_silence_ms,
default 1500) until vad.min_command_ms (default 700) of speech is in
hand, then reverts to vad.silence_ms, so a pause before the command is
tolerated while a real command still ends promptly.

Front-end hardening (the ways it was silently dying or losing work):

- Utterances run on a worker thread, not the audio thread, and a task
  error is traced and spoken rather than propagated, so one bad command
  cannot stop the mic or take the front end down.
- Capture-stream watchdog: read with a timeout and close/reopen the input
  after a sustained stall, so a wedged PortAudio/ALSA callback recovers
  instead of hanging the gateway (traced voice_stream_stalled/reopened).
- faulthandler enabled (CLI + unit) so a fatal signal dumps every
  thread's stack to the journal.
- The scheduler's answer-side entry points (answer, answer_question,
  resolve_repair, answer_approval) are guarded like submit_request: an
  EngineUnavailable is fatal-and-reported and any other resume/repair
  error returns a reply instead of propagating into a front end.
This commit is contained in:
gabby committed 2026-10-09 09:41:00 +00:00
1 parent e86ed805ee
commit f6ef66b532
9 files changed
+391 -33

No files matched your search

+7
View File
@@ -13,6 +13,7 @@ Run on a host with SemIf + a GGUF + a local OpenAI-compatible server:
from __future__ import annotations
import argparse
import faulthandler
import json
import os
import sys
@@ -822,6 +823,12 @@ def run_gateway(
run two scheduler processes over one skill store), so each gets its own
transport thread but they route through one `GatewayService`.
"""
# Dump every thread's Python stack on a fatal signal (SIGSEGV/SIGABRT/...):
# a wedged front end (e.g. a voice loop stuck on the mic) leaves a trace in
# the journal instead of dying silently. Also enabled by the unit's
# PYTHONFAULTHANDLER=1; harmless when set twice.
faulthandler.enable()
gateway_cfg = config.get("gateway", {}) or {}
platforms = _resolve_platforms(platform, gateway_cfg)
+44 -10
View File
@@ -42,6 +42,11 @@ class VoiceAdapter(GatewayAdapter):
#: `run()` blocks on the mic; this daemon owns capture/wake/STT/TTS.
self.daemon = VoiceDaemon(cfg, trace=trace, name=self.name)
self._on_inbound = None
#: Utterances are handed to a worker thread, not run on the audio
#: thread: the scheduler is synchronous and can block on the decision
#: engine, and a slow or failing task must neither stop the mic being
#: read nor kill the front end. `None` asks the worker to stop.
self._inbound: "queue.Queue[InboundMessage | None]" = queue.Queue()
# ---- requirements ----
@@ -69,13 +74,42 @@ class VoiceAdapter(GatewayAdapter):
self.daemon.speak(message.text)
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
self.daemon.run(self._on_utterance)
threading.Thread(
target=self._inbound_worker, name="voice-inbound-worker", daemon=True
).start()
try:
self.daemon.run(self._on_utterance)
finally:
self._inbound.put(None)
def close(self) -> None:
self.daemon.close()
# ---- inbound ----
def _inbound_worker(self) -> None:
"""Run the scheduler off the audio thread, one utterance at a time.
The scheduler is synchronous and can block on the decision engine; a
slow task must not stop the mic being read, and a task error is traced
and spoken rather than propagated — one bad command must not take the
voice front end down with it.
"""
while True:
message = self._inbound.get()
if message is None:
return
self._handle(message)
def _handle(self, message: InboundMessage) -> None:
if self._on_inbound is None:
return
try:
self._on_inbound(message)
except Exception as exc:
self.daemon._event("gateway_handler_failed", message=str(exc)[:300])
self.daemon.speak("Sorry, something went wrong handling that.")
def _on_utterance(self, text: str) -> None:
text = (text or "").strip()
if not text:
@@ -86,13 +120,13 @@ class VoiceAdapter(GatewayAdapter):
display_name=self.display_name,
chars=len(text),
)
message = InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
self._inbound.put(
InboundMessage(
text=text,
chat_id=self.chat_id,
chat_type="dm",
contact_id=self.chat_id,
display_name=self.display_name,
raw={},
)
)
if self._on_inbound is not None:
self._on_inbound(message)
+43 -2
View File
@@ -631,7 +631,21 @@ class Scheduler:
a pre-act contract variable is left unset and marked skipped, and an
act-driven pause receives the empty string (the body may then fail,
which is assessed normally).
Guarded like `submit_request`: a front end calls this synchronously
(the voice adapter from its worker thread), so an engine failure must
be fatal-and-reported, and any other error must come back as a reply
rather than propagate and take the front end down.
"""
try:
return self._answer(text)
except EngineUnavailable as exc:
return SchedulerReply("fatal", self._mark_fatal(exc))
except Exception as exc:
self.trace.append("error", "?", phase="answer", message=str(exc))
return SchedulerReply("error", f"could not resume the run: {exc}")
def _answer(self, text: str) -> SchedulerReply:
with self._lock:
if self.pending is None:
return SchedulerReply("error", "no run is waiting for input")
@@ -818,8 +832,17 @@ class Scheduler:
"""Answer a deferred question. An empty answer skips it.
A repair question carries the detail the user wants the skill repaired
with; answering it starts the repair directly.
with; answering it starts the repair directly. Guarded so an engine or
repair failure is reported instead of propagating into the front end.
"""
try:
return self._answer_question(question_id, text)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not record the answer: {exc}"
def _answer_question(self, question_id: str, text: str) -> tuple[str, str]:
offer_id: str | None = None
answer = (text or "").strip()
with self._lock:
@@ -870,7 +893,16 @@ class Scheduler:
The draft worker is blocked in `_request_approval`; setting the status
and notifying releases it (True registers + writes the body, False
aborts). The terminal trace event is written by the worker, not here.
Guarded so an unexpected failure is reported instead of propagating.
"""
try:
return self._answer_approval(approval_id, approved)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not record the approval: {exc}"
def _answer_approval(self, approval_id: str, approved: bool) -> tuple[str, str]:
with self._lock:
approval = next(
(a for a in self.approvals if a.id == approval_id), None
@@ -915,8 +947,17 @@ class Scheduler:
`retry` requeues the original request; `repair_skill` rewrites the body
from the observed failure; `ask_user` posts a question whose answer
starts the repair; `no_repair` closes the offer. Repair writes are
bounded by `codegen.repair.max_attempts` per skill.
bounded by `codegen.repair.max_attempts` per skill. Guarded so a retry
run or write failure is reported instead of propagating.
"""
try:
return self._resolve_repair(offer_id, action)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc)
except Exception as exc:
return "error", f"could not execute the repair: {exc}"
def _resolve_repair(self, offer_id: str, action: str | None = None) -> tuple[str, str]:
with self._lock:
offer = next((r for r in self.repairs if r.id == offer_id), None)
if offer is None:
+102 -10
View File
@@ -103,15 +103,17 @@ class Synthesizer:
class AudioIO:
"""Mic capture and speaker playback.
`read()` blocks for one frame and returns its bytes, or `None` once the
input is closed (the loop exits on `None`). `open_output`/`write` may be
called at any sample rate the synthesizer produced.
`read(timeout)` returns one frame's bytes; with a `timeout` it returns
`b""` when no frame arrived in time, and `None` once the input is closed
(the loop exits on `None`). The timeout is how the loop detects a stalled
capture stream and recovers from it. `open_output`/`write` may be called at
any sample rate the synthesizer produced.
"""
def open_input(self, sample_rate: int, frame_ms: int, device: str = "") -> None:
raise NotImplementedError
def read(self) -> bytes | None:
def read(self, timeout: float | None = None) -> bytes | None:
raise NotImplementedError
def open_output(self, sample_rate: int, device: str = "") -> None:
@@ -442,8 +444,9 @@ class SoundDeviceAudio(AudioIO):
def read(self, timeout: float | None = None) -> bytes | None:
"""Block for the next frame (or up to `timeout` seconds).
Returns `None` once the input is closed, or on a `timeout` with no
frame — a caller that passes a timeout can detect a stalled stream
Returns `None` once the input is closed (the sentinel `close()` puts on
the queue), or `b""` when a `timeout` elapses with no frame — so a
caller that passes a timeout can detect a stalled capture stream
instead of blocking forever.
"""
if timeout is None:
@@ -451,7 +454,7 @@ class SoundDeviceAudio(AudioIO):
try:
return self._frames.get(timeout=timeout)
except queue.Empty:
return None
return b""
def open_output(self, sample_rate: int, device: str = "") -> None:
pass # a raw stream is opened per utterance in `write`
@@ -610,10 +613,28 @@ class VoiceDaemon:
self.sample_rate = int(audio_cfg.get("sample_rate", SAMPLE_RATE) or SAMPLE_RATE)
self.frame_ms = int(audio_cfg.get("frame_ms", 80) or 80)
self.input_device = str(audio_cfg.get("input_device", "") or "")
#: Capture-stream watchdog. `read_timeout_s` is how long a frame read
#: waits before it counts as a stall; when the stream stalls
#: continuously for `stall_timeout_s` the input is closed and reopened
#: (a wedged PortAudio/ALSA callback otherwise blocks `read()` forever).
#: 0 for either restores the old blocking read with no recovery.
self.read_timeout_s = float(audio_cfg.get("read_timeout_s", 1.0) or 0.0)
self.stall_timeout_s = float(audio_cfg.get("stall_timeout_s", 5.0) or 0.0)
self._stall_since = 0.0
vad_cfg = cfg.get("vad", {}) or {}
self.vad_silence_ms = int(vad_cfg.get("silence_ms", 1000) or 1000)
self.min_speech_ms = int(vad_cfg.get("min_speech_ms", 120) or 120)
self.max_utterance_s = float(vad_cfg.get("max_utterance_s", 30) or 30)
#: A longer silence tolerance while the utterance is still short. The
#: wake detector can fire inside the wake phrase (the cue beep follows),
#: so the first speech after it is the phrase's tail, not the command;
#: a natural pause before the command must not end the capture. Once
#: `min_command_ms` of speech is in hand, the normal `vad_silence_ms`
#: endpoint applies (so a real command still ends promptly).
self.min_command_ms = int(vad_cfg.get("min_command_ms", 700) or 0)
self.initial_silence_ms = max(
int(vad_cfg.get("initial_silence_ms", 1500) or 0), self.vad_silence_ms
)
self.follow_up_window = float(cfg.get("follow_up_window_s", 5.0) or 0.0)
self.max_speak_chars = int(cfg.get("max_speak_chars", 600) or 0)
cue = cfg.get("cue", {}) or {}
@@ -698,9 +719,11 @@ class VoiceDaemon:
def _loop(self, engines: VoiceEngines) -> None:
while not self._stop.is_set():
pcm = engines.audio.read()
pcm = self._read_frame(engines)
if pcm is None:
return
if not pcm:
continue
if self._speaking.is_set():
continue
armed = time.time() < self._follow_until
@@ -763,9 +786,16 @@ class VoiceDaemon:
break # a reply started; stop capturing so we don't transcribe it
if self.max_utterance_s > 0 and (time.time() - started) >= self.max_utterance_s:
break
pcm = engines.audio.read()
pcm = self._read_frame(engines)
if pcm is None:
break
if not pcm:
# No frame within the read timeout: keep waiting, but still
# honor the "command never started" deadline below.
if waiting and (time.time() - wait_started) * 1000.0 >= wait_for_speech_ms:
self._event("voice_no_command", waited_ms=wait_for_speech_ms)
return b""
continue
is_speech = engines.vad.is_speech(pcm, self.sample_rate)
if waiting:
if not is_speech:
@@ -781,7 +811,15 @@ class VoiceDaemon:
last_speech_ts = time.time()
else:
silence_ms += self.frame_ms
if silence_ms >= self.vad_silence_ms:
# Tolerate a longer pause until the command's speech is underway
# (see `initial_silence_ms`): the wake phrase's tail is captured
# first, and a pause before the actual command must not end it.
limit = (
self.initial_silence_ms
if speech_ms < self.min_command_ms
else self.vad_silence_ms
)
if silence_ms >= limit:
break
if speech_ms < self.min_speech_ms:
self._event(
@@ -795,6 +833,60 @@ class VoiceDaemon:
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
return b"".join(frames)
# ---- capture health ----
def _read_frame(self, engines: VoiceEngines) -> bytes | None:
"""Read one capture frame, recovering from a stalled stream.
Returns the frame bytes, `b""` when no frame arrived within
`read_timeout_s`, or `None` once the input is closed. When the stream
stalls continuously for `stall_timeout_s` — the PortAudio callback has
stopped delivering, so a blocking `read()` would hang the front end
forever — the input is closed and reopened so the loop recovers.
"""
timeout = self.read_timeout_s if self.read_timeout_s > 0 else None
pcm = engines.audio.read(timeout=timeout)
if pcm is None:
return None
if pcm:
self._stall_since = 0.0
return pcm
if timeout is None or self.stall_timeout_s <= 0:
return b""
now = time.time()
if not self._stall_since:
self._stall_since = now
return b""
if now - self._stall_since >= self.stall_timeout_s:
self._stall_since = 0.0
self._reopen_input(engines)
return b""
def _reopen_input(self, engines: VoiceEngines) -> None:
"""Close and reopen the capture stream after a stall (best-effort).
A stalled PortAudio/ALSA stream never delivers another frame, so the
blocking read would hang the whole front end. Reopening gives the
device a fresh stream; a hard failure is traced and backed off rather
than raised, so the loop keeps retrying instead of dying.
"""
self._event("voice_stream_stalled", stall_s=round(self.stall_timeout_s, 3))
try:
engines.audio.close()
except Exception:
pass
try:
engines.audio.open_input(self.sample_rate, self.frame_ms, self.input_device)
except Exception as exc:
self._event("voice_stream_reopen_failed", message=str(exc)[:200])
time.sleep(min(2.0, self.stall_timeout_s or 1.0))
return
try:
engines.wake.reset()
except Exception:
pass
self._event("voice_stream_reopened")
# ---- speaking ----
def _cue(self, frequency: float, duration_ms: int) -> None: