From a8f3844fa54e3f14d1d671b2b9d1fa699b06e9c8 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 00:13:53 +0100 Subject: [PATCH 1/6] feat: let config choose the daemon's backend --- README.md | 16 ++++++ stackvox/cli.py | 78 ++++++++++++++++++++++++----- stackvox/config.py | 114 ++++++++++++++++++++++++++++++++++++++++-- tests/test_cli.py | 116 +++++++++++++++++++++++++++++++++++++++++++ tests/test_config.py | 92 +++++++++++++++++++++++++++++++++- 5 files changed, 399 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 4a897d3..a68b00f 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,8 @@ lang = "en-gb" CLI flags always win over config values, and config values always win over the built-in defaults. The one thing between a flag and the config is a [voice mix](#voice-mixes)'s own `lang` and `speed`, so `--voice chip` stays transatlantic even when `[defaults]` sets `lang = "en-us"`. A missing file is fine — built-ins apply. A malformed file logs a warning and is ignored. +A `[serve]` table picks the backend the daemon starts with, for when something else starts it and you can't add flags. See [Local MLX models](#local-mlx-models-apple-silicon). + ## Daemon mode Keeps the model resident so each subsequent call is instant: @@ -208,6 +210,20 @@ stackvox say \ "This request uses the resident model." ``` +To make a model the daemon's default, put it in the [config file](#configuration) instead. A plain `stackvox serve` then loads it, whatever starts the daemon (a login item, an app): + +```toml +[serve] +backend = "mlx" +model_dir = "~/models/my-model" +model_adapter = "~/.config/stackvox/adapters/my_model.py" # optional +# Optional generation defaults, the same names as the flags: +reference_audio = "~/voices/reference.wav" +reference_text = "The exact transcript of the reference audio." +``` + +Passing `--backend` ignores the table altogether. Any other flag beats its matching key. Only `serve` acts on `[serve]`, so `speak` from an install without the mlx extra isn't affected. If the configured model fails to load, `serve` logs why and starts Kokoro instead, so a daemon that gets restarted automatically doesn't crash loop into silence. `--backend mlx` on the command line still fails outright. + Generation options (`--reference-audio`, `--reference-text`, `--instruct`, `--temperature`, `--top-p`, `--top-k`) are forwarded only when set, so each model's own defaults apply otherwise; which ones a model honours depends on diff --git a/stackvox/cli.py b/stackvox/cli.py index 0727512..430753d 100644 --- a/stackvox/cli.py +++ b/stackvox/cli.py @@ -3,6 +3,7 @@ from __future__ import annotations import argparse +import functools import logging import os import sys @@ -170,7 +171,7 @@ def _build_parser(defaults: config.Defaults | None = None) -> argparse.ArgumentP p_serve = sub.add_parser("serve", help="Run the daemon in the foreground") _add_voice_args(p_serve, defaults) - _add_backend_args(p_serve) + _add_backend_args(p_serve, from_config=True) _add_generation_args(p_serve) sub.add_parser("stop", help="Stop the running daemon") @@ -225,12 +226,15 @@ def _voice_params(args: argparse.Namespace) -> tuple[VoiceParams, dict[str, Voic return params, custom -def _add_backend_args(parser: argparse.ArgumentParser) -> None: +def _add_backend_args(parser: argparse.ArgumentParser, *, from_config: bool = False) -> None: + # serve leaves --backend unset when it isn't given, so _apply_serve_config can + # tell "no flag" from an explicit --backend kokoro and consult [serve]. + default_help = f"[serve] backend in config, then {DEFAULT_BACKEND}" if from_config else DEFAULT_BACKEND parser.add_argument( "--backend", choices=BACKENDS, - default=DEFAULT_BACKEND, - help="TTS backend (default: %(default)s). --voice/--lang apply to kokoro only", + default=None if from_config else DEFAULT_BACKEND, + help=f"TTS backend (default: {default_help}). --voice/--lang apply to kokoro only", ) parser.add_argument( "--model-dir", type=Path, help="Local MLX Audio model directory (required for --backend mlx)" @@ -275,6 +279,32 @@ def _validate_backend_args(parser: argparse.ArgumentParser, args: argparse.Names ) +def _apply_serve_config(args: argparse.Namespace) -> None: + """Fill serve's backend settings from ``[serve]`` when no --backend flag chose one. + + An explicit --backend means exactly what the flags say, so the config is only + consulted without one. Within the config's backend a flag still beats the + matching key. ``backend_from_config`` lets _cmd_serve fall back to Kokoro + when the configured model can't load. + """ + args.backend_from_config = False + if args.backend is not None: + return + serve_config = config.load_serve() + if serve_config.backend is None: + args.backend = DEFAULT_BACKEND + return + args.backend = serve_config.backend + args.backend_from_config = True + if args.model_dir is None: + args.model_dir = serve_config.model_dir + if args.model_adapter is None: + args.model_adapter = serve_config.model_adapter + for key, value in serve_config.generation.items(): + if getattr(args, key) is None: + setattr(args, key, value) + + def _add_normalize_args(parser: argparse.ArgumentParser, *, with_switch: bool) -> None: """Flags mapping one-to-one onto ``stackvox.text.normalize_for_speech``. @@ -509,16 +539,28 @@ def _cmd_normalize(args: argparse.Namespace) -> int: def _cmd_serve(args: argparse.Namespace) -> int: try: params, custom = _voice_params(args) - daemon.serve( - voice=params.voice, - speed=params.speed, - lang=params.lang, - custom_voices=custom, - backend=args.backend, - model_dir=args.model_dir, - model_adapter=args.model_adapter, - **_generation_kwargs(args), + start_daemon = functools.partial( + daemon.serve, voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom ) + try: + start_daemon( + backend=args.backend, + model_dir=args.model_dir, + model_adapter=args.model_adapter, + **_generation_kwargs(args), + ) + except ModelLoadError as exc: + # A daemon that exits here is restarted by whatever supervises it, + # fails the same way, and leaves the user with no voice at all. A model + # chosen by flag still fails, as before: whoever passed it asked for it. + if not getattr(args, "backend_from_config", False): + raise + print(f"[stackvox] {exc}", file=sys.stderr) + print( + f"[stackvox] the [serve] backend failed to load; serving {DEFAULT_BACKEND} instead", + file=sys.stderr, + ) + start_daemon() except RuntimeError as exc: print(f"[stackvox] {exc}", file=sys.stderr) return 1 @@ -600,6 +642,14 @@ def _cmd_config(_: argparse.Namespace) -> int: print(f"voice: {defaults.voice}") print(f"speed: {defaults.speed}") print(f"lang: {defaults.lang}") + serve_config = config.load_serve() + print(f"serve backend: {serve_config.backend or f'{DEFAULT_BACKEND} (built-in)'}") + if serve_config.model_dir is not None: + print(f"serve model_dir: {serve_config.model_dir}") + if serve_config.model_adapter is not None: + print(f"serve model_adapter: {serve_config.model_adapter}") + for key, value in serve_config.generation.items(): + print(f"serve {key}: {value}") return 0 @@ -683,6 +733,8 @@ def main() -> int: parser = _build_parser(config.load_defaults()) args = parser.parse_args(argv) + if args.cmd == "serve": + _apply_serve_config(args) _validate_backend_args(parser, args) if not args.cmd: diff --git a/stackvox/config.py b/stackvox/config.py index c72a529..7a706cd 100644 --- a/stackvox/config.py +++ b/stackvox/config.py @@ -1,4 +1,5 @@ -"""User config file: per-user defaults for voice / speed / lang, and voice mixes. +"""User config file: per-user defaults for voice / speed / lang, voice mixes, and +the daemon's backend. Lives at `$XDG_CONFIG_HOME/stackvox/config.toml` (falling back to `~/.config/stackvox/config.toml`), or wherever `STACKVOX_CONFIG` points if set. @@ -17,9 +18,18 @@ lang = "en-gb" speed = 1.0 + [serve] + backend = "mlx" + model_dir = "~/models/my-model" + model_adapter = "~/.config/stackvox/adapters/my_model.py" + Each ``[voices.]`` table defines a Kokoro voice mix addressable by that name, alongside the built-in ones in ``stackvox.voices``. A table with a built-in's name replaces it. + +``[serve]`` picks the backend ``stackvox serve`` starts when no ``--backend`` +flag is given, plus that backend's model and generation defaults (the +``stackvox.engine.MLX_OPTIONS`` names). No other command acts on it. """ from __future__ import annotations @@ -27,15 +37,17 @@ import logging import os import sys -from dataclasses import dataclass +from collections.abc import Callable +from dataclasses import dataclass, field from pathlib import Path +from typing import Any if sys.version_info >= (3, 11): import tomllib else: # pragma: no cover - covered by 3.10 CI import tomli as tomllib -from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE +from stackvox.engine import BACKENDS, DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE from stackvox.voices import BUILTIN_VOICES, VoiceMix logger = logging.getLogger(__name__) @@ -50,6 +62,16 @@ class Defaults: lang: str = DEFAULT_LANG +@dataclass(frozen=True) +class ServeConfig: + """The daemon's backend settings from ``[serve]``. A None backend leaves the choice to the flags.""" + + backend: str | None = None + model_dir: Path | None = None + model_adapter: Path | None = None + generation: dict[str, Any] = field(default_factory=dict) + + def config_path() -> Path: """Resolve where the config file lives. @@ -148,3 +170,89 @@ def _parse_mix(table: object) -> VoiceMix | None: lang=lang, speed=float(speed) if speed is not None else None, ) + + +def load_serve(path: Path | None = None) -> ServeConfig: + """Read the daemon's backend settings from ``[serve]``. + + Only ``stackvox serve`` acts on this. The file is shared by every stackvox + install on the machine, and a ``speak`` from one without the mlx extra + would fail if it picked the mlx backend up from here. + + Lenient like ``[defaults]``: a missing table gives an empty ServeConfig and a + bad value is logged and dropped. An mlx backend without a usable + ``model_dir`` is dropped whole, since the daemon could not start with it. + """ + p = path or config_path() + data = _read(p) + if data is None: + return ServeConfig() + section = data.get("serve", {}) + if not isinstance(section, dict): + logger.warning("config %s: [serve] must be a table; ignoring", p) + return ServeConfig() + backend = section.get("backend") + if backend is None: + if section: + logger.warning("config %s: [serve] settings need a backend; ignoring [serve]", p) + return ServeConfig() + if backend not in BACKENDS: + logger.warning( + "config %s: [serve] backend must be one of %s; ignoring [serve]", p, ", ".join(BACKENDS) + ) + return ServeConfig() + if backend != "mlx": + ignored = sorted(set(section) - {"backend"}) + if ignored: + logger.warning( + "config %s: [serve] %s apply to the mlx backend only; ignoring", p, ", ".join(ignored) + ) + return ServeConfig(backend=backend) + model_dir = _path(section.get("model_dir")) + if model_dir is None: + logger.warning('config %s: [serve] backend = "mlx" needs model_dir; ignoring [serve]', p) + return ServeConfig() + model_adapter = _path(section.get("model_adapter")) + if model_adapter is None and "model_adapter" in section: + logger.warning("config %s: [serve] model_adapter must be a path; ignoring it", p) + generation: dict[str, Any] = {} + for key, parse in _GENERATION_PARSERS.items(): + if key not in section: + continue + value = parse(section[key]) + if value is None: + logger.warning("config %s: [serve] %s has the wrong type; ignoring it", p, key) + continue + generation[key] = value + return ServeConfig(backend="mlx", model_dir=model_dir, model_adapter=model_adapter, generation=generation) + + +def _path(value: object) -> Path | None: + return Path(value).expanduser() if isinstance(value, str) and value else None + + +def _text(value: object) -> str | None: + return value if isinstance(value, str) else None + + +def _number(value: object) -> float | None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + return float(value) + + +def _integer(value: object) -> int | None: + if isinstance(value, bool) or not isinstance(value, int): + return None + return value + + +# One entry per name in stackvox.engine.MLX_OPTIONS, typed as the engine takes it. +_GENERATION_PARSERS: dict[str, Callable[[object], Any]] = { + "reference_audio": _path, + "reference_text": _text, + "instruct": _text, + "temperature": _number, + "top_p": _number, + "top_k": _integer, +} diff --git a/tests/test_cli.py b/tests/test_cli.py index 9cfd9c5..26d22e5 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -834,3 +834,119 @@ def test_adapter_on_kokoro_is_a_usage_error(self, mocker, capsys): cli.main() assert exc.value.code == 2 assert "require --backend mlx" in capsys.readouterr().err + + +class TestServeBackendFromConfig: + """``[serve]`` picks serve's backend only when no --backend flag does.""" + + MLX_SERVE = '[serve]\nbackend = "mlx"\nmodel_dir = "/models/voice"\nmodel_adapter = "/adapters/voice.py"\ntop_k = 20\n' + + def _config(self, monkeypatch, tmp_path, body): + path = tmp_path / "config.toml" + path.write_text(body, encoding="utf-8") + monkeypatch.setenv("STACKVOX_CONFIG", str(path)) + + def _serve_args(self, **overrides): + values = { + "backend": None, + "model_dir": None, + "model_adapter": None, + **{key: None for key in cli.MLX_OPTIONS}, + } + return _ns(**{**values, **overrides}) + + def test_config_supplies_the_backend_when_no_flag_does(self, monkeypatch, tmp_path): + from pathlib import Path + + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + args = self._serve_args() + + cli._apply_serve_config(args) + + assert args.backend == "mlx" + assert args.backend_from_config is True + assert args.model_dir == Path("/models/voice") + assert args.model_adapter == Path("/adapters/voice.py") + assert args.top_k == 20 + + def test_explicit_backend_flag_ignores_the_config(self, monkeypatch, tmp_path): + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + args = self._serve_args(backend="kokoro") + + cli._apply_serve_config(args) + + assert args.backend == "kokoro" + assert args.backend_from_config is False + assert args.model_dir is None + assert args.top_k is None + + def test_flags_beat_the_matching_config_keys(self, monkeypatch, tmp_path): + from pathlib import Path + + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + args = self._serve_args(model_adapter=Path("/elsewhere.py"), top_k=5) + + cli._apply_serve_config(args) + + assert args.model_adapter == Path("/elsewhere.py") + assert args.top_k == 5 + + def test_no_serve_table_means_kokoro(self): + args = self._serve_args() + + cli._apply_serve_config(args) + + assert args.backend == "kokoro" + assert args.backend_from_config is False + + def test_config_backend_admits_generation_flags_through_main(self, mocker, monkeypatch, tmp_path): + """[serve] is applied before validation, so --instruct isn't refused as Kokoro-only.""" + from pathlib import Path + + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + serve = mocker.patch.object(cli.daemon, "serve") + mocker.patch.object(cli.sys, "argv", ["stackvox", "serve", "--instruct", "Warmly."]) + + assert cli.main() == 0 + kwargs = serve.call_args.kwargs + assert kwargs["backend"] == "mlx" + assert kwargs["model_dir"] == Path("/models/voice") + assert kwargs["instruct"] == "Warmly." + assert kwargs["top_k"] == 20 + + def test_falls_back_to_kokoro_when_the_configured_model_fails_to_load(self, mocker, capsys): + serve = mocker.patch.object(cli.daemon, "serve", side_effect=[cli.ModelLoadError("no model"), None]) + args = self._serve_args( + voice="af_sarah", speed=1.0, lang="en-us", backend="mlx", backend_from_config=True + ) + + assert cli._cmd_serve(args) == 0 + assert serve.call_count == 2 + assert serve.call_args.kwargs == { + "voice": "af_sarah", + "speed": 1.0, + "lang": "en-us", + "custom_voices": BUILTIN_VOICES, + } + err = capsys.readouterr().err + assert "no model" in err + assert "serving kokoro instead" in err + + def test_a_flagged_model_that_fails_to_load_still_fails(self, mocker, capsys): + serve = mocker.patch.object(cli.daemon, "serve", side_effect=cli.ModelLoadError("no model")) + args = self._serve_args( + voice="af_sarah", speed=1.0, lang="en-us", backend="mlx", backend_from_config=False + ) + + assert cli._cmd_serve(args) == 1 + assert serve.call_count == 1 + assert "no model" in capsys.readouterr().err + + def test_config_command_shows_the_serve_backend(self, monkeypatch, tmp_path, capsys): + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + + assert cli._cmd_config(_ns()) == 0 + out = capsys.readouterr().out + assert "serve backend: mlx" in out + assert "serve model_dir: /models/voice" in out + assert "serve top_k: 20" in out diff --git a/tests/test_config.py b/tests/test_config.py index 594c59b..9890f87 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,9 +3,10 @@ from __future__ import annotations import logging +from pathlib import Path from stackvox import config -from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE +from stackvox.engine import DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE, MLX_OPTIONS from stackvox.voices import BUILTIN_VOICES, VoiceMix @@ -154,3 +155,92 @@ def test_voices_section_must_be_a_table(self, tmp_path, caplog): with caplog.at_level(logging.WARNING, logger="stackvox.config"): assert config.load_voices(path) == BUILTIN_VOICES assert "[voices] must be a table" in caplog.text + + +class TestLoadServe: + def _write(self, tmp_path, body): + path = tmp_path / "config.toml" + path.write_text(body, encoding="utf-8") + return path + + def test_missing_file_leaves_the_backend_to_the_flags(self, tmp_path): + assert config.load_serve(tmp_path / "absent.toml") == config.ServeConfig() + + def test_file_without_a_serve_table_leaves_the_backend_to_the_flags(self, tmp_path): + path = self._write(tmp_path, '[defaults]\nvoice = "bf_emma"\n') + assert config.load_serve(path) == config.ServeConfig() + + def test_mlx_backend_with_model_and_generation_defaults(self, tmp_path): + path = self._write( + tmp_path, + "[serve]\n" + 'backend = "mlx"\n' + 'model_dir = "~/models/voice"\n' + 'model_adapter = "~/adapters/voice.py"\n' + 'reference_audio = "~/ref.wav"\n' + 'reference_text = "Ref."\n' + "temperature = 1\n" + "top_k = 20\n", + ) + + actual = config.load_serve(path) + + assert actual.backend == "mlx" + assert actual.model_dir == Path("~/models/voice").expanduser() + assert actual.model_adapter == Path("~/adapters/voice.py").expanduser() + assert actual.generation == { + "reference_audio": Path("~/ref.wav").expanduser(), + "reference_text": "Ref.", + "temperature": 1.0, + "top_k": 20, + } + + def test_mlx_backend_without_model_dir_is_dropped(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nbackend = "mlx"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "needs model_dir" in caplog.text + + def test_unknown_backend_is_dropped(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nbackend = "espeak"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "backend must be one of" in caplog.text + + def test_settings_without_a_backend_are_dropped(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nmodel_dir = "/models/voice"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "need a backend" in caplog.text + + def test_kokoro_backend_ignores_mlx_only_settings(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nbackend = "kokoro"\nmodel_dir = "/models/voice"\ntop_k = 5\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig(backend="kokoro") + assert "model_dir, top_k apply to the mlx backend only" in caplog.text + + def test_a_badly_typed_value_drops_only_that_key(self, tmp_path, caplog): + path = self._write( + tmp_path, + '[serve]\nbackend = "mlx"\nmodel_dir = "/models/voice"\nmodel_adapter = 3\ntop_k = 1.5\ntop_p = 0.9\n', + ) + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + actual = config.load_serve(path) + assert actual == config.ServeConfig( + backend="mlx", model_dir=Path("/models/voice"), generation={"top_p": 0.9} + ) + assert "model_adapter must be a path" in caplog.text + assert "top_k has the wrong type" in caplog.text + + def test_boolean_is_not_a_number(self, tmp_path): + path = self._write(tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\ntemperature = true\n') + assert config.load_serve(path).generation == {} + + def test_serve_section_must_be_a_table(self, tmp_path, caplog): + path = self._write(tmp_path, 'serve = "mlx"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "[serve] must be a table" in caplog.text + + def test_parses_every_generation_option_the_engine_takes(self): + assert set(config._GENERATION_PARSERS) == set(MLX_OPTIONS) From 396f0ba8079289594672f08474f7aa830f8a48cf Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 00:23:07 +0100 Subject: [PATCH 2/6] fix: drop half reference pairs and unusable paths --- stackvox/config.py | 22 ++++++++++++++++++---- tests/test_config.py | 31 ++++++++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/stackvox/config.py b/stackvox/config.py index 7a706cd..c3b36d6 100644 --- a/stackvox/config.py +++ b/stackvox/config.py @@ -210,25 +210,39 @@ def load_serve(path: Path | None = None) -> ServeConfig: return ServeConfig(backend=backend) model_dir = _path(section.get("model_dir")) if model_dir is None: - logger.warning('config %s: [serve] backend = "mlx" needs model_dir; ignoring [serve]', p) + logger.warning('config %s: [serve] backend = "mlx" needs a usable model_dir; ignoring [serve]', p) return ServeConfig() model_adapter = _path(section.get("model_adapter")) if model_adapter is None and "model_adapter" in section: - logger.warning("config %s: [serve] model_adapter must be a path; ignoring it", p) + logger.warning("config %s: [serve] model_adapter is not a usable path; ignoring it", p) generation: dict[str, Any] = {} for key, parse in _GENERATION_PARSERS.items(): if key not in section: continue value = parse(section[key]) if value is None: - logger.warning("config %s: [serve] %s has the wrong type; ignoring it", p, key) + logger.warning("config %s: [serve] %s is invalid; ignoring it", p, key) continue generation[key] = value + # The engine refuses one without the other on every request, so a daemon + # started with half a pair would come up and then fail everything it's asked. + if ("reference_audio" in generation) != ("reference_text" in generation): + logger.warning( + "config %s: [serve] reference_audio and reference_text only work together; ignoring the one given", + p, + ) + generation.pop("reference_audio", None) + generation.pop("reference_text", None) return ServeConfig(backend="mlx", model_dir=model_dir, model_adapter=model_adapter, generation=generation) def _path(value: object) -> Path | None: - return Path(value).expanduser() if isinstance(value, str) and value else None + if not isinstance(value, str) or not value: + return None + try: + return Path(value).expanduser() + except RuntimeError: # "~name/..." for a user this machine doesn't have + return None def _text(value: object) -> str | None: diff --git a/tests/test_config.py b/tests/test_config.py index 9890f87..e72bfde 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -199,7 +199,7 @@ def test_mlx_backend_without_model_dir_is_dropped(self, tmp_path, caplog): path = self._write(tmp_path, '[serve]\nbackend = "mlx"\n') with caplog.at_level(logging.WARNING, logger="stackvox.config"): assert config.load_serve(path) == config.ServeConfig() - assert "needs model_dir" in caplog.text + assert "needs a usable model_dir" in caplog.text def test_unknown_backend_is_dropped(self, tmp_path, caplog): path = self._write(tmp_path, '[serve]\nbackend = "espeak"\n') @@ -229,8 +229,8 @@ def test_a_badly_typed_value_drops_only_that_key(self, tmp_path, caplog): assert actual == config.ServeConfig( backend="mlx", model_dir=Path("/models/voice"), generation={"top_p": 0.9} ) - assert "model_adapter must be a path" in caplog.text - assert "top_k has the wrong type" in caplog.text + assert "model_adapter is not a usable path" in caplog.text + assert "top_k is invalid" in caplog.text def test_boolean_is_not_a_number(self, tmp_path): path = self._write(tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\ntemperature = true\n') @@ -244,3 +244,28 @@ def test_serve_section_must_be_a_table(self, tmp_path, caplog): def test_parses_every_generation_option_the_engine_takes(self): assert set(config._GENERATION_PARSERS) == set(MLX_OPTIONS) + + def test_half_a_reference_pair_is_dropped(self, tmp_path, caplog): + path = self._write( + tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\nreference_audio = "/ref.wav"\ntop_k = 5\n' + ) + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + actual = config.load_serve(path) + assert actual.generation == {"top_k": 5} + assert "only work together" in caplog.text + + def test_unexpandable_model_dir_is_dropped_rather_than_raising(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "~no-such-user-xyz/model"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "needs a usable model_dir" in caplog.text + + def test_unexpandable_adapter_is_dropped_rather_than_raising(self, tmp_path, caplog): + path = self._write( + tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\nmodel_adapter = "~no-such-user-xyz/a.py"\n' + ) + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + actual = config.load_serve(path) + assert actual.model_adapter is None + assert actual.model_dir == Path("/m") + assert "model_adapter is not a usable path" in caplog.text From 33ee2c00fde5b118ef63dd58ca3306e9763af724 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 00:41:24 +0100 Subject: [PATCH 3/6] feat: lock daemon startup and tighten [serve] --- README.md | 6 +- stackvox/cli.py | 123 +++++++++++++++++---------- stackvox/config.py | 42 +++++++--- stackvox/daemon.py | 151 +++++++++++++++++++++++---------- stackvox/engine.py | 2 + stackvox/paths.py | 9 +- tests/test_cli.py | 152 ++++++++++++++++++++++++++++++++++ tests/test_config.py | 40 +++++++++ tests/test_daemon.py | 72 ++++++++++++++++ tests/test_daemon_protocol.py | 5 ++ 10 files changed, 501 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index a68b00f..b1d35a0 100644 --- a/README.md +++ b/README.md @@ -107,11 +107,13 @@ Keeps the model resident so each subsequent call is instant: ```bash stackvox serve # foreground; run with `nohup stackvox serve &` to background -stackvox status # is the daemon up? also shows version + any pending PyPI update +stackvox status # is the daemon up? also shows version, backend + any pending PyPI update stackvox say "Hello" # send text to the daemon (fails if not running) stackvox stop # graceful shutdown, force-killed if it acknowledges but is still up after 5s ``` +Only one daemon starts at a time. A `serve` started while another is running, or still loading its model, exits straight away rather than loading a second copy. + 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. ## `stackvox-say` (bash helper, ~13ms) @@ -222,7 +224,7 @@ reference_audio = "~/voices/reference.wav" reference_text = "The exact transcript of the reference audio." ``` -Passing `--backend` ignores the table altogether. Any other flag beats its matching key. Only `serve` acts on `[serve]`, so `speak` from an install without the mlx extra isn't affected. If the configured model fails to load, `serve` logs why and starts Kokoro instead, so a daemon that gets restarted automatically doesn't crash loop into silence. `--backend mlx` on the command line still fails outright. +Passing `--backend` or `--model-dir` ignores the table altogether, since the flags then describe the model. Any other flag beats its matching key, and the reference clip and its transcript count as one setting, so give both flags or neither. Relative paths are relative to the config file's folder, and an unknown key (`top-p` for `top_p`, say) gets a warning. Only `serve` acts on `[serve]`, so `speak` from an install without the mlx extra isn't affected. If the configured model fails to load, `serve` logs why and starts Kokoro instead, so a daemon that gets restarted automatically doesn't crash loop into silence, and `stackvox status` shows which backend is actually running. A model named on the command line still fails outright. Generation options (`--reference-audio`, `--reference-text`, `--instruct`, `--temperature`, `--top-p`, `--top-k`) are forwarded only when set, so each diff --git a/stackvox/cli.py b/stackvox/cli.py index 430753d..8005d9b 100644 --- a/stackvox/cli.py +++ b/stackvox/cli.py @@ -12,7 +12,7 @@ import soundfile as sf from stackvox import config, daemon, paths, updates -from stackvox.engine import BACKENDS, DEFAULT_BACKEND, MLX_OPTIONS, Stackvox +from stackvox.engine import BACKENDS, DEFAULT_BACKEND, MLX_OPTIONS, REFERENCE_PAIR, Stackvox from stackvox.mlx_backend import ModelLoadError from stackvox.text import normalize_for_speech from stackvox.voices import VoiceMix, VoiceParams, resolve @@ -265,44 +265,55 @@ def _generation_kwargs(args: argparse.Namespace) -> dict: def _validate_backend_args(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: """Fail fast on backend/option mismatches before loading a model. - ``say`` has no ``--backend``: the daemon decides, and rejects generation options - itself when it is running Kokoro. + For serve this runs after _apply_serve_config, so it checks what the flags and + ``[serve]`` add up to. ``say`` has no ``--backend``: the daemon decides, and + rejects generation options itself when it is running Kokoro. The reference + pair is checked for ``say`` too, since the engine refuses half a pair. """ + if sum(getattr(args, key, None) is not None for key in REFERENCE_PAIR) == 1: + parser.error("--reference-audio and --reference-text must be given together") backend = getattr(args, "backend", None) if backend is None: return if backend == "mlx" and args.model_dir is None: parser.error("--backend mlx requires --model-dir") - if backend != "mlx" and (_generation_kwargs(args) or args.model_adapter is not None): + if backend != "mlx" and ( + _generation_kwargs(args) or args.model_dir is not None or args.model_adapter is not None + ): parser.error( - "--model-adapter and generation options (--reference-audio, --instruct, ...) require --backend mlx" + "--model-dir, --model-adapter and generation options (--reference-audio, --instruct, ...) " + "require --backend mlx" ) def _apply_serve_config(args: argparse.Namespace) -> None: - """Fill serve's backend settings from ``[serve]`` when no --backend flag chose one. - - An explicit --backend means exactly what the flags say, so the config is only - consulted without one. Within the config's backend a flag still beats the - matching key. ``backend_from_config`` lets _cmd_serve fall back to Kokoro - when the configured model can't load. + """Fill serve's backend settings from ``[serve]`` when no flag chose the model. + + --backend or --model-dir on the command line means the flags describe the + model, so the table is left out entirely: its adapter and voice belong to + its own model, and a model someone named by flag should fail loudly rather + than fall back. Otherwise a flag still beats its matching key, with the + reference clip and its transcript treated as one setting. + ``backend_from_config`` lets _cmd_serve fall back to Kokoro when the + configured model can't load. """ args.backend_from_config = False - if args.backend is not None: - return - serve_config = config.load_serve() - if serve_config.backend is None: + if args.backend is None and args.model_dir is None: + serve_config = config.load_serve() + if serve_config.backend is not None: + args.backend = serve_config.backend + args.backend_from_config = True + args.model_dir = serve_config.model_dir + if args.model_adapter is None: + args.model_adapter = serve_config.model_adapter + reference_flagged = any(getattr(args, key) is not None for key in REFERENCE_PAIR) + for key, value in serve_config.generation.items(): + if key in REFERENCE_PAIR and reference_flagged: + continue + if getattr(args, key) is None: + setattr(args, key, value) + if args.backend is None: args.backend = DEFAULT_BACKEND - return - args.backend = serve_config.backend - args.backend_from_config = True - if args.model_dir is None: - args.model_dir = serve_config.model_dir - if args.model_adapter is None: - args.model_adapter = serve_config.model_adapter - for key, value in serve_config.generation.items(): - if getattr(args, key) is None: - setattr(args, key, value) def _add_normalize_args(parser: argparse.ArgumentParser, *, with_switch: bool) -> None: @@ -542,25 +553,29 @@ def _cmd_serve(args: argparse.Namespace) -> int: start_daemon = functools.partial( daemon.serve, voice=params.voice, speed=params.speed, lang=params.lang, custom_voices=custom ) - try: - start_daemon( - backend=args.backend, - model_dir=args.model_dir, - model_adapter=args.model_adapter, - **_generation_kwargs(args), - ) - except ModelLoadError as exc: - # A daemon that exits here is restarted by whatever supervises it, - # fails the same way, and leaves the user with no voice at all. A model - # chosen by flag still fails, as before: whoever passed it asked for it. - if not getattr(args, "backend_from_config", False): - raise - print(f"[stackvox] {exc}", file=sys.stderr) - print( - f"[stackvox] the [serve] backend failed to load; serving {DEFAULT_BACKEND} instead", - file=sys.stderr, - ) - start_daemon() + # Held across both attempts, so no other daemon can start in the gap + # between a failed configured backend and its fallback. + with daemon.startup_lock(): + try: + start_daemon( + backend=args.backend, + model_dir=args.model_dir, + model_adapter=args.model_adapter, + **_generation_kwargs(args), + ) + except ModelLoadError as exc: + # A daemon that exits here is restarted by whatever supervises it, + # fails the same way, and leaves the user with no voice at all. A + # model chosen by flag still fails, as before: whoever passed it + # asked for it. + if not getattr(args, "backend_from_config", False): + raise + print(f"[stackvox] {exc}", file=sys.stderr) + print( + f"[stackvox] the [serve] backend failed to load; serving {DEFAULT_BACKEND} instead", + file=sys.stderr, + ) + start_daemon() except RuntimeError as exc: print(f"[stackvox] {exc}", file=sys.stderr) return 1 @@ -607,6 +622,7 @@ def _cmd_status(_: argparse.Namespace) -> int: f"daemon running {running_version} is newer than the {installed} client " f"you just ran; no restart needed" ) + _print_running_backend() else: print("stopped") rc = 1 @@ -620,6 +636,25 @@ def _cmd_status(_: argparse.Namespace) -> int: return rc +def _print_running_backend() -> None: + """Show the backend the daemon is serving, and say so when it isn't the [serve] one. + + ``stackvox config`` shows what is configured. After a fallback, or with a + --backend flag, the daemon runs something else, and the voice alone doesn't + say which. A daemon too old to answer prints nothing. + """ + got, running = daemon.backend() + if not got: + return + print(f"backend: {running}") + configured = config.load_serve().backend + if configured is not None and configured != running: + print( + f"[serve] asks for {configured}, but this daemon runs {running}: it was started with " + f"--backend, or the {configured} model failed to load (see the daemon's log)" + ) + + def _cmd_voices(args: argparse.Namespace) -> int: tts = Stackvox(custom_voices=config.load_voices()) for name in tts.voices(): diff --git a/stackvox/config.py b/stackvox/config.py index c3b36d6..70b2336 100644 --- a/stackvox/config.py +++ b/stackvox/config.py @@ -27,9 +27,10 @@ name, alongside the built-in ones in ``stackvox.voices``. A table with a built-in's name replaces it. -``[serve]`` picks the backend ``stackvox serve`` starts when no ``--backend`` -flag is given, plus that backend's model and generation defaults (the -``stackvox.engine.MLX_OPTIONS`` names). No other command acts on it. +``[serve]`` picks the backend ``stackvox serve`` starts when no ``--backend`` or +``--model-dir`` flag is given, plus that backend's model and generation defaults (the +``stackvox.engine.MLX_OPTIONS`` names). No other command acts on it. Relative +paths in it are relative to the config file's folder. """ from __future__ import annotations @@ -47,7 +48,7 @@ else: # pragma: no cover - covered by 3.10 CI import tomli as tomllib -from stackvox.engine import BACKENDS, DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE +from stackvox.engine import BACKENDS, DEFAULT_LANG, DEFAULT_SPEED, DEFAULT_VOICE, REFERENCE_PAIR from stackvox.voices import BUILTIN_VOICES, VoiceMix logger = logging.getLogger(__name__) @@ -182,6 +183,11 @@ def load_serve(path: Path | None = None) -> ServeConfig: Lenient like ``[defaults]``: a missing table gives an empty ServeConfig and a bad value is logged and dropped. An mlx backend without a usable ``model_dir`` is dropped whole, since the daemon could not start with it. + Unknown keys are warned about too, because a misspelt one (``top-p``) + otherwise vanishes silently. + + Relative paths resolve against the config file's folder, not the working + directory, which for a daemon started by a supervisor is often ``/``. """ p = path or config_path() data = _read(p) @@ -191,6 +197,15 @@ def load_serve(path: Path | None = None) -> ServeConfig: if not isinstance(section, dict): logger.warning("config %s: [serve] must be a table; ignoring", p) return ServeConfig() + unknown = sorted(set(section) - _SERVE_KEYS) + if unknown: + logger.warning( + "config %s: [serve] has unknown keys %s (names use underscores, like top_p); ignoring them", + p, + ", ".join(unknown), + ) + section = {key: value for key, value in section.items() if key in _SERVE_KEYS} + base = p.parent backend = section.get("backend") if backend is None: if section: @@ -208,11 +223,11 @@ def load_serve(path: Path | None = None) -> ServeConfig: "config %s: [serve] %s apply to the mlx backend only; ignoring", p, ", ".join(ignored) ) return ServeConfig(backend=backend) - model_dir = _path(section.get("model_dir")) + model_dir = _anchored(_path(section.get("model_dir")), base) if model_dir is None: logger.warning('config %s: [serve] backend = "mlx" needs a usable model_dir; ignoring [serve]', p) return ServeConfig() - model_adapter = _path(section.get("model_adapter")) + model_adapter = _anchored(_path(section.get("model_adapter")), base) if model_adapter is None and "model_adapter" in section: logger.warning("config %s: [serve] model_adapter is not a usable path; ignoring it", p) generation: dict[str, Any] = {} @@ -223,16 +238,16 @@ def load_serve(path: Path | None = None) -> ServeConfig: if value is None: logger.warning("config %s: [serve] %s is invalid; ignoring it", p, key) continue - generation[key] = value + generation[key] = _anchored(value, base) if isinstance(value, Path) else value # The engine refuses one without the other on every request, so a daemon # started with half a pair would come up and then fail everything it's asked. - if ("reference_audio" in generation) != ("reference_text" in generation): + if sum(key in generation for key in REFERENCE_PAIR) == 1: logger.warning( "config %s: [serve] reference_audio and reference_text only work together; ignoring the one given", p, ) - generation.pop("reference_audio", None) - generation.pop("reference_text", None) + for key in REFERENCE_PAIR: + generation.pop(key, None) return ServeConfig(backend="mlx", model_dir=model_dir, model_adapter=model_adapter, generation=generation) @@ -245,6 +260,12 @@ def _path(value: object) -> Path | None: return None +def _anchored(path: Path | None, base: Path) -> Path | None: + if path is None or path.is_absolute(): + return path + return base / path + + def _text(value: object) -> str | None: return value if isinstance(value, str) else None @@ -270,3 +291,4 @@ def _integer(value: object) -> int | None: "top_p": _number, "top_k": _integer, } +_SERVE_KEYS = {"backend", "model_dir", "model_adapter", *_GENERATION_PARSERS} diff --git a/stackvox/daemon.py b/stackvox/daemon.py index f16263a..b1b3845 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -1,6 +1,7 @@ -"""Long-running daemon that preloads Kokoro and plays speech on request. +"""Long-running daemon that preloads a TTS model and plays speech on request. -Avoids the ~1-2s model load on every invocation. Listens on a unix socket. +Avoids the model load on every invocation (~1-2s for Kokoro, far longer for a +large MLX model). Listens on a unix socket. Protocol: one JSON object per connection (line-terminated), reply is a status line. Request shapes: @@ -9,6 +10,7 @@ {"command": "cancel"} # stop the current utterance, keep the daemon up {"command": "ping"} {"command": "version"} + {"command": "backend"} # the backend this daemon is running Replies: "ok", "busy", "err: ". """ @@ -17,6 +19,7 @@ import ctypes import ctypes.util +import fcntl import json import logging import os @@ -27,14 +30,16 @@ import sys import threading import time -from collections.abc import Mapping +from collections.abc import Iterator, Mapping +from contextlib import contextmanager from pathlib import Path -from typing import Any +from typing import IO, Any import sounddevice as sd from stackvox import updates from stackvox.engine import ( + BACKENDS, DEFAULT_BACKEND, DEFAULT_LANG, DEFAULT_SPEED, @@ -42,13 +47,14 @@ MLX_OPTIONS, Stackvox, ) -from stackvox.paths import pid_path, socket_path +from stackvox.paths import lock_path, pid_path, socket_path from stackvox.voices import VoiceMix logger = logging.getLogger(__name__) SOCKET_PATH = socket_path() PID_PATH = pid_path() +LOCK_PATH = lock_path() MAX_QUEUE = 2 WORKER_POLL_SECONDS = 0.5 CLIENT_TIMEOUT_SECONDS = 1.0 @@ -341,6 +347,10 @@ def handle(self) -> None: self.wfile.write(f"{updates._current_version()}\n".encode()) return + if command == "backend": + self.wfile.write(f"{state.tts.backend}\n".encode()) + return + if command == "stop": self.wfile.write(b"ok\n") threading.Thread(target=self.server.shutdown, daemon=True).start() @@ -417,6 +427,46 @@ def _worker() -> None: threading.Thread(target=_worker, daemon=True, name="update-check").start() +# This process's hold on the startup lock, so a nested startup_lock() is a no-op. +_startup_lock: IO[str] | None = None + + +@contextmanager +def startup_lock() -> Iterator[None]: + """Hold the daemon's exclusive startup lock, or raise RuntimeError if another process has it. + + Taken before the model loads and held until the daemon exits. Without it, + everything that starts ``serve`` while the socket is missing (a supervisor + restarting it, clients that spawn it on demand) loads its own copy of the + model, and all but one then die failing to bind. With a large model that + is gigabytes each. The kernel drops a flock when its process dies, so a + killed daemon never leaves it stale, and the file itself is left in place: + deleting a lock file someone may hold reopens the race. + + Reentrant within a process, so the CLI can hold it across a failed backend + and its fallback without another daemon slipping in between. + """ + global _startup_lock + if _startup_lock is not None: + yield + return + LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) + handle = open(LOCK_PATH, "a") # noqa: SIM115 - held for the daemon's lifetime, closed below + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + handle.close() + raise RuntimeError( + f"another daemon is already starting or running (lock held on {LOCK_PATH})" + ) from None + _startup_lock = handle + try: + yield + finally: + _startup_lock = None + handle.close() + + def serve( voice: str = DEFAULT_VOICE, speed: float = DEFAULT_SPEED, @@ -432,48 +482,52 @@ def serve( top_p: float | None = None, top_k: int | None = None, ) -> None: - if is_running(): - raise RuntimeError(f"daemon already running (pid {PID_PATH.read_text().strip()})") - - SOCKET_PATH.parent.mkdir(parents=True, exist_ok=True) - if SOCKET_PATH.exists(): - SOCKET_PATH.unlink() - - state = _DaemonState( - voice=voice, - speed=speed, - lang=lang, - custom_voices=custom_voices, - backend=backend, - model_dir=model_dir, - model_adapter=model_adapter, - generation_defaults={ - "reference_audio": reference_audio, - "reference_text": reference_text, - "instruct": instruct, - "temperature": temperature, - "top_p": top_p, - "top_k": top_k, - }, - ) - server = _UnixServer(str(SOCKET_PATH), _Handler) - server.state = state # type: ignore[attr-defined] + with startup_lock(): + if is_running(): + raise RuntimeError(f"daemon already running (pid {PID_PATH.read_text().strip()})") - PID_PATH.write_text(str(os.getpid())) - _check_for_update_async() + SOCKET_PATH.parent.mkdir(parents=True, exist_ok=True) + if SOCKET_PATH.exists(): + SOCKET_PATH.unlink() - def handle_signal(signum: int, frame: object) -> None: - state.shutdown() - threading.Thread(target=server.shutdown, daemon=True).start() + state = _DaemonState( + voice=voice, + speed=speed, + lang=lang, + custom_voices=custom_voices, + backend=backend, + model_dir=model_dir, + model_adapter=model_adapter, + generation_defaults={ + "reference_audio": reference_audio, + "reference_text": reference_text, + "instruct": instruct, + "temperature": temperature, + "top_p": top_p, + "top_k": top_k, + }, + ) + try: + server = _UnixServer(str(SOCKET_PATH), _Handler) + except OSError as exc: + raise RuntimeError(f"could not listen on {SOCKET_PATH}: {exc}") from exc + server.state = state # type: ignore[attr-defined] - signal.signal(signal.SIGTERM, handle_signal) - signal.signal(signal.SIGINT, handle_signal) + PID_PATH.write_text(str(os.getpid())) + _check_for_update_async() - logger.info("daemon listening on %s (pid %d)", SOCKET_PATH, os.getpid()) - try: - server.serve_forever() - finally: - _remove_runtime_files() + def handle_signal(signum: int, frame: object) -> None: + state.shutdown() + threading.Thread(target=server.shutdown, daemon=True).start() + + signal.signal(signal.SIGTERM, handle_signal) + signal.signal(signal.SIGINT, handle_signal) + + logger.info("daemon listening on %s (pid %d)", SOCKET_PATH, os.getpid()) + try: + server.serve_forever() + finally: + _remove_runtime_files() def send(req: dict, timeout: float = CLIENT_TIMEOUT_SECONDS) -> tuple[bool, str]: @@ -588,3 +642,14 @@ def version(timeout: float = PING_TIMEOUT_SECONDS) -> tuple[bool, str]: """ _, resp = send({"command": "version"}, timeout=timeout) return resp[:1].isdigit(), resp + + +def backend(timeout: float = PING_TIMEOUT_SECONDS) -> tuple[bool, str]: + """(got_backend, backend_or_error) the running daemon is serving. + + It can differ from ``[serve]`` in the config: a --backend flag wins, and a + configured model that fails to load falls back to Kokoro. A daemon from + before this command replies with an error, which comes back as not got. + """ + _, resp = send({"command": "backend"}, timeout=timeout) + return resp in BACKENDS, resp diff --git a/stackvox/engine.py b/stackvox/engine.py index 964e6a1..832e417 100644 --- a/stackvox/engine.py +++ b/stackvox/engine.py @@ -34,6 +34,8 @@ # Per-request generation options only the MLX backend understands. Kokoro # rejects them rather than silently dropping a voice-cloning request. MLX_OPTIONS = ("reference_audio", "reference_text", "instruct", "temperature", "top_p", "top_k") +# Voice cloning takes both or neither: the mlx backend refuses one alone. +REFERENCE_PAIR = ("reference_audio", "reference_text") # Streaming playback smoothing: play a touch of silence before the first word so # output-device warm-up (notably a Bluetooth codec/profile switch) lands during diff --git a/stackvox/paths.py b/stackvox/paths.py index 9feabaa..f08e361 100644 --- a/stackvox/paths.py +++ b/stackvox/paths.py @@ -1,4 +1,4 @@ -"""Filesystem paths used across stackvox: model cache, daemon socket, pid file. +"""Filesystem paths used across stackvox: model cache, daemon socket, pid file, lock. Centralising these avoids leaking private helpers between modules and keeps the `STACKVOX_CACHE_DIR` / `STACKVOX_SOCKET` override rules in one place. @@ -11,7 +11,7 @@ def cache_dir() -> Path: - """Directory holding the model, voice pack, socket, and pid file. + """Directory holding the model, voice pack, socket, pid file and startup lock. Honours `STACKVOX_CACHE_DIR`; defaults to `~/.cache/stackvox`. """ @@ -34,3 +34,8 @@ def socket_path() -> Path: def pid_path() -> Path: return cache_dir() / "daemon.pid" + + +def lock_path() -> Path: + """Startup lock the daemon holds for its whole life (see ``daemon.startup_lock``).""" + return cache_dir() / "daemon.lock" diff --git a/tests/test_cli.py b/tests/test_cli.py index 26d22e5..e9d784b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -26,6 +26,12 @@ def _no_user_config(monkeypatch, tmp_path): monkeypatch.setenv("STACKVOX_CONFIG", str(tmp_path / "absent.toml")) +@pytest.fixture(autouse=True) +def _private_startup_lock(monkeypatch, tmp_path): + """serve takes the daemon's startup lock; keep it off the developer's real cache dir.""" + monkeypatch.setattr(cli.daemon, "LOCK_PATH", tmp_path / "daemon.lock") + + @pytest.fixture(autouse=True) def _no_network_update_check(mocker): """Block the PyPI update check from making real HTTP requests in tests. @@ -448,6 +454,7 @@ def test_running_prints_pid_and_returns_zero(self, mocker, capsys): # status now queries the running daemon's version; stub it so the test # doesn't reach a real socket. mocker.patch.object(cli.daemon, "version", return_value=(False, "n/a")) + mocker.patch.object(cli.daemon, "backend", return_value=(False, "n/a")) rc = cli._cmd_status(_ns()) @@ -463,6 +470,7 @@ def test_running_flags_daemon_version_skew(self, mocker, capsys): mocker.patch.object(cli.daemon, "PID_PATH", pid_path) mocker.patch.object(cli.daemon, "SOCKET_PATH", "/tmp/x.sock") mocker.patch.object(cli.daemon, "version", return_value=(True, "0.5.0")) + mocker.patch.object(cli.daemon, "backend", return_value=(False, "n/a")) mocker.patch.object(cli.updates, "_current_version", return_value="0.8.0") mocker.patch.object(cli.updates, "check_for_update", return_value=None) @@ -482,6 +490,7 @@ def test_running_does_not_advise_restart_when_the_daemon_is_ahead(self, mocker, mocker.patch.object(cli.daemon, "PID_PATH", pid_path) mocker.patch.object(cli.daemon, "SOCKET_PATH", "/tmp/x.sock") mocker.patch.object(cli.daemon, "version", return_value=(True, "0.11.0")) + mocker.patch.object(cli.daemon, "backend", return_value=(False, "n/a")) mocker.patch.object(cli.updates, "_current_version", return_value="0.9.0") mocker.patch.object(cli.updates, "check_for_update", return_value=None) @@ -950,3 +959,146 @@ def test_config_command_shows_the_serve_backend(self, monkeypatch, tmp_path, cap assert "serve backend: mlx" in out assert "serve model_dir: /models/voice" in out assert "serve top_k: 20" in out + + def test_model_dir_flag_leaves_the_table_out(self, monkeypatch, tmp_path): + from pathlib import Path + + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + args = self._serve_args(backend="mlx", model_dir=Path("/other/model")) + + cli._apply_serve_config(args) + + assert args.model_dir == Path("/other/model") + assert args.model_adapter is None + assert args.top_k is None + assert args.backend_from_config is False + + def test_model_dir_flag_without_backend_is_a_usage_error(self, mocker, monkeypatch, tmp_path, capsys): + self._config(monkeypatch, tmp_path, self.MLX_SERVE) + serve = mocker.patch.object(cli.daemon, "serve") + mocker.patch.object(cli.sys, "argv", ["stackvox", "serve", "--model-dir", "/other/model"]) + + with pytest.raises(SystemExit) as exc: + cli.main() + + assert exc.value.code == 2 + assert "require --backend mlx" in capsys.readouterr().err + serve.assert_not_called() + + def test_one_reference_flag_does_not_borrow_the_tables_other_half( + self, mocker, monkeypatch, tmp_path, capsys + ): + self._config( + monkeypatch, + tmp_path, + '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\nreference_audio = "/ref.wav"\nreference_text = "Ref."\n', + ) + serve = mocker.patch.object(cli.daemon, "serve") + mocker.patch.object(cli.sys, "argv", ["stackvox", "serve", "--reference-audio", "/mine.wav"]) + + with pytest.raises(SystemExit) as exc: + cli.main() + + assert exc.value.code == 2 + assert "must be given together" in capsys.readouterr().err + serve.assert_not_called() + + def test_both_reference_flags_replace_the_tables_pair(self, monkeypatch, tmp_path): + from pathlib import Path + + self._config( + monkeypatch, + tmp_path, + '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\nreference_audio = "/ref.wav"\nreference_text = "Ref."\n', + ) + args = self._serve_args(reference_audio=Path("/mine.wav"), reference_text="Mine.") + + cli._apply_serve_config(args) + + assert (args.reference_audio, args.reference_text) == (Path("/mine.wav"), "Mine.") + + def test_say_with_half_a_reference_pair_is_a_usage_error(self, mocker, capsys): + say = mocker.patch.object(cli.daemon, "say") + mocker.patch.object(cli.sys, "argv", ["stackvox", "say", "--reference-text", "Ref.", "hi"]) + + with pytest.raises(SystemExit) as exc: + cli.main() + + assert exc.value.code == 2 + assert "must be given together" in capsys.readouterr().err + say.assert_not_called() + + def test_other_errors_do_not_trigger_the_fallback(self, mocker, capsys): + serve = mocker.patch.object(cli.daemon, "serve", side_effect=RuntimeError("daemon already running")) + args = self._serve_args( + voice="af_sarah", speed=1.0, lang="en-us", backend="mlx", backend_from_config=True + ) + + assert cli._cmd_serve(args) == 1 + assert serve.call_count == 1 + assert "already running" in capsys.readouterr().err + + def test_fallback_holds_one_startup_lock_across_both_attempts(self, mocker): + lock = mocker.patch.object(cli.daemon, "startup_lock") + serve = mocker.patch.object(cli.daemon, "serve", side_effect=[cli.ModelLoadError("no model"), None]) + args = self._serve_args( + voice="af_sarah", speed=1.0, lang="en-us", backend="mlx", backend_from_config=True + ) + + assert cli._cmd_serve(args) == 0 + assert serve.call_count == 2 + lock.assert_called_once_with() + assert lock.return_value.__enter__.call_count == 1 + + def test_lock_held_by_another_daemon_starts_nothing(self, mocker, capsys): + mocker.patch.object( + cli.daemon, + "startup_lock", + side_effect=RuntimeError("another daemon is already starting or running"), + ) + serve = mocker.patch.object(cli.daemon, "serve") + args = self._serve_args(voice="af_sarah", speed=1.0, lang="en-us", backend="kokoro") + + assert cli._cmd_serve(args) == 1 + serve.assert_not_called() + assert "already starting or running" in capsys.readouterr().err + + +class TestStatusShowsRunningBackend: + def _running(self, mocker, tmp_path, backend_reply): + pid_path = tmp_path / "daemon.pid" + pid_path.write_text("4242") + mocker.patch.object(cli.daemon, "is_running", return_value=True) + mocker.patch.object(cli.daemon, "PID_PATH", pid_path) + mocker.patch.object(cli.daemon, "version", return_value=(False, "n/a")) + mocker.patch.object(cli.daemon, "backend", return_value=backend_reply) + + def test_prints_the_running_backend(self, mocker, tmp_path, capsys): + self._running(mocker, tmp_path, (True, "kokoro")) + + cli._cmd_status(_ns()) + + out = capsys.readouterr().out + assert "backend: kokoro" in out + assert "[serve] asks for" not in out + + def test_says_when_the_daemon_is_not_running_the_serve_backend( + self, mocker, monkeypatch, tmp_path, capsys + ): + config_file = tmp_path / "config.toml" + config_file.write_text('[serve]\nbackend = "mlx"\nmodel_dir = "/m"\n', encoding="utf-8") + monkeypatch.setenv("STACKVOX_CONFIG", str(config_file)) + self._running(mocker, tmp_path, (True, "kokoro")) + + cli._cmd_status(_ns()) + + out = capsys.readouterr().out + assert "backend: kokoro" in out + assert "[serve] asks for mlx, but this daemon runs kokoro" in out + + def test_a_daemon_too_old_to_answer_prints_no_backend(self, mocker, tmp_path, capsys): + self._running(mocker, tmp_path, (False, "err: missing text")) + + cli._cmd_status(_ns()) + + assert "backend:" not in capsys.readouterr().out diff --git a/tests/test_config.py b/tests/test_config.py index e72bfde..a6c7469 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -269,3 +269,43 @@ def test_unexpandable_adapter_is_dropped_rather_than_raising(self, tmp_path, cap assert actual.model_adapter is None assert actual.model_dir == Path("/m") assert "model_adapter is not a usable path" in caplog.text + + def test_text_without_audio_is_dropped_too(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\nreference_text = "Ref."\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + actual = config.load_serve(path) + assert actual.generation == {} + assert "only work together" in caplog.text + + def test_relative_paths_resolve_against_the_config_folder(self, tmp_path): + path = self._write( + tmp_path, + "[serve]\n" + 'backend = "mlx"\n' + 'model_dir = "models/voice"\n' + 'model_adapter = "adapters/voice.py"\n' + 'reference_audio = "voices/ref.wav"\n' + 'reference_text = "Ref."\n', + ) + + actual = config.load_serve(path) + + assert actual.model_dir == tmp_path / "models/voice" + assert actual.model_adapter == tmp_path / "adapters/voice.py" + assert actual.generation["reference_audio"] == tmp_path / "voices/ref.wav" + + def test_unknown_keys_are_warned_about_and_ignored(self, tmp_path, caplog): + path = self._write( + tmp_path, '[serve]\nbackend = "mlx"\nmodel_dir = "/m"\ntop-p = 0.9\ntemprature = 1.0\ntop_k = 5\n' + ) + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + actual = config.load_serve(path) + assert actual == config.ServeConfig(backend="mlx", model_dir=Path("/m"), generation={"top_k": 5}) + assert "unknown keys temprature, top-p" in caplog.text + + def test_only_unknown_keys_warns_once(self, tmp_path, caplog): + path = self._write(tmp_path, '[serve]\nmodel-dir = "/m"\n') + with caplog.at_level(logging.WARNING, logger="stackvox.config"): + assert config.load_serve(path) == config.ServeConfig() + assert "unknown keys model-dir" in caplog.text + assert "need a backend" not in caplog.text diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 4a7a76d..88cf2eb 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -403,3 +403,75 @@ def test_leaves_a_worker_within_its_deadline_alone(self, state, exit_wedged): time.sleep(0.1) exit_wedged.assert_not_called() + + +def _hold_lock_elsewhere(path): + """Take the startup lock through a separate open file description, as another process would.""" + import fcntl + + handle = open(path, "a") # noqa: SIM115 - closed by the caller + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + return handle + + +@pytest.fixture +def private_paths(mocker, tmp_path): + mocker.patch.object(daemon, "LOCK_PATH", tmp_path / "daemon.lock") + mocker.patch.object(daemon, "PID_PATH", tmp_path / "daemon.pid") + mocker.patch.object(daemon, "SOCKET_PATH", tmp_path / "daemon.sock") + return tmp_path + + +class TestStartupLock: + def test_refuses_while_another_holder_has_it(self, private_paths): + other = _hold_lock_elsewhere(private_paths / "daemon.lock") + try: + with pytest.raises(RuntimeError, match="already starting or running"), daemon.startup_lock(): + pass + finally: + other.close() + + def test_is_reentrant_within_a_process(self, private_paths): + with daemon.startup_lock(), daemon.startup_lock(): + pass + + def test_releases_on_exit(self, private_paths): + with daemon.startup_lock(): + pass + + _hold_lock_elsewhere(private_paths / "daemon.lock").close() # would raise if still held + + def test_serve_loads_nothing_while_another_daemon_holds_it(self, mocker, private_paths): + state = mocker.patch.object(daemon, "_DaemonState") + other = _hold_lock_elsewhere(private_paths / "daemon.lock") + try: + with pytest.raises(RuntimeError, match="already starting or running"): + daemon.serve() + finally: + other.close() + state.assert_not_called() + + def test_serve_releases_it_when_startup_fails(self, mocker, private_paths): + mocker.patch.object(daemon, "_DaemonState", side_effect=RuntimeError("model failed to load")) + + with pytest.raises(RuntimeError, match="model failed to load"): + daemon.serve() + + _hold_lock_elsewhere(private_paths / "daemon.lock").close() # would raise if still held + + def test_bind_failure_is_a_clean_runtime_error(self, mocker, private_paths): + mocker.patch.object(daemon, "_DaemonState") + mocker.patch.object(daemon, "_UnixServer", side_effect=OSError(48, "Address already in use")) + + with pytest.raises(RuntimeError, match="could not listen on"): + daemon.serve() + + +class TestBackendClient: + def test_reports_the_backend_the_daemon_names(self, mocker): + mocker.patch.object(daemon, "send", return_value=(False, "mlx")) + assert daemon.backend() == (True, "mlx") + + def test_an_old_daemons_error_is_not_a_backend(self, mocker): + mocker.patch.object(daemon, "send", return_value=(False, "err: missing text")) + assert daemon.backend() == (False, "err: missing text") diff --git a/tests/test_daemon_protocol.py b/tests/test_daemon_protocol.py index f172c09..60c5f75 100644 --- a/tests/test_daemon_protocol.py +++ b/tests/test_daemon_protocol.py @@ -219,3 +219,8 @@ def test_cancel_stops_playback_and_keeps_daemon_up(server: ServerHarness): server.tts.stop.assert_called() # current utterance aborted # unlike `stop`, the daemon stays up assert _roundtrip(server.sock, json.dumps({"command": "ping"}) + "\n") == "ok" + + +def test_backend_reports_the_engine_backend(server: ServerHarness): + server.tts.backend = "mlx" + assert _roundtrip(server.sock, json.dumps({"command": "backend"}) + "\n") == "mlx" From 9bcdcc4ed192161091bf7ed239c89d6ae7a4e583 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 01:24:26 +0100 Subject: [PATCH 4/6] docs: scope the startup lock to the cache dir --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b1d35a0..5e26f2a 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ stackvox say "Hello" # send text to the daemon (fails if not running) stackvox stop # graceful shutdown, force-killed if it acknowledges but is still up after 5s ``` -Only one daemon starts at a time. A `serve` started while another is running, or still loading its model, exits straight away rather than loading a second copy. +Only one daemon starts at a time per cache directory, which is also where its socket lives. A `serve` started while another is running there, or still loading its model, exits straight away rather than loading a second copy. One with a different `STACKVOX_CACHE_DIR` is a separate daemon and runs alongside. 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. From f1793c964fa013889645985d72e56ae10ff3effa Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 01:33:24 +0100 Subject: [PATCH 5/6] fix: handle startup lock errors cleanly --- README.md | 2 +- stackvox/config.py | 6 +++-- stackvox/daemon.py | 48 ++++++++++++++++++++++++++--------- tests/test_daemon.py | 59 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 5e26f2a..1d1b285 100644 --- a/README.md +++ b/README.md @@ -224,7 +224,7 @@ reference_audio = "~/voices/reference.wav" reference_text = "The exact transcript of the reference audio." ``` -Passing `--backend` or `--model-dir` ignores the table altogether, since the flags then describe the model. Any other flag beats its matching key, and the reference clip and its transcript count as one setting, so give both flags or neither. Relative paths are relative to the config file's folder, and an unknown key (`top-p` for `top_p`, say) gets a warning. Only `serve` acts on `[serve]`, so `speak` from an install without the mlx extra isn't affected. If the configured model fails to load, `serve` logs why and starts Kokoro instead, so a daemon that gets restarted automatically doesn't crash loop into silence, and `stackvox status` shows which backend is actually running. A model named on the command line still fails outright. +Passing `--backend` or `--model-dir` ignores the table altogether, since the flags then describe the model. Any other flag beats its matching key, and the reference clip and its transcript count as one setting, so give both flags or neither. Relative paths are relative to the folder the config file is in (the link's folder, if it's a symlink), and an unknown key (`top-p` for `top_p`, say) gets a warning. Only `serve` acts on `[serve]`, so `speak` from an install without the mlx extra isn't affected. If the configured model fails to load, `serve` logs why and starts Kokoro instead, so a daemon that gets restarted automatically doesn't crash loop into silence, and `stackvox status` shows which backend is actually running. A model named on the command line still fails outright. Generation options (`--reference-audio`, `--reference-text`, `--instruct`, `--temperature`, `--top-p`, `--top-k`) are forwarded only when set, so each diff --git a/stackvox/config.py b/stackvox/config.py index 70b2336..74a1ee8 100644 --- a/stackvox/config.py +++ b/stackvox/config.py @@ -30,7 +30,8 @@ ``[serve]`` picks the backend ``stackvox serve`` starts when no ``--backend`` or ``--model-dir`` flag is given, plus that backend's model and generation defaults (the ``stackvox.engine.MLX_OPTIONS`` names). No other command acts on it. Relative -paths in it are relative to the config file's folder. +paths in it are relative to the config file's folder (a symlink's own folder, +not its target's). """ from __future__ import annotations @@ -187,7 +188,8 @@ def load_serve(path: Path | None = None) -> ServeConfig: otherwise vanishes silently. Relative paths resolve against the config file's folder, not the working - directory, which for a daemon started by a supervisor is often ``/``. + directory, which for a daemon started by a supervisor is often ``/``. For a + symlinked config that is the link's folder, where the user sees the file. """ p = path or config_path() data = _read(p) diff --git a/stackvox/daemon.py b/stackvox/daemon.py index b1b3845..122eb47 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -19,6 +19,7 @@ import ctypes import ctypes.util +import errno import fcntl import json import logging @@ -427,8 +428,10 @@ def _worker() -> None: threading.Thread(target=_worker, daemon=True, name="update-check").start() -# This process's hold on the startup lock, so a nested startup_lock() is a no-op. -_startup_lock: IO[str] | None = None +# True while this process is inside startup_lock(), so a nested call is a no-op. +_holding_startup_lock = False +# flock errors meaning the filesystem can't lock at all, rather than that it's held. +_LOCKING_UNSUPPORTED = {errno.ENOTSUP, errno.EOPNOTSUPP, errno.ENOLCK} @contextmanager @@ -443,15 +446,33 @@ def startup_lock() -> Iterator[None]: killed daemon never leaves it stale, and the file itself is left in place: deleting a lock file someone may hold reopens the race. + On a filesystem that can't lock at all it warns and carries on unlocked, + as daemons did before the lock existed, rather than refusing to start. + Reentrant within a process, so the CLI can hold it across a failed backend and its fallback without another daemon slipping in between. """ - global _startup_lock - if _startup_lock is not None: + global _holding_startup_lock + if _holding_startup_lock: yield return - LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) - handle = open(LOCK_PATH, "a") # noqa: SIM115 - held for the daemon's lifetime, closed below + handle = _acquire_startup_lock() + _holding_startup_lock = True + try: + yield + finally: + _holding_startup_lock = False + if handle is not None: + handle.close() + + +def _acquire_startup_lock() -> IO[str] | None: + """The locked file, or None where the filesystem doesn't support locking.""" + try: + LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) + handle = open(LOCK_PATH, "a") # noqa: SIM115 - held for the daemon's lifetime, closed by startup_lock + except OSError as exc: + raise RuntimeError(f"could not open the startup lock {LOCK_PATH}: {exc}") from exc try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: @@ -459,12 +480,17 @@ def startup_lock() -> Iterator[None]: raise RuntimeError( f"another daemon is already starting or running (lock held on {LOCK_PATH})" ) from None - _startup_lock = handle - try: - yield - finally: - _startup_lock = None + except OSError as exc: handle.close() + if exc.errno not in _LOCKING_UNSUPPORTED: + raise RuntimeError(f"could not take the startup lock {LOCK_PATH}: {exc}") from exc + logger.warning( + "the filesystem under %s can't lock (%s); starting without the startup lock", + LOCK_PATH, + exc.strerror, + ) + return None + return handle def serve( diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 88cf2eb..0f458f0 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -466,6 +466,65 @@ def test_bind_failure_is_a_clean_runtime_error(self, mocker, private_paths): with pytest.raises(RuntimeError, match="could not listen on"): daemon.serve() + def test_is_held_for_the_whole_block(self, private_paths): + with daemon.startup_lock(), pytest.raises(BlockingIOError): + _hold_lock_elsewhere(private_paths / "daemon.lock") + + def test_serve_holds_it_while_serving(self, mocker, private_paths): + """Pins the lock to the daemon's life, not just its startup.""" + mocker.patch.object(daemon, "_DaemonState") + mocker.patch.object(daemon, "_check_for_update_async") + mocker.patch.object(daemon.signal, "signal") + held_while_serving = [] + + def serve_forever(): + try: + _hold_lock_elsewhere(private_paths / "daemon.lock").close() + held_while_serving.append(False) + except BlockingIOError: + held_while_serving.append(True) + + mocker.patch.object(daemon, "_UnixServer").return_value.serve_forever.side_effect = serve_forever + + daemon.serve() + + assert held_while_serving == [True] + + def test_unopenable_lock_file_is_a_clean_runtime_error(self, mocker, private_paths): + mocker.patch.object(daemon, "open", create=True, side_effect=PermissionError(13, "Permission denied")) + + with pytest.raises(RuntimeError, match="could not open the startup lock"), daemon.startup_lock(): + pass + + def test_other_lock_failures_are_a_clean_runtime_error(self, mocker, private_paths): + import errno + + mocker.patch.object(daemon.fcntl, "flock", side_effect=OSError(errno.EIO, "Input/output error")) + + with pytest.raises(RuntimeError, match="could not take the startup lock"), daemon.startup_lock(): + pass + + def test_a_filesystem_without_locking_starts_unlocked_with_one_warning( + self, mocker, private_paths, caplog + ): + import errno + import logging + + mocker.patch.object( + daemon.fcntl, "flock", side_effect=OSError(errno.ENOTSUP, "Operation not supported") + ) + entered = [] + + with ( + caplog.at_level(logging.WARNING, logger="stackvox.daemon"), + daemon.startup_lock(), + daemon.startup_lock(), + ): + entered.append(True) + + assert entered == [True] + assert caplog.text.count("starting without the startup lock") == 1 + class TestBackendClient: def test_reports_the_backend_the_daemon_names(self, mocker): From b87cd546481caedccd32561858734f0508aa3386 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Sun, 25 Oct 2026 01:47:06 +0100 Subject: [PATCH 6/6] fix: describe ENOLCK accurately in the startup lock --- stackvox/daemon.py | 18 +++++++++++------- tests/test_daemon.py | 4 +--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/stackvox/daemon.py b/stackvox/daemon.py index 122eb47..4cd3955 100644 --- a/stackvox/daemon.py +++ b/stackvox/daemon.py @@ -430,8 +430,11 @@ def _worker() -> None: # True while this process is inside startup_lock(), so a nested call is a no-op. _holding_startup_lock = False -# flock errors meaning the filesystem can't lock at all, rather than that it's held. -_LOCKING_UNSUPPORTED = {errno.ENOTSUP, errno.EOPNOTSUPP, errno.ENOLCK} +# flock errors meaning locking isn't available here, rather than that someone holds +# it: a filesystem without it, or (ENOLCK) a remote lock service that isn't there. +# ENOLCK can also mean the kernel ran out of lock records. Going on unlocked then +# only brings back the race the lock prevents, which beats a daemon that can't start. +_LOCKING_UNAVAILABLE = {errno.ENOTSUP, errno.EOPNOTSUPP, errno.ENOLCK} @contextmanager @@ -446,8 +449,9 @@ def startup_lock() -> Iterator[None]: killed daemon never leaves it stale, and the file itself is left in place: deleting a lock file someone may hold reopens the race. - On a filesystem that can't lock at all it warns and carries on unlocked, - as daemons did before the lock existed, rather than refusing to start. + Where locking isn't available (a filesystem without it, a missing remote + lock service) it warns and carries on unlocked, as daemons did before the + lock existed, rather than refusing to start. Reentrant within a process, so the CLI can hold it across a failed backend and its fallback without another daemon slipping in between. @@ -467,7 +471,7 @@ def startup_lock() -> Iterator[None]: def _acquire_startup_lock() -> IO[str] | None: - """The locked file, or None where the filesystem doesn't support locking.""" + """The locked file, or None where locking isn't available.""" try: LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) handle = open(LOCK_PATH, "a") # noqa: SIM115 - held for the daemon's lifetime, closed by startup_lock @@ -482,10 +486,10 @@ def _acquire_startup_lock() -> IO[str] | None: ) from None except OSError as exc: handle.close() - if exc.errno not in _LOCKING_UNSUPPORTED: + if exc.errno not in _LOCKING_UNAVAILABLE: raise RuntimeError(f"could not take the startup lock {LOCK_PATH}: {exc}") from exc logger.warning( - "the filesystem under %s can't lock (%s); starting without the startup lock", + "locking isn't available for %s (%s); starting without the startup lock", LOCK_PATH, exc.strerror, ) diff --git a/tests/test_daemon.py b/tests/test_daemon.py index 0f458f0..327e883 100644 --- a/tests/test_daemon.py +++ b/tests/test_daemon.py @@ -504,9 +504,7 @@ def test_other_lock_failures_are_a_clean_runtime_error(self, mocker, private_pat with pytest.raises(RuntimeError, match="could not take the startup lock"), daemon.startup_lock(): pass - def test_a_filesystem_without_locking_starts_unlocked_with_one_warning( - self, mocker, private_paths, caplog - ): + def test_unavailable_locking_starts_unlocked_with_one_warning(self, mocker, private_paths, caplog): import errno import logging