From 0353ea7109819249f639711c3351bf6c172d1cdc Mon Sep 17 00:00:00 2001 From: StuBehan Date: Tue, 29 Sep 2026 12:55:09 +0100 Subject: [PATCH 1/3] fix: recover the daemon from a wedged audio worker --- README.md | 4 +- stackvox/daemon.py | 91 ++++++++++++++++++-- tests/test_daemon.py | 193 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 278 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 2e28d2c..b4044fd 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Keeps the model resident so each subsequent call is instant: stackvox serve # foreground; run with `nohup stackvox serve &` to background stackvox status # is the daemon up? also shows version + any pending PyPI update stackvox say "Hello" # send text to the daemon (fails if not running) -stackvox stop # graceful shutdown +stackvox stop # graceful shutdown, force-killed if it's still up after 5s ``` stackvox checks PyPI for newer versions but only at two moments — when you run `stackvox status` and at daemon startup. The script-heavy paths (`say`, `speak`, `stackvox-say`, hooks, CI) never make a network call. To see notices on every invocation set `STACKVOX_UPDATE_NOTICE=1`. To disable the check entirely set `STACKVOX_NO_UPDATE_CHECK=1`. The check is auto-skipped when common CI env vars (`CI`, `GITHUB_ACTIONS`, etc.) are set so build logs stay clean. @@ -227,6 +227,8 @@ Socket lives at `~/.cache/stackvox/daemon.sock` (override with `STACKVOX_SOCKET` Queue depth is 2 — rapid-fire requests beyond that get `busy` rather than piling up. +If playback hangs the daemon exits rather than answering `busy` forever. Each utterance gets 60s plus half a second per character, slower than any voice reads it even at speed 0.5. Past that the daemon removes its socket and exits with status 70, so `say` reports it isn't running and anything that starts the daemon on demand gets a fresh one. On macOS this has been a deadlock inside PortAudio stopping a stream, which `cancel` can't break. + Before each utterance the daemon resets PortAudio so it picks up the current system default output device. Swap from speakers to Bluetooth headphones mid-session and the next `say` follows you — no daemon restart needed. The refresh costs ~10–50ms per play, which is invisible next to synthesis time. ## Requirements diff --git a/stackvox/daemon.py b/stackvox/daemon.py index bca0c3c..d8e6b10 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -46,11 +46,23 @@ CLIENT_TIMEOUT_SECONDS = 1.0 PING_TIMEOUT_SECONDS = 0.5 # How long `stop` waits for the daemon process to actually exit after it has -# acknowledged the request, and how often it re-checks. +# acknowledged the request, and how often it re-checks. Past the timeout it +# sends SIGKILL and waits up to KILL_TIMEOUT_SECONDS for that to take. STOP_TIMEOUT_SECONDS = 5.0 STOP_POLL_SECONDS = 0.05 +KILL_TIMEOUT_SECONDS = 1.0 RECV_BYTES = 1024 +# Watchdog budget for one utterance: a fixed allowance for synthesis and stream +# setup and teardown, plus the text read slower than any voice actually reads +# it. Dense text (numbers, acronyms) at kokoro's minimum speed of 0.5 measures +# about 3.4 chars/s, so 2 chars/s leaves headroom even there. A worker still on +# one utterance past its budget is treated as wedged. The case seen so far is a +# deadlock in native audio code, which no Python-level cancel can interrupt. +WATCHDOG_GRACE_SECONDS = 60.0 +WATCHDOG_MIN_CHARS_PER_SECOND = 2.0 +WATCHDOG_POLL_SECONDS = 5.0 + # Set when PortAudio's cached default-output device is suspected stale and # needs Pa_Terminate / Pa_Initialize before the next playback. Initial state @@ -171,6 +183,30 @@ def _on_device_change(obj_id: int, n: int, addrs: Any, data: Any) -> int: logger.debug("audio device watcher started") +def _utterance_budget(text: str) -> float: + """Seconds the worker may spend on one request before it counts as wedged.""" + return WATCHDOG_GRACE_SECONDS + len(text) / WATCHDOG_MIN_CHARS_PER_SECOND + + +def _remove_runtime_files() -> None: + SOCKET_PATH.unlink(missing_ok=True) + PID_PATH.unlink(missing_ok=True) + + +def _exit_wedged() -> None: + """Exit hard so a fresh daemon can take over from a wedged one. + + On macOS the worker has been seen deadlocked inside PortAudio's stream stop, + waiting on a CoreAudio lock held by CoreAudio's own IO thread. A normal + shutdown didn't get out either (`stop` timed out with the process still + alive), so this uses `os._exit`. The socket goes first: clients that start + the daemon on demand do so when the socket is missing, and until it is gone + they keep getting `busy`. + """ + _remove_runtime_files() + os._exit(os.EX_SOFTWARE) + + class _DaemonState: def __init__( self, voice: str, speed: float, lang: str, custom_voices: Mapping[str, VoiceMix] | None = None @@ -178,8 +214,12 @@ def __init__( self.tts = Stackvox(voice=voice, speed=speed, lang=lang, custom_voices=custom_voices) self.queue: queue.Queue[dict] = queue.Queue(maxsize=MAX_QUEUE) self.stop_event = threading.Event() + # Monotonic time by which the worker must finish its current request; + # None while idle. + self.deadline: float | None = None self.worker = threading.Thread(target=self._worker, daemon=True) self.worker.start() + threading.Thread(target=self._watchdog, daemon=True, name="stackvox-watchdog").start() _start_device_watcher() def _worker(self) -> None: @@ -188,6 +228,9 @@ def _worker(self) -> None: req = self.queue.get(timeout=WORKER_POLL_SECONDS) except queue.Empty: continue + # Armed before the audio refresh as well as playback: both call into + # PortAudio, and either can block on a CoreAudio lock for good. + self.deadline = time.monotonic() + _utterance_budget(req["text"]) if _audio_dirty.is_set(): _refresh_audio_devices() _audio_dirty.clear() @@ -203,6 +246,25 @@ def _worker(self) -> None: # Failed playback might be a stale audio context; mark dirty # so the next request refreshes before trying again. _audio_dirty.set() + self.deadline = None + + def overrun(self, now: float) -> float | None: + """Seconds the current request has run past its deadline, or None if + the worker is idle or still within budget.""" + deadline = self.deadline + if deadline is None or now <= deadline: + return None + return now - deadline + + def _watchdog(self) -> None: + while not self.stop_event.wait(WATCHDOG_POLL_SECONDS): + overrun = self.overrun(time.monotonic()) + if overrun is not None: + logger.error( + "playback worker is %.1fs past its deadline; exiting so a fresh daemon can start", + overrun, + ) + _exit_wedged() def submit(self, req: dict) -> bool: try: @@ -344,8 +406,7 @@ def handle_signal(signum: int, frame: object) -> None: try: server.serve_forever() finally: - SOCKET_PATH.unlink(missing_ok=True) - PID_PATH.unlink(missing_ok=True) + _remove_runtime_files() def send(req: dict, timeout: float = CLIENT_TIMEOUT_SECONDS) -> tuple[bool, str]: @@ -387,6 +448,10 @@ def stop(timeout: float = STOP_TIMEOUT_SECONDS) -> tuple[bool, str]: to start, and the shutdown then completed, leaving nothing running at all. Reporting success before the process has exited makes that sequence, the one `status` recommends, silently useless. + + A daemon still alive after `timeout` gets SIGKILL. One with its worker + deadlocked in PortAudio (see `_exit_wedged`) has been seen to acknowledge + and then never exit. """ pid = _read_pid() ok, resp = send({"command": "stop"}) @@ -394,12 +459,28 @@ def stop(timeout: float = STOP_TIMEOUT_SECONDS) -> tuple[bool, str]: # Nothing acknowledged, or no pid to watch: the caller's own # `is_running` check is as good as it gets. return ok, resp + if _wait_for_exit(pid, timeout): + return True, resp + try: + os.kill(pid, signal.SIGKILL) + except ProcessLookupError: + return True, resp # exited on its own just after the last check + if not _wait_for_exit(pid, KILL_TIMEOUT_SECONDS): + return False, f"daemon acknowledged stop but pid {pid} is still alive after SIGKILL" + # The killed daemon can't remove its own files. Leave them if a new daemon + # has started since and rewritten the pid file. + if _read_pid() == pid: + _remove_runtime_files() + return True, f"daemon did not exit within {timeout:g}s of acknowledging stop; killed pid {pid}" + + +def _wait_for_exit(pid: int, timeout: float) -> bool: deadline = time.monotonic() + timeout while True: if not _pid_alive(pid): - return True, resp + return True if time.monotonic() >= deadline: - return False, f"daemon acknowledged stop but pid {pid} is still alive after {timeout:g}s" + return False time.sleep(STOP_POLL_SECONDS) diff --git a/tests/test_daemon.py b/tests/test_daemon.py index e7c0673..f2e0c4d 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -1,11 +1,12 @@ """Daemon tests for non-protocol surface — pid/socket helpers, send/say/stop/ping -client, _refresh_audio_devices, and the cross-platform watcher entry point. -The protocol/handler tests live in test_daemon_protocol.py. +client, _refresh_audio_devices, the cross-platform watcher entry point, and the +wedge watchdog. The protocol/handler tests live in test_daemon_protocol.py. """ from __future__ import annotations import os +import time import pytest @@ -179,17 +180,70 @@ def test_waits_until_the_process_has_exited(self, mocker): assert alive.call_count == 3 assert sleep.call_count == 2 - def test_fails_when_the_process_outlives_the_timeout(self, mocker): + +class TestStopKillsAHungDaemon: + """A daemon that acknowledges `stop` but outlives the wait gets SIGKILL. + + A worker deadlocked in PortAudio blocks the normal shutdown path too, so + without the kill `stop` reported failure and left the daemon running. + """ + + def test_kills_the_process_and_removes_its_files(self, mocker): + mocker.patch.object(daemon, "_read_pid", return_value=4242) + mocker.patch.object(daemon, "send", return_value=(True, "ok")) + mocker.patch.object(daemon, "_pid_alive", side_effect=[True, False]) + mocker.patch.object(daemon.time, "sleep") + kill = mocker.patch.object(daemon.os, "kill") + remove = mocker.patch.object(daemon, "_remove_runtime_files") + + ok, resp = daemon.stop(timeout=0.0) + + assert ok is True + assert "killed pid 4242" in resp + kill.assert_called_once_with(4242, daemon.signal.SIGKILL) + remove.assert_called_once() + + def test_keeps_the_files_of_a_daemon_started_since(self, mocker): + mocker.patch.object(daemon, "_read_pid", side_effect=[4242, 5151]) + mocker.patch.object(daemon, "send", return_value=(True, "ok")) + mocker.patch.object(daemon, "_pid_alive", side_effect=[True, False]) + mocker.patch.object(daemon.time, "sleep") + mocker.patch.object(daemon.os, "kill") + remove = mocker.patch.object(daemon, "_remove_runtime_files") + + ok, _resp = daemon.stop(timeout=0.0) + + assert ok is True + remove.assert_not_called() + + def test_reports_success_when_the_process_exits_before_the_kill(self, mocker): mocker.patch.object(daemon, "_read_pid", return_value=4242) mocker.patch.object(daemon, "send", return_value=(True, "ok")) mocker.patch.object(daemon, "_pid_alive", return_value=True) mocker.patch.object(daemon.time, "sleep") + mocker.patch.object(daemon.os, "kill", side_effect=ProcessLookupError) + remove = mocker.patch.object(daemon, "_remove_runtime_files") + + actual = daemon.stop(timeout=0.0) + + assert actual == (True, "ok") + remove.assert_not_called() + + def test_fails_when_the_process_survives_sigkill(self, mocker): + mocker.patch.object(daemon, "_read_pid", return_value=4242) + mocker.patch.object(daemon, "send", return_value=(True, "ok")) + mocker.patch.object(daemon, "_pid_alive", return_value=True) + mocker.patch.object(daemon.time, "sleep") + mocker.patch.object(daemon, "KILL_TIMEOUT_SECONDS", 0.0) + mocker.patch.object(daemon.os, "kill") + remove = mocker.patch.object(daemon, "_remove_runtime_files") ok, resp = daemon.stop(timeout=0.0) assert ok is False - assert "still alive" in resp + assert "still alive after SIGKILL" in resp assert "4242" in resp + remove.assert_not_called() class TestReadPid: @@ -208,3 +262,134 @@ def test_returns_the_recorded_pid(self, mocker, tmp_path): pid.write_text("4242\n") mocker.patch.object(daemon, "PID_PATH", pid) assert daemon._read_pid() == 4242 + + +class TestRemoveRuntimeFiles: + def test_removes_the_socket_and_pid_files(self, mocker, tmp_path): + sock = tmp_path / "daemon.sock" + pid = tmp_path / "daemon.pid" + sock.touch() + pid.write_text("4242") + mocker.patch.object(daemon, "SOCKET_PATH", sock) + mocker.patch.object(daemon, "PID_PATH", pid) + + daemon._remove_runtime_files() + + assert not sock.exists() + assert not pid.exists() + + def test_tolerates_files_already_gone(self, mocker, tmp_path): + mocker.patch.object(daemon, "SOCKET_PATH", tmp_path / "daemon.sock") + mocker.patch.object(daemon, "PID_PATH", tmp_path / "daemon.pid") + + daemon._remove_runtime_files() # must not raise + + +class TestExitWedged: + def test_removes_the_socket_before_exiting(self, mocker, tmp_path): + """Clients start a fresh daemon when the socket is missing, so it must + be gone by the time the process is.""" + sock = tmp_path / "daemon.sock" + sock.touch() + mocker.patch.object(daemon, "SOCKET_PATH", sock) + mocker.patch.object(daemon, "PID_PATH", tmp_path / "daemon.pid") + socket_present_at_exit = [] + hard_exit = mocker.patch.object( + daemon.os, "_exit", side_effect=lambda code: socket_present_at_exit.append(sock.exists()) + ) + + daemon._exit_wedged() + + hard_exit.assert_called_once_with(daemon.os.EX_SOFTWARE) + assert socket_present_at_exit == [False] + + +class TestUtteranceBudget: + def test_empty_text_gets_the_grace_allowance(self): + assert daemon._utterance_budget("") == daemon.WATCHDOG_GRACE_SECONDS + + def test_grows_with_the_length_of_the_text(self): + actual = daemon._utterance_budget("x" * 1000) + + assert actual == daemon.WATCHDOG_GRACE_SECONDS + 1000 / daemon.WATCHDOG_MIN_CHARS_PER_SECOND + + +@pytest.fixture +def exit_wedged(mocker): + """The watchdog's hard exit, mocked: the real one would end the test run and + delete the live daemon's socket and pid files.""" + return mocker.patch.object(daemon, "_exit_wedged") + + +@pytest.fixture +def state(mocker, exit_wedged): + """A _DaemonState with the engine and the audio side mocked out, and a + watchdog that polls fast enough to test. The poll interval is patched before + the watchdog starts, because its first wait reads it once.""" + mocker.patch.object(daemon, "WATCHDOG_POLL_SECONDS", 0.01) + mocker.patch.object(daemon, "Stackvox") + mocker.patch.object(daemon, "_refresh_audio_devices") + mocker.patch.object(daemon, "_start_device_watcher") + daemon_state = daemon._DaemonState(voice="af_sarah", speed=1.0, lang="en-us") + try: + yield daemon_state + finally: + daemon_state.shutdown() + + +def _wait_until(condition, timeout: float = 1.0) -> None: + deadline = time.monotonic() + timeout + while not condition() and time.monotonic() < deadline: + time.sleep(0.01) + + +class TestWorkerDeadline: + def test_is_armed_during_playback_and_cleared_after(self, state): + deadlines_seen = [] + state.tts.speak.side_effect = lambda *args, **kwargs: deadlines_seen.append(state.deadline) + before = time.monotonic() + + state.submit({"text": "hello"}) + _wait_until(lambda: deadlines_seen and state.deadline is None) + + assert len(deadlines_seen) == 1 + assert deadlines_seen[0] >= before + daemon._utterance_budget("hello") + assert state.deadline is None + + def test_is_cleared_when_playback_fails(self, state): + state.tts.speak.side_effect = RuntimeError("device gone") + + state.submit({"text": "hello"}) + _wait_until(lambda: state.tts.speak.called and state.deadline is None) + + assert state.tts.speak.called + assert state.deadline is None + + +class TestOverrun: + def test_is_none_while_idle(self, state): + assert state.overrun(time.monotonic()) is None + + def test_is_none_within_the_deadline(self, state): + state.deadline = 100.0 + + assert state.overrun(99.0) is None + + def test_is_the_time_past_the_deadline(self, state): + state.deadline = 100.0 + + assert state.overrun(130.0) == 30.0 + + +class TestWatchdog: + def test_exits_once_the_worker_overruns_its_deadline(self, state, exit_wedged): + state.deadline = time.monotonic() - 1.0 + _wait_until(lambda: exit_wedged.called) + + exit_wedged.assert_called() + + def test_leaves_a_worker_within_its_deadline_alone(self, state, exit_wedged): + state.deadline = time.monotonic() + 60.0 + time.sleep(0.1) + + exit_wedged.assert_not_called() From 349e1e52aedc106cc2c79b7afeec59e91a46c69d Mon Sep 17 00:00:00 2001 From: StuBehan Date: Wed, 7 Oct 2026 22:42:28 +0100 Subject: [PATCH 2/3] docs: note the stuck-write wedge alongside the stop deadlock --- README.md | 2 +- stackvox/daemon.py | 12 +++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index b4044fd..7f23a85 100644 --- a/README.md +++ b/README.md @@ -227,7 +227,7 @@ Socket lives at `~/.cache/stackvox/daemon.sock` (override with `STACKVOX_SOCKET` Queue depth is 2 — rapid-fire requests beyond that get `busy` rather than piling up. -If playback hangs the daemon exits rather than answering `busy` forever. Each utterance gets 60s plus half a second per character, slower than any voice reads it even at speed 0.5. Past that the daemon removes its socket and exits with status 70, so `say` reports it isn't running and anything that starts the daemon on demand gets a fresh one. On macOS this has been a deadlock inside PortAudio stopping a stream, which `cancel` can't break. +If playback hangs the daemon exits rather than answering `busy` forever. Each utterance gets 60s plus half a second per character, slower than any voice reads it even at speed 0.5. Past that the daemon removes its socket and exits with status 70, so `say` reports it isn't running and anything that starts the daemon on demand gets a fresh one. On macOS this has been PortAudio deadlocked stopping a stream, or stuck writing to an output device that stopped taking audio, and `cancel` can't break either. Before each utterance the daemon resets PortAudio so it picks up the current system default output device. Swap from speakers to Bluetooth headphones mid-session and the next `say` follows you — no daemon restart needed. The refresh costs ~10–50ms per play, which is invisible next to synthesis time. diff --git a/stackvox/daemon.py b/stackvox/daemon.py index d8e6b10..60d8855 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -57,8 +57,8 @@ # setup and teardown, plus the text read slower than any voice actually reads # it. Dense text (numbers, acronyms) at kokoro's minimum speed of 0.5 measures # about 3.4 chars/s, so 2 chars/s leaves headroom even there. A worker still on -# one utterance past its budget is treated as wedged. The case seen so far is a -# deadlock in native audio code, which no Python-level cancel can interrupt. +# one utterance past its budget is treated as wedged. The cases seen so far hang +# in native audio code, which no Python-level cancel can interrupt. WATCHDOG_GRACE_SECONDS = 60.0 WATCHDOG_MIN_CHARS_PER_SECOND = 2.0 WATCHDOG_POLL_SECONDS = 5.0 @@ -197,9 +197,11 @@ def _exit_wedged() -> None: """Exit hard so a fresh daemon can take over from a wedged one. On macOS the worker has been seen deadlocked inside PortAudio's stream stop, - waiting on a CoreAudio lock held by CoreAudio's own IO thread. A normal - shutdown didn't get out either (`stop` timed out with the process still - alive), so this uses `os._exit`. The socket goes first: clients that start + waiting on a CoreAudio lock held by CoreAudio's own IO thread, and parked + for days in a blocking write to an output device that stopped taking audio, + which `cancel`'s stream abort didn't release. A normal shutdown didn't get + out of the first (`stop` timed out with the process still alive), so this + uses `os._exit`. The socket goes first: clients that start the daemon on demand do so when the socket is missing, and until it is gone they keep getting `busy`. """ From 00f6d9b7777074c1a40d94ce766966bb881ba66c Mon Sep 17 00:00:00 2001 From: StuBehan Date: Wed, 7 Oct 2026 22:53:27 +0100 Subject: [PATCH 3/3] fix: refuse non-string text before it reaches the worker --- README.md | 2 +- stackvox/daemon.py | 5 +++++ tests/test_daemon_protocol.py | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7f23a85..2ebed0c 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ Keeps the model resident so each subsequent call is instant: stackvox serve # foreground; run with `nohup stackvox serve &` to background stackvox status # is the daemon up? also shows version + any pending PyPI update stackvox say "Hello" # send text to the daemon (fails if not running) -stackvox stop # graceful shutdown, force-killed if it's still up after 5s +stackvox stop # graceful shutdown, force-killed if it acknowledges but is still up after 5s ``` stackvox checks PyPI for newer versions but only at two moments — when you run `stackvox status` and at daemon startup. The script-heavy paths (`say`, `speak`, `stackvox-say`, hooks, CI) never make a network call. To see notices on every invocation set `STACKVOX_UPDATE_NOTICE=1`. To disable the check entirely set `STACKVOX_NO_UPDATE_CHECK=1`. The check is auto-skipped when common CI env vars (`CI`, `GITHUB_ACTIONS`, etc.) are set so build logs stay clean. diff --git a/stackvox/daemon.py b/stackvox/daemon.py index 60d8855..8cea416 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -326,6 +326,11 @@ def handle(self) -> None: if not text: self.wfile.write(b"err: missing text\n") return + # The worker sizes its watchdog budget from len(text) before playback's + # try, so anything else queued here would kill the worker. + if not isinstance(text, str): + self.wfile.write(b"err: text must be a string\n") + return if state.submit(req): self.wfile.write(b"ok\n") diff --git a/tests/test_daemon_protocol.py b/tests/test_daemon_protocol.py index c554f68..ad6d0a3 100644 --- a/tests/test_daemon_protocol.py +++ b/tests/test_daemon_protocol.py @@ -110,6 +110,18 @@ def test_missing_text_yields_error(server: ServerHarness): assert reply.startswith("err:") +def test_non_string_text_is_refused_and_the_worker_keeps_playing(server: ServerHarness): + import time + + assert _roundtrip(server.sock, json.dumps({"text": 5}) + "\n") == "err: text must be a string" + + assert _roundtrip(server.sock, "hello\n") == "ok" + deadline = time.monotonic() + 1.0 + while not server.tts.speak.call_args_list and time.monotonic() < deadline: + time.sleep(0.01) + assert server.tts.speak.call_args.args[0] == "hello" + + def test_full_queue_returns_busy(server: ServerHarness): from stackvox import daemon