diff --git a/docs/TASKS.md b/docs/TASKS.md index 9d9c526..6551f2b 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -27,7 +27,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty — next up: T1.6 on branch `arch/tts/t1.6`)_ | | | | | +| T1.6 | Jobs manager | `arch/tts/t1.6` | 140 unit tests (37 new); 13 integration tests (7 new) vs `en_US-lessac-medium` (progress ≥ 1 → succeeded, injected engine failure → no `.wav`/`.part` + status `failed`, cancel mid-run → status `cancelled` + no file, two submits strictly sequential); Ruff check/format; strict mypy; `git diff --check`; PR CI green (lint, unit ubuntu+windows, integration, e2e) | [#13](https://github.com/prateekchaplot/tts/pull/13) open — awaiting review | ## Remaining @@ -37,9 +37,7 @@ _All P0 tasks done._ ### P1 — Service layer -| ID | Task | Files | Deps | Acceptance criteria (summary) | -|---|---|---|---|---| -| T1.6 | Jobs manager | `src/tts/jobs/` | T1.2, T1.3, T1.4, T1.5 | Progress/success, atomic failure cleanup, cancellation, sequential jobs | +_T1.6 in progress on `arch/tts/t1.6`; P1 is otherwise complete._ ### P2 — HTTP surface @@ -103,3 +101,15 @@ _All P0 tasks done._ - T1.5 eviction ordering: the system clock is far too coarse to order rapid inserts (2000 `datetime.now()` calls on this machine produced 3 distinct values), so `created_at` is now emitted strictly increasing — the clock value is nudged forward by 1 µs when it would repeat, and a reopened DAL resumes after the newest stored row. History order (newest first) and eviction order (oldest first) therefore follow insertion order instead of an arbitrary UUID tiebreaker. `created_at` stays ISO-8601 UTC; the stored format gained microsecond precision. - T1.5 settings: `put_settings` now rejects keys outside `{defaultVoiceId, rate, volume}` with `ValueError` and `get_settings` ignores unknown stored keys, enforcing §8.2's key set in the DAL. Lazy seeding stays in the API layer (T2.3), as T0.4 decided. - T1.5 environment finding: `tests/integration/test_piper_engine.py::test_rate_scales_duration_within_ten_percent` is flaky (measured ratio 0.814–0.913 over 10 attempts against the [0.72, 0.88] band; 6/10 pass) because piper 1.8's duration predictor is stochastic. It was pre-existing (T1.2) and unrelated to T1.5, so that task did not edit a file owned by T1.2 (§16); the fix merged as PR #12 (squash `6910a09`, branch `fix/integration-rate-flake`, 7 runs per rate, band [0.78, 0.93] around the measured 0.87) before T1.5 merged. +- T1.6 decisions: **sentence segmentation lives in `jobs/manager.py` (`split_sentences`)** — §7.4 forbids the engine from splitting text, the caller supplies `char_offset_map`, and no other component owns a splitter, so jobs owns it. Rule: a terminator (`.!?…`) plus optional closing punctuation ends a sentence only when followed by whitespace or end-of-text; a decimal point (`3.14`) and an abbreviation or initial (`Dr.`, `e.g.`, `J. Smith`) do not end one. §16 ambiguity rule: recorded here because §14.2 does not specify a splitter. +- T1.6 write order: PCM frames are streamed per sentence into `{id}.wav.part` (§11 "streamed to disk per sentence"), the file is closed and `os.replace`d to `{id}.wav` only **after** the timings and cues are derived (§10.1 order), and the row is set `succeeded` only after that rename (§1, NFR-03). A failure or cancellation removes the `.part`. On Windows the WAV is closed before the rename because an open file cannot be renamed. +- T1.6 downstream contract (T1.3): `build_cues` receives one `(char_start, char_end, first_word_idx)` triplet per sentence, and `first_word_idx` is built from **per-sentence** `derive_word_timings` calls, so a sentence that collapses to one unaligned entry contributes exactly one index. Assuming one entry per token would mis-index every later sentence. +- T1.6 downstream contract (T1.5): `evict_to_limit` is called from `submit` right after the insert with **every** in-flight id (`set(self._jobs)`), not just the new one, because the DAL protects exactly the ids it is given (§8.5). +- T1.6 downstream contract (T2.2): `JobManager.submit` raises `voices.store.VoiceNotFoundError` for an unknown voice and creates the row itself (§7.8's signature returns the id). The API must map that to 422 `VOICE_NOT_FOUND` and must check for an empty store first to answer 409 `NO_VOICES_INSTALLED`. `subscribe`/`cancel` raise `GenerationNotFoundError` (→ 404 `GENERATION_NOT_FOUND`) and `cancel` raises `GenerationNotCancellableError` on a terminal row (→ 409 `GENERATION_BUSY`). +- T1.6 SSE contract (T2.2): `jobs/sse.py` exposes `RETRY_LINE` (`"retry: 3000\n\n"`) and `SseEvent.to_wire()`, which emits `event: ` + `data: ` + a blank line. The route sends `RETRY_LINE` once on connect and then yields `subscriber.events()` until the terminal event; the manager already replays the current state to a new subscriber, so a reconnect is stateless-safe (§9.2). +- T1.6 ambiguity (T2.2 to decide): `cancel()` returns `cancelling` both when the job was `running` and when it was already `cancelling`. §9.2 literally says a job that was "already `cancelling`" answers `200 {"status":"cancelled"}`, while §7.8 and §10.2 only allow the two states `cancelled`/`cancelling` and describe `cancelling` as "the worker confirms via `cancelled` SSE + row update". Jobs reports the truthful state; the API layer owns the §9.2 mapping. +- T1.6 deviation (§7.1): `TTS_FAULT` is read in `jobs/manager.py` rather than `config.py`. §14.2 assigns the `TTS_FAULT` implementation to T1.6, while `config.py` is owned by T0.2 and later T4.3, and the skill's ownership guardrail forbids editing another task's file. §7.1 ("`config` is the only reader of environment variables") is therefore bent for this one variable; **T4.3 owns the follow-up that folds it into `Settings`**. The fault fires after the first sentence, and a cancel that was requested first wins over the injected fault (so AC11 and AC12 can share the env var). +- T1.6 decision: `bootstrap(settings, dal)` is implemented here because §7.8 lists it in the `JobManager` interface and §14.2 T1.6 says "per §7.8"; **T2.3 owns the wiring** (app startup) and the settings route, including §8.2's lazy `dal.seed_settings(default_voice_id)` seeding that the T1.5 note assigned to it. The `dal` argument is accepted for interface stability and is currently unused. +- T1.6 decision: a generation that renders **no audio at all** fails with `ENGINE_ERROR` ("The speech engine produced no audio for this text.") instead of succeeding with a valid but empty WAV that no player can use (§1 "degrade honestly"). The API still rejects empty input with 422 `EMPTY_INPUT`, so this only guards text that the engine renders as silence. +- T1.6 test layout: unit and integration test files use distinct basenames (`tests/unit/test_jobs_manager.py`, `tests/unit/test_jobs_sse.py`, `tests/integration/test_jobs_pipeline.py`) because a bare `pytest` run fails when `tests/unit` and `tests/integration` share a basename and neither directory is a package (see the T1.2 note). +- T1.6 environment note: the integration suite renders with the real voice but keeps the database and the audio in a `tmp_path`; the manager points the voice store at its own data directory, so the fixture calls `ensure_data_dirs()` again with the real settings afterwards. `pytest` needs `--basetemp .venv/ptmp-*` on this machine (the default system temp directory is inaccessible — see the T0.2 note). diff --git a/src/tts/jobs/__init__.py b/src/tts/jobs/__init__.py new file mode 100644 index 0000000..876db40 --- /dev/null +++ b/src/tts/jobs/__init__.py @@ -0,0 +1 @@ +"""Job execution: one generation at a time, atomically, with progress events.""" diff --git a/src/tts/jobs/manager.py b/src/tts/jobs/manager.py new file mode 100644 index 0000000..6b612fd --- /dev/null +++ b/src/tts/jobs/manager.py @@ -0,0 +1,687 @@ +"""Run one generation at a time to completion, atomically, with cancellation. + +The manager owns the whole life cycle of a generation: it queues the job, runs +it on a single worker thread, writes the audio atomically, derives honest word +timings and subtitle cues, and publishes progress events (ARCHITECTURE.md +§7.8, §10.1, §10.2). + +Two invariants shape the code: + +* **Partial output is never success.** Audio is written to ``{id}.wav.part`` + and renamed to ``{id}.wav`` only after every derived artifact exists; the + database row is marked ``succeeded`` only after that rename (§1, NFR-03). +* **One synthesis at a time.** A single-worker executor serializes the queue, + so two submissions can never synthesize concurrently (§7.8, ADR-8). +""" + +from __future__ import annotations + +import json +import logging +import math +import os +import threading +import wave +from collections.abc import Callable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np + +from tts.config import Settings +from tts.engine.piper_engine import synthesize +from tts.history.dal import Dal +from tts.jobs.sse import EventBus, SseEvent, Subscriber +from tts.subtitles.cues import build_cues +from tts.timing.reconcile import derive_word_timings +from tts.types import Cue, SentenceAudio, SynthesisResult, WordTiming +from tts.voices.store import ( + VoiceNotFoundError, + ensure_data_dirs, + install_voice, + list_voices, + load_voice, +) + +if TYPE_CHECKING: + from tts.voices.store import LoadedVoice + +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.""" + +LOG_PREVIEW_CHARS = 80 +"""Longest input preview that may appear in a log line (§11).""" + +_TERMINATORS = ".!?…" +"""Characters that end a sentence.""" + +_CLOSERS = "\"'”’)]}" +"""Characters that may trail a sentence terminator.""" + +_ABBREVIATIONS = frozenset( + { + "mr", + "mrs", + "ms", + "dr", + "prof", + "sr", + "jr", + "st", + "mt", + "ft", + "vs", + "etc", + "e.g", + "i.e", + "no", + "inc", + "ltd", + "co", + "fig", + "approx", + "a.m", + "p.m", + "u.s", + "u.k", + } +) +"""Tokens whose trailing period does not end a sentence.""" + + +class JobError(RuntimeError): + """Base class for errors the API layer maps to a §9.1 code.""" + + +class GenerationNotFoundError(JobError): + """Raised when a generation id does not exist.""" + + +class GenerationNotCancellableError(JobError): + """Raised when a generation already reached a terminal state.""" + + +class EngineFaultError(RuntimeError): + """Raised by the injected fault to simulate a mid-run engine failure.""" + + +@dataclass +class _Job: + """The in-memory state of one queued or running generation.""" + + cancel_event: threading.Event + sentence_index: int = 0 + sentence_count: int = 0 + + +def split_sentences(text: str) -> list[tuple[int, int]]: + """Split text into sentence spans with their character offsets. + + The engine never splits text itself: the caller supplies the segmentation + (§7.4), so the jobs manager owns it. A sentence ends at ``.``, ``!``, ``?`` + or ``…`` — optionally followed by closing punctuation — when the next + character is whitespace or the end of the text. A period inside a decimal + number or an abbreviation (``Dr.``, ``e.g.``) does not end a sentence. + + The spans are returned in source order and never overlap. + """ + spans: list[tuple[int, int]] = [] + start = 0 + index = 0 + length = len(text) + while index < length: + if text[index] in _TERMINATORS: + end = index + 1 + while end < length and text[end] in _TERMINATORS: + end += 1 + while end < length and text[end] in _CLOSERS: + end += 1 + if (end >= length or text[end].isspace()) and not _is_abbreviation(text, start, index): + spans.append((start, end)) + while end < length and text[end].isspace(): + end += 1 + start = end + index = end + continue + index += 1 + if start < length: + spans.append((start, length)) + return spans + + +def _is_abbreviation(text: str, sentence_start: int, terminator_index: int) -> bool: + """Report whether the token before a terminator is an abbreviation.""" + words = text[sentence_start:terminator_index].split() + if not words: + return False + lowered = words[-1].lower() + if lowered in _ABBREVIATIONS: + return True + # A single letter before a period is an initial (``J. Smith``). + return len(lowered) == 1 and lowered.isalpha() + + +def _samples_to_bytes(samples: np.ndarray) -> bytes: + """Convert float PCM samples to 16-bit little-endian bytes. + + The scale matches piper's own WAV writer so a rendered file is identical + to one produced by ``piper`` (ADR-5). + """ + if samples.size == 0: + return b"" + scaled = np.clip(samples * MAX_WAV_VALUE, -MAX_WAV_VALUE, MAX_WAV_VALUE) + return scaled.astype(np.int16).tobytes() + + +def _duration_seconds(result: SynthesisResult) -> float: + """Return the rendered duration in seconds.""" + if result.sample_rate <= 0: + return 0.0 + return result.total_samples / result.sample_rate + + +def _duration_ms(result: SynthesisResult) -> int: + """Return the rendered duration in whole milliseconds, rounded half up.""" + if result.sample_rate <= 0: + return 0 + 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 _sentence_triplets(voice: LoadedVoice, result: SynthesisResult) -> list[tuple[int, int, int]]: + """Return one ``(char_start, char_end, first_word_idx)`` triplet per sentence. + + ``build_cues`` needs the index at which each sentence starts in the final + word list (§7.6). A sentence whose words cannot be reconciled collapses to + a single unaligned entry, so the count cannot be assumed to equal the + token count; deriving the sentence on its own yields the real number of + entries the reconciler produced for it. + """ + triplets: list[tuple[int, int, int]] = [] + first_word_idx = 0 + for sentence in result.sentences: + triplets.append((sentence.char_start, sentence.char_end, first_word_idx)) + first_word_idx += _sentence_word_count(voice, sentence, result.supports_alignments) + return triplets + + +def _sentence_word_count( + voice: LoadedVoice, sentence: SentenceAudio, supports_alignments: bool +) -> int: + """Count the word entries one sentence contributes to the final word list.""" + single = SynthesisResult( + sentences=[sentence], + total_samples=len(sentence.samples), + sample_rate=sentence.sample_rate, + supports_alignments=supports_alignments, + ) + timings, _ = derive_word_timings(voice, single) + return len(timings) + + +def _progress_event(generation_id: str, status: str, job: _Job | None) -> SseEvent: + """Build a progress event carrying the current sentence position (§9.2).""" + return SseEvent( + name="progress", + data={ + "generationId": generation_id, + "status": status, + "sentenceIndex": job.sentence_index if job else 0, + "sentenceCount": job.sentence_count if job else 0, + }, + ) + + +def _succeeded_event(generation_id: str, duration_seconds: float | None) -> SseEvent: + """Build the terminal event of a successful generation.""" + return SseEvent( + name="succeeded", + data={ + "generationId": generation_id, + "status": "succeeded", + "durationSeconds": duration_seconds, + }, + terminal=True, + ) + + +def _failed_event(generation_id: str, code: str, message: str) -> SseEvent: + """Build the terminal event of a failed generation.""" + return SseEvent( + name="failed", + data={ + "generationId": generation_id, + "status": "failed", + "error": {"code": code, "message": message}, + }, + terminal=True, + ) + + +def _cancelled_event(generation_id: str) -> SseEvent: + """Build the terminal event of a cancelled generation.""" + return SseEvent( + name="cancelled", + data={"generationId": generation_id, "status": "cancelled"}, + terminal=True, + ) + + +def _remove_file(path: Path) -> None: + """Delete a file, tolerating one that is already gone.""" + try: + path.unlink() + except FileNotFoundError: + return + except OSError: + logger.warning("Could not remove %s", path) + + +class JobManager: + """Runs one generation at a time to completion, atomically.""" + + def __init__(self, dal: Dal, settings: Settings) -> None: + self._dal = dal + self._settings = settings + self._lock = threading.RLock() + self._bus = EventBus() + self._jobs: dict[str, _Job] = {} + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="tts-jobs") + self._generations_dir = settings.data_dir / "generations" + self._generations_dir.mkdir(parents=True, exist_ok=True) + ensure_data_dirs(settings) + + # -- public interface ---------------------------------------------------- + + def submit( + self, + voice_id: str, + text: str, + source_type: str = "text", + input_filename: str | None = None, + rate: float = 1.0, + volume: float = 1.0, + ) -> str: + """Queue a generation and return its id. + + The row is created as ``queued`` before the job reaches the worker, so + a client that receives the id can always read the generation back. + """ + voice_name = self._voice_name(voice_id) + generation_id = self._dal.create_generation( + text=text, + voice_id=voice_id, + voice_name=voice_name, + source_type=source_type, + input_filename=input_filename, + rate=rate, + volume=volume, + ) + job = _Job(cancel_event=threading.Event()) + with self._lock: + self._jobs[generation_id] = job + # §8.5: every in-flight id is protected from eviction, not just + # the one that was just inserted. + self._dal.evict_to_limit(set(self._jobs)) + self._executor.submit(self._run_job, generation_id, job) + return generation_id + + def cancel(self, generation_id: str) -> Literal["cancelled", "cancelling"]: + """Request cancellation and report the resulting state. + + A job that never started is cancelled outright; a running job is asked + to stop and reports ``cancelling`` until the worker confirms it. A + generation that already reached a terminal state cannot be cancelled + and raises :class:`GenerationNotCancellableError`. + """ + with self._lock: + row = self._dal.get(generation_id) + if row is None: + raise GenerationNotFoundError(generation_id) + status = row["status"] + job = self._jobs.get(generation_id) + + if status == "queued": + if job is not None: + job.cancel_event.set() + self._dal.set_status(generation_id, "cancelled") + self._jobs.pop(generation_id, None) + self._bus.publish(generation_id, _cancelled_event(generation_id)) + self._bus.close(generation_id) + return "cancelled" + + if status == "running": + if job is not None: + job.cancel_event.set() + self._dal.set_status(generation_id, "cancelling") + self._bus.publish(generation_id, _progress_event(generation_id, "cancelling", job)) + return "cancelling" + + if status == "cancelling": + return "cancelling" + + raise GenerationNotCancellableError(generation_id) + + def subscribe(self, generation_id: str) -> Subscriber: + """Register an SSE subscriber and replay the current state. + + Replaying the state makes a reconnect stateless-safe: the client sees + where the generation stands without replaying its whole history + (§9.2). + """ + with self._lock: + row = self._dal.get(generation_id) + if row is None: + raise GenerationNotFoundError(generation_id) + subscriber = self._bus.subscribe(generation_id) + self._replay_state(generation_id, subscriber, row) + return subscriber + + def close(self) -> None: + """Stop the worker and close every event stream.""" + self._executor.shutdown(wait=True) + with self._lock: + self._jobs.clear() + self._bus.close_all() + + # -- worker --------------------------------------------------------------- + + def _run_job(self, generation_id: str, job: _Job) -> None: + """Claim a queued job and run it, or skip it when it was cancelled.""" + with self._lock: + row = self._dal.get(generation_id) + if row is None or row["status"] != "queued": + return + self._dal.set_status(generation_id, "running") + self._bus.publish(generation_id, _progress_event(generation_id, "running", job)) + try: + self._execute(generation_id, job, row) + except Exception: + logger.exception("Generation %s crashed outside its failure handler", generation_id) + + def _execute(self, generation_id: str, job: _Job, row: dict[str, Any]) -> None: + """Synthesize one generation and publish its outcome.""" + text = str(row["input_text"]) + voice_id = str(row["voice_id"]) + part_path = self._generations_dir / f"{generation_id}.wav.part" + final_path = self._generations_dir / f"{generation_id}.wav" + voice: LoadedVoice | None = None + + try: + voice = load_voice(voice_id) + segments = split_sentences(text) + job.sentence_count = len(segments) + sample_rate = int(voice.voice.config.sample_rate) + logger.info( + "Generation %s started for voice %s (%d characters, %d sentences)", + generation_id, + voice_id, + len(text), + job.sentence_count, + ) + + with wave.open(str(part_path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(sample_rate) + result = synthesize( + voice, + text, + segments, + rate=float(row["rate"]), + volume=float(row["volume"]), + cancel_event=job.cancel_event, + on_sentence=self._on_sentence(generation_id, job, wav_file), + ) + + if job.cancel_event.is_set(): + self._finish_cancelled(generation_id, job, part_path) + return + + if result.total_samples <= 0: + # A generation with no audio is not a success: the file would + # be a valid but empty WAV that no player can use. + logger.warning( + "Generation %s produced no audio for %d characters", generation_id, len(text) + ) + self._finish_failed( + generation_id, + job, + part_path, + "ENGINE_ERROR", + "The speech engine produced no audio for this text.", + "synthesis produced no samples", + ) + return + + words, ratio = derive_word_timings(voice, result) + triplets = _sentence_triplets(voice, result) + cues = build_cues(words, triplets, _duration_ms(result)) + self._finish_succeeded( + generation_id, job, result, words, cues, ratio, part_path, final_path + ) + except EngineFaultError as error: + logger.exception( + "Generation %s failed for voice %s (%d characters, preview %r)", + generation_id, + voice_id, + len(text), + text[:LOG_PREVIEW_CHARS], + ) + self._finish_failed( + generation_id, + job, + part_path, + "ENGINE_ERROR", + "The speech engine could not render this text.", + str(error), + ) + except Exception as error: + logger.exception( + "Generation %s failed for voice %s (%d characters, preview %r)", + generation_id, + voice_id, + len(text), + text[:LOG_PREVIEW_CHARS], + ) + self._finish_failed( + generation_id, + job, + part_path, + "INTERNAL_ERROR", + "The generation failed unexpectedly.", + str(error), + ) + + def _on_sentence( + self, generation_id: str, job: _Job, wav_file: wave.Wave_write + ) -> Callable[[SentenceAudio], None]: + """Build the callback that streams one sentence and reports progress.""" + + def on_sentence(sentence: SentenceAudio) -> None: + if job.cancel_event.is_set(): + return + wav_file.writeframes(_samples_to_bytes(sentence.samples)) + 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: + raise EngineFaultError("injected engine failure") + + return on_sentence + + # -- terminal transitions ------------------------------------------------- + + def _finish_succeeded( + self, + generation_id: str, + job: _Job, + result: SynthesisResult, + words: list[WordTiming], + cues: list[Cue], + ratio: float, + part_path: Path, + final_path: Path, + ) -> None: + """Rename the audio, store the results, and publish the outcome.""" + with self._lock: + if job.cancel_event.is_set(): + self._cancel_locked(generation_id, job, part_path) + return + os.replace(part_path, final_path) + duration_seconds = _duration_seconds(result) + self._dal.set_status( + generation_id, + "succeeded", + duration_seconds=duration_seconds, + sample_rate=result.sample_rate, + audio_path=str(final_path), + word_timings_json=json.dumps( + [ + { + "text": word.text, + "startMs": word.start_ms, + "endMs": word.end_ms, + "aligned": word.aligned, + } + for word in words + ] + ), + cues_json=json.dumps( + [ + { + "index": cue.index, + "startMs": cue.start_ms, + "endMs": cue.end_ms, + "text": cue.text, + } + for cue in cues + ] + ), + aligned_word_ratio=ratio if ratio >= 0 else None, + ) + self._jobs.pop(generation_id, None) + if ratio < 0: + logger.warning("Generation %s finished without word alignments", generation_id) + else: + logger.info( + "Generation %s succeeded in %.2fs (aligned ratio %.3f)", + generation_id, + duration_seconds, + ratio, + ) + self._bus.publish(generation_id, _succeeded_event(generation_id, duration_seconds)) + self._bus.close(generation_id) + + def _finish_cancelled(self, generation_id: str, job: _Job, part_path: Path) -> None: + """Discard the partial output and mark the generation cancelled.""" + with self._lock: + self._cancel_locked(generation_id, job, part_path) + + def _cancel_locked(self, generation_id: str, job: _Job, part_path: Path) -> None: + """Cancel a generation; the caller already holds the manager lock.""" + _remove_file(part_path) + self._dal.set_status(generation_id, "cancelled") + self._jobs.pop(generation_id, None) + logger.info("Generation %s cancelled", generation_id) + self._bus.publish(generation_id, _cancelled_event(generation_id)) + self._bus.close(generation_id) + + def _finish_failed( + self, + generation_id: str, + job: _Job, + part_path: Path, + code: str, + message: str, + reason: str, + ) -> None: + """Discard the partial output and mark the generation failed.""" + with self._lock: + _remove_file(part_path) + self._dal.set_status(generation_id, "failed", error={"code": code, "message": message}) + self._jobs.pop(generation_id, None) + logger.warning("Generation %s failed (%s): %s", generation_id, code, reason) + self._bus.publish(generation_id, _failed_event(generation_id, code, message)) + self._bus.close(generation_id) + + # -- helpers -------------------------------------------------------------- + + def _voice_name(self, voice_id: str) -> str: + """Resolve the display name of a voice, refusing an unknown one.""" + for voice in list_voices(): + if voice.id == voice_id: + return voice.name + raise VoiceNotFoundError(voice_id) + + def _replay_state( + self, generation_id: str, subscriber: Subscriber, row: dict[str, Any] + ) -> None: + """Send the current state of a generation to a fresh subscriber.""" + status = row["status"] + job = self._jobs.get(generation_id) + if status == "succeeded": + subscriber.put(_succeeded_event(generation_id, row["duration_seconds"])) + self._bus.close(generation_id) + elif status == "failed": + subscriber.put( + _failed_event( + generation_id, + str(row["error_code"] or "INTERNAL_ERROR"), + str(row["error_message"] or "The generation failed unexpectedly."), + ) + ) + self._bus.close(generation_id) + elif status == "cancelled": + subscriber.put(_cancelled_event(generation_id)) + self._bus.close(generation_id) + else: + subscriber.put(_progress_event(generation_id, status, job)) + + +def bootstrap(settings: Settings, dal: Dal) -> None: + """Install the default voice on first run, tolerating an offline machine. + + A failure to download is not fatal: the application keeps serving and the + UI shows the no-voice guidance with the exact remedy (§10.4, R7). The + settings seeding that §8.2 asks for belongs to the settings route, so the + DAL is accepted here only to keep the startup hook in one place. + """ + ensure_data_dirs(settings) + if list_voices(): + return + logger.info( + "Downloading default voice %s (one-time, requires internet)", settings.default_voice_id + ) + try: + install_voice(settings.default_voice_id) + except Exception as error: # noqa: BLE001 - an offline first run must not crash + logger.warning( + "Could not download the default voice %s: %s", settings.default_voice_id, error + ) + logger.warning( + "No voices are installed. Run `tts add-voice %s` (needs internet once), then reload.", + settings.default_voice_id, + ) + return + logger.info("Installed default voice %s", settings.default_voice_id) diff --git a/src/tts/jobs/sse.py b/src/tts/jobs/sse.py new file mode 100644 index 0000000..09e5b73 --- /dev/null +++ b/src/tts/jobs/sse.py @@ -0,0 +1,111 @@ +"""In-memory SSE subscriber registry and wire formatting for generation events. + +The jobs manager publishes one event per generation; the API layer turns those +events into the ``text/event-stream`` body described in ARCHITECTURE.md §9.2. +The registry lives in the process, so a reconnecting client is served the +current state again instead of a gap in the history (§7.8). +""" + +from __future__ import annotations + +import json +import queue +import threading +from collections.abc import Iterator +from dataclasses import dataclass +from typing import Any + +RETRY_LINE = "retry: 3000\n\n" +"""Reconnect hint sent once when an event stream opens (§9.2).""" + + +@dataclass(frozen=True) +class SseEvent: + """One named SSE event with its JSON payload.""" + + name: str + data: dict[str, Any] + terminal: bool = False + + def to_wire(self) -> str: + """Serialize the event as an SSE frame (§9.2).""" + payload = json.dumps(self.data, separators=(",", ":")) + return f"event: {self.name}\ndata: {payload}\n\n" + + +class Subscriber: + """A queue of events for one generation id.""" + + def __init__(self, generation_id: str) -> None: + self.generation_id = generation_id + self._queue: queue.Queue[SseEvent | None] = queue.Queue() + + def put(self, event: SseEvent) -> None: + """Queue an event for the subscriber.""" + self._queue.put(event) + + def close(self) -> None: + """Signal the end of the stream.""" + self._queue.put(None) + + def events(self) -> Iterator[SseEvent | None]: + """Yield queued events until the stream is closed.""" + while True: + event = self._queue.get() + yield event + if event is None: + return + + def get(self, timeout: float | None = None) -> SseEvent | None: + """Pop the next event, waiting at most ``timeout`` seconds. + + Raises :class:`queue.Empty` when no event arrives in time; ``None`` + marks the end of the stream. + """ + return self._queue.get(timeout=timeout) + + +class EventBus: + """Registry of SSE subscribers, keyed by generation id.""" + + def __init__(self) -> None: + self._lock = threading.RLock() + self._subscribers: dict[str, list[Subscriber]] = {} + + def subscribe(self, generation_id: str) -> Subscriber: + """Register a new subscriber for a generation.""" + with self._lock: + subscriber = Subscriber(generation_id) + self._subscribers.setdefault(generation_id, []).append(subscriber) + return subscriber + + def unsubscribe(self, generation_id: str, subscriber: Subscriber) -> None: + """Forget a subscriber without ending any other stream.""" + with self._lock: + subscribers = self._subscribers.get(generation_id) + if not subscribers: + return + if subscriber in subscribers: + subscribers.remove(subscriber) + if not subscribers: + del self._subscribers[generation_id] + + def publish(self, generation_id: str, event: SseEvent) -> None: + """Deliver an event to every subscriber of a generation.""" + with self._lock: + for subscriber in list(self._subscribers.get(generation_id, ())): + subscriber.put(event) + + def close(self, generation_id: str) -> None: + """End every stream of a generation after its terminal event.""" + with self._lock: + subscribers = self._subscribers.pop(generation_id, []) + for subscriber in subscribers: + subscriber.close() + + def close_all(self) -> None: + """End every open stream, for example when the process shuts down.""" + with self._lock: + generation_ids = list(self._subscribers) + for generation_id in generation_ids: + self.close(generation_id) diff --git a/tests/integration/test_jobs_pipeline.py b/tests/integration/test_jobs_pipeline.py new file mode 100644 index 0000000..0f55144 --- /dev/null +++ b/tests/integration/test_jobs_pipeline.py @@ -0,0 +1,250 @@ +"""Integration tests for the jobs manager against a real Piper voice.""" + +from __future__ import annotations + +import json +import queue +import time +import wave +from pathlib import Path +from typing import Any + +import pytest + +from tts.config import Settings +from tts.history.dal import Dal +from tts.jobs.manager import JobManager +from tts.jobs.sse import SseEvent +from tts.voices.store import ensure_data_dirs, list_voices + +pytestmark = pytest.mark.integration + +DEFAULT_VOICE_ID = "en_US-lessac-medium" + +TERMINAL_STATUSES = {"succeeded", "failed", "cancelled"} + +LONG_TEXT = ( + "The first sentence says hello. " + "The second sentence says goodbye. " + "The third sentence keeps going. " + "The fourth sentence ends the text." +) + + +@pytest.fixture +def environment(tmp_path: Path) -> Any: + """Build a manager that renders with the downloaded voice but writes to a temp dir.""" + real_settings = Settings.load() + voices_dir = ensure_data_dirs(real_settings) + installed = {voice.id for voice in list_voices()} + if DEFAULT_VOICE_ID not in installed: + pytest.skip( + f"{DEFAULT_VOICE_ID} is not installed; run: python -m piper.download_voices " + f"{DEFAULT_VOICE_ID} --download-dir {voices_dir}" + ) + + settings = Settings( + host=real_settings.host, + port=real_settings.port, + data_dir=tmp_path, + max_input_chars=real_settings.max_input_chars, + history_limit=real_settings.history_limit, + log_level=real_settings.log_level, + default_voice_id=real_settings.default_voice_id, + ) + 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() + + +def _wait_for_status(dal: Dal, generation_id: str, timeout: float = 60.0) -> dict[str, Any]: + """Wait until a generation reaches a terminal status.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + row = dal.get(generation_id) + if row is not None and row["status"] in TERMINAL_STATUSES: + return row + time.sleep(0.01) + raise AssertionError(f"generation {generation_id} never finished") + + +def _wait_until_running(dal: Dal, generation_id: str, timeout: float = 60.0) -> dict[str, Any]: + """Wait until a generation is claimed by the worker.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + row = dal.get(generation_id) + if row is None: + raise AssertionError(f"generation {generation_id} disappeared") + if row["status"] == "running": + return row + if row["status"] in TERMINAL_STATUSES: + raise AssertionError(f"generation {generation_id} finished before it was observed") + time.sleep(0.005) + raise AssertionError(f"generation {generation_id} never started") + + +def _drain(subscriber: Any, timeout: float = 60.0) -> list[SseEvent]: + """Collect every event a subscriber receives until its stream closes.""" + events: list[SseEvent] = [] + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + event = subscriber.get(timeout=max(0.01, deadline - time.monotonic())) + except queue.Empty: + break + if event is None: + break + events.append(event) + return events + + +def _audio_paths(tmp_path: Path, generation_id: str) -> tuple[Path, Path]: + """Return the ``.part`` and final audio paths of a generation.""" + generations = tmp_path / "generations" + return generations / f"{generation_id}.wav.part", generations / f"{generation_id}.wav" + + +def test_real_voice_job_reports_progress_and_succeeds(environment: Any) -> None: + manager, dal, tmp_path = environment + generation_id = manager.submit(DEFAULT_VOICE_ID, "Hello there. This is a test.") + + _wait_until_running(dal, generation_id) + subscriber = manager.subscribe(generation_id) + events = _drain(subscriber) + + progress = [event for event in events if event.name == "progress"] + assert len(progress) >= 1 + assert progress[-1].data["sentenceIndex"] >= 1 + assert progress[-1].data["sentenceCount"] == 2 + assert events[-1].name == "succeeded" + + row = dal.get(generation_id) + assert row is not None + assert row["status"] == "succeeded" + assert row["duration_seconds"] is not None and row["duration_seconds"] > 0 + assert row["sample_rate"] == 22_050 + assert row["aligned_word_ratio"] is not None + + part_path, final_path = _audio_paths(tmp_path, generation_id) + assert final_path.is_file() + assert not part_path.exists() + with wave.open(str(final_path), "rb") as wav_file: + assert wav_file.getnchannels() == 1 + assert wav_file.getsampwidth() == 2 + assert wav_file.getframerate() == 22_050 + assert wav_file.getnframes() > 0 + + +def test_real_voice_job_derives_one_cue_per_sentence(environment: Any) -> None: + manager, dal, _ = environment + generation_id = manager.submit(DEFAULT_VOICE_ID, "First sentence here. Second sentence here.") + + row = _wait_for_status(dal, generation_id) + + assert row["status"] == "succeeded" + cues = json.loads(row["cues_json"]) + assert len(cues) == 2 + assert cues[0]["index"] == 1 + assert cues[1]["index"] == 2 + 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") + + generation_id = manager.submit(DEFAULT_VOICE_ID, "One sentence. Two sentences.") + + row = _wait_for_status(dal, generation_id) + part_path, final_path = _audio_paths(tmp_path, generation_id) + + assert row["status"] == "failed" + assert row["error_code"] == "ENGINE_ERROR" + assert not final_path.exists() + assert not part_path.exists() + + +def test_cancel_mid_run_leaves_no_audio(environment: Any) -> None: + manager, dal, tmp_path = environment + generation_id = manager.submit(DEFAULT_VOICE_ID, LONG_TEXT) + + _wait_until_running(dal, generation_id) + assert manager.cancel(generation_id) == "cancelling" + + row = _wait_for_status(dal, generation_id) + part_path, final_path = _audio_paths(tmp_path, generation_id) + + assert row["status"] == "cancelled" + assert not final_path.exists() + assert not part_path.exists() + + +def test_two_jobs_run_strictly_sequentially(environment: Any) -> None: + manager, dal, tmp_path = environment + first = manager.submit(DEFAULT_VOICE_ID, "First job text.") + second = manager.submit(DEFAULT_VOICE_ID, "Second job text.") + + deadline = time.monotonic() + 60.0 + overlapped = False + while time.monotonic() < deadline: + first_row = dal.get(first) + second_row = dal.get(second) + assert first_row is not None + assert second_row is not None + if first_row["status"] == "running" and second_row["status"] == "running": + overlapped = True + if first_row["status"] in TERMINAL_STATUSES and second_row["status"] in TERMINAL_STATUSES: + break + time.sleep(0.005) + + assert not overlapped + assert dal.get(first) is not None + assert dal.get(first)["status"] == "succeeded" # type: ignore[index] + assert dal.get(second)["status"] == "succeeded" # type: ignore[index] + + _, first_audio = _audio_paths(tmp_path, first) + _, second_audio = _audio_paths(tmp_path, second) + assert first_audio.is_file() + assert second_audio.is_file() + + +def test_a_second_job_does_not_start_before_the_first_finishes(environment: Any) -> None: + manager, dal, _ = environment + first = manager.submit(DEFAULT_VOICE_ID, "First job text.") + second = manager.submit(DEFAULT_VOICE_ID, "Second job text.") + + deadline = time.monotonic() + 60.0 + second_started_early = False + while time.monotonic() < deadline: + first_row = dal.get(first) + second_row = dal.get(second) + assert first_row is not None + assert second_row is not None + if second_row["status"] == "running" and first_row["status"] not in TERMINAL_STATUSES: + second_started_early = True + if first_row["status"] in TERMINAL_STATUSES and second_row["status"] in TERMINAL_STATUSES: + break + time.sleep(0.005) + + assert not second_started_early + + +def test_bootstrap_is_a_no_op_when_a_voice_is_installed(environment: Any) -> None: + """The first-run download must not run again once a voice is present.""" + _, dal, _ = environment + before = {voice.id for voice in list_voices()} + + from tts.jobs.manager import bootstrap + + bootstrap(Settings.load(), dal) + + assert {voice.id for voice in list_voices()} == before diff --git a/tests/unit/test_jobs_manager.py b/tests/unit/test_jobs_manager.py new file mode 100644 index 0000000..a896d0b --- /dev/null +++ b/tests/unit/test_jobs_manager.py @@ -0,0 +1,542 @@ +"""Unit tests for the jobs manager using a fake engine and a real DAL.""" + +from __future__ import annotations + +import itertools +import json +import queue +import threading +import time +import wave +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pytest + +from tts.config import Settings +from tts.history.dal import Dal +from tts.jobs import manager as manager_module +from tts.jobs.manager import ( + EngineFaultError, + GenerationNotCancellableError, + GenerationNotFoundError, + JobManager, + split_sentences, +) +from tts.jobs.sse import SseEvent +from tts.types import Cue, SentenceAudio, SynthesisResult, WordTiming +from tts.voices.store import LoadedVoice + +SAMPLE_RATE = 22_050 +VOICE_ID = "test-voice" +SENTENCE_MS = 100 + + +class FakeEngine: + """Stands in for the piper engine: deterministic sentences, optional faults.""" + + def __init__( + self, + *, + gate: threading.Event | None = None, + fail_after: int | None = None, + silent: bool = False, + ) -> None: + self.gate = gate + self.fail_after = fail_after + self.silent = silent + self.started = threading.Event() + self.calls: list[str] = [] + self.concurrent = 0 + self.max_concurrent = 0 + + def synthesize( + self, + voice: LoadedVoice, + text: str, + char_offset_map: list[tuple[int, int]], + rate: float, + volume: float, + cancel_event: threading.Event, + on_sentence: Any, + ) -> SynthesisResult: + self.started.set() + self.calls.append(text) + self.concurrent += 1 + self.max_concurrent = max(self.max_concurrent, self.concurrent) + try: + if self.gate is not None: + self.gate.wait(timeout=10) + sentences: list[SentenceAudio] = [] + for index, (start, end) in enumerate(char_offset_map): + if cancel_event.is_set(): + break + if self.fail_after is not None and index >= self.fail_after: + raise RuntimeError("engine exploded") + sentence = _sentence(text, start, end, silent=self.silent) + sentences.append(sentence) + on_sentence(sentence) + return SynthesisResult( + sentences=sentences, + total_samples=sum(len(item.samples) for item in sentences), + sample_rate=SAMPLE_RATE, + supports_alignments=True, + ) + finally: + self.concurrent -= 1 + + +def _sentence(text: str, start: int, end: int, *, silent: bool = False) -> SentenceAudio: + """Build one deterministic sentence of silent audio.""" + sample_count = 0 if silent else SAMPLE_RATE * SENTENCE_MS // 1000 + samples = np.zeros(sample_count, dtype=np.float32) + return SentenceAudio( + text=text[start:end], + char_start=start, + char_end=end, + samples=samples, + sample_rate=SAMPLE_RATE, + phoneme_alignments=[("h", len(samples))], + supports_alignments=True, + ) + + +def _fake_timings(voice: LoadedVoice, result: SynthesisResult) -> tuple[list[WordTiming], float]: + """Derive one word timing per whitespace token, ignoring the collapse rule.""" + words: list[WordTiming] = [] + for sentence in result.sentences: + for token in sentence.text.split(): + words.append(WordTiming(text=token, start_ms=0, end_ms=SENTENCE_MS, aligned=True)) + return words, 1.0 + + +def _install_fake_voice(data_dir: Path) -> None: + """Write a minimal voice pair so the real voice store can list it.""" + voices_dir = data_dir / "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", + ) + + +class Harness: + """A manager wired to fakes, plus the DAL and the fake engine behind it.""" + + def __init__(self, manager: JobManager, dal: Dal, engine: FakeEngine) -> None: + self.manager = manager + self.dal = dal + self.engine = engine + + +@pytest.fixture +def harness(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Harness: + """Build a manager with a fake engine and an installed fake voice.""" + _install_fake_voice(tmp_path) + 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, + ) + 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 = FakeEngine() + 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", _fake_timings) + + harness = Harness(manager, dal, engine) + yield harness + manager.close() + dal.close() + + +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.005) + raise AssertionError(f"generation {generation_id} never reached {sorted(statuses)}") + + +def _drain(subscriber: Any, timeout: float = 10.0) -> list[SseEvent]: + """Collect every event a subscriber receives until its stream closes.""" + events: list[SseEvent] = [] + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + event = subscriber.get(timeout=max(0.01, deadline - time.monotonic())) + except queue.Empty: + break + if event is None: + break + events.append(event) + return events + + +def _generation_files(harness: Harness, generation_id: str) -> tuple[Path, Path]: + """Return the ``.part`` and final audio paths of a generation.""" + generations = harness.manager._generations_dir + return ( + generations / f"{generation_id}.wav.part", + generations / f"{generation_id}.wav", + ) + + +# -- submission --------------------------------------------------------------- + + +def test_submit_creates_a_row_and_reaches_succeeded(harness: Harness) -> None: + generation_id = harness.manager.submit(VOICE_ID, "Hello there. Second one.") + + row = _wait_for_status(harness.dal, generation_id, {"succeeded"}) + + assert row["status"] == "succeeded" + assert row["voice_id"] == VOICE_ID + assert row["voice_name"] == VOICE_ID + assert row["input_text"] == "Hello there. Second one." + assert row["source_type"] == "text" + assert row["sample_rate"] == SAMPLE_RATE + assert row["duration_seconds"] == pytest.approx(0.2) + assert row["aligned_word_ratio"] == pytest.approx(1.0) + + +def test_submit_rejects_an_unknown_voice(harness: Harness) -> None: + from tts.voices.store import VoiceNotFoundError + + with pytest.raises(VoiceNotFoundError): + harness.manager.submit("missing-voice", "Hello.") + + +def test_successful_job_writes_audio_atomically(harness: Harness) -> None: + generation_id = harness.manager.submit(VOICE_ID, "One. Two.") + _wait_for_status(harness.dal, generation_id, {"succeeded"}) + + part_path, final_path = _generation_files(harness, generation_id) + + assert final_path.is_file() + assert not part_path.exists() + + with wave.open(str(final_path), "rb") as wav_file: + assert wav_file.getnchannels() == 1 + assert wav_file.getsampwidth() == 2 + assert wav_file.getframerate() == SAMPLE_RATE + assert wav_file.getnframes() == SAMPLE_RATE * 2 * SENTENCE_MS // 1000 + + +def test_successful_job_stores_timings_and_cues(harness: Harness) -> None: + generation_id = harness.manager.submit(VOICE_ID, "Hello there. Second one.") + _wait_for_status(harness.dal, generation_id, {"succeeded"}) + + row = harness.dal.get(generation_id) + assert row is not None + + word_timings = json.loads(row["word_timings_json"]) + assert word_timings == [ + {"text": "Hello", "startMs": 0, "endMs": 100, "aligned": True}, + {"text": "there.", "startMs": 0, "endMs": 100, "aligned": True}, + {"text": "Second", "startMs": 0, "endMs": 100, "aligned": True}, + {"text": "one.", "startMs": 0, "endMs": 100, "aligned": True}, + ] + + cues = json.loads(row["cues_json"]) + assert [cue["index"] for cue in cues] == [1, 2] + assert cues[0]["text"] == "Hello there." + assert cues[0]["startMs"] == 0 + assert set(cues[0]) == {"index", "startMs", "endMs", "text"} + + assert row["audio_path"] == str(_generation_files(harness, generation_id)[1]) + + +# -- events ------------------------------------------------------------------- + + +def test_progress_events_are_published_before_success(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) + + subscriber = harness.manager.subscribe(generation_id) + gate.set() + events = _drain(subscriber) + + progress = [event for event in events if event.name == "progress"] + assert len(progress) >= 1 + assert progress[-1].data["sentenceIndex"] == 2 + assert progress[-1].data["sentenceCount"] == 2 + assert progress[-1].data["status"] == "running" + assert events[-1].name == "succeeded" + assert events[-1].data["durationSeconds"] == pytest.approx(0.2) + + +def test_subscribe_replays_the_terminal_state(harness: Harness) -> None: + generation_id = harness.manager.submit(VOICE_ID, "One.") + _wait_for_status(harness.dal, generation_id, {"succeeded"}) + + subscriber = harness.manager.subscribe(generation_id) + events = _drain(subscriber) + + assert [event.name for event in events] == ["succeeded"] + assert events[0].data["status"] == "succeeded" + + +def test_subscribe_replays_a_running_state(harness: Harness) -> None: + gate = threading.Event() + harness.engine.gate = gate + generation_id = harness.manager.submit(VOICE_ID, "One.") + assert harness.engine.started.wait(timeout=10) + + subscriber = harness.manager.subscribe(generation_id) + gate.set() + events = _drain(subscriber) + + assert events[0].name == "progress" + assert events[0].data["status"] == "running" + + +def test_subscribe_rejects_an_unknown_generation(harness: Harness) -> None: + with pytest.raises(GenerationNotFoundError): + harness.manager.subscribe("6f0c8e2a-0000-4000-8000-000000000000") + + +# -- failures ----------------------------------------------------------------- + + +def test_engine_failure_leaves_no_audio_and_marks_failed(harness: Harness) -> None: + harness.engine.fail_after = 1 + generation_id = harness.manager.submit(VOICE_ID, "One. Two. Three.") + + row = _wait_for_status(harness.dal, generation_id, {"failed"}) + part_path, final_path = _generation_files(harness, generation_id) + + assert row["status"] == "failed" + assert row["error_code"] == "INTERNAL_ERROR" + assert row["error_message"] + assert not final_path.exists() + assert not part_path.exists() + + +def test_a_generation_without_audio_fails_instead_of_succeeding(harness: Harness) -> None: + """A valid but empty WAV would be unplayable, so it must not be a success.""" + harness.engine.silent = True + generation_id = harness.manager.submit(VOICE_ID, "---") + + row = _wait_for_status(harness.dal, generation_id, {"failed"}) + part_path, final_path = _generation_files(harness, generation_id) + + assert row["error_code"] == "ENGINE_ERROR" + assert not final_path.exists() + 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.") + + row = _wait_for_status(harness.dal, generation_id, {"failed"}) + part_path, final_path = _generation_files(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) + gate = threading.Event() + harness.engine.gate = gate + generation_id = harness.manager.submit(VOICE_ID, "One. Two.") + assert harness.engine.started.wait(timeout=10) + + assert harness.manager.cancel(generation_id) == "cancelling" + gate.set() + row = _wait_for_status(harness.dal, generation_id, {"cancelled"}) + + assert row["status"] == "cancelled" + assert row["error_code"] is None + + +# -- cancellation ------------------------------------------------------------- + + +def test_cancel_mid_run_cancels_the_job_and_removes_the_output(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) + + assert harness.manager.cancel(generation_id) == "cancelling" + gate.set() + row = _wait_for_status(harness.dal, generation_id, {"cancelled"}) + part_path, final_path = _generation_files(harness, generation_id) + + assert row["status"] == "cancelled" + assert not final_path.exists() + assert not part_path.exists() + + +def test_cancel_while_queued_never_starts_the_job(harness: Harness) -> None: + gate = threading.Event() + harness.engine.gate = gate + first = harness.manager.submit(VOICE_ID, "Blocking.") + assert harness.engine.started.wait(timeout=10) + + second = harness.manager.submit(VOICE_ID, "Second job.") + assert harness.manager.cancel(second) == "cancelled" + + row = _wait_for_status(harness.dal, second, {"cancelled"}) + assert row["status"] == "cancelled" + + gate.set() + _wait_for_status(harness.dal, first, {"succeeded"}) + assert harness.engine.calls == ["Blocking."] + + +def test_cancel_rejects_an_unknown_generation(harness: Harness) -> None: + with pytest.raises(GenerationNotFoundError): + harness.manager.cancel("6f0c8e2a-0000-4000-8000-000000000000") + + +def test_cancel_rejects_a_terminal_generation(harness: Harness) -> None: + generation_id = harness.manager.submit(VOICE_ID, "One.") + _wait_for_status(harness.dal, generation_id, {"succeeded"}) + + with pytest.raises(GenerationNotCancellableError): + harness.manager.cancel(generation_id) + + +# -- serialization ------------------------------------------------------------ + + +def test_two_jobs_run_strictly_sequentially(harness: Harness) -> None: + first = harness.manager.submit(VOICE_ID, "One.") + second = harness.manager.submit(VOICE_ID, "Two.") + + _wait_for_status(harness.dal, first, {"succeeded"}) + _wait_for_status(harness.dal, second, {"succeeded"}) + + assert harness.engine.max_concurrent == 1 + assert harness.engine.calls == ["One.", "Two."] + + +def test_eviction_is_given_every_in_flight_id( + harness: Harness, monkeypatch: pytest.MonkeyPatch +) -> None: + captured: list[set[str]] = [] + original = harness.dal.evict_to_limit + + def spy(active_ids: set[str] | None = None) -> list[str]: + captured.append(set(active_ids or set())) + return original(active_ids) + + monkeypatch.setattr(harness.dal, "evict_to_limit", spy) + + gate = threading.Event() + harness.engine.gate = gate + first = harness.manager.submit(VOICE_ID, "One.") + assert harness.engine.started.wait(timeout=10) + second = harness.manager.submit(VOICE_ID, "Two.") + + assert captured[-1] == {first, second} + + gate.set() + _wait_for_status(harness.dal, first, {"succeeded"}) + _wait_for_status(harness.dal, second, {"succeeded"}) + + +# -- sentence segmentation ---------------------------------------------------- + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("Hello. World.", [(0, 6), (7, 13)]), + ("Hello world", [(0, 11)]), + ("Hello.", [(0, 6)]), + ("Wait! What? Yes.", [(0, 5), (6, 11), (12, 16)]), + ('He said "stop." Then left.', [(0, 15), (16, 26)]), + ("Dr. Smith went home.", [(0, 20)]), + ("J. Smith went home.", [(0, 19)]), + ("The price is 3.14 today.", [(0, 24)]), + ("One. Two.", [(0, 4), (7, 11)]), + ], +) +def test_split_sentences(text: str, expected: list[tuple[int, int]]) -> None: + assert split_sentences(text) == expected + + +def test_split_sentences_covers_the_text_without_overlap() -> None: + text = "First one. Second one! Third one? Done" + spans = split_sentences(text) + + assert spans[0][0] == 0 + assert spans[-1][1] == len(text) + for previous, current in itertools.pairwise(spans): + assert previous[1] <= current[0] + assert previous[1] < current[1] + + +# -- cue sentence triplets ---------------------------------------------------- + + +def test_sentence_triplets_use_the_real_per_sentence_entry_count( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A collapsed sentence contributes one entry, not one entry per token.""" + sentences = [ + _sentence("Hello there.", 0, 12), + _sentence("Goodbye.", 13, 21), + ] + result = SynthesisResult( + sentences=sentences, + total_samples=sum(len(item.samples) for item in sentences), + sample_rate=SAMPLE_RATE, + supports_alignments=True, + ) + + def collapsing_timings( + voice: LoadedVoice, synthesis: SynthesisResult + ) -> tuple[list[WordTiming], float]: + if len(synthesis.sentences) == 1: + # The reconciler collapses an unplaceable sentence to one entry. + return [ + WordTiming(text=synthesis.sentences[0].text, start_ms=0, end_ms=1, aligned=False) + ], 0.0 + return _fake_timings(voice, synthesis) + + monkeypatch.setattr(manager_module, "derive_word_timings", collapsing_timings) + fake_voice = LoadedVoice( + voice=SimpleNamespace(config=SimpleNamespace(sample_rate=SAMPLE_RATE)), # type: ignore[arg-type] + supports_alignments=True, + ) + + triplets = manager_module._sentence_triplets(fake_voice, result) + + assert triplets == [(0, 12, 0), (13, 21, 1)] + + +def test_engine_fault_error_is_an_exception() -> None: + assert issubclass(EngineFaultError, RuntimeError) + assert isinstance(Cue(index=1, start_ms=0, end_ms=1, text="x"), Cue) diff --git a/tests/unit/test_jobs_sse.py b/tests/unit/test_jobs_sse.py new file mode 100644 index 0000000..fde9345 --- /dev/null +++ b/tests/unit/test_jobs_sse.py @@ -0,0 +1,88 @@ +"""Unit tests for the SSE subscriber registry and wire format.""" + +from __future__ import annotations + +import json +import queue + +import pytest + +from tts.jobs.sse import RETRY_LINE, EventBus, SseEvent, Subscriber + + +def test_event_serializes_to_an_sse_frame() -> None: + event = SseEvent(name="progress", data={"generationId": "abc", "status": "running"}) + + wire = event.to_wire() + + assert wire.startswith("event: progress\n") + assert wire.endswith("\n\n") + payload_line = next(line for line in wire.splitlines() if line.startswith("data: ")) + assert json.loads(payload_line.removeprefix("data: ")) == { + "generationId": "abc", + "status": "running", + } + + +def test_retry_line_is_a_single_reconnect_hint() -> None: + assert RETRY_LINE == "retry: 3000\n\n" + + +def test_subscriber_yields_events_until_the_stream_closes() -> None: + subscriber = Subscriber("generation-1") + first = SseEvent(name="progress", data={"generationId": "generation-1"}) + second = SseEvent(name="succeeded", data={"generationId": "generation-1"}, terminal=True) + + subscriber.put(first) + subscriber.put(second) + subscriber.close() + + assert list(subscriber.events()) == [first, second, None] + + +def test_bus_delivers_to_every_subscriber_of_a_generation() -> None: + bus = EventBus() + first = bus.subscribe("generation-1") + second = bus.subscribe("generation-1") + other = bus.subscribe("generation-2") + + bus.publish("generation-1", SseEvent(name="progress", data={"generationId": "generation-1"})) + + assert first.get(timeout=1) is not None + assert second.get(timeout=1) is not None + with pytest.raises(queue.Empty): + other.get(timeout=0.05) + + +def test_bus_close_ends_every_stream_of_a_generation() -> None: + bus = EventBus() + subscriber = bus.subscribe("generation-1") + + bus.publish("generation-1", SseEvent(name="succeeded", data={}, terminal=True)) + bus.close("generation-1") + + events = list(subscriber.events()) + assert events[-1] is None + assert events[0].name == "succeeded" + + +def test_bus_unsubscribe_forgets_only_that_subscriber() -> None: + bus = EventBus() + first = bus.subscribe("generation-1") + second = bus.subscribe("generation-1") + + bus.unsubscribe("generation-1", first) + bus.publish("generation-1", SseEvent(name="progress", data={})) + + assert second.get(timeout=1) is not None + with pytest.raises(queue.Empty): + first.get(timeout=0.05) + + +def test_bus_close_all_ends_every_open_stream() -> None: + bus = EventBus() + subscriber = bus.subscribe("generation-1") + + bus.close_all() + + assert list(subscriber.events()) == [None]