The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(voice): fall back to blocking reads when read_available never advances
liuhao1024d79de94195e4
diff --git a/tests/tools/test_wake_word.py b/tests/tools/test_wake_word.pyindex 51b1f564acb..b3e65c6de46 100644--- a/tests/tools/test_wake_word.py+++ b/tests/tools/test_wake_word.py@@ -728,6 +728,99 @@ def test_wedged_stream_halts_without_blocking_read_and_aborts_before_close(monkeassert stream.calls[:2] == ["abort", "close"]+def test_starved_read_available_falls_back_to_blocking_read(monkeypatch, caplog):+ """A stream that never advances read_available (#118552, Windows DirectSound) must+ not spin in the poll guard forever: after the stall window it warns once, then+ reads blocking — audio flows on such devices, so frames keep arriving."""+ class _StarvedStream(_FakeStream):+ read_available = 0++ def __init__(self, **kw):+ super().__init__(**kw)+ self.read_calls = 0++ def read(self, n):+ self.read_calls += 1+ time.sleep(0.01)+ return [0] * n, False++ streams = []++ def _stream(**kw):+ streams.append(_StarvedStream(**kw))+ return streams[-1]++ monkeypatch.setattr(ww, "_import_audio", lambda: (types.SimpleNamespace(InputStream=_stream), None))+ monkeypatch.setattr(ww, "_READ_STALL_FALLBACK_SECONDS", 0.1)+ det = ww.WakeWordDetector(_FakeEngine(fire=False), on_wake=lambda: None)+ with caplog.at_level("WARNING", logger="tools.wake_word"):+ det.start()+ assert det.running is True+ deadline = time.monotonic() + 3+ while streams and streams[0].read_calls < 5 and time.monotonic() < deadline:+ time.sleep(0.02)+ assert streams[0].read_calls >= 5, "must block-read frames once read_available is starved"+ warnings = [r for r in caplog.records if "falling back to blocking reads" in r.message]+ assert len(warnings) == 1, "the stall fallback warns exactly once per capture"+ det.pause()+ assert det.running is False+++def test_starved_and_wedged_read_is_released_by_halt_abort(monkeypatch):+ """Worst case for the #118552 fallback: read_available is starved AND the blocking+ read truly wedges. pause() must join out, abort the capture to unblock the reader,+ and leave ``running`` truthful — the #117096 guarantee survives the fallback."""+ class _StarvedWedgedStream(_FakeStream):+ read_available = 0++ def __init__(self, **kw):+ super().__init__(**kw)+ self.read_calls = 0+ self.calls = []+ self._unblock = threading.Event()++ def read(self, n):+ self.read_calls += 1+ self._unblock.wait(30) # blocks like a wedged PortAudio read; abort releases+ return [0] * n, False++ def abort(self):+ self.calls.append("abort")+ self._unblock.set()++ def stop(self):+ self.calls.append("stop")++ def close(self):+ self.calls.append("close")+ self.closed = True++ streams = []++ def _stream(**kw):+ streams.append(_StarvedWedgedStream(**kw))+ return streams[-1]++ monkeypatch.setattr(ww, "_import_audio", lambda: (types.SimpleNamespace(InputStream=_stream), None))+ monkeypatch.setattr(ww, "_READ_STALL_FALLBACK_SECONDS", 0.1)+ monkeypatch.setattr(ww, "_HALT_JOIN_SECONDS", 0.2)+ det = ww.WakeWordDetector(_FakeEngine(fire=False), on_wake=lambda: None)+ det.start()+ assert det.running is True+ deadline = time.monotonic() + 3+ while streams and streams[0].read_calls < 1 and time.monotonic() < deadline:+ time.sleep(0.02)+ assert streams[0].read_calls == 1, "starved guard must have fallen back into read()"+ t0 = time.monotonic()+ det.pause()+ assert time.monotonic() - t0 < 2.5, "pause() must abort the wedged read, not block on it"+ stream = streams[0]+ assert "abort" in stream.calls, "halt must abort the capture to release the reader"+ if det._thread is not None:+ det._thread.join(timeout=2)+ assert det.running is False++def test_startup_failure_releases_owner_and_machine_lock(monkeypatch, tmp_path):class _BrokenSoundDevice:@staticmethoddiff --git a/tools/wake_word.py b/tools/wake_word.pyindex 857e31bcb51..69126059e69 100644--- a/tools/wake_word.py+++ b/tools/wake_word.py@@ -40,6 +40,11 @@ SAMPLE_RATE = 16000 # 16 kHz mono int16 — Whisper-native and what every engin_FIRE_COOLDOWN_SECONDS = 2.0_START_TIMEOUT_SECONDS = 5.0_READ_POLL_SECONDS = 0.05 # slice between read_available polls; bounds halt latency+# Some hostapis (Windows DirectSound) never advance ``read_available`` even while+# audio flows; after this much starvation the poll guard is abandoned for the+# blocking read (see ``_Capture.read``).+_READ_STALL_FALLBACK_SECONDS = 2.0+_HALT_JOIN_SECONDS = 2.0# Ambient-speech rejection: N consecutive over-threshold frames before firing# (a stray phoneme spikes one frame; a real phrase holds several).@@ -434,6 +439,9 @@ class _Capture:np: Any = Nonerate: int = SAMPLE_RATEframe_length: int = 1280 # samples per read at ``rate``+ # Set once ``read_available`` proves unreliable for this stream: skip the poll+ # guard and go straight to the blocking read.+ _skip_available_poll: bool = Falsedef read(self, stop: Optional[threading.Event] = None):"""One raw block; None when nothing arrived within ~250 ms (client) or ``stop`` was@@ -443,13 +451,26 @@ class _Capture:PipeWire device, never returns — so the halting thread's ``join`` timed out and``close()`` raced the still-pending read. Poll ``read_available`` in short slicesagainst ``stop`` and only call ``read`` once the block is guaranteed to be there.++ A device that never advances ``read_available`` (Windows DirectSound) would spin+ here forever, so after ``_READ_STALL_FALLBACK_SECONDS`` of starvation the guard is+ abandoned (with a warning) and the blocking read takes over; a truly wedged+ blocking read is released by ``_halt_thread`` aborting the stream."""if self.stream is not None:available = getattr(self.stream, "read_available", None)- if stop is not None and available is not None:+ if stop is not None and available is not None and not self._skip_available_poll:+ stalled = 0.0while self.stream.read_available < self.frame_length:if stop.wait(_READ_POLL_SECONDS):return None+ stalled += _READ_POLL_SECONDS+ if stalled >= _READ_STALL_FALLBACK_SECONDS:+ logger.warning(+ "wake word: read_available stuck below frame length for "+ "%.1fs — falling back to blocking reads", stalled)+ self._skip_available_poll = True+ breakreturn self.stream.read(self.frame_length)[0]with suppress(Exception):return self.queue.get(timeout=0.25)@@ -483,6 +504,9 @@ class WakeWordDetector:{"selector": "client", "name": "client capture", "hostapi": "remote"}if self.external_audio else {"selector": input_device})self._thread: Optional[threading.Thread] = None+ # Armed capture of the current reader thread; lets _halt_thread abort a+ # blocking read the poll guard cannot return from. Written by _run.+ self._cap: Optional[_Capture] = Noneself._stop, self._callback_inflight = threading.Event(), threading.Event()self._lock, self._last_fire = threading.Lock(), 0.0# Client-capture PCM queue (int16 mono frames). Local mode ignores this.@@ -561,7 +585,15 @@ class WakeWordDetector:# Join OUTSIDE the lock: a reader wedged in PortAudio would otherwise pin the lock# for the whole timeout and stall every start()/pause() caller behind it.if t is not None and t is not threading.current_thread():- t.join(timeout=2.0)+ t.join(timeout=_HALT_JOIN_SECONDS)+ if t.is_alive():+ # The reader is wedged in a blocking read (read_available proved+ # unreliable, or the device died mid-read). abort() discards pending+ # buffers and unblocks it; close() is idempotent and the reader's+ # own finally will close it again.+ cap = self._cap+ if cap is not None:+ cap.close()with self._lock:# Keep the handle while the thread is still alive (join timed out) so# ``running`` stays truthful and the next start() does not double-arm.@@ -668,6 +700,7 @@ class WakeWordDetector:frame_length = self.engine.frame_lengthtry:cap = self._open_capture(frame_length)+ self._cap = capexcept Exception as e:startup_errors.append(e)ready.set()