cmvr-visual/backend/tests/test_normalized_cache.py

190 lines
6.8 KiB
Python

from app.services.normalized_cache import clip_key
def test_recipe_includes_trim_and_owner():
base = ("alice", "a" * 64, 3, 12, 2, (320, 180), "contain", 24)
for i, value in enumerate(("bob", "b" * 64, 4, 13, 1, (180, 320), "cover", 30)):
args = list(base)
args[i] = value
assert clip_key(*args) != clip_key(*base)
import asyncio
import subprocess
from datetime import timedelta
from unittest.mock import patch
import pytest
from sqlalchemy import delete, select
from app.adapters import media
from app.domain.stories import StoryRenderPlan
from app.models import Asset, AssetReference, Job, User, utcnow
from app.services.normalized_cache import ClipCache, active_cache, digest
from app.services.retention import collect_garbage
@pytest.mark.asyncio
async def test_real_clip_reuse_repair_retention(system, other_client):
settings, db = system.settings, system.app.state.db
source = settings.workspace_root / "source.mp4"
subprocess.run(
[
settings.ffmpeg_bin,
"-loglevel",
"error",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x64:rate=24",
"-frames:v",
"24",
str(source),
],
check=True,
)
async with db.session() as session:
owner = await session.scalar(select(User.id).where(User.username == "admin"))
other = await session.scalar(select(User.id).where(User.username == "alice"))
asset = Asset(
owner_id=owner,
name="source",
storage_key="test/source.mp4",
kind="video",
mime_type="video/mp4",
size_bytes=source.stat().st_size,
sha256=digest(source),
)
job = Job(
owner_id=owner,
task_type="video.compose",
state="running",
phase="cpu_running",
input_json={},
parameters={},
request_hash="r",
upstream_key="k",
)
session.add_all([asset, job])
await session.commit()
clip = dict(
asset_id=asset.id,
sha256=asset.sha256,
width=64,
height=64,
start_frame=3,
duration_frames=8,
)
plan = StoryRenderPlan(
dict(
schema_version=4,
profile="test",
shots=[{"edit": {"dedup_frames": 2}}],
render=dict(audio=None, subtitles=[], fit="contain"),
),
(64, 64),
8,
(clip,),
)
token = active_cache.set(ClipCache(db, settings, owner, job.id))
try:
async def render(index):
work = settings.workspace_root / str(index)
with patch.object(media, "run_process", wraps=media.run_process) as run:
await media.compose_story(plan, work, settings=settings, sources=[source])
return sum(
"shot-0.mp4" in str(call.args[0][-1]) and "-vf" in call.args[0]
for call in run.await_args_list
)
import errno
from app.domain.errors import MediaError
with patch(
"app.services.normalized_cache.os.link",
side_effect=OSError(errno.EXDEV, "cross-device"),
):
assert await render("cross-device") == 1
async with db.session() as session:
assert await session.scalar(select(Asset).where(Asset.origin == "normalized")) is None
with patch.object(
media, "cacheable_segment", side_effect=MediaError("timeout", "probe timed out")
):
assert await render("probe-timeout") == 1
with patch.object(media, "cacheable_segment", side_effect=asyncio.CancelledError):
with pytest.raises(asyncio.CancelledError):
await render("probe-cancel")
assert await render(1) == 1
assert await render(2) == 0
def unreadable_cache_link(path):
if path.parent.name == "restore-permission":
raise PermissionError("cache read denied")
return digest(path)
with patch("app.services.normalized_cache.digest", side_effect=unreadable_cache_link):
assert await render("restore-permission") == 1
def unreadable_existing(path):
if path.is_relative_to(settings.asset_root):
raise PermissionError("cache winner unreadable")
return digest(path)
with (
patch.object(ClipCache, "restore", return_value=False),
patch("app.services.normalized_cache.digest", side_effect=unreadable_existing),
):
assert await render("publish-permission") == 1
assert await render("permissions-restored") == 0
async with db.session() as session:
row = await session.scalar(select(Asset).where(Asset.origin == "normalized"))
(settings.asset_root / row.storage_key).write_bytes(b"broken")
row.created_at = utcnow() - timedelta(days=30)
session.add(
AssetReference(owner_id=owner, asset_id=asset.id, ref_kind="draft", ref_id="d")
)
await session.commit()
assert await render(3) == 1
assert await render(4) == 0
assert row.id in (await collect_garbage(db, settings))["protected"]
clip["start_frame"] += 1
assert await render(5) == 1
assert await render(6) == 0
clip["start_frame"] += 1
with patch.object(settings, "max_owner_asset_bytes", 1):
assert await render(7) == 1
assert await render(8) == 1
await asyncio.gather(
*(
media.compose_story(
plan,
settings.workspace_root / f"parallel-{i}",
settings=settings,
sources=[source],
)
for i in range(2)
)
)
assert await render(10) == 0
async with db.session() as session:
await session.execute(delete(AssetReference).where(AssetReference.asset_id == asset.id))
await session.commit()
(settings.state_root / "maintenance").touch()
assert row.id in (await collect_garbage(db, settings, dry_run=False))["deleted"]
assert not (settings.asset_root / row.storage_key).parent.exists()
async with db.session() as session:
current = await session.get(Job, job.id)
current.cancel_requested = True
await session.commit()
with pytest.raises(asyncio.CancelledError):
await render(9)
from app.domain.errors import MediaError
with pytest.raises(MediaError):
await ClipCache(db, settings, other, job.id).restore(
clip, "bad", source.parent / "other"
)
finally:
active_cache.reset(token)