329 lines
13 KiB
Python
329 lines
13 KiB
Python
"""TP2 is explicit, independently certified, and preserves the v1 crop contract."""
|
|
|
|
from copy import deepcopy
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
import pytest
|
|
|
|
from app.adapters.provider.client import Provider, ProviderError, capabilities, validate_arguments
|
|
from app.adapters.provider.video_generation import normalize
|
|
from app.domain.stories import StorySpecV3
|
|
from app.domain.timeline import WorkflowSpec, compile_timeline
|
|
from app.domain.video_generation import required_output_frames
|
|
from app.services.orchestration.editor_engine import build_recipes
|
|
from app.services.stories.common import current_hash
|
|
from test_editor_engine import manifest
|
|
from test_multishot_v3 import story
|
|
from test_story_studio import story_spec
|
|
|
|
|
|
TP2 = "minimax-h3-fl2va-bf16-tp2-v1"
|
|
H3 = "minimax-h3-fl2va-bf16-v1"
|
|
V2 = "minimax-h3-fl2va-bf16-v2"
|
|
|
|
|
|
def certificate():
|
|
return dict(
|
|
available=True,
|
|
profile=TP2,
|
|
revision="12253298adb81e36757eabebb81d2ba1c0cc70cc",
|
|
adapter_contract_version="h3-fl2va-tp2-v1",
|
|
gpu_count=2,
|
|
runtime_revision="423ab90580b2847998591669b8326f47b6d14d8b",
|
|
input_modes=["first_frame"],
|
|
output_policy="crop_requested",
|
|
fps=24,
|
|
canvases=[[1344, 768], [768, 1344]],
|
|
upscale=False,
|
|
max_requested_frames=145,
|
|
max_source_seconds=6,
|
|
)
|
|
|
|
|
|
def generation(items):
|
|
return next(x for x in items if x["task_type"] == "video.generate")
|
|
|
|
|
|
def test_tp2_static_contract_is_closed_even_when_selected_as_settings_default(system):
|
|
from app.core.config import Settings
|
|
|
|
Settings(mode="test", database_url="sqlite+aiosqlite:///:memory:", video_generation_profile=TP2)
|
|
system.settings.video_generation_profile = TP2
|
|
row = generation(capabilities(system.settings))
|
|
assert row["available"] is False
|
|
option = next(p for p in row["video_profiles"] if p["profile"] == TP2)
|
|
assert option["available"] is False
|
|
assert option["defaults"]["upscale"] is False
|
|
assert option["constraints"]["upscale"] == {"values": [False]}
|
|
assert option["constraints"]["num_frames"] == {"min": 25, "max": 145, "step": 4}
|
|
assert option["constraints"]["source_seconds"] == {"min": 1, "max": 6}
|
|
assert "两张" in option["description"]
|
|
|
|
|
|
@pytest.mark.parametrize("field", [None, *certificate()])
|
|
async def test_tp2_certificate_requires_every_exact_field_independent_of_v1_v2(system, field):
|
|
cert = certificate()
|
|
if field is not None:
|
|
cert.pop(field)
|
|
system.settings.video_generation_profile = TP2
|
|
system.provider.upstream_capabilities = AsyncMock(
|
|
return_value={"video_generation": {"tp2": cert}}
|
|
)
|
|
response = await system.client.get("/api/capabilities")
|
|
assert response.status_code == 200
|
|
row = generation(response.json()["items"])
|
|
options = {p["profile"]: p for p in row["video_profiles"]}
|
|
assert row["available"] is (field is None)
|
|
assert options[TP2]["available"] is (field is None)
|
|
assert options[H3]["available"] is False
|
|
assert options[V2]["available"] is False
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"field,value",
|
|
[
|
|
("available", "true"),
|
|
("available", 1),
|
|
("profile", H3),
|
|
("revision", "other"),
|
|
("runtime_revision", "other"),
|
|
("adapter_contract_version", "h3-fl2va-v2"),
|
|
("gpu_count", 1),
|
|
("gpu_count", 2.0),
|
|
("input_modes", ["first_frame", "first_last_frame"]),
|
|
("output_policy", "full_native"),
|
|
("fps", 24.0),
|
|
("fps", 25),
|
|
("canvases", [[1344, 768]]),
|
|
("upscale", 0),
|
|
("upscale", True),
|
|
],
|
|
)
|
|
async def test_tp2_mismatched_certificate_cannot_enable_or_accept_new_job(system, field, value):
|
|
cert = certificate()
|
|
cert[field] = value
|
|
system.provider.upstream_capabilities = AsyncMock(
|
|
return_value={"video_generation": {"tp2": cert}}
|
|
)
|
|
row = generation((await system.client.get("/api/capabilities")).json()["items"])
|
|
assert next(p for p in row["video_profiles"] if p["profile"] == TP2)["available"] is False
|
|
response = await system.client.post(
|
|
"/api/jobs",
|
|
json={
|
|
"task_type": "video.generate",
|
|
"input": {"prompt": "first frame", "image_asset_id": "image"},
|
|
"parameters": {"profile": TP2},
|
|
},
|
|
)
|
|
assert response.status_code == 503, response.text
|
|
assert response.json()["detail"]["code"] == "capability_unavailable"
|
|
|
|
|
|
@pytest.mark.parametrize("frames", [25, 121, 145])
|
|
def test_tp2_uses_v1_requested_frames_and_first_frame_only(system, frames):
|
|
p = normalize(
|
|
{"profile": TP2, "num_frames": frames}, {"prompt": "x", "image_asset_id": "first"}
|
|
)
|
|
assert p["num_frames"] == required_output_frames(p) == frames
|
|
assert p["upscale"] is False
|
|
assert "guidance_scale" not in p and "conditioning_mode" not in p
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"parameters,inputs",
|
|
[
|
|
({"upscale": True}, {"image_asset_id": "first"}),
|
|
({"conditioning_mode": "first_frame"}, {"image_asset_id": "first"}),
|
|
({}, {"first_frame_asset_id": "first"}),
|
|
({}, {"image_asset_id": "first", "last_frame_asset_id": "last"}),
|
|
({}, {}),
|
|
({"num_frames": 124}, {"image_asset_id": "first"}),
|
|
({"num_frames": 149}, {"image_asset_id": "first"}),
|
|
({"num_frames": 337}, {"image_asset_id": "first"}),
|
|
],
|
|
)
|
|
def test_tp2_rejects_unsupported_inputs_parameters(system, parameters, inputs):
|
|
with pytest.raises((ProviderError, ValueError)):
|
|
validate_arguments(
|
|
"video.generate",
|
|
{"prompt": "x", **inputs},
|
|
{"profile": TP2, **parameters},
|
|
system.settings,
|
|
)
|
|
|
|
|
|
async def test_tp2_provider_checks_certificate_before_upload_and_freezes_explicit_profile(
|
|
system, tmp_path, monkeypatch
|
|
):
|
|
provider = Provider(system.settings)
|
|
provider.upstream_capabilities = AsyncMock(return_value={})
|
|
work = system.settings.job_work_root / "tp2"
|
|
work.mkdir(parents=True)
|
|
try:
|
|
with pytest.raises(ProviderError, match="认证"):
|
|
await provider.prepare_gpu_payload(
|
|
"video.generate",
|
|
{"prompt": "x", "image_asset_id": "first"},
|
|
{"profile": TP2},
|
|
{},
|
|
work,
|
|
)
|
|
provider.upstream_capabilities.return_value = {"video_generation": {"tp2": certificate()}}
|
|
monkeypatch.setattr(
|
|
"app.adapters.provider.gpu.inspect_media", AsyncMock(return_value={"kind": "image"})
|
|
)
|
|
monkeypatch.setattr(provider, "_asset", lambda *_: tmp_path / "first.png")
|
|
payload = await provider.prepare_gpu_payload(
|
|
"video.generate",
|
|
{"prompt": "x", "image_asset_id": "first"},
|
|
{"profile": TP2, "num_frames": 145},
|
|
{},
|
|
work,
|
|
)
|
|
assert payload["parameters"]["profile"] == TP2
|
|
assert payload["parameters"]["num_frames"] == 145
|
|
assert payload["timeout_seconds"] == 21600
|
|
assert set(payload["input"]) == {"prompt", "image_path"}
|
|
finally:
|
|
await provider.aclose()
|
|
|
|
|
|
async def test_tp2_story_and_workflow_compile_explicit_recipes_without_changing_old_hashes():
|
|
from app.domain.stories import compile_story
|
|
|
|
raw = StorySpecV3.model_validate(story_spec()).model_dump(mode="json")
|
|
original = deepcopy(raw)
|
|
raw["shots"][0]["video_parameters"].update(profile=TP2, upscale=False)
|
|
parsed = StorySpecV3.model_validate(raw)
|
|
assert "guidance_scale" not in parsed.model_dump()["shots"][0]["video_parameters"]
|
|
draft = SimpleNamespace(spec=original)
|
|
compiled = compile_story(StorySpecV3.model_validate(original), {})
|
|
old_hash = await current_hash(None, draft, "1" * 32, "video", compiled, latest={})
|
|
draft.spec = raw
|
|
assert await current_hash(None, draft, "1" * 32, "video", compiled, latest={}) != old_hash
|
|
workflow = story(durations=[120])
|
|
legacy = deepcopy(workflow)
|
|
workflow["shots"][0]["parameters"]["profile"] = TP2
|
|
p = compile_timeline(workflow, {}).shot_generation_parameters["shot_1"]
|
|
assert p["profile"] == TP2 and p["num_frames"] == 121 and p["upscale"] is False
|
|
assert "guidance_scale" not in p
|
|
assert (
|
|
"profile" not in WorkflowSpec.model_validate(legacy).model_dump()["shots"][0]["parameters"]
|
|
)
|
|
m = manifest(1)
|
|
before = build_recipes(m, {}, {}, SimpleNamespace())
|
|
m["spec"]["shots"][0]["parameters"]["profile"] = TP2
|
|
after = build_recipes(m, {}, {}, SimpleNamespace())
|
|
assert after[1]["parameters"]["profile"] == TP2
|
|
assert after[1]["context_hash"] != before[1]["context_hash"]
|
|
|
|
|
|
async def test_tp2_output_validation_checks_exact_frames_and_dimensions(system, monkeypatch):
|
|
from app.services.assets import validate_workflow_output
|
|
|
|
p = dict(profile=TP2, num_frames=145, fps=24, width=1344, height=768, upscale=False)
|
|
job = SimpleNamespace(task_type="video.generate", parameters=p, request_key=None, run_id=None)
|
|
inspector = AsyncMock(return_value={"frames": 145, "fps": 24, "width": 1344, "height": 768})
|
|
monkeypatch.setattr("app.adapters.media.inspect_video_track", inspector)
|
|
await validate_workflow_output(job, "native.mp4", system.settings)
|
|
inspector.return_value["frames"] = 158
|
|
with pytest.raises(ValueError, match="H3"):
|
|
await validate_workflow_output(job, "uncropped.mp4", system.settings)
|
|
|
|
|
|
async def test_tp2_frozen_payload_requires_live_certificate_without_rewriting_payload(system):
|
|
provider = Provider(system.settings)
|
|
payload = {
|
|
"task_type": "video.generate",
|
|
"input": {"prompt": "x", "image_path": "/frozen.png"},
|
|
"parameters": {"profile": TP2},
|
|
"timeout_seconds": 21600,
|
|
}
|
|
original = deepcopy(payload)
|
|
provider.upstream_capabilities = AsyncMock(return_value={})
|
|
provider._json = AsyncMock(return_value={"id": "remote-tp2", "state": "queued"})
|
|
provider._headers = lambda: {}
|
|
try:
|
|
with pytest.raises(ProviderError, match="认证"):
|
|
await provider.submit(payload, "frozen-tp2")
|
|
provider._json.assert_not_awaited()
|
|
provider.upstream_capabilities.return_value = {"video_generation": {"tp2": certificate()}}
|
|
await provider.submit(payload, "frozen-tp2")
|
|
assert payload == original
|
|
assert provider._json.call_args.kwargs["payload"] == original
|
|
finally:
|
|
await provider.aclose()
|
|
|
|
|
|
async def test_tp2_certified_api_accepts_explicit_job_and_preserves_replay_when_certificate_closes(
|
|
system, png_bytes
|
|
):
|
|
uploaded = await system.client.post(
|
|
"/api/assets", files={"file": ("first.png", png_bytes, "image/png")}
|
|
)
|
|
assert uploaded.status_code == 201, uploaded.text
|
|
system.provider.upstream_capabilities = AsyncMock(
|
|
return_value={"video_generation": {"tp2": certificate()}}
|
|
)
|
|
body = {
|
|
"task_type": "video.generate",
|
|
"input": {"prompt": "x", "image_asset_id": uploaded.json()["id"]},
|
|
"parameters": {"profile": TP2, "num_frames": 145},
|
|
}
|
|
first = await system.client.post(
|
|
"/api/jobs", json=body, headers={"Idempotency-Key": "tp2-certified"}
|
|
)
|
|
assert first.status_code == 202, first.text
|
|
system.provider.upstream_capabilities.return_value = {}
|
|
replay = await system.client.post(
|
|
"/api/jobs", json=body, headers={"Idempotency-Key": "tp2-certified"}
|
|
)
|
|
assert replay.status_code == 202, replay.text
|
|
assert replay.json()["jobs"][0]["id"] == first.json()["jobs"][0]["id"]
|
|
assert replay.json()["jobs"][0]["parameters"] == body["parameters"]
|
|
|
|
|
|
async def test_tp2_story_candidate_blocks_uncertified_then_freezes_first_frame_recipe(
|
|
system, monkeypatch
|
|
):
|
|
from app.models import ShotCandidate
|
|
from test_story_studio import prepare_manual_frame
|
|
|
|
raw = story_spec()
|
|
raw["shots"][0]["video_parameters"] = {"profile": TP2, "upscale": False, "source_seconds": 6}
|
|
created = await system.client.post("/api/stories", json={"name": "TP2 story", "spec": raw})
|
|
assert created.status_code == 201, created.text
|
|
draft, frame, _ = await prepare_manual_frame(system, monkeypatch, created.json())
|
|
path = f"/api/stories/{draft['id']}"
|
|
selected = await system.client.post(
|
|
path + "/selections",
|
|
headers={"Idempotency-Key": "tp2-frame"},
|
|
json={
|
|
"expected_version": 1,
|
|
"shot_id": "1" * 32,
|
|
"kind": "frame",
|
|
"candidate_id": frame["id"],
|
|
},
|
|
)
|
|
assert selected.status_code == 200, selected.text
|
|
body = {"expected_version": selected.json()["version"], "shot_id": "1" * 32, "kind": "video"}
|
|
blocked = await system.client.post(
|
|
path + "/candidates", json=body, headers={"Idempotency-Key": "tp2-video"}
|
|
)
|
|
assert blocked.status_code == 503, blocked.text
|
|
system.provider.upstream_capabilities = AsyncMock(
|
|
return_value={"video_generation": {"tp2": certificate()}}
|
|
)
|
|
accepted = await system.client.post(
|
|
path + "/candidates", json=body, headers={"Idempotency-Key": "tp2-video"}
|
|
)
|
|
assert accepted.status_code == 202, accepted.text
|
|
async with system.app.state.db.session() as session:
|
|
c = await session.get(ShotCandidate, accepted.json()["candidates"][0]["id"])
|
|
assert c.plan_json["parameters"]["profile"] == TP2
|
|
assert c.plan_json["parameters"]["num_frames"] == 145
|
|
assert c.plan_json["parameters"]["upscale"] is False
|
|
assert "guidance_scale" not in c.plan_json["parameters"]
|
|
assert set(c.plan_json["input"]) == {"prompt", "image_asset_id"}
|