voice gateway: instrument end-to-end latency

Add trace boundaries and timings so the last-word -> first-audio latency can
be split by section:

- voice_transport: emit `voice_speech_end` (the last VAD-speech frame, i.e. the
  true "last word"), `voice_speak_start`, `voice_tts_synth` (Piper duration +
  audio length), and `voice_playback_start` (the instant the first reply
  samples reach the device).
- trace: `TraceLog.append` accepts an explicit `ts` so an event records when it
  happened, not when it was written.
- gateway/voice: trace `gateway_reply_dequeued` at the outbound pump.
- gateway/service: trace `humanize` (duration) and `gateway_reply_queued`; a
  best-effort `_trace` helper tolerates test doubles with no trace log.
- log: persist the engine's per-decision `input_tokens`/`forward_seconds`/
  `total_seconds` (already computed by the backend, previously discarded) into
  the decision row's `extra.timing`.

scripts/voice-latency.py reads data/runs.jsonl and prints a per-interaction
breakdown (endpointing, STT, each SemIf guard, act/assess, humanize, TTS,
playback) plus aggregates.
This commit is contained in:
gabby committed 2026-10-06 22:01:32 +00:00
1 parent e426998cf7
commit 5bb0e9d21d
6 files changed
+284 -4

No files matched your search

+14
View File
@@ -24,6 +24,7 @@ from __future__ import annotations
import queue
import re
import threading
import time
from .base import InboundMessage, OutboundMessage
from .humanize import Humanizer
@@ -426,6 +427,12 @@ class GatewayService:
# ---- outbound ----
def _trace(self, kind: str, **fields) -> None:
"""Best-effort trace (a test double's scheduler may have no trace log)."""
trace = getattr(self.scheduler, "trace", None)
if trace is not None:
trace.append(kind, "?", **fields)
def _reply(
self, platform: str, chat_id: str, text: str, kind: str = "reply"
) -> None:
@@ -442,7 +449,13 @@ class GatewayService:
# result before optionally cleaning it up.
text = _result_detail(text)
if humanize:
started = time.time()
text = self.humanizer.humanize(text)
self._trace(
"humanize",
elapsed_s=round(time.time() - started, 3),
chars=len(text),
)
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
if prefix:
text = f"{prefix}{text}"
@@ -451,4 +464,5 @@ class GatewayService:
target_queue = self.outbound.get(platform)
if target_queue is None:
return
self._trace("gateway_reply_queued", reply_kind=kind, chars=len(text))
target_queue.put(OutboundMessage(chat_id=str(chat_id), text=text))
+1
View File
@@ -65,6 +65,7 @@ class VoiceAdapter(GatewayAdapter):
if message is None:
self.daemon.stop()
return
self.daemon._event("gateway_reply_dequeued", chars=len(message.text))
self.daemon.speak(message.text)
threading.Thread(target=_pump, name="voice-outbound-pump", daemon=True).start()
+8
View File
@@ -42,6 +42,14 @@ class DecisionLog:
}
if extra:
row["extra"] = extra
result_extra = getattr(result, "extra", None) or {}
timing = {
key: result_extra[key]
for key in ("input_tokens", "forward_seconds", "total_seconds")
if key in result_extra
}
if timing:
row.setdefault("extra", {})["timing"] = timing
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a") as handle:
handle.write(json.dumps(row) + "\n")
+4 -2
View File
@@ -19,8 +19,10 @@ class TraceLog:
def __init__(self, path: str = "data/runs.jsonl"):
self.path = Path(path)
def append(self, kind: str, run_id: str, **fields) -> None:
row = {"kind": kind, "run_id": run_id, "ts": time.time(), **fields}
def append(self, kind: str, run_id: str, ts: float | None = None, **fields) -> None:
# `ts` lets a caller record the moment an event *happened* (e.g. the last
# speech frame of an utterance) rather than when the row was written.
row = {"kind": kind, "run_id": run_id, "ts": time.time() if ts is None else ts, **fields}
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a") as handle:
handle.write(json.dumps(row) + "\n")
+19 -2
View File
@@ -719,6 +719,9 @@ class VoiceDaemon:
speech_ms = self.frame_ms
silence_ms = 0
started = time.time()
#: Wall-clock of the most recent frame the VAD called speech — the
#: "last word spoken" boundary the latency breakdown measures from.
last_speech_ts = started
while not self._stop.is_set():
if self._speaking.is_set():
break # a reply started; stop capturing so we don't transcribe it
@@ -731,6 +734,7 @@ class VoiceDaemon:
if engines.vad.is_speech(pcm, self.sample_rate):
speech_ms += self.frame_ms
silence_ms = 0
last_speech_ts = time.time()
else:
silence_ms += self.frame_ms
if silence_ms >= self.vad_silence_ms:
@@ -743,6 +747,7 @@ class VoiceDaemon:
silence_ms=silence_ms,
)
return b""
self._event("voice_speech_end", ts=last_speech_ts, speech_ms=speech_ms)
self._event("voice_utterance", frames=len(frames), speech_ms=speech_ms)
return b"".join(frames)
@@ -776,11 +781,23 @@ class VoiceDaemon:
text = (clipped or text[: self.max_speak_chars]) + "…"
engines = self._ensure_engines()
self._speaking.set()
self._event("voice_speak_start", chars=len(text))
try:
synth_started = time.time()
pcm, sample_rate = engines.tts.synthesize(text)
self._event(
"voice_tts_synth",
synth_s=round(time.time() - synth_started, 3),
chars=len(text),
audio_s=round(len(pcm) / BYTES_PER_SAMPLE / sample_rate, 3)
if pcm and sample_rate
else 0.0,
)
if pcm:
with self._audio_lock:
engines.audio.open_output(sample_rate)
# The instant the first reply audio is handed to the device.
self._event("voice_playback_start", ts=time.time(), chars=len(text))
engines.audio.write(pcm, sample_rate)
self._event("voice_spoke", chars=len(text))
except Exception as exc:
@@ -800,6 +817,6 @@ class VoiceDaemon:
# ---- tracing ----
def _event(self, kind: str, **fields) -> None:
def _event(self, kind: str, ts: float | None = None, **fields) -> None:
if self.trace is not None:
self.trace.append(kind, "?", **fields)
self.trace.append(kind, "?", ts=ts, **fields)