Files
video-analyse/tests/test_pipeline.py
T
alex dca19074f4 tests: cover the cached-turns guard and the analyse cross-door parity (code-review B6)
Two verification gaps from the review:

- the `transcript is not None` guard added in d94188e had no test. The stage skip
  policy normally keeps a transcript-less diarize apply out of the scheduler's way,
  so the test calls the apply callable the scheduler invokes (RunContext with no
  transcript) and asserts the load leaves the run untouched; removing the guard
  makes it fail with NoneType.model_copy inside attribute_speakers
- the third #9 divergence (va analyse --max-shots / --no-describe) was only
  asserted CLI-side. The new parity test runs both doors against the same fake
  pipeline and asserts identical stage calls *and* that max_shots=8 reaches the
  shots stage from both (shown red against an MCP tool that dropped max_shots)
2026-11-24 12:56:40 +00:00

1124 lines
42 KiB
Python

"""Pipeline orchestration tests using injected fake stages.
The ``stages`` dependency-injection mapping of
:class:`video_analyse.pipeline.Pipeline` replaces every stage, so these tests never
import the ffmpeg/ffprobe wrappers, an STT/diarization backend or the VLM modules and
never touch the network or a model file. Media files are plain bytes: only their
content hash matters to the pipeline.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import pytest
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.diarize import DiarizeOptions
from video_analyse.ingest import IngestResult, fetch, ingest_key_params
from video_analyse.media import ShotOptions
from video_analyse.models import (
Artifacts,
MediaFacts,
MediaRef,
Segment,
Shot,
ShotDescription,
SpeakerTurn,
Transcript,
VideoReport,
Word,
)
from video_analyse.pipeline import (
_DOWNSTREAM,
STAGE_ORDER,
STAGES_TABLE,
Pipeline,
ProgressEvent,
RunContext,
StageSpec,
_apply_diarize,
_resolve_want,
_TurnsArtifact,
)
from video_analyse.synthesis import ReportOptions
from video_analyse.transcribe import SttOptions
from video_analyse.vision import DescribeOptions
VA_ENV_VARS = (
"VA_PROFILE",
"VA_CACHE_DIR",
"VA_LANGUAGE",
"VA_STT_BACKEND",
"VA_STT_API_BASE_URL",
"VA_STT_API_MODEL",
"VA_STT_MAX_UPLOAD_BYTES",
"VA_WHISPER_MODEL",
"VA_DIARIZE",
"VA_DIARIZE_BACKEND",
"VA_DIARIZE_CLUSTER_THRESHOLD",
"VA_DIARIZE_MIN_DURATION_ON",
"VA_DIARIZE_MIN_DURATION_OFF",
"VA_VLM_MODEL",
"VA_LLAMA_SERVER_URL",
"VA_SYNTHESIS_MODEL",
)
@pytest.fixture(autouse=True)
def clean_va_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep every test independent of the developer's environment."""
for name in VA_ENV_VARS:
monkeypatch.delenv(name, raising=False)
def _settings(tmp_path: Path, **overrides: Any) -> Settings:
"""Settings rooted at ``tmp_path``; each stage test overrides only its own knob."""
values: dict[str, Any] = {"cache_dir": tmp_path / "cache"}
values.update(overrides)
return Settings(**values)
def _make_source(tmp_path: Path, name: str = "clip.mp4", payload: bytes = b"fake video") -> Path:
"""Create a local file whose bytes the pipeline can hash."""
path = tmp_path / "media" / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(payload)
return path
class FakeStages:
"""Deterministic stand-ins for every pipeline stage, recording every call."""
def __init__(
self,
source: Path,
*,
has_audio: bool = True,
has_video: bool = True,
shots: list[Shot] | None = None,
turns: list[SpeakerTurn] | None = None,
) -> None:
self.source = source
self.has_audio = has_audio
self.has_video = has_video
self.shot_template = (
shots
if shots is not None
else [Shot(index=0, start=0.0, end=5.0), Shot(index=1, start=5.0, end=10.0)]
)
self.turn_template = (
turns
if turns is not None
else [
SpeakerTurn(start=0.0, end=5.0, speaker="S1"),
SpeakerTurn(start=5.0, end=10.0, speaker="S2"),
]
)
self.calls: list[str] = []
self.ingest_calls: list[tuple[str, Path, int]] = []
self.probe_calls: list[Path] = []
self.audio_calls: list[tuple[Path, Path]] = []
self.transcribe_calls: list[Path] = []
self.transcribe_options: list[SttOptions] = []
self.diarize_calls: list[Path] = []
self.diarize_options: list[DiarizeOptions] = []
self.shots_calls: list[tuple[Path, Path]] = []
self.shots_options: list[ShotOptions] = []
self.describe_calls: list[int] = []
self.describe_options: list[DescribeOptions] = []
self.report_calls: list[bool] = []
self.report_options: list[ReportOptions] = []
def mapping(self) -> dict[str, Any]:
"""The ``stages`` mapping for :class:`Pipeline`."""
return {
"ingest": self.ingest,
"probe": self.probe,
"audio": self.audio,
"transcribe": self.transcribe,
"diarize": self.diarize,
"shots": self.shots,
"describe": self.describe,
"report": self.report,
}
# ------------------------------------------------------------------ #
# stage fakes
# ------------------------------------------------------------------ #
async def ingest(self, source: str, *, cache_dir: Path, quality: int) -> IngestResult:
"""Pretend to download ``source`` into the cache."""
self.calls.append("ingest")
self.ingest_calls.append((source, cache_dir, quality))
return IngestResult(
path=self.source,
info={
"title": "Fake video",
"filepath": str(self.source),
"_filename": str(self.source),
"requested_downloads": [{"filepath": str(self.source)}],
},
downloaded=True,
title="Fake video",
)
async def probe(self, path: Path) -> MediaFacts:
"""Return synthetic content facts for ``path``."""
self.calls.append("probe")
self.probe_calls.append(path)
return MediaFacts(
duration=10.0,
width=640 if self.has_video else None,
height=360 if self.has_video else None,
fps=12.0 if self.has_video else None,
has_audio=self.has_audio,
size_bytes=path.stat().st_size,
format="mp4",
extra={"title": "Fake video"},
)
async def audio(self, path: Path, workdir: Path) -> Path:
"""Write a placeholder WAV where the real extractor would."""
self.calls.append("audio")
self.audio_calls.append((path, workdir))
wav = Path(workdir) / "audio.wav"
wav.parent.mkdir(parents=True, exist_ok=True)
wav.write_bytes(b"RIFF" + b"\x00" * 64)
return wav
async def transcribe(self, wav: Path, *, options: SttOptions) -> Transcript:
"""Return a two-segment transcript with word timings."""
self.calls.append("transcribe")
self.transcribe_calls.append(wav)
self.transcribe_options.append(options)
return Transcript(
language=options.language or "en",
duration=10.0,
segments=[
Segment(
start=0.0,
end=4.0,
text="first line",
words=[Word(text="first", start=1.0, end=1.5)],
),
Segment(
start=5.0,
end=9.0,
text="second line",
words=[Word(text="second", start=6.0, end=6.5)],
),
],
backend="fake",
model="fake-model",
)
async def diarize(self, wav: Path, *, options: DiarizeOptions) -> list[SpeakerTurn]:
"""Return the canned speaker turns."""
self.calls.append("diarize")
self.diarize_calls.append(wav)
self.diarize_options.append(options)
return [turn.model_copy(deep=True) for turn in self.turn_template]
async def shots(
self, path: Path, info: MediaFacts, *, workdir: Path, options: ShotOptions
) -> list[Shot]:
"""Return the canned shot list."""
self.calls.append("shots")
self.shots_calls.append((path, workdir))
self.shots_options.append(options)
return [shot.model_copy(deep=True) for shot in self.shot_template]
async def describe(
self, shots: list[Shot], transcript: Transcript | None, *, options: DescribeOptions
) -> list[Shot]:
"""Attach a description to every shot."""
self.calls.append("describe")
self.describe_calls.append(len(shots))
self.describe_options.append(options)
for shot in shots:
shot.description = ShotDescription(
summary=f"shot {shot.index} summary", shot_type="screen"
)
return shots
async def report(
self,
shots: list[Shot],
transcript: Transcript | None,
info: MediaFacts,
*,
source: str,
options: ReportOptions,
) -> VideoReport:
"""Assemble a report from exactly the material that was handed in."""
self.calls.append("report")
self.report_calls.append(transcript is not None)
self.report_options.append(options)
return VideoReport(
source=source,
title="Fake video",
duration=info.duration,
summary="fake report",
topics=["fakes"],
people=[],
highlights=[],
shots=[shot.model_copy(deep=True) for shot in shots],
transcript=transcript,
metadata={"has_audio": info.has_audio, "extra": dict(info.extra)},
)
def _stage_messages(messages: list[ProgressEvent]) -> list[str]:
"""Return each stage name once, in the order the run first reported it."""
stages: list[str] = []
for event in messages:
if event.stage not in stages:
stages.append(event.stage)
return stages
def _has(messages: list[ProgressEvent], stage: str, state: str) -> bool:
"""True when ``stage`` produced an event in ``state``."""
return any(event.stage == stage and event.state == state for event in messages)
def _states(messages: list[ProgressEvent], stage: str) -> list[str]:
"""Every state ``stage`` reported, in order."""
return [event.state for event in messages if event.stage == stage]
# --------------------------------------------------------------------------- #
# happy path, ordering, progress
# --------------------------------------------------------------------------- #
async def test_full_run_orders_stages_and_assembles_artifacts(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == list(STAGE_ORDER)
assert _stage_messages(messages) == list(STAGE_ORDER)
assert _has(messages, "probe", "start") and _has(messages, "report", "start")
assert all(event.total == len(STAGE_ORDER) for event in messages)
cache = StageCache(settings.cache_dir)
assert artifacts.source == str(source)
assert artifacts.workdir == cache.source_dir(cache.source_hash(source))
assert artifacts.media is not None
assert artifacts.ref == MediaRef(source=str(source), local_path=source.resolve())
assert artifacts.transcript is not None
assert [segment.speaker for segment in artifacts.transcript.segments] == ["S1", "S2"]
assert len(artifacts.transcript.speaker_turns) == 2
assert len(artifacts.shots) == 2
assert all(shot.description is not None for shot in artifacts.shots)
assert fakes.describe_calls == [2]
assert artifacts.report is not None
assert artifacts.report.source == str(source)
assert artifacts.report.transcript == artifacts.transcript
assert artifacts.report.shots == artifacts.shots
assert fakes.report_calls == [True]
async def test_stage_callables_receive_source_and_workdir(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
artifacts = await pipeline.run(str(source), want={"transcribe", "shots"})
assert fakes.probe_calls == [source.resolve()]
assert fakes.audio_calls == [(source.resolve(), artifacts.workdir)]
assert fakes.transcribe_calls == [artifacts.workdir / "audio.wav"]
assert fakes.shots_calls == [(source.resolve(), artifacts.workdir)]
async def test_stage_seam_receives_only_the_frozen_option_values(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
settings = _settings(
tmp_path,
diarize_cluster_threshold=0.42,
shot_sampling="uniform",
vlm_model="local:fake-vlm",
synthesis_model="local:fake-synthesis",
)
await Pipeline(settings, fakes.mapping()).run(str(source))
(stt,) = fakes.transcribe_options
assert isinstance(stt, SttOptions)
assert stt.backend == "parakeet"
(diarize,) = fakes.diarize_options
assert isinstance(diarize, DiarizeOptions)
assert diarize.cluster_threshold == pytest.approx(0.42)
(shots,) = fakes.shots_options
assert isinstance(shots, ShotOptions)
assert shots.sampling == "uniform"
(describe,) = fakes.describe_options
assert isinstance(describe, DescribeOptions)
assert describe.vlm_model == "local:fake-vlm"
(report,) = fakes.report_options
assert isinstance(report, ReportOptions)
assert report.synthesis_model == "local:fake-synthesis"
# --------------------------------------------------------------------------- #
# caching
# --------------------------------------------------------------------------- #
async def test_second_run_is_fully_cached(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
executed = list(fakes.calls)
messages: list[ProgressEvent] = []
second = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == executed # every stage was a cache hit
assert all(_has(messages, stage, "cached") for stage in STAGE_ORDER)
assert second.report is not None
assert second.report.model_dump(mode="json") == first.report.model_dump(mode="json")
assert second.transcript == first.transcript
async def test_report_only_run_reuses_cached_material(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
executed = list(fakes.calls)
messages: list[ProgressEvent] = []
second = await pipeline.run(str(source), want={"report"}, progress=messages.append)
assert fakes.calls == executed
assert _has(messages, "probe", "cached")
assert _has(messages, "audio", "skipped")
assert _has(messages, "transcribe", "cached")
assert _has(messages, "diarize", "cached")
assert _has(messages, "shots", "cached")
assert _has(messages, "describe", "cached")
assert _has(messages, "report", "cached")
assert second.report is not None
assert second.report.model_dump(mode="json") == first.report.model_dump(mode="json")
async def test_force_reruns_wanted_stage_and_drops_downstream_cache(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
workdir = first.workdir
assert list(workdir.glob("stage-diarize-*.json"))
assert list(workdir.glob("stage-report-*.json"))
fakes.calls.clear()
messages: list[ProgressEvent] = []
second = await pipeline.run(
str(source), want={"transcribe"}, force=True, progress=messages.append
)
assert fakes.calls == ["transcribe"] # probe/audio stayed cached
assert _has(messages, "probe", "cached")
assert _has(messages, "audio", "cached")
assert _states(messages, "transcribe") == ["start", "done"]
assert list(workdir.glob("stage-transcribe-*.json"))
assert not list(workdir.glob("stage-diarize-*.json"))
assert not list(workdir.glob("stage-report-*.json"))
# Descriptions embed the transcript slice, so a forced re-transcription must drop
# them as well (the describe key now includes the transcript/diarize keys).
assert not list(workdir.glob("stage-describe-*.json"))
assert second.transcript is not None
assert second.report is None
async def test_force_shots_drops_descriptions_and_report(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
workdir = first.workdir
fakes.calls.clear()
messages: list[ProgressEvent] = []
second = await pipeline.run(str(source), want={"shots"}, force=True, progress=messages.append)
assert fakes.calls == ["shots"]
assert _states(messages, "shots") == ["start", "done"]
assert not list(workdir.glob("stage-describe-*.json"))
assert not list(workdir.glob("stage-report-*.json"))
assert list(workdir.glob("stage-diarize-*.json"))
assert len(second.shots) == 2
assert all(shot.description is None for shot in second.shots)
async def test_force_report_reruns_only_the_report(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
await pipeline.run(str(source))
fakes.calls.clear()
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(
str(source), want={"report"}, force=True, progress=messages.append
)
assert fakes.calls == ["report"]
assert _states(messages, "report") == ["start", "done"]
assert artifacts.report is not None
async def test_corrupt_cache_artifact_is_treated_as_a_miss(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
first = await pipeline.run(str(source))
(report_file,) = first.workdir.glob("stage-report-*.json")
report_file.write_text("{not json", encoding="utf-8")
fakes.calls.clear()
messages: list[ProgressEvent] = []
second = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["report"]
assert _states(messages, "report") == ["start", "done"]
assert second.report is not None
async def test_transcribe_cache_key_tracks_stt_configuration(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path, whisper_model="tiny"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["probe", "audio", "transcribe"]
fakes.calls.clear()
await Pipeline(_settings(tmp_path, whisper_model="base"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["transcribe"]
fakes.calls.clear()
await Pipeline(_settings(tmp_path, whisper_model="base", language="en"), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["transcribe"]
async def test_transcribe_cache_key_tracks_the_stt_endpoint(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
base = {
"stt_backend": "openai-transcriptions",
"stt_api_base_url": "https://one.example.invalid/v1",
}
await Pipeline(_settings(tmp_path, **base), fakes.mapping()).run(
str(source), want={"transcribe"}
)
assert fakes.calls == ["probe", "audio", "transcribe"]
fakes.calls.clear()
await Pipeline(
_settings(tmp_path, **{**base, "stt_api_base_url": "https://two.example.invalid/v1"}),
fakes.mapping(),
).run(str(source), want={"transcribe"})
assert fakes.calls == ["transcribe"]
async def test_artifacts_json_is_persisted(tmp_path: Path) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
artifacts = await pipeline.run(str(source))
path = artifacts.workdir / "artifacts.json"
assert path.is_file()
loaded = Artifacts.model_validate_json(path.read_text(encoding="utf-8"))
assert loaded.model_dump(mode="json") == artifacts.model_dump(mode="json")
# --------------------------------------------------------------------------- #
# diarization gating
# --------------------------------------------------------------------------- #
async def test_diarize_disabled_in_settings_skips_the_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path, diarize=False), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert "diarize" not in fakes.calls
assert _has(messages, "diarize", "skipped")
assert artifacts.transcript is not None
assert artifacts.transcript.speaker_turns == []
assert all(segment.speaker is None for segment in artifacts.transcript.segments)
async def test_diarize_not_in_want_skips_the_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), want={"transcribe"}, progress=messages.append)
assert fakes.calls == ["probe", "audio", "transcribe"]
assert "diarize" not in _stage_messages(messages)
assert artifacts.transcript is not None
assert artifacts.transcript.speaker_turns == []
async def test_diarize_attributes_speakers_into_the_transcript(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
artifacts = await Pipeline(_settings(tmp_path), fakes.mapping()).run(
str(source), want={"diarize"}
)
assert fakes.calls == ["probe", "audio", "transcribe", "diarize"]
assert artifacts.transcript is not None
assert [segment.speaker for segment in artifacts.transcript.segments] == ["S1", "S2"]
assert [turn.speaker for turn in artifacts.transcript.speaker_turns] == ["S1", "S2"]
assert artifacts.report is None
async def test_sherpa_diarize_cache_tracks_its_clustering_options(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(
_settings(tmp_path, diarize_backend="sherpa", diarize_cluster_threshold=0.7),
fakes.mapping(),
).run(str(source), want={"diarize"})
fakes.calls.clear()
await Pipeline(
_settings(tmp_path, diarize_backend="sherpa", diarize_cluster_threshold=0.2),
fakes.mapping(),
).run(str(source), want={"diarize"})
assert "diarize" in fakes.calls
async def test_pyannote_diarize_cache_ignores_options_it_does_not_apply(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(
_settings(tmp_path, diarize_backend="pyannote", diarize_cluster_threshold=0.7),
fakes.mapping(),
).run(str(source), want={"diarize"})
fakes.calls.clear()
await Pipeline(
_settings(tmp_path, diarize_backend="pyannote", diarize_cluster_threshold=0.2),
fakes.mapping(),
).run(str(source), want={"diarize"})
assert "diarize" not in fakes.calls
# --------------------------------------------------------------------------- #
# graceful degradation
# --------------------------------------------------------------------------- #
async def test_describe_skipped_without_shots(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, shots=[])
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert "describe" not in fakes.calls
assert _has(messages, "describe", "skipped")
assert artifacts.shots == []
assert artifacts.report is not None # the transcript alone is enough material
async def test_report_skipped_without_any_material(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, has_audio=False, shots=[])
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["probe", "shots"]
assert _has(messages, "report", "skipped")
assert artifacts.transcript is None
assert artifacts.report is None
assert artifacts.media is not None
async def test_source_without_audio_skips_speech_stages(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source, has_audio=False)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(str(source), progress=messages.append)
assert fakes.calls == ["probe", "shots", "describe", "report"]
assert _has(messages, "audio", "skipped")
assert _has(messages, "transcribe", "skipped")
assert _has(messages, "diarize", "skipped")
assert artifacts.transcript is None
assert len(artifacts.shots) == 2
assert artifacts.report is not None
assert artifacts.report.transcript is None
async def test_source_without_video_skips_shots(tmp_path: Path) -> None:
source = _make_source(tmp_path, name="audio.mp3")
fakes = FakeStages(source, has_video=False)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(
str(source), want={"shots", "transcribe"}, progress=messages.append
)
assert fakes.calls == ["probe", "audio", "transcribe"]
assert _has(messages, "shots", "skipped")
assert artifacts.shots == []
# --------------------------------------------------------------------------- #
# URL sources and the ingest stage
# --------------------------------------------------------------------------- #
async def test_url_source_runs_the_ingest_stage_first(tmp_path: Path) -> None:
url = "https://example.com/videos/clip.mp4"
local = _make_source(tmp_path)
fakes = FakeStages(local)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping(), ingest_quality=720)
messages: list[ProgressEvent] = []
artifacts = await pipeline.run(url, want={"probe"}, progress=messages.append)
assert fakes.calls == ["ingest", "probe"]
assert fakes.ingest_calls == [(url, settings.cache_dir, 720)]
assert fakes.probe_calls == [local]
assert _states(messages, "ingest") == ["start", "done"]
assert _has(messages, "probe", "done")
assert artifacts.source == url
assert artifacts.media is not None
assert artifacts.ref == MediaRef(source=url, local_path=local)
async def test_local_source_never_calls_the_ingest_stage(tmp_path: Path) -> None:
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path), fakes.mapping()).run(str(source), want={"probe"})
assert "ingest" not in fakes.calls
assert fakes.calls == ["probe"]
# --------------------------------------------------------------------------- #
# validation
# --------------------------------------------------------------------------- #
async def test_unknown_stage_names_are_rejected(tmp_path: Path) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
with pytest.raises(ValueError, match="unknown pipeline stage"):
await pipeline.run(str(source), want={"probe", "nope"})
with pytest.raises(TypeError, match="collection of stage names"):
await pipeline.run(str(source), want="probe") # type: ignore[arg-type]
with pytest.raises(ValueError, match="source must not be empty"):
await pipeline.run(" ")
async def test_missing_and_unsupported_sources_are_rejected(tmp_path: Path) -> None:
pipeline = Pipeline(_settings(tmp_path), FakeStages(_make_source(tmp_path)).mapping())
with pytest.raises(ValueError, match="Local media file not found"):
await pipeline.run(str(tmp_path / "absent.mp4"))
with pytest.raises(ValueError, match="unsupported URL scheme"):
await pipeline.run("ftp://example.com/clip.mp4")
def test_constructor_validates_its_options(tmp_path: Path) -> None:
settings = _settings(tmp_path)
with pytest.raises(ValueError, match="max_shots"):
Pipeline(settings, max_shots=0)
with pytest.raises(ValueError, match="min_scene_len"):
Pipeline(settings, min_scene_len=-0.5)
with pytest.raises(ValueError, match="ingest_quality"):
Pipeline(settings, ingest_quality=0)
with pytest.raises(ValueError, match="unknown stage"):
Pipeline(settings, {"bogus": object()}) # type: ignore[dict-item]
async def test_transcript_slice_is_populated_for_every_shot(tmp_path: Path) -> None:
"""PLAN §4: shots carry the words spoken during them (speaker-prefixed)."""
source = _make_source(tmp_path)
artifacts = await Pipeline(_settings(tmp_path), FakeStages(source).mapping()).run(str(source))
assert [shot.transcript_slice for shot in artifacts.shots] == [
"[00:00] S1: first",
"[00:05] S2: second",
]
assert artifacts.report is not None
assert artifacts.report.shots[1].transcript_slice == "[00:05] S2: second"
async def test_probe_facts_are_shared_by_aliases_and_ref_tracks_the_alias(
tmp_path: Path,
) -> None:
"""Two aliases of identical bytes share one probe artifact; the ref is per run."""
first = _make_source(tmp_path, name="one.mp4")
settings = _settings(tmp_path)
first_artifacts = await Pipeline(settings, FakeStages(first).mapping()).run(
str(first), want={"probe"}
)
first.unlink()
second = _make_source(tmp_path, name="two.mp4")
fakes = FakeStages(second)
messages: list[ProgressEvent] = []
artifacts = await Pipeline(settings, fakes.mapping()).run(
str(second), want={"probe"}, progress=messages.append
)
assert fakes.probe_calls == [] # the probe entry is shared by content, not by name
assert _has(messages, "probe", "cached")
assert artifacts.media == first_artifacts.media
assert artifacts.ref == MediaRef(source=str(second), local_path=second.resolve())
assert len(list(artifacts.workdir.glob("stage-probe-*.json"))) == 1
async def test_url_facts_and_report_carry_no_local_paths(tmp_path: Path) -> None:
"""yt-dlp metadata is kept, but the download path never enters the artifacts."""
url = "https://example.invalid/watch?v=abc"
local = _make_source(tmp_path)
fakes = FakeStages(local)
artifacts = await Pipeline(_settings(tmp_path), fakes.mapping()).run(url)
assert artifacts.media is not None
assert artifacts.media.extra["title"] == "Fake video"
assert artifacts.media.extra["yt_dlp"]["title"] == "Fake video"
assert str(local) not in json.dumps(artifacts.media.extra)
assert artifacts.report is not None
assert artifacts.report.source == url
assert str(local) not in artifacts.report.model_dump_json()
async def test_describe_cache_key_tracks_diarization_context(tmp_path: Path) -> None:
"""Descriptions embed the speaker-labelled transcript, so --no-diarize re-describes."""
source = _make_source(tmp_path)
fakes = FakeStages(source)
await Pipeline(_settings(tmp_path), fakes.mapping()).run(str(source))
assert fakes.describe_calls == [2]
fakes.calls.clear()
fakes.describe_calls.clear()
await Pipeline(_settings(tmp_path, diarize=False), fakes.mapping()).run(str(source))
assert fakes.describe_calls == [2]
# --------------------------------------------------------------------------- #
# the stage descriptor table (issue #8)
# --------------------------------------------------------------------------- #
def test_stage_table_is_the_single_encoding_of_the_dependency_graph() -> None:
assert tuple(STAGES_TABLE) == ("ingest", *STAGE_ORDER)
assert all(isinstance(spec, StageSpec) for spec in STAGES_TABLE.values())
assert all(spec.name == name for name, spec in STAGES_TABLE.items())
assert STAGES_TABLE["ingest"].prereqs == ()
assert STAGES_TABLE["probe"].prereqs == ("ingest",)
assert STAGES_TABLE["report"].prereqs == (
"probe",
"audio",
"transcribe",
"diarize",
"shots",
"describe",
)
def test_downstream_is_derived_from_the_descriptor_prereqs() -> None:
assert _DOWNSTREAM["probe"] == (
"audio",
"transcribe",
"diarize",
"shots",
"describe",
"report",
)
assert _DOWNSTREAM["audio"] == ("transcribe", "diarize", "describe", "report")
assert _DOWNSTREAM["shots"] == ("describe", "report")
assert _DOWNSTREAM["report"] == ()
def test_want_closure_follows_prereqs_and_honours_source_applicability() -> None:
hard, context = _resolve_want({"report"}, "/media/clip.mp4")
assert hard == {"probe", "report"}
assert context == {"audio", "transcribe", "diarize", "shots", "describe"}
hard, context = _resolve_want({"describe"}, "/media/clip.mp4")
assert hard == {"probe", "shots", "describe"}
assert context == {"transcribe", "diarize"}
assert context == {"transcribe", "diarize"}
hard, context = _resolve_want({"probe"}, "https://example.invalid/clip.mp4")
assert hard == {"ingest", "probe"}
assert context == frozenset()
local_ingest, context = _resolve_want({"ingest"}, "/media/clip.mp4")
assert local_ingest == frozenset()
assert context == frozenset()
def _run_context(tmp_path: Path, **overrides: Any) -> RunContext:
"""A RunContext with every value a key-params callable may read."""
settings = _settings(tmp_path)
cache = StageCache(settings.cache_dir)
values: dict[str, Any] = {
"pipeline": Pipeline(settings),
"source": "https://example.invalid/watch?v=abc",
"settings": settings,
"cache": cache,
"wanted": frozenset({"report"}),
"force": False,
"ingest_quality": 720,
"max_shots": 12,
"min_scene_len": 0.25,
"video_sha": "a" * 64,
"audio_sha": "b" * 64,
"turns_applied": True,
"descriptions_applied": True,
"keys": {
"probe": "1" * 64,
"audio": "2" * 64,
"transcribe": "3" * 64,
"diarize": "4" * 64,
"shots": "5" * 64,
"describe": "6" * 64,
},
}
values.update(overrides)
return RunContext(**values)
def test_ingest_key_params_include_url_quality_and_yt_dlp_version(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("video_analyse.ingest.yt_dlp_version", lambda: "2026.01.01")
ctx = _run_context(tmp_path)
params = STAGES_TABLE["ingest"].key_params(ctx)
assert params == ingest_key_params(ctx.source, 720)
assert params["url"] == ctx.source
assert params["quality"] == 720
assert params["yt_dlp"] == "2026.01.01"
def test_probe_and_audio_key_params_use_the_content_hash(tmp_path: Path) -> None:
ctx = _run_context(tmp_path)
assert STAGES_TABLE["probe"].key_params(ctx) == {"video_sha256": "a" * 64}
assert STAGES_TABLE["audio"].key_params(ctx) == {"video_sha256": "a" * 64}
def test_transcribe_key_params_carry_the_adapter_identity_and_language(
tmp_path: Path,
) -> None:
from video_analyse.transcribe import get_transcriber
ctx = _run_context(tmp_path, settings=_settings(tmp_path, language="en"))
options = ctx.settings.options_for("stt")
identity = get_transcriber(options).identity()
params = STAGES_TABLE["transcribe"].key_params(ctx)
assert params == {
"audio_sha256": "b" * 64,
"backend": identity.backend,
"model": identity.model,
"endpoint": identity.endpoint,
"language": "en",
}
def test_diarize_key_params_use_only_the_backends_applicable_options(tmp_path: Path) -> None:
from video_analyse.diarize import get_diarizer
ctx = _run_context(tmp_path, settings=_settings(tmp_path, diarize_backend="pyannote"))
options = ctx.settings.options_for("diarize")
params = STAGES_TABLE["diarize"].key_params(ctx)
assert params == {"audio_sha256": "b" * 64, **get_diarizer(options).cache_params()}
def test_shots_key_params_carry_detector_options_and_pipeline_overrides(tmp_path: Path) -> None:
ctx = _run_context(
tmp_path,
media=MediaFacts(duration=10.0, width=640, height=360, has_audio=True, size_bytes=1),
)
params = STAGES_TABLE["shots"].key_params(ctx)
assert params["video_sha256"] == "a" * 64
assert params["detector"] == "adaptive"
assert params["max_shots"] == 12
assert params["min_scene_len"] == 0.25
assert params["keyframe_width"] == 768
def test_describe_and_report_key_params_are_composed_from_upstream_keys(
tmp_path: Path,
) -> None:
ctx = _run_context(tmp_path)
describe = STAGES_TABLE["describe"].key_params(ctx)
assert describe["shots_key"] == "5" * 64
assert describe["transcript_key"] == "3" * 64
assert describe["diarize"] == {"key": "4" * 64, "applied": True}
report = STAGES_TABLE["report"].key_params(ctx)
assert report["source"] == ctx.source
assert report["probe"] == "1" * 64
assert report["audio"] == "2" * 64
assert report["transcribe"] == "3" * 64
assert report["diarize"] == {"key": "4" * 64, "applied": True}
assert report["shots"] == "5" * 64
assert report["describe"] == {"key": "6" * 64, "applied": True}
async def test_apply_diarize_without_a_transcript_marks_no_attribution(tmp_path: Path) -> None:
"""The cached-turns re-attribution guard (d94188e): no transcript, no attribution.
The stage skip policy normally keeps this state out of the scheduler's way, so the
guard is exercised at the callable the scheduler invokes: loading speaker turns must
leave the run untouched instead of calling ``attribute_speakers(None, turns)``.
"""
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
ctx = RunContext(
pipeline=pipeline,
source=str(source),
settings=pipeline.settings,
cache=StageCache(pipeline.settings.cache_dir),
wanted=frozenset({"diarize"}),
force=False,
ingest_quality=1080,
max_shots=64,
min_scene_len=0.6,
)
turns = _TurnsArtifact(turns=[SpeakerTurn(start=0.0, end=1.0, speaker="S1")])
await _apply_diarize(ctx, turns)
assert ctx.transcript is None
# --------------------------------------------------------------------------- #
# ingest as a real cached stage
# --------------------------------------------------------------------------- #
def test_the_descriptor_table_carries_the_ingest_cache_policy() -> None:
"""The scheduler loop has no ingest branches: its two extra policies live in the table."""
ingest = STAGES_TABLE["ingest"]
assert ingest.namespace == "source" # its artifact precedes the content hash
assert ingest.hit_update == {"downloaded": False} # a cache hit means no download
assert ingest.force_invalidates_content is True # new bytes -> drop content entries
assert {name for name, spec in STAGES_TABLE.items() if spec.namespace == "source"} == {"ingest"}
assert {name for name, spec in STAGES_TABLE.items() if spec.force_invalidates_content} == {
"ingest"
}
async def test_ingest_stage_artifact_is_cached_and_force_redownloads(tmp_path: Path) -> None:
url = "https://example.invalid/watch?v=8"
local = _make_source(tmp_path)
fakes = FakeStages(local)
settings = _settings(tmp_path)
pipeline = Pipeline(settings, fakes.mapping())
await pipeline.run(url, want={"ingest"})
assert fakes.ingest_calls == [(url, settings.cache_dir, 1080)]
ingest_artifacts = list(StageCache(settings.cache_dir).cache_dir.glob("*/stage-ingest-*.json"))
assert len(ingest_artifacts) == 1
fakes.ingest_calls.clear()
messages: list[ProgressEvent] = []
await pipeline.run(url, want={"ingest"}, progress=messages.append)
assert fakes.ingest_calls == []
assert _has(messages, "ingest", "cached")
await pipeline.run(url, want={"ingest"}, force=True)
assert fakes.ingest_calls == [(url, settings.cache_dir, 1080)]
def test_forced_invalidation_drops_the_derived_downstream_stages(tmp_path: Path) -> None:
cache = StageCache(tmp_path / "cache")
digest = "a" * 64
model = MediaFacts(duration=1.0, has_audio=True, size_bytes=1)
for stage in ("transcribe", "diarize", "shots", "describe", "report"):
key = cache.stage_key(stage, {"probe": digest})
cache.save_model(cache.stage_path(digest, stage, key), model)
Pipeline._invalidate_downstream(cache, digest, "transcribe")
remaining = {
path.name.removeprefix("stage-").split("-", 1)[0]
for path in cache.source_dir(digest).glob("stage-*.json")
}
assert remaining == {"transcribe", "shots"}
async def test_force_ingest_drops_every_downstream_artifact(tmp_path: Path) -> None:
url = "https://example.invalid/watch?v=9"
local = _make_source(tmp_path)
fakes = FakeStages(local)
pipeline = Pipeline(_settings(tmp_path), fakes.mapping())
full = await pipeline.run(url)
assert list(full.workdir.glob("stage-probe-*.json"))
assert list(full.workdir.glob("stage-report-*.json"))
forced = await pipeline.run(url, want={"ingest"}, force=True)
assert not list(forced.workdir.glob("stage-probe-*.json"))
assert not list(forced.workdir.glob("stage-report-*.json"))
async def test_want_ingest_on_a_local_path_is_an_explicit_validation_error(
tmp_path: Path,
) -> None:
source = _make_source(tmp_path)
pipeline = Pipeline(_settings(tmp_path), FakeStages(source).mapping())
with pytest.raises(ValueError, match=r"ingest.*http"):
await pipeline.run(str(source), want={"ingest"})
async def test_empty_local_source_fails_once_with_the_shared_message(tmp_path: Path) -> None:
empty = _make_source(tmp_path, name="empty.mp4", payload=b"")
pipeline = Pipeline(_settings(tmp_path), FakeStages(_make_source(tmp_path)).mapping())
with pytest.raises(ValueError) as via_pipeline:
await pipeline.run(str(empty), want={"probe"})
with pytest.raises(ValueError) as via_ingest:
await fetch(str(empty), cache_dir=tmp_path / "cache")
assert "empty" in str(via_pipeline.value)
assert str(via_pipeline.value) == str(via_ingest.value)