import copy import pytest from pydantic import ValidationError def story_spec(): return { "schema_version": 3, "shots": [{"id": "1" * 32, "name": "Shot", "visual_prompt": "A tree"}], } def test_v3_visual_hash_ignores_seed_trim_motion_and_order(): from app.domain.stories import StorySpecV3, compile_story spec = StorySpecV3.model_validate(story_spec()) before = compile_story(spec, {})["shots"][0] changed = spec.model_dump(mode="json") changed["shots"][0]["frame_parameters"]["seed"] = 99 changed["shots"][0]["motion_prompt"] = "pan right" changed["shots"][0]["edit"]["duration_frames"] = 24 changed["render"]["total_frames"] = 24 after = compile_story(StorySpecV3.model_validate(changed), {})["shots"][0] assert before["context_hash"] == after["context_hash"] changed["shots"][0]["visual_prompt"] = "A river" assert ( compile_story(StorySpecV3.model_validate(changed), {})["shots"][0]["context_hash"] != before["context_hash"] ) def test_v3_rejects_forged_selection_and_dangling_cast(): from app.domain.stories import StorySpecV3 forged = {**story_spec(), "selections": []} with pytest.raises(ValidationError): StorySpecV3.model_validate(forged) spec = copy.deepcopy(story_spec()) spec["shots"][0]["cast"] = [{"id": "2" * 32, "entity_id": "3" * 32}] with pytest.raises(ValidationError): StorySpecV3.model_validate(spec) @pytest.mark.asyncio async def test_story_crud_isolation_cas_and_no_legacy_leak(system, other_client): c = system.client response = await c.post("/api/stories", json={"name": "Story", "spec": story_spec()}) assert response.status_code == 201, response.text d = response.json() assert d["kind"] == "story_v3" and d["selections"] == [] assert not d["readiness"]["ready"] assert (await other_client.get(f"/api/stories/{d['id']}")).status_code == 404 assert all(x["id"] != d["id"] for x in (await c.get("/api/workflows")).json()["items"]) path = f"/api/stories/{d['id']}" assert ( await c.patch(path, headers={"If-Match": "999"}, json={"name": "bad"}) ).status_code == 409 preview = (await c.get(path + "/preview")).json() assert preview["shots"][0]["shot_id"] == "1" * 32 assert preview["shots"][0]["context_hash"] assert ( await c.patch(path, headers={"If-Match": "1"}, json={"selections": []}) ).status_code == 422 @pytest.mark.asyncio async def test_clear_is_append_only_idempotent_and_versioned(system): c = system.client d = (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() path = f"/api/stories/{d['id']}/selections/clear" body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"} response = await c.post(path, headers={"Idempotency-Key": "clear-1"}, json=body) assert response.status_code == 200, response.text first = response.json() assert first["version"] == 2 and first["revision"] == 2 assert first["selections"][0]["candidate_id"] is None assert (await c.post(path, headers={"Idempotency-Key": "clear-1"}, json=body)).json() == first body["expected_version"] = 2 second = (await c.post(path, headers={"Idempotency-Key": "clear-2"}, json=body)).json() assert second["selections"][0]["version"] == 2 async def prepare_manual_frame(system, monkeypatch, story=None, key="manual"): from app.adapters.provider.client import Provider import asyncio import io from PIL import Image c = system.client story = ( story or (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() ) content = io.BytesIO() Image.new("RGB", (60, 30), "red").save(content, "PNG") asset = ( await c.post("/api/assets", files={"file": ("input.png", content.getvalue(), "image/png")}) ).json() response = await c.post( f"/api/stories/{story['id']}/candidates", headers={"Idempotency-Key": key}, json={ "expected_version": story["version"], "shot_id": "1" * 32, "kind": "frame", "source_kind": "manual", "asset_id": asset["id"], }, ) assert response.status_code == 202, response.text candidate = response.json()["candidates"][0] assert candidate["state"] == "queued" and candidate["asset"] is None real = Provider(system.settings) monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) try: for _ in range(4): await system.app.state.coordinator.run_once() tasks = list(system.app.state.coordinator._cpu.values()) if tasks: await asyncio.gather(*tasks) result = await c.get(f"/api/stories/{story['id']}/candidates") assert result.status_code == 200, result.text ready = result.json()["items"][0] assert ready["state"] == "ready", ready assert ready["asset"]["id"] != asset["id"] assert (ready["asset"]["width"], ready["asset"]["height"]) == (1280, 704) return story, ready, asset finally: await real.aclose() @pytest.mark.asyncio async def test_manual_frame_real_cpu_confirm_cas_refs_and_clear(system, monkeypatch, other_client): story, candidate, source = await prepare_manual_frame(system, monkeypatch) c = system.client path = f"/api/stories/{story['id']}" body = { "expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "candidate_id": candidate["id"], } assert ( await other_client.post( path + "/selections", headers={"Idempotency-Key": "foreign"}, json=body ) ).status_code == 404 first = await c.post(path + "/selections", headers={"Idempotency-Key": "confirm"}, json=body) assert first.status_code == 200, first.text assert first.json()["version"] == 2 assert ( await c.post(path + "/selections", headers={"Idempotency-Key": "late-window"}, json=body) ).status_code == 409 assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409 response = await c.delete( path + "/candidates/" + candidate["id"], headers={"If-Match": str(candidate["version"])} ) assert response.status_code == 200, response.text # 删除候选只释放候选引用,当前选择仍保护其素材。 assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 409 body.pop("candidate_id") body["expected_version"] = 2 cleared = await c.post( path + "/selections/clear", headers={"Idempotency-Key": "clear"}, json=body ) assert cleared.status_code == 200 assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204 @pytest.mark.asyncio async def test_candidate_batch_lazy_feeder_seed_hash_and_stale(system): from app.services.orchestration.workflow_engine import advance_workflows from app.models import Job, ShotCandidate from sqlalchemy import select, func c = system.client system.settings.inference_base_url = "http://fake" spec = story_spec() spec["shots"] += [{"id": f"{i:032x}", "visual_prompt": "tree"} for i in range(2, 7)] d = (await c.post("/api/stories", json={"name": "Batch", "spec": spec})).json() response = await c.post( f"/api/stories/{d['id']}/candidate-batches", headers={"Idempotency-Key": "batch"}, json={ "expected_version": 1, "shot_ids": [x["id"] for x in spec["shots"]], "kind": "frame", "count": 2, "execution_mode": "batch", }, ) assert response.status_code == 202, response.text candidates = response.json()["candidates"] assert len(candidates) == 12 and all(x["job_id"] is None for x in candidates) assert candidates[0]["context_hash"] == candidates[1]["context_hash"] assert candidates[0]["generation_hash"] != candidates[1]["generation_hash"] async with system.app.state.db.session() as s: assert await s.scalar(select(func.count()).select_from(Job)) == 0 await advance_workflows(system.app.state.db, system.settings, system.provider) async with system.app.state.db.session() as s: assert await s.scalar(select(func.count()).select_from(Job)) == 8 await advance_workflows(system.app.state.db, system.settings, system.provider) async with system.app.state.db.session() as s: assert await s.scalar(select(func.count()).select_from(Job)) == 12 rows = (await s.scalars(select(ShotCandidate))).all() assert all(x.job_id for x in rows) @pytest.mark.asyncio async def test_seed_and_trim_changes_preserve_frame_selection_visual_change_stales( system, monkeypatch ): d, candidate, _ = await prepare_manual_frame(system, monkeypatch) c = system.client path = f"/api/stories/{d['id']}" spec = copy.deepcopy(d["spec"]) spec["shots"][0]["frame_parameters"]["seed"] = 987 spec["shots"][0]["edit"]["duration_frames"] = 24 spec["render"]["total_frames"] = 24 changed = await c.patch(path, headers={"If-Match": "1"}, json={"spec": spec}) assert changed.status_code == 200, changed.text selected = await c.post( path + "/selections", headers={"Idempotency-Key": "after-seed"}, json={ "expected_version": 2, "shot_id": "1" * 32, "kind": "frame", "candidate_id": candidate["id"], }, ) assert selected.status_code == 200, selected.text spec["shots"][0]["visual_prompt"] = "A river" changed = await c.patch(path, headers={"If-Match": "3"}, json={"spec": spec}) assert changed.status_code == 200 assert changed.json()["selections"][0]["stale"] @pytest.mark.asyncio async def test_reference_unavailable_never_silently_generates_text(system, png_bytes): c = system.client a = (await c.post("/api/assets", files={"file": ("ref.png", png_bytes, "image/png")})).json() spec = story_spec() spec["entities"] = [{"id": "2" * 32, "name": "Person", "reference_asset_ids": [a["id"]]}] spec["shots"][0]["cast"] = [{"id": "3" * 32, "entity_id": "2" * 32}] d = (await c.post("/api/stories", json={"name": "Ref", "spec": spec})).json() path = f"/api/stories/{d['id']}/candidates" body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "source_kind": "generated"} response = await c.post(path, headers={"Idempotency-Key": "ref-disabled"}, json=body) assert ( response.status_code == 503 and response.json()["detail"]["code"] == "reference_generation_unavailable" ) system.settings.inference_base_url = "" response = await c.post( path, headers={"Idempotency-Key": "force-text"}, json={**body, "reference_mode": "text"} ) assert response.status_code == 503 # 文字服务也须真实可用,不能伪造能力。 system.settings.inference_base_url = "http://fake" response = await c.post( path, headers={"Idempotency-Key": "explicit-text"}, json={**body, "reference_mode": "text"} ) assert response.status_code == 202, response.text summary = response.json()["candidates"][0]["input_summary"] assert summary["reference_mode"] == "text" and summary["actual_reference_asset_ids"] == [] @pytest.mark.asyncio async def test_deleting_shot_before_dispatch_does_not_recreate_it(system): from app.services.orchestration.workflow_engine import advance_workflows from app.models import Job from sqlalchemy import select, func c = system.client system.settings.inference_base_url = "http://fake" spec = story_spec() spec["shots"].append({"id": "2" * 32, "visual_prompt": "River"}) d = (await c.post("/api/stories", json={"name": "Delete", "spec": spec})).json() path = f"/api/stories/{d['id']}" candidate = ( await c.post( path + "/candidates", headers={"Idempotency-Key": "pending"}, json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, ) ).json()["candidates"][0] spec["shots"].pop(0) assert (await c.patch(path, headers={"If-Match": "1"}, json={"spec": spec})).status_code == 200 await advance_workflows(system.app.state.db, system.settings, system.provider) row = (await c.get(path + "/candidates")).json()["items"][0] assert row["id"] == candidate["id"] and row["stale"] and row["state"] == "failed" async with system.app.state.db.session() as s: assert await s.scalar(select(func.count()).select_from(Job)) == 0 assert len((await c.get(path)).json()["spec"]["shots"]) == 1 @pytest.mark.asyncio async def test_story_cannot_be_mutated_or_started_through_legacy_workflow_api(system): c = system.client d = (await c.post("/api/stories", json={"name": "Story", "spec": story_spec()})).json() path = f"/api/workflows/{d['id']}" assert (await c.get(path)).status_code == 404 assert ( await c.patch(path, headers={"If-Match": "1"}, json={"name": "bypass"}) ).status_code == 404 assert (await c.delete(path, headers={"If-Match": "1"})).status_code == 404 response = await c.post( path + "/runs", headers={"Idempotency-Key": "old-run"}, json={"expected_version": 1, "draft_revision": 1}, ) assert response.status_code == 404 @pytest.mark.asyncio async def test_story_delete_releases_candidates_and_selection_refs(system, monkeypatch): from sqlalchemy import select from app.models import ShotCandidate, ShotSelection, AssetReference, Job d, candidate, source = await prepare_manual_frame(system, monkeypatch) c = system.client path = f"/api/stories/{d['id']}" selected = await c.post( path + "/selections", headers={"Idempotency-Key": "select-delete"}, json={ "expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "candidate_id": candidate["id"], }, ) assert selected.status_code == 200 deleted = await c.delete(path, headers={"If-Match": "2"}) assert deleted.status_code == 200, deleted.text assert (await c.get(path)).status_code == 404 async with system.app.state.db.session() as s: row = await s.get(ShotCandidate, candidate["id"]) assert row.deleted_at is not None assert (await s.get(Job, candidate["job_id"])).deleted_at is not None selection_ids = select(ShotSelection.id).where(ShotSelection.draft_id == d["id"]) assert not await s.scalar( select(AssetReference.id).where( AssetReference.ref_kind == "selection", AssetReference.ref_id.in_(selection_ids) ) ) assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204 @pytest.mark.asyncio async def test_manual_video_frozen_compose_history_and_nonzero_trim(system, monkeypatch): import asyncio from app.adapters.media import run_process, inspect_video_track from app.adapters.provider.client import Provider from app.models import Asset import shutil if not shutil.which("ffmpeg") or not shutil.which("ffprobe"): pytest.skip("FFmpeg and ffprobe are required for the decoded video integration test") system.settings.ffmpeg_bin = shutil.which("ffmpeg") system.settings.ffprobe_bin = shutil.which("ffprobe") c = system.client spec = story_spec() spec["shots"][0]["edit"] = {"start_frame": 24, "duration_frames": 24} spec["render"] = {"total_frames": 24} d = (await c.post("/api/stories", json={"name": "Frozen", "spec": spec})).json() d, frame, _ = await prepare_manual_frame(system, monkeypatch, d) path = f"/api/stories/{d['id']}" selected = await c.post( path + "/selections", headers={"Idempotency-Key": "frame"}, json={ "expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "candidate_id": frame["id"], }, ) assert selected.status_code == 200 video = system.settings.workspace_root / "source.mp4" await run_process( [ system.settings.ffmpeg_bin, "-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=256x256:r=24", "-frames:v", "48", "-c:v", "libx264", "-pix_fmt", "yuv420p", str(video), ] ) uploaded = await c.post( "/api/assets", files={"file": ("source.mp4", video.read_bytes(), "video/mp4")} ) assert uploaded.status_code == 201, uploaded.text candidate = await c.post( path + "/candidates", headers={"Idempotency-Key": "manual-video"}, json={ "expected_version": 2, "shot_id": "1" * 32, "kind": "video", "source_kind": "manual", "asset_id": uploaded.json()["id"], }, ) assert candidate.status_code == 202, candidate.text candidate = candidate.json()["candidates"][0] assert candidate["state"] == "ready" and candidate["job_id"] is None selected = await c.post( path + "/selections", headers={"Idempotency-Key": "video"}, json={ "expected_version": 2, "shot_id": "1" * 32, "kind": "video", "candidate_id": candidate["id"], }, ) assert selected.status_code == 200, selected.text assert selected.json()["readiness"]["ready"] # 已接纳的首帧/人工视频各扣一次,此次合成达到共享创建命令预算上限。 system.settings.max_creation_commands_per_minute = 3 response = await c.post( path + "/renders", headers={"Idempotency-Key": "render"}, json={"expected_version": 3, "execution_mode": "interactive"}, ) assert response.status_code == 202, response.text snap = response.json() replay = await c.post( path + "/renders", headers={"Idempotency-Key": "render"}, json={"expected_version": 3, "execution_mode": "interactive"}, ) assert replay.status_code == 202 and replay.json() == snap blocked = await c.post( path + "/renders", headers={"Idempotency-Key": "render-second"}, json={"expected_version": 4, "execution_mode": "interactive"}, ) assert blocked.status_code == 429 assert [s["step_key"] for s in snap["steps"]] == ["compose"] assert len(snap["run"]["render_inputs"]["selections"]) == 2 assert snap["run"]["render_inputs"]["clips"][0]["start_frame"] == 24 latest = (await c.get(path)).json() changed = latest["spec"] changed["shots"][0]["visual_prompt"] = "A different story" assert ( await c.patch(path, headers={"If-Match": str(latest["version"])}, json={"spec": changed}) ).status_code == 200 real = Provider(system.settings) monkeypatch.setattr(system.provider, "run_cpu", real.run_cpu) try: for _ in range(5): await system.app.state.coordinator.run_once() tasks = list(system.app.state.coordinator._cpu.values()) if tasks: await asyncio.gather(*tasks) current = (await c.get("/api/workflow-runs/" + snap["run"]["id"])).json() assert current["draft"]["spec"]["shots"][0]["visual_prompt"] == "A tree" assert current["run"]["state"] == "succeeded", current output = current["run"]["result_assets"][0] async with system.app.state.db.session() as s: asset = await s.get(Asset, output["id"]) track = await inspect_video_track( system.settings.asset_root / asset.storage_key, system.settings ) assert track["frames"] == 24 and track["fps"] == 24 assert (track["width"], track["height"]) == (1920, 1080) finally: await real.aclose() def test_override_inheritance_and_only_selected_entity_references(): from app.domain.stories import compile_story, StorySpecV3 spec = story_spec() spec["context"] = {"lighting": "sunlight", "palette": "warm"} spec["scenes"] = [{"id": "2" * 32, "lighting": "moonlight"}] spec["entities"] = [{"id": "3" * 32, "name": "Unused", "reference_asset_ids": ["unused"]}] spec["shots"][0].update(scene_id="2" * 32, overrides={"lighting": ""}) parsed = StorySpecV3.model_validate(spec) output = compile_story(parsed, {})["shots"][0] assert output["effective_settings"]["lighting"] == "" assert output["references"] == [] assert parsed.model_dump()["shots"][0]["overrides"] == {"lighting": ""} spec["shots"][0]["overrides"] = {} assert compile_story(spec, {})["shots"][0]["effective_settings"]["lighting"] == "moonlight" @pytest.mark.asyncio async def test_retry_keeps_frozen_generation_input_and_never_selects_automatically(system): from app.models import ShotCandidate, Job from app.services.orchestration.workflow_engine import advance_workflows c = system.client d = (await c.post("/api/stories", json={"name": "Retry", "spec": story_spec()})).json() path = f"/api/stories/{d['id']}" response = await c.post( path + "/candidates", headers={"Idempotency-Key": "candidate"}, json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, ) assert response.status_code == 202, response.text old = response.json()["candidates"][0] await advance_workflows(system.app.state.db, system.settings, system.provider) async with system.app.state.db.session() as s: candidate = await s.get(ShotCandidate, old["id"]) job = await s.get(Job, candidate.job_id) job.state = "failed" frozen = candidate.plan_json await s.commit() retry = await c.post( path + "/candidates/" + old["id"] + "/retry", headers={"Idempotency-Key": "retry"}, json={"expected_version": 1}, ) assert retry.status_code == 202, retry.text new = retry.json()["candidates"][0] assert new["id"] != old["id"] and new["generation_hash"] == old["generation_hash"] async with system.app.state.db.session() as s: retried = (await s.get(ShotCandidate, new["id"])).plan_json assert {k: v for k, v in retried.items() if k != "parent_plan_id"} == { k: v for k, v in frozen.items() if k != "parent_plan_id" } assert retried["parent_plan_id"] != frozen["parent_plan_id"] assert (await c.get(path)).json()["selections"] == [] @pytest.mark.asyncio async def test_cancel_undispatched_candidate_batch_is_terminal_and_emits_events(system): from app.services.orchestration.workflow_engine import advance_workflows from app.models import Event, Job from sqlalchemy import select, func c = system.client d = (await c.post("/api/stories", json={"name": "Cancel", "spec": story_spec()})).json() response = await c.post( f"/api/stories/{d['id']}/candidate-batches", headers={"Idempotency-Key": "cancel-batch"}, json={ "expected_version": 1, "shot_ids": ["1" * 32], "kind": "frame", "count": 2, "execution_mode": "batch", }, ) assert response.status_code == 202, response.text bid = response.json()["batch_id"] cancelled = await c.post( "/api/batches/" + bid + "/control", headers={"Idempotency-Key": "cancel"}, json={"desired_state": "cancel"}, ) assert cancelled.status_code == 200 await advance_workflows(system.app.state.db, system.settings, system.provider) assert (await c.get("/api/batches/" + bid)).json()["batch"]["state"] == "cancelled" candidates = (await c.get(f"/api/stories/{d['id']}/candidates")).json()["items"] assert all(x["state"] == "failed" and x["error"]["code"] == "cancelled" for x in candidates) async with system.app.state.db.session() as s: assert await s.scalar(select(func.count()).select_from(Job)) == 0 events = (await s.scalars(select(Event.event_type))).all() assert ( "story.updated" in events and "candidate.updated" in events and "batch.updated" in events ) @pytest.mark.asyncio @pytest.mark.parametrize("upscale", [False, True]) async def test_candidate_video_validator_checks_native_and_enhanced_profiles( system, monkeypatch, upscale ): from app.services.assets import validate_workflow_output from types import SimpleNamespace from unittest.mock import AsyncMock p = dict( num_frames=121, width=1280, height=704, upscale=upscale, upscale_width=1920, upscale_height=1056, ) job = SimpleNamespace( request_key="candidate:one", task_type="video.generate", run_id=None, parameters=p ) track = { "frames": 121, "fps": 24, "width": 1920 if upscale else 1280, "height": 1056 if upscale else 704, } mock = AsyncMock(return_value=track) monkeypatch.setattr("app.adapters.media.inspect_video_track", mock) await validate_workflow_output(job, "source.mp4", system.settings) for invalid in ({**track, "fps": 25}, {**track, "frames": 119}, {**track, "width": 256}): mock.return_value = invalid with pytest.raises(ValueError): await validate_workflow_output(job, "source.mp4", system.settings) @pytest.mark.asyncio async def test_candidate_retry_requires_confirmed_execution_cleanup(system): from app.models import ShotCandidate, Job, Execution from app.services.orchestration.workflow_engine import advance_workflows c = system.client d = (await c.post("/api/stories", json={"name": "Cleanup", "spec": story_spec()})).json() path = f"/api/stories/{d['id']}" response = await c.post( path + "/candidates", headers={"Idempotency-Key": "candidate"}, json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}, ) cid = response.json()["candidates"][0]["id"] await advance_workflows(system.app.state.db, system.settings, system.provider) async with system.app.state.db.session() as s: candidate = await s.get(ShotCandidate, cid) job = await s.get(Job, candidate.job_id) job.state = "failed" s.add( Execution( job_id=job.id, ordinal=1, phase_key="execute", resource_pool="new_gpu", fence_token="fence", state="running", ) ) await s.commit() retry = await c.post( path + "/candidates/" + cid + "/retry", headers={"Idempotency-Key": "retry"}, json={"expected_version": 1}, ) assert retry.status_code == 409 and retry.json()["detail"]["code"] == "cleanup_pending"