diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index c20afb4..e9a1353 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -251,7 +251,7 @@ tts/ ### 7.1 `config` - **Responsibility:** parse environment into an immutable `Settings` object and configure logging. - **Owns:** `src/tts/config.py` -- **Public interface:** `Settings.load()` → dataclass with fields `host, port, data_dir, max_input_chars, history_limit, log_level, default_voice_id`; `configure_logging(settings)`. +- **Public interface:** `Settings.load()` → dataclass with fields `host, port, data_dir, max_input_chars, history_limit, log_level, default_voice_id, fault` (where `fault` is the `TTS_FAULT` test hook, `none` by default); `configure_logging(settings)`. - **Depends on:** stdlib only. - **Must not:** read env vars anywhere else; mutate `os.environ`; do I/O beyond creating the data dir and logs dir. - **PRD requirements covered:** NFR-06, A-3. diff --git a/docs/TASKS.md b/docs/TASKS.md index 3051970..414cbf1 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -30,14 +30,13 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | T3.2 | `arch/tts/t3.2` | [#18](https://github.com/prateekchaplot/tts/pull/18) | `a291da14620f9bb32cce5b5cd51d0da8ccd9689d` | 83 Vitest (32 new); ESLint; `tsc --noEmit`; Prettier (CRLF); live + mock Vite builds; mock-mode Chromium 13/13 (highlight advance/pause, word click, cue click, ArrowRight ±5 s, Space toggle, ended reset, WAV/SRT/VTT names + content); 196 pytest; Ruff check/format; strict mypy; `git diff --check`; PR CI green (lint, unit ubuntu+windows, integration, e2e) | | T3.3 | `arch/tts/t3.3` | [#19](https://github.com/prateekchaplot/tts/pull/19) | `dce6ca5aa311965fd78d7e49a38dcad338ccdd66` | 93 Vitest (10 new); ESLint; `tsc --noEmit`; Prettier (CRLF); live + mock Vite builds; mock-mode Chromium 15/15 (narrow starts collapsed, summary toggle, empty state, 2 entries with preview/voice/time, restore loads subtitles + audio, delete one keeps the other, delete open entry clears playback, no console errors); 196 pytest; Ruff check/format; strict mypy; `git diff --check` | | T4.1 | `arch/tts/t4.1` | [#20](https://github.com/prateekchaplot/tts/pull/20) | `898deff1b4717ddf604401a582df043f39485ddc` | 36/36 live browser checks on the built bundle **and** behind the Vite dev proxy (voice list + preview, SSE progress → succeeded, playback/highlight/seek, three §9.2-named downloads, history restore/delete, `putSettings` on blur persisted across reload); 25 live generations at limit 20 → 20 rows + 20 WAVs, five oldest ids 404, no `.part`; 93 Vitest; ESLint; `tsc --noEmit`; Prettier (CRLF); live build; 196 pytest unit + 16 integration; `git diff --check` | - | T4.2 | `arch/tts/t4.2` | [#21](https://github.com/prateekchaplot/tts/pull/21) | `cae500631aff66b38d18f2aeda94246c5e8e5393` | 111 Vitest (18 new); ESLint; `tsc --noEmit`; Prettier (CRLF); live Vite build; 23/23 keyboard-only AC15 checks against the built bundle with the real voice (isolated `TTS_DATA_DIR`); 196 pytest unit; `git diff --check`; PR CI green (lint, unit ubuntu+windows, integration, e2e) | ## Doing | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty)_ | | | | | +| T4.3 | Observability polish | `arch/tts/t4.3` | 201 unit tests (5 new); 7 jobs integration tests; Ruff check/format; strict mypy; `git diff --check` | PR open, awaiting review | ## Remaining @@ -59,11 +58,7 @@ _All P3 tasks done._ ### P4 — Integration -_T4.1 done — see Done._ - -| ID | Task | Files | Deps | Acceptance criteria (summary) | -|---|---|---|---|---| -| T4.3 | Observability polish | `src/tts/config.py`, `src/tts/jobs/manager.py` | P2 | Failure reason logged without full input text | +_T4.1 and T4.2 done — see Done. T4.3 is in Doing._ ### P5 — Verification + docs @@ -152,3 +147,6 @@ _T4.1 done — see Done._ - T4.2 history delete: T3.3's deferred confirmation is an inline two-step — Delete swaps to `Confirm delete` + `Keep` and shows "Delete this entry? This cannot be undone.", the confirm button autofocuses, and Keep returns focus to the row's Delete button. No `window.confirm`, no new dependency. Focus effects are not unit-tested (no jsdom, §5 lists vitest only); they were verified in the live keyboard run, while the confirmation markup and labels are covered by static-markup tests. - T4.2 AC15 record: 23/23 keyboard-only checks passed in **live** mode against the built bundle served by `tts` (port 8322, isolated `TTS_DATA_DIR=.venv\tts-data`, real `en_US-lessac-medium`). Driven by keyboard events only (Tab/Shift+Tab/Enter/Space): first Tab → skip link → Enter → main landmark; Tab → textarea → typed "Hello world. This is a keyboard check."; Tab → voice select (populated) → Tab → Generate audio → Enter → "Audio ready." (aligned ratio 0.714); Tab → Play → Enter starts playback, Space pauses; Tab → sentence cue (focusable `Jump to 00:00: …`); Tab → WAV, SRT, VTT downloads all named `hello-world-this-is-a-keyboard_20261123-125257.{wav,srt,vtt}`; Tab → Delete → Enter (focus moves to Confirm delete) → Tab → Keep → Enter (focus returns to Delete); empty-input pass: error banner takes focus, shows "Enter some text before generating…" plus "What you can do: …", Tab reaches Dismiss, Enter returns focus to Generate audio. The temporary headless-Chromium script was removed after the run and is not committed. - T4.2 environment: port 8321 was already bound by a stale `tts` process, so the live run used 8322; the temporary script lives in `frontend/` so it resolves `@playwright/test` from `frontend/node_modules`. Vitest count moved 93 → 111 (9 in `strings.test.ts`, 4 in new `ErrorBanner.test.tsx`, 2 history-confirm markup, 2 skip-link/main, 1 `aria-busy`). +- T4.3 decision (closes T1.6's `TTS_FAULT` note): `TTS_FAULT` is now read only by `config.py`, which adds a `fault` field to `Settings` (`none` by default, `engine` the test fault), normalizes case/whitespace, falls back to `none` with a warning on an unknown value, and logs "Fault injection enabled: engine" when armed. `jobs/manager.py` compares `self._settings.fault` and no longer touches `os.environ`, so §7.1 is true again; §7.1's field list was updated in this PR (§14.4). Dependent tests switched from env mutation to fault-enabled fixtures: `tests/unit/test_jobs_manager.py` gained a `fault_harness` fixture (built by the shared `_build_harness` helper) and `tests/integration/test_jobs_pipeline.py` gained a `fault_environment` fixture (built by `_build_environment(tmp_path, fault=...)`). +- T4.3 logging: the two failure branches call the new `_log_preview(text)` helper (`text[:LOG_PREVIEW_CHARS]`, 80 chars) so the input preview can never exceed §11's limit; the existing WARNING line still carries the §9.1 code and the failure reason, and the exception keeps the traceback at ERROR. No production behavior other than `TTS_FAULT`'s source changed — the §11 log lines (start/success/failure/cancel, degraded timings, eviction, offline first run) already existed. +- T4.3 enforcement test: new `tests/unit/test_observability.py` (unique basename, per the T1.2 note) proves a failed generation logs `ENGINE_ERROR` + the reason + the 80-char preview, and uses `difflib.SequenceMatcher` to assert the longest common run between the >80-char input and all captured log text is ≤ 80 characters (the marker after char 80 never appears, no timing JSON is logged). It also pins `Settings.load()` fault parsing (default/override/unknown) and proves a manager built with `fault="none"` succeeds even when `TTS_FAULT=engine` is set in the environment. diff --git a/src/tts/config.py b/src/tts/config.py index fd0d3e5..54efe2c 100644 --- a/src/tts/config.py +++ b/src/tts/config.py @@ -11,6 +11,15 @@ logger = logging.getLogger(__name__) +FAULT_NONE = "none" +"""Default fault-injection mode: no injected failures.""" + +FAULT_ENGINE = "engine" +"""Fault mode that fails a generation after its first sentence (§11, §15).""" + +FAULT_MODES = frozenset({FAULT_NONE, FAULT_ENGINE}) +"""Fault-injection modes accepted by ``TTS_FAULT``.""" + def _default_data_dir() -> Path: if sys.platform == "win32": @@ -31,6 +40,7 @@ class Settings: history_limit: int log_level: str default_voice_id: str + fault: str = FAULT_NONE @classmethod def load(cls) -> Settings: @@ -40,11 +50,16 @@ def load(cls) -> Settings: logger.warning("Unknown TTS_LOG_LEVEL %r; falling back to INFO", raw_log_level) raw_log_level = "INFO" + raw_fault = os.environ.get("TTS_FAULT", FAULT_NONE).strip().lower() + if raw_fault not in FAULT_MODES: + logger.warning("Unknown TTS_FAULT %r; fault injection disabled", raw_fault) + raw_fault = FAULT_NONE + data_dir = Path(os.environ.get("TTS_DATA_DIR", _default_data_dir())).expanduser() data_dir.mkdir(parents=True, exist_ok=True) (data_dir / "logs").mkdir(parents=True, exist_ok=True) - return cls( + settings = cls( host=os.environ.get("TTS_HOST", "127.0.0.1"), port=int(os.environ.get("TTS_PORT", "8321")), data_dir=data_dir, @@ -52,7 +67,11 @@ def load(cls) -> Settings: history_limit=int(os.environ.get("TTS_HISTORY_LIMIT", "20")), log_level=raw_log_level, default_voice_id=os.environ.get("TTS_DEFAULT_VOICE", "en_US-lessac-medium"), + fault=raw_fault, ) + if settings.fault != FAULT_NONE: + logger.warning("Fault injection enabled: %s", settings.fault) + return settings def configure_logging(settings: Settings) -> None: diff --git a/src/tts/jobs/manager.py b/src/tts/jobs/manager.py index 6b612fd..5323969 100644 --- a/src/tts/jobs/manager.py +++ b/src/tts/jobs/manager.py @@ -30,7 +30,7 @@ import numpy as np -from tts.config import Settings +from tts.config import FAULT_ENGINE, Settings from tts.engine.piper_engine import synthesize from tts.history.dal import Dal from tts.jobs.sse import EventBus, SseEvent, Subscriber @@ -50,12 +50,6 @@ logger = logging.getLogger(__name__) -FAULT_ENV_VAR = "TTS_FAULT" -"""Environment variable that injects a mid-run engine failure (§11, §15).""" - -FAULT_ENGINE = "engine" -"""Fault mode that fails a job after its first sentence.""" - MAX_WAV_VALUE = 32767.0 """Float-to-int16 scale used by piper when it writes WAV files.""" @@ -197,15 +191,9 @@ def _duration_ms(result: SynthesisResult) -> int: return math.floor(result.total_samples * 1000.0 / result.sample_rate + 0.5) -def _fault_mode() -> str: - """Return the configured fault-injection mode (§11, §15). - - ARCHITECTURE §7.1 makes ``config`` the only reader of environment - variables, but §14.2 assigns the ``TTS_FAULT`` implementation to T1.6 and - ``config.py`` to T0.2/T4.3, so the variable is read here. T4.3 owns the - follow-up that folds it into ``Settings``. - """ - return os.environ.get(FAULT_ENV_VAR, "none").strip().lower() +def _log_preview(text: str) -> str: + """Return the longest input fragment that may appear in a log line (§11).""" + return text[:LOG_PREVIEW_CHARS] def _sentence_triplets(voice: LoadedVoice, result: SynthesisResult) -> list[tuple[int, int, int]]: @@ -486,7 +474,7 @@ def _execute(self, generation_id: str, job: _Job, row: dict[str, Any]) -> None: generation_id, voice_id, len(text), - text[:LOG_PREVIEW_CHARS], + _log_preview(text), ) self._finish_failed( generation_id, @@ -502,7 +490,7 @@ def _execute(self, generation_id: str, job: _Job, row: dict[str, Any]) -> None: generation_id, voice_id, len(text), - text[:LOG_PREVIEW_CHARS], + _log_preview(text), ) self._finish_failed( generation_id, @@ -525,7 +513,7 @@ def on_sentence(sentence: SentenceAudio) -> None: with self._lock: job.sentence_index += 1 self._bus.publish(generation_id, _progress_event(generation_id, "running", job)) - if _fault_mode() == FAULT_ENGINE and job.sentence_index == 1: + if self._settings.fault == FAULT_ENGINE and job.sentence_index == 1: raise EngineFaultError("injected engine failure") return on_sentence diff --git a/tests/integration/test_jobs_pipeline.py b/tests/integration/test_jobs_pipeline.py index 0f55144..b628dbe 100644 --- a/tests/integration/test_jobs_pipeline.py +++ b/tests/integration/test_jobs_pipeline.py @@ -11,7 +11,7 @@ import pytest -from tts.config import Settings +from tts.config import FAULT_ENGINE, Settings from tts.history.dal import Dal from tts.jobs.manager import JobManager from tts.jobs.sse import SseEvent @@ -34,6 +34,27 @@ @pytest.fixture def environment(tmp_path: Path) -> Any: """Build a manager that renders with the downloaded voice but writes to a temp dir.""" + manager, dal = _build_environment(tmp_path) + + yield manager, dal, tmp_path + + manager.close() + dal.close() + + +@pytest.fixture +def fault_environment(tmp_path: Path) -> Any: + """Build a manager whose first job fails after its first sentence.""" + manager, dal = _build_environment(tmp_path, fault=FAULT_ENGINE) + + yield manager, dal, tmp_path + + manager.close() + dal.close() + + +def _build_environment(tmp_path: Path, *, fault: str = "none") -> tuple[JobManager, Dal]: + """Wire a manager to the real voice store while writing to a temp dir.""" real_settings = Settings.load() voices_dir = ensure_data_dirs(real_settings) installed = {voice.id for voice in list_voices()} @@ -51,17 +72,14 @@ def environment(tmp_path: Path) -> Any: history_limit=real_settings.history_limit, log_level=real_settings.log_level, default_voice_id=real_settings.default_voice_id, + fault=fault, ) dal = Dal(tmp_path) manager = JobManager(dal, settings) # The manager points the voice store at its own data directory; restore the # real one so the downloaded voice stays visible to the store. ensure_data_dirs(real_settings) - - yield manager, dal, tmp_path - - manager.close() - dal.close() + return manager, dal def _wait_for_status(dal: Dal, generation_id: str, timeout: float = 60.0) -> dict[str, Any]: @@ -156,11 +174,8 @@ def test_real_voice_job_derives_one_cue_per_sentence(environment: Any) -> None: assert cues[0]["endMs"] <= cues[1]["startMs"] -def test_injected_engine_fault_leaves_no_audio( - environment: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - manager, dal, tmp_path = environment - monkeypatch.setenv("TTS_FAULT", "engine") +def test_injected_engine_fault_leaves_no_audio(fault_environment: Any) -> None: + manager, dal, tmp_path = fault_environment generation_id = manager.submit(DEFAULT_VOICE_ID, "One sentence. Two sentences.") diff --git a/tests/unit/test_jobs_manager.py b/tests/unit/test_jobs_manager.py index a896d0b..9b7e566 100644 --- a/tests/unit/test_jobs_manager.py +++ b/tests/unit/test_jobs_manager.py @@ -8,6 +8,7 @@ import threading import time import wave +from collections.abc import Iterator from pathlib import Path from types import SimpleNamespace from typing import Any @@ -132,8 +133,9 @@ def __init__(self, manager: JobManager, dal: Dal, engine: FakeEngine) -> None: self.engine = engine -@pytest.fixture -def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Harness: +def _build_harness( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, fault: str = "none" +) -> Harness: """Build a manager with a fake engine and an installed fake voice.""" _install_fake_voice(tmp_path) settings = Settings( @@ -144,6 +146,7 @@ def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Harness: history_limit=20, log_level="INFO", default_voice_id=VOICE_ID, + fault=fault, ) dal = Dal(tmp_path) manager = JobManager(dal, settings) @@ -157,10 +160,25 @@ def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Harness: monkeypatch.setattr(manager_module, "synthesize", engine.synthesize) monkeypatch.setattr(manager_module, "derive_word_timings", _fake_timings) - harness = Harness(manager, dal, engine) - yield harness - manager.close() - dal.close() + return Harness(manager, dal, engine) + + +@pytest.fixture +def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Harness]: + """Build a manager with fault injection disabled.""" + built = _build_harness(tmp_path, monkeypatch) + yield built + built.manager.close() + built.dal.close() + + +@pytest.fixture +def fault_harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Harness]: + """Build a manager that fails the generation after its first sentence.""" + built = _build_harness(tmp_path, monkeypatch, fault=manager_module.FAULT_ENGINE) + yield built + built.manager.close() + built.dal.close() def _wait_for_status( @@ -347,32 +365,26 @@ def test_a_generation_without_audio_fails_instead_of_succeeding(harness: Harness assert not part_path.exists() -def test_injected_fault_marks_the_job_failed_with_engine_error( - harness: Harness, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setenv(manager_module.FAULT_ENV_VAR, manager_module.FAULT_ENGINE) - generation_id = harness.manager.submit(VOICE_ID, "One. Two.") +def test_injected_fault_marks_the_job_failed_with_engine_error(fault_harness: Harness) -> None: + generation_id = fault_harness.manager.submit(VOICE_ID, "One. Two.") - row = _wait_for_status(harness.dal, generation_id, {"failed"}) - part_path, final_path = _generation_files(harness, generation_id) + row = _wait_for_status(fault_harness.dal, generation_id, {"failed"}) + part_path, final_path = _generation_files(fault_harness, generation_id) assert row["error_code"] == "ENGINE_ERROR" assert not final_path.exists() assert not part_path.exists() -def test_a_cancelled_job_is_not_turned_into_a_failure( - harness: Harness, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setenv(manager_module.FAULT_ENV_VAR, manager_module.FAULT_ENGINE) +def test_a_cancelled_job_is_not_turned_into_a_failure(fault_harness: Harness) -> None: gate = threading.Event() - harness.engine.gate = gate - generation_id = harness.manager.submit(VOICE_ID, "One. Two.") - assert harness.engine.started.wait(timeout=10) + fault_harness.engine.gate = gate + generation_id = fault_harness.manager.submit(VOICE_ID, "One. Two.") + assert fault_harness.engine.started.wait(timeout=10) - assert harness.manager.cancel(generation_id) == "cancelling" + assert fault_harness.manager.cancel(generation_id) == "cancelling" gate.set() - row = _wait_for_status(harness.dal, generation_id, {"cancelled"}) + row = _wait_for_status(fault_harness.dal, generation_id, {"cancelled"}) assert row["status"] == "cancelled" assert row["error_code"] is None diff --git a/tests/unit/test_observability.py b/tests/unit/test_observability.py new file mode 100644 index 0000000..5e4f966 --- /dev/null +++ b/tests/unit/test_observability.py @@ -0,0 +1,200 @@ +"""Tests for the section 11 logging rules and the never-log enforcement.""" + +from __future__ import annotations + +import json +import logging +import time +from difflib import SequenceMatcher +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pytest + +from tts.config import FAULT_ENGINE, FAULT_NONE, Settings +from tts.history.dal import Dal +from tts.jobs import manager as manager_module +from tts.jobs.manager import LOG_PREVIEW_CHARS, JobManager +from tts.types import SentenceAudio, SynthesisResult, WordTiming +from tts.voices.store import LoadedVoice + +VOICE_ID = "test-voice" +SAMPLE_RATE = 22_050 +SENTENCE_SAMPLES = SAMPLE_RATE // 10 +SENTENCE_MS = 100 + +SECRET_TAIL = "SECRET-TAIL-MARKER-9f3c" +LONG_INPUT = "Hello world. " * 10 + SECRET_TAIL + + +class RecordingEngine: + """Emits one sentence so the manager's per-sentence hooks run.""" + + def synthesize( + self, + voice: LoadedVoice, + text: str, + char_offset_map: list[tuple[int, int]], + rate: float, + volume: float, + cancel_event: Any, + on_sentence: Any, + ) -> SynthesisResult: + sentence = SentenceAudio( + text=text, + char_start=0, + char_end=len(text), + samples=np.zeros(SENTENCE_SAMPLES, dtype=np.float32), + sample_rate=SAMPLE_RATE, + phoneme_alignments=[("h", SENTENCE_SAMPLES)], + supports_alignments=True, + ) + on_sentence(sentence) + return SynthesisResult( + sentences=[sentence], + total_samples=SENTENCE_SAMPLES, + sample_rate=SAMPLE_RATE, + supports_alignments=True, + ) + + +def _one_word_timing(voice: LoadedVoice, result: SynthesisResult) -> tuple[list[WordTiming], float]: + """Return a single aligned word so a successful generation can finish.""" + word = WordTiming(text="word", start_ms=0, end_ms=SENTENCE_MS, aligned=True) + return [word], 1.0 + + +def _build_manager( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, *, fault: str +) -> tuple[JobManager, Dal]: + """Wire a manager to a fake voice and engine, using the given fault mode.""" + voices_dir = tmp_path / "voices" + voices_dir.mkdir(parents=True, exist_ok=True) + (voices_dir / f"{VOICE_ID}.onnx").write_bytes(b"") + (voices_dir / f"{VOICE_ID}.onnx.json").write_text( + json.dumps({"audio": {"sample_rate": SAMPLE_RATE}, "language": {"code": "en_US"}}), + encoding="utf-8", + ) + + settings = Settings( + host="127.0.0.1", + port=8321, + data_dir=tmp_path, + max_input_chars=50_000, + history_limit=20, + log_level="INFO", + default_voice_id=VOICE_ID, + fault=fault, + ) + dal = Dal(tmp_path) + manager = JobManager(dal, settings) + + fake_voice = LoadedVoice( + voice=SimpleNamespace(config=SimpleNamespace(sample_rate=SAMPLE_RATE)), # type: ignore[arg-type] + supports_alignments=True, + ) + engine = RecordingEngine() + monkeypatch.setattr(manager_module, "load_voice", lambda voice_id: fake_voice) + monkeypatch.setattr(manager_module, "synthesize", engine.synthesize) + monkeypatch.setattr(manager_module, "derive_word_timings", _one_word_timing) + return manager, dal + + +def _wait_for_status( + dal: Dal, generation_id: str, statuses: set[str], timeout: float = 10.0 +) -> dict[str, Any]: + """Wait until a generation reaches one of the given statuses.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + row = dal.get(generation_id) + if row is not None and row["status"] in statuses: + return row + time.sleep(0.01) + raise AssertionError(f"generation {generation_id} never reached {statuses}") + + +def _clear_fault_environment(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + """Point settings at a temp data dir and remove any inherited fault mode.""" + monkeypatch.setenv("TTS_DATA_DIR", str(tmp_path / "data")) + monkeypatch.delenv("TTS_FAULT", raising=False) + + +def test_settings_default_to_no_fault(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + _clear_fault_environment(monkeypatch, tmp_path) + + assert Settings.load().fault == FAULT_NONE + + +def test_settings_read_fault_mode_from_the_environment( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + _clear_fault_environment(monkeypatch, tmp_path) + monkeypatch.setenv("TTS_FAULT", " Engine ") + + with caplog.at_level(logging.WARNING, logger="tts.config"): + settings = Settings.load() + + assert settings.fault == FAULT_ENGINE + assert "Fault injection enabled: engine" in caplog.text + + +def test_unknown_fault_mode_warns_and_disables_injection( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + _clear_fault_environment(monkeypatch, tmp_path) + monkeypatch.setenv("TTS_FAULT", "explode") + + with caplog.at_level(logging.WARNING, logger="tts.config"): + settings = Settings.load() + + assert settings.fault == FAULT_NONE + assert "Unknown TTS_FAULT 'explode'" in caplog.text + assert "Fault injection enabled" not in caplog.text + + +def test_failed_generation_logs_reason_but_not_the_input_text( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """§11: log the failure reason, never log input beyond an 80-char preview.""" + manager, dal = _build_manager(tmp_path, monkeypatch, fault=FAULT_ENGINE) + try: + with caplog.at_level(logging.DEBUG, logger="tts"): + generation_id = manager.submit(VOICE_ID, LONG_INPUT) + row = _wait_for_status(dal, generation_id, {"failed"}) + + assert row["error_code"] == "ENGINE_ERROR" + assert "ENGINE_ERROR" in caplog.text + assert "injected engine failure" in caplog.text + assert repr(LONG_INPUT[:LOG_PREVIEW_CHARS]) in caplog.text + assert any(record.exc_info for record in caplog.records) + + assert LONG_INPUT not in caplog.text + assert SECRET_TAIL not in caplog.text + match = SequenceMatcher(None, LONG_INPUT, caplog.text, autojunk=False).find_longest_match( + 0, len(LONG_INPUT), 0, len(caplog.text) + ) + assert match.size <= LOG_PREVIEW_CHARS + assert "wordTimings" not in caplog.text + assert "startMs" not in caplog.text + finally: + manager.close() + dal.close() + + +def test_the_manager_does_not_read_the_fault_environment_variable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """§7.1: only config reads the environment, so a Settings without fault succeeds.""" + monkeypatch.setenv("TTS_FAULT", FAULT_ENGINE) + manager, dal = _build_manager(tmp_path, monkeypatch, fault=FAULT_NONE) + try: + generation_id = manager.submit(VOICE_ID, "One. Two.") + + row = _wait_for_status(dal, generation_id, {"succeeded", "failed"}) + + assert row["status"] == "succeeded", row + finally: + manager.close() + dal.close()