Files
video-analyse/tests/test_cache.py
T

473 lines
18 KiB
Python

"""Tests for the content-addressed stage cache (``video_analyse.cache``).
Everything here is local: file hashing uses the synthetic ``sample_video`` fixture or
small temporary files, and the model round-trips use the pydantic models from
``video_analyse.models``. No network access, no model downloads.
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import pytest
from video_analyse import cache as cache_module
from video_analyse.cache import StageCache
from video_analyse.ingest import IngestResult
from video_analyse.models import MediaFacts, Segment, Transcript, Word
@pytest.fixture
def cache(tmp_path: Path) -> StageCache:
"""Cache rooted at a temporary directory (nothing is created eagerly)."""
return StageCache(tmp_path / "cache")
@pytest.fixture
def sample_media(sample_video: Path) -> MediaFacts:
"""Content facts for the conftest sample video (the fixture skips without ffmpeg)."""
return MediaFacts(
duration=10.0,
width=640,
height=360,
fps=12.0,
has_audio=True,
size_bytes=sample_video.stat().st_size,
format="mov,mp4,m4a,3gp,3g2,mj2",
video_codec="h264",
audio_codec="aac",
extra={"fixture": True},
)
# --------------------------------------------------------------------------- #
# hashing
# --------------------------------------------------------------------------- #
def test_source_hash_matches_hashlib_for_a_real_file(cache: StageCache, sample_video: Path) -> None:
expected = hashlib.sha256(sample_video.read_bytes()).hexdigest()
assert cache.source_hash(sample_video) == expected
assert cache.source_hash(sample_video) == cache.source_hash(sample_video)
assert len(expected) == 64
def test_source_hash_streams_regardless_of_chunk_size(
cache: StageCache, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = bytes(range(256)) * 8193 # 2 MiB + 256 bytes: several chunks, odd tail
path = tmp_path / "blob.mp4"
path.write_bytes(payload)
expected = hashlib.sha256(payload).hexdigest()
assert cache.source_hash(path) == expected
monkeypatch.setattr(cache_module, "HASH_CHUNK_SIZE", 7)
assert cache.source_hash(path) == expected
monkeypatch.setattr(cache_module, "HASH_CHUNK_SIZE", 2**20)
assert cache.source_hash(path) == expected
def test_source_hash_changes_with_content(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "clip.mp4"
path.write_bytes(b"first version")
first = cache.source_hash(path)
path.write_bytes(b"second version")
assert cache.source_hash(path) != first
def test_source_hash_rejects_missing_files_and_directories(
cache: StageCache, tmp_path: Path
) -> None:
with pytest.raises(ValueError, match="missing file"):
cache.source_hash(tmp_path / "nope.mp4")
with pytest.raises(ValueError, match="non-file path"):
cache.source_hash(tmp_path)
# --------------------------------------------------------------------------- #
# stage keys
# --------------------------------------------------------------------------- #
def test_stage_key_is_stable_and_param_order_insensitive(cache: StageCache) -> None:
first = cache.stage_key("transcribe", {"backend": "whisper", "model": "tiny"})
second = cache.stage_key("transcribe", {"model": "tiny", "backend": "whisper"})
assert first == second
assert first == cache.stage_key("transcribe", {"backend": "whisper", "model": "tiny"})
assert len(first) == 64
int(first, 16) # lowercase hex, parseable
def test_stage_key_is_sensitive_to_every_parameter(cache: StageCache) -> None:
base = cache.stage_key("shots", {"max_shots": 64, "detector": "adaptive"})
assert cache.stage_key("shots", {"max_shots": 65, "detector": "adaptive"}) != base
assert cache.stage_key("shots", {"max_shots": 64, "detector": "content"}) != base
assert cache.stage_key("report", {"max_shots": 64, "detector": "adaptive"}) != base
assert cache.stage_key("shots", {"max_shots": 64}) != base
assert cache.stage_key("shots", {"max_shots": 64, "detector": "adaptive", "x": None}) != base
assert cache.stage_key("shots") == cache.stage_key("shots", {})
def test_stage_key_stringifies_non_json_values(cache: StageCache, tmp_path: Path) -> None:
media = tmp_path / "a.mp4"
key = cache.stage_key("probe", {"path": media, "opts": (1, 2)})
# Paths render through str(); tuples become JSON arrays like lists do.
assert key == cache.stage_key("probe", {"path": str(media), "opts": [1, 2]})
assert key != cache.stage_key("probe", {"path": str(media), "opts": "(1, 2)"})
assert key != cache.stage_key("probe", {"path": str(media)})
def test_stage_key_rejects_bad_input(cache: StageCache) -> None:
for bad_name in ("", "bad name", "../escape", "stage:1", "-leading"):
with pytest.raises(ValueError, match="invalid stage name"):
cache.stage_key(bad_name, {"a": 1})
with pytest.raises(TypeError, match="params must be a mapping"):
cache.stage_key("probe", ["not", "a", "mapping"]) # type: ignore[arg-type]
# --------------------------------------------------------------------------- #
# path layout
# --------------------------------------------------------------------------- #
def test_stage_path_layout(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
key = cache.stage_key("transcribe", {"audio_sha256": digest})
path = cache.stage_path(digest, "transcribe", key)
assert path == cache.cache_dir / digest[:16] / f"stage-transcribe-{key}.json"
assert path.parent == cache.source_dir(digest)
assert path.parent.name == digest[:16]
assert len(digest[:16]) == cache_module.SOURCE_HASH_PREFIX_LENGTH
def test_asset_paths_share_the_source_dir(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
root = cache.cache_dir / digest[:16]
assert cache.source_dir(digest) == root
assert cache.asset_dir(digest) == root
assert cache.audio_path(digest) == root / "audio.wav"
assert cache.keyframes_dir(digest) == root / "keyframes"
assert cache.keyframe_path(digest, 3) == root / "keyframes" / "shot-3.jpg"
assert cache.artifacts_path(digest) == root / "artifacts.json"
def test_paths_accept_short_prefixes_and_uppercase_digests(
cache: StageCache, sample_video: Path
) -> None:
digest = cache.source_hash(sample_video)
assert cache.source_dir(digest[:16]) == cache.source_dir(digest)
assert cache.source_dir(digest.upper()) == cache.source_dir(digest)
with pytest.raises(ValueError, match="invalid source sha256"):
cache.source_dir(digest[:15])
with pytest.raises(ValueError, match="invalid source sha256"):
cache.source_dir("z" * 16)
with pytest.raises(TypeError, match="source_sha must be a string"):
cache.source_dir(42) # type: ignore[arg-type]
def test_paths_reject_unsafe_stage_keys_and_indices(cache: StageCache, sample_video: Path) -> None:
digest = cache.source_hash(sample_video)
assert (
cache.stage_path(digest, "probe", "0123456789abcdef").name
== "stage-probe-0123456789abcdef.json"
)
for bad_key in ("", "../escape", "0123456789ABCDEF", "zz", "0" * 65):
with pytest.raises(ValueError, match="invalid stage key"):
cache.stage_path(digest, "probe", bad_key)
for bad_index in (-1, 1.5, True):
with pytest.raises(ValueError, match="shot_index"):
cache.keyframe_path(digest, bad_index) # type: ignore[arg-type]
def test_cache_dir_expands_the_home_directory(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
cache = StageCache("~/video-cache")
assert cache.cache_dir == tmp_path / "video-cache"
assert not cache.cache_dir.exists() # constructing a cache creates nothing
# --------------------------------------------------------------------------- #
# model / JSON round-trips
# --------------------------------------------------------------------------- #
def test_save_and_load_model_round_trip(
cache: StageCache, sample_video: Path, sample_media: MediaFacts
) -> None:
digest = cache.source_hash(sample_video)
key = cache.stage_key("probe", {"video_sha256": digest})
path = cache.stage_path(digest, "probe", key)
cache.save_model(path, sample_media)
assert path.is_file()
assert path.read_text(encoding="utf-8").endswith("\n")
assert json.loads(path.read_text(encoding="utf-8"))["duration"] == 10.0
loaded = cache.load_model(path, MediaFacts)
assert loaded == sample_media
def test_save_and_load_nested_models(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "nested" / "artifact.json"
transcript = Transcript(
language="en",
duration=2.0,
segments=[
Segment(
start=0.0,
end=1.0,
text="hello world",
words=[Word(text="hello", start=0.0, end=0.5, probability=0.9)],
speaker="S1",
)
],
)
cache.save_model(path, transcript)
assert path.parent.is_dir()
assert cache.load_model(path, Transcript) == transcript
def test_save_model_rejects_plain_values(cache: StageCache, tmp_path: Path) -> None:
with pytest.raises(TypeError, match="pydantic BaseModel"):
cache.save_model(tmp_path / "x.json", {"not": "a model"}) # type: ignore[arg-type]
def test_load_model_handles_missing_and_corrupt_artifacts(
cache: StageCache, tmp_path: Path
) -> None:
missing = tmp_path / "missing.json"
assert cache.load_model(missing, MediaFacts) is None
corrupt = tmp_path / "corrupt.json"
corrupt.write_text("{not json", encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaFacts"):
cache.load_model(corrupt, MediaFacts)
wrong_shape = tmp_path / "wrong.json"
wrong_shape.write_text('{"duration": 1.0}', encoding="utf-8")
with pytest.raises(ValueError, match="does not match MediaFacts"):
cache.load_model(wrong_shape, MediaFacts)
with pytest.raises(TypeError, match="model_type must be a pydantic BaseModel"):
cache.load_model(missing, dict) # type: ignore[arg-type]
def test_save_and_load_json_payloads(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "raw" / "payload.json"
payload = {"turns": [{"start": 0.0, "end": 1.5, "speaker": "S1"}], "path": tmp_path}
cache.save_json(path, payload)
assert json.loads(path.read_text(encoding="utf-8"))["path"] == str(tmp_path)
assert cache.load_json(path) == {
"turns": [{"start": 0.0, "end": 1.5, "speaker": "S1"}],
"path": str(tmp_path),
}
assert cache.load_json(tmp_path / "absent.json") is None
path.write_text("[", encoding="utf-8")
with pytest.raises(ValueError, match="not valid JSON"):
cache.load_json(path)
# --------------------------------------------------------------------------- #
# existence / invalidation
# --------------------------------------------------------------------------- #
def test_exists_only_true_for_regular_files(cache: StageCache, tmp_path: Path) -> None:
path = tmp_path / "artifact.json"
assert cache.exists(path) is False
path.write_text("{}", encoding="utf-8")
assert cache.exists(path) is True
assert cache.exists(tmp_path) is False
def test_clear_stage_removes_only_that_stage(
cache: StageCache, sample_video: Path, sample_media: MediaFacts
) -> None:
digest = cache.source_hash(sample_video)
keep = cache.stage_path(digest, "probe", cache.stage_key("probe", {"video_sha256": digest}))
for key in ("a" * 64, "b" * 64):
cache.save_model(cache.stage_path(digest, "report", key), sample_media)
cache.save_model(keep, sample_media)
assert cache.clear_stage(digest, "report") == 2
assert cache.clear_stage(digest, "report") == 0
assert keep.is_file()
assert list(cache.source_dir(digest).glob("stage-report-*.json")) == []
assert list(cache.source_dir(digest).glob("stage-probe-*.json")) == [keep]
def test_writes_are_atomic_and_leave_no_temporary_files(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
assert [entry.name for entry in tmp_path.iterdir()] == ["artifact.json"]
# --------------------------------------------------------------------------- #
# cached_run: the single load -> miss -> run -> save policy
# --------------------------------------------------------------------------- #
async def test_cached_run_returns_a_hit_without_running(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
hits: list[str] = []
async def runner() -> MediaFacts: # pragma: no cover - must not run
raise AssertionError("runner must not run on a cache hit")
loaded = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert loaded == sample_media
assert hits == ["hit"]
async def test_cached_run_runs_saves_and_then_hits(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "nested" / "artifact.json"
calls: list[str] = []
hits: list[str] = []
async def runner() -> MediaFacts:
calls.append("run")
return sample_media
first = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert first == sample_media
assert calls == ["run"]
assert hits == []
assert path.is_file()
assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"]
second = await cache.cached_run(path, MediaFacts, runner, on_hit=lambda: hits.append("hit"))
assert second == sample_media
assert calls == ["run"] # the second call was a hit
assert hits == ["hit"]
@pytest.mark.parametrize(
"payload",
["{not json", '{"duration": 1.0}', '{"duration": "ten"}'],
ids=["not-json", "missing-fields", "wrong-types"],
)
async def test_cached_run_treats_a_corrupt_artifact_as_a_miss(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts, payload: str
) -> None:
path = tmp_path / "artifact.json"
path.write_text(payload, encoding="utf-8")
calls: list[str] = []
async def runner() -> MediaFacts:
calls.append("run")
return sample_media
loaded = await cache.cached_run(path, MediaFacts, runner)
assert loaded == sample_media
assert calls == ["run"]
assert cache.load_model(path, MediaFacts) == sample_media # corrupt file rewritten
assert [entry.name for entry in path.parent.iterdir()] == ["artifact.json"]
async def test_ingest_artifacts_share_the_atomic_corruption_safe_cache(
cache: StageCache, tmp_path: Path
) -> None:
"""The ingest artifact is a normal StageCache model: atomic writes, miss on corrupt."""
media = tmp_path / "clip.mp4"
media.write_bytes(b"video bytes")
artifact = IngestResult(path=media, info={"id": "abc"}, downloaded=True, title="Clip")
digest = "a" * 64
key = cache.stage_key("ingest", {"url": "https://example.invalid/v", "quality": 720})
path = cache.stage_path(digest, "ingest", key)
cache.save_model(path, artifact)
assert [entry.name for entry in path.parent.iterdir()] == [path.name]
assert cache.load_model(path, IngestResult) == artifact
calls: list[str] = []
async def runner() -> IngestResult:
calls.append("run")
return artifact
for payload in ("{not json", '{"path": "x.mp4"}', '{"path": 1, "downloaded": true}'):
path.write_text(payload, encoding="utf-8")
calls.clear()
assert await cache.cached_run(path, IngestResult, runner) == artifact
assert calls == ["run"]
assert cache.load_model(path, IngestResult) == artifact
async def test_cached_run_reruns_when_validation_rejects_the_cached_model(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
calls: list[str] = []
replacement = sample_media.model_copy(update={"duration": 12.0})
async def runner() -> MediaFacts:
calls.append("run")
return replacement
loaded = await cache.cached_run(
path, MediaFacts, runner, validate=lambda item: item.duration != 10.0
)
assert loaded == replacement
assert calls == ["run"]
assert cache.load_model(path, MediaFacts) == replacement
async def test_cached_run_force_bypasses_an_existing_artifact(
cache: StageCache, tmp_path: Path, sample_media: MediaFacts
) -> None:
path = tmp_path / "artifact.json"
cache.save_model(path, sample_media)
replacement = sample_media.model_copy(update={"duration": 12.0})
calls: list[str] = []
async def runner() -> MediaFacts:
calls.append("run")
return replacement
loaded = await cache.cached_run(path, MediaFacts, runner, force=True)
assert loaded == replacement
assert calls == ["run"]
assert cache.load_model(path, MediaFacts) == replacement
async def test_cached_run_keeps_the_value_when_saving_fails(
cache: StageCache,
tmp_path: Path,
sample_media: MediaFacts,
monkeypatch: pytest.MonkeyPatch,
) -> None:
path = tmp_path / "artifact.json"
def explode(*args: object, **kwargs: object) -> Path: # pragma: no cover - must not return
raise OSError("cache is read-only")
monkeypatch.setattr(cache, "save_model", explode)
async def runner() -> MediaFacts:
return sample_media
assert await cache.cached_run(path, MediaFacts, runner) == sample_media