cmvr-visual/backend/tests/test_h3_tp2_review_fixes.py

202 lines
8.1 KiB
Python
Raw Permalink Normal View History

"""TP2 admission follows the current target closure and independent six-second certificate."""
from unittest.mock import AsyncMock
import pytest
from sqlalchemy import func, select
from app.models import Asset, Job, WorkflowRun
from app.domain.video_generation import recipe_parameters
from app.adapters.provider.contracts import h3_tp2_certified
from app.adapters.provider.video_generation import normalize
from app.domain.errors import MediaError
from test_editor_engine import editor
from test_h3_tp2_product import TP2, H3, certificate
@pytest.mark.parametrize(
"key,value",
[
("max_requested_frames", None),
("max_requested_frames", 145.0),
("max_requested_frames", 337),
("max_source_seconds", None),
("max_source_seconds", 6.0),
("max_source_seconds", 14),
],
)
def test_tp2_six_second_certificate_fields_are_exact_integers(key, value):
cert = certificate()
if value is None:
cert.pop(key)
else:
cert[key] = value
assert not h3_tp2_certified(cert)
def test_tp2_generation_limit_preserves_old_duration_and_v1_capacity():
original = {"num_frames": 337, "upscale": False}
with pytest.raises(ValueError, match="6"):
recipe_parameters(original, TP2)
assert original["num_frames"] == 337
assert recipe_parameters(original, H3)["num_frames"] == 337
@pytest.mark.parametrize("frames", [149, 337, 145.0])
def test_tp2_normalizer_explains_the_six_second_request_limit(frames):
with pytest.raises(MediaError, match="1–6秒"):
normalize(
{"profile": TP2, "num_frames": frames}, {"prompt": "x", "image_asset_id": "first"}
)
async def tp2_editor(system, n=2, source_kind="workflow"):
if source_kind == "story":
created = await system.client.post(
"/api/stories",
json={
"name": "TP2 auto story",
"spec": {
"schema_version": 3,
"shots": [
{"id": f"{i + 1:032x}", "visual_prompt": "mountain"} for i in range(n)
],
},
},
)
assert created.status_code == 201, created.text
id = created.json()["id"]
m = (await system.client.get(f"/api/editors/{id}")).json()["manifest"]
m["spec"]["shots"][0]["video_parameters"].update(profile=TP2, upscale=False)
else:
id, m = await editor(system, n)
m["spec"]["shots"][0]["parameters"]["profile"] = TP2
saved = await system.client.post(
f"/api/editors/{id}/save",
json={"expected_version": 1, "manifest": m},
headers={"Idempotency-Key": "tp2-review-save"},
)
assert saved.status_code == 200, saved.text
return id, saved.json()["manifest"]
@pytest.mark.parametrize("source_kind", ["workflow", "story"])
async def test_tp2_editor_plan_blocks_before_any_frame_or_audio_is_accepted_and_rechecks_run(
system, source_kind
):
id, m = await tp2_editor(system, source_kind=source_kind)
path = f"/api/editors/{id}"
body = {"expected_version": 2, "output_goal": "media", "targets": ["video:" + m["shot_ids"][0]]}
system.provider.upstream_capabilities = AsyncMock(return_value={})
blocked = await system.client.post(path + "/plan", json=body)
assert blocked.status_code == 200, blocked.text
assert any(
i["code"] == "capability_unavailable" and "双卡" in i["message"]
for i in blocked.json()["issues"]
)
reject = await system.client.post(
path + "/runs",
json={**body, "expected_plan_hash": blocked.json()["plan_hash"]},
headers={"Idempotency-Key": "tp2-review-blocked"},
)
assert reject.status_code == 422, reject.text
system.provider.upstream_capabilities.return_value = {
"video_generation": {"tp2": certificate()}
}
allowed = await system.client.post(path + "/plan", json=body)
assert allowed.status_code == 200 and not allowed.json()["issues"], allowed.text
run_body = {**body, "expected_plan_hash": allowed.json()["plan_hash"]}
system.provider.upstream_capabilities.return_value = {}
revoked = await system.client.post(
path + "/runs", json=run_body, headers={"Idempotency-Key": "tp2-review-run"}
)
assert revoked.status_code in {409, 422}, revoked.text
async with system.app.state.db.session() as s:
assert await s.scalar(select(func.count()).select_from(WorkflowRun)) == 0
assert await s.scalar(select(func.count()).select_from(Job)) == 0
system.provider.upstream_capabilities.return_value = {
"video_generation": {"tp2": certificate()}
}
run = await system.client.post(
path + "/runs", json=run_body, headers={"Idempotency-Key": "tp2-review-run"}
)
assert run.status_code == 202, run.text
system.provider.upstream_capabilities = AsyncMock(
side_effect=AssertionError("historical replay must not probe TP2")
)
replay = await system.client.post(
path + "/runs", json=run_body, headers={"Idempotency-Key": "tp2-review-run"}
)
assert replay.status_code == 202 and replay.json()["run"]["id"] == run.json()["run"]["id"]
async def test_tp2_editor_gate_ignores_unrelated_targets_reuse_and_compose_but_catches_force(
system, monkeypatch, png_bytes
):
id, m = await tp2_editor(system)
path = f"/api/editors/{id}"
system.provider.upstream_capabilities = AsyncMock(
side_effect=AssertionError("unrelated and reused targets must not probe TP2")
)
unrelated = await system.client.post(
path + "/plan",
json={
"expected_version": 2,
"output_goal": "media",
"targets": ["frame:" + m["shot_ids"][1]],
},
)
assert unrelated.status_code == 200 and not unrelated.json()["issues"], unrelated.text
uploaded = await system.client.post(
"/api/assets", files={"file": ("reused.png", png_bytes, "image/png")}
)
assert uploaded.status_code == 201
aid = uploaded.json()["id"]
async with system.app.state.db.session() as s:
a = await s.get(Asset, aid)
a.kind, a.width, a.height, a.duration_seconds = "video", 1344, 768, 10
sha = a.sha256
await s.commit()
monkeypatch.setattr("app.services.stories.candidates.validate_video", AsyncMock())
for sid in m["shot_ids"]:
m["bindings"]["video:" + sid] = {
"asset_id": aid,
"sha256": sha,
"kind": "video",
"source": "manual",
}
saved = await system.client.post(
path + "/save",
json={"expected_version": 2, "manifest": m},
headers={"Idempotency-Key": "tp2-review-reuse"},
)
assert saved.status_code == 200, saved.text
body = {"expected_version": 3, "output_goal": "film"}
plan = await system.client.post(path + "/plan", json=body)
assert plan.status_code == 200 and not plan.json()["issues"], plan.text
assert all(x["reuse"] for x in plan.json()["steps"] if x["kind"] == "video.generate")
accepted = await system.client.post(
path + "/runs",
json={**body, "expected_plan_hash": plan.json()["plan_hash"]},
headers={"Idempotency-Key": "tp2-review-compose"},
)
assert accepted.status_code == 202, accepted.text
system.provider.upstream_capabilities.assert_not_awaited()
system.provider.upstream_capabilities = AsyncMock(return_value={})
forced = await system.client.post(
path + "/plan", json={**body, "force": ["video:" + m["shot_ids"][0]]}
)
assert forced.status_code == 200
assert any(i["code"] == "capability_unavailable" for i in forced.json()["issues"])
# 上一次预览可复用不构成这次接纳的事实;当前绑定失效后要重新检查真实生成闭包。
monkeypatch.setattr(
"app.services.stories.candidates.validate_video",
AsyncMock(side_effect=ValueError("media changed")),
)
changed = await system.client.post(
path + "/runs",
json={**body, "expected_plan_hash": plan.json()["plan_hash"]},
headers={"Idempotency-Key": "tp2-review-stale-binding"},
)
assert changed.status_code in {409, 422}, changed.text