Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 5 additions & 7 deletions docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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.
21 changes: 20 additions & 1 deletion src/tts/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand All @@ -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:
Expand All @@ -40,19 +50,28 @@ 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,
max_input_chars=int(os.environ.get("TTS_MAX_INPUT_CHARS", "50000")),
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:
Expand Down
26 changes: 7 additions & 19 deletions src/tts/jobs/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""

Expand Down Expand Up @@ -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]]:
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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
Expand Down
37 changes: 26 additions & 11 deletions tests/integration/test_jobs_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()}
Expand All @@ -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]:
Expand Down Expand Up @@ -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.")

Expand Down
56 changes: 34 additions & 22 deletions tests/unit/test_jobs_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand Down
Loading