from types import SimpleNamespace import pytest from app.services.orchestration.editor_engine import build_recipes def manifest(n=2): ids = [f"{i + 1:032x}" for i in range(n)] return dict( schema_version=1, source_kind="workflow", shot_ids=ids, bindings={}, audio={"mode": "silent", "segments": []}, captions={"mode": "none", "cues": []}, spec={ "schema_version": 2, "profile": "landscape_1080_v1", "shots": [ { "key": f"shot_{i + 1}", "prompt": "mountain", "duration_frames": 120, "parameters": {"seed": 42}, } for i in range(n) ], "render": {"fps": 24, "audio": None, "subtitles": []}, }, ) def test_media_target_ancestor_closure_and_film_compose(): m = manifest(8) steps = build_recipes( m, {}, {"output_goal": "media", "targets": ["video:" + m["shot_ids"][3]]}, SimpleNamespace() ) assert [x["key"] for x in steps] == ["frame_0004", "video_0004"] assert steps[-1]["dependencies"] == ["frame_0004"] assert build_recipes(m, {}, {"output_goal": "film"}, SimpleNamespace())[-1]["key"] == "compose" def test_reused_video_does_not_require_frame_or_old_job(): m = manifest() key = "video:" + m["shot_ids"][0] binding = {"asset_id": "a", "sha256": "sha", "kind": "video", "source": "manual"} steps = build_recipes( m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() ) assert len(steps) == 1 and steps[0]["reuse"] == binding assert steps[0]["dependencies"] == [] def test_force_only_explicit_stage(): m = manifest(1) key = "video:" + m["shot_ids"][0] steps = build_recipes( m, {key: {"asset_id": "a", "source": "manual"}}, {"output_goal": "media", "force": [key]}, SimpleNamespace(), ) assert [s["key"] for s in steps] == ["frame_0001", "video_0001"] assert steps[-1]["forced"] is True and not steps[0]["forced"] async def editor(system, n=1): response = await system.client.post( "/api/workflows", json={"name": "Editor", "spec": manifest(n)["spec"]} ) assert response.status_code == 201, response.text id = response.json()["id"] m = (await system.client.get("/api/editors/" + id)).json()["manifest"] return id, m async def test_media_reuse_finishes_without_jobs_or_compose_and_applies(system, png_bytes): from sqlalchemy import select from app.models import WorkflowRun, WorkflowStep, Job, WorkflowDraft from app.services.orchestration.workflow_engine import advance_run c = system.client id, m = await editor(system) a = await c.post("/api/assets", files={"file": ("frame.png", png_bytes, "image/png")}) aid = a.json()["id"] sid = m["shot_ids"][0] m["bindings"]["frame:" + sid] = { "asset_id": aid, "sha256": "0" * 64, "kind": "image", "source": "manual", } saved = await c.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "save-frame"}, ) assert saved.status_code == 200, saved.text body = {"expected_version": 2, "output_goal": "media", "targets": ["frame:" + sid]} plan = await c.post("/api/editors/" + id + "/plan", json=body) assert plan.status_code == 200, plan.text assert plan.json()["steps"][0]["status"] == "reuse" body["expected_plan_hash"] = plan.json()["plan_hash"] run = await c.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "media"} ) assert run.status_code == 202, run.text rid = run.json()["run"]["id"] again = await c.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "media"} ) assert again.json()["run"]["id"] == rid async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) await s.commit() r = await s.get(WorkflowRun, rid) assert r.state == "succeeded" and r.apply_state == "applied" assert r.current_output_asset_id is None steps = (await s.scalars(select(WorkflowStep).where(WorkflowStep.run_id == rid))).all() assert len(steps) == 1 and steps[0].selected_job_id is None assert not (await s.scalars(select(Job).where(Job.run_id == rid))).all() assert (await s.get(WorkflowDraft, id)).version == 3 snapshot = await c.get("/api/workflow-runs/" + rid) assert snapshot.status_code == 200, snapshot.text assert snapshot.json()["run"]["output_goal"] == "media" assert snapshot.json()["steps"][0]["result"]["asset_id"] == aid async def test_direct_frame_job_frozen_input_pause_cancel_and_no_candidate(system): from sqlalchemy import select, func from app.models import WorkflowRun, WorkflowStep, Job, ShotCandidate from app.services.orchestration.workflow_engine import advance_run from app.services.workflows import control_run c = system.client id, m = await editor(system) body = { "expected_version": 1, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]], "force": ["frame:" + m["shot_ids"][0]], } plan = await c.post("/api/editors/" + id + "/plan", json=body) assert plan.status_code == 200, plan.text body["expected_plan_hash"] = plan.json()["plan_hash"] response = await c.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "new-frame"} ) assert response.status_code == 202, response.text rid = response.json()["run"]["id"] async with system.app.state.db.session() as s: r = await s.get(WorkflowRun, rid) await control_run(s, r, "pause") await advance_run(s, rid, system.settings) assert not (await s.scalars(select(Job).where(Job.run_id == rid))).all() await control_run(s, r, "run") await advance_run(s, rid, system.settings) await s.commit() step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) job = await s.get(Job, step.selected_job_id) assert job.task_type == "image.generate" and job.step_key == "frame_0001" assert job.parameters["seed"] == step.recipe_json["parameters"]["seed"] assert step.resolved_input_json["input"] == job.input_json assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 0 await control_run(s, r, "cancel") await advance_run(s, rid, system.settings) await s.commit() assert r.state == "cancelled" def test_generated_video_reuse_depends_on_actual_frame_and_trim_not_source_request(): m = manifest(1) sid = m["shot_ids"][0] frame = {"asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "manual"} first = build_recipes(m, {"frame:" + sid: frame}, {"output_goal": "film"}, SimpleNamespace()) context = next(s["context_hash"] for s in first if s["key"] == "video_0001") video = { "asset_id": "v", "sha256": "b" * 64, "kind": "video", "source": "generated", "context_hash": context, } recipes = build_recipes( m, {"frame:" + sid: frame, "video:" + sid: video}, {"output_goal": "media"}, SimpleNamespace(), ) assert len(recipes) == 1 and recipes[0]["reuse"] frame["sha256"] = "c" * 64 recipes = build_recipes( m, {"frame:" + sid: frame, "video:" + sid: video}, {"output_goal": "media"}, SimpleNamespace(), ) assert len(recipes) == 2 and not recipes[-1]["reuse"] async def start_frame(system): id, m = await editor(system) body = { "expected_version": 1, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]], "force": ["frame:" + m["shot_ids"][0]], } p = await system.client.post("/api/editors/" + id + "/plan", json=body) body["expected_plan_hash"] = p.json()["plan_hash"] r = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "frame-run"} ) assert r.status_code == 202, r.text return id, r.json()["run"]["id"], body async def test_retry_preserves_frozen_seed_and_ignores_late_attempt(system): from sqlalchemy import select from app.models import WorkflowRun, WorkflowStep, Job from app.services.orchestration.workflow_engine import advance_run id, rid, body = await start_frame(system) async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) old = await s.get(Job, step.selected_job_id) old.state = "failed" await advance_run(s, rid, system.settings) await s.commit() r = await s.get(WorkflowRun, rid) version = r.version old_id = old.id frozen = step.resolved_input_json response = await system.client.post( f"/api/workflow-runs/{rid}/steps/frame_0001/retry", json={"expected_run_version": version, "target_job_id": old_id}, headers={"Idempotency-Key": "retry-frame"}, ) assert response.status_code == 202, response.text async with system.app.state.db.session() as s: step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) new = await s.get(Job, step.selected_job_id) assert new.id != old_id and new.parameters == frozen["parameters"] assert step.resolved_input_json == frozen old = await s.get(Job, old_id) old.state = "succeeded" await advance_run(s, rid, system.settings) assert step.state == "ready" and step.selected_job_id == new.id replay = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "frame-run"} ) assert replay.json()["run"]["id"] == rid async def test_frame_result_materialized_and_auto_apply_conflict_does_not_fail_media(system): import io from PIL import Image from sqlalchemy import select from app.models import WorkflowRun, WorkflowStep, Job, Asset, WorkflowDraft from app.services.orchestration.workflow_engine import advance_run id, rid, _ = await start_frame(system) async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) await s.commit() step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) jid = step.selected_job_id data = io.BytesIO() Image.new("RGB", (1280, 704), "red").save(data, format="PNG") response = await system.client.post( "/api/assets", files={"file": ("result.png", data.getvalue(), "image/png")} ) aid = response.json()["id"] async with system.app.state.db.session() as s: a = await s.get(Asset, aid) a.source_job_id = jid a.source_output_index = 0 j = await s.get(Job, jid) j.state = "succeeded" d = await s.get(WorkflowDraft, id) d.version += 1 await advance_run(s, rid, system.settings) await s.commit() r = await s.get(WorkflowRun, rid) assert r.state == "succeeded" and r.apply_state == "conflict" b = next(iter(r.result_manifest["bindings"].values())) assert b["asset_id"] == aid and b["source_job_id"] == jid and b["input_hash"] assert d.editor_manifest is None def test_eight_shots_only_changed_video_and_enough_source_reused(): from copy import deepcopy m = manifest(8) reusable = {} for sid in m["shot_ids"]: reusable["frame:" + sid] = { "asset_id": "f" + sid, "sha256": "a" * 64, "kind": "image", "source": "manual", } reusable["video:" + sid] = { "asset_id": "v" + sid, "sha256": "b" * 64, "kind": "video", "source": "manual", } target = "video:" + m["shot_ids"][4] recipes = build_recipes( m, reusable, {"output_goal": "film", "force": [target]}, SimpleNamespace() ) assert len([s for s in recipes if s["kind"] == "video.generate" and not s["reuse"]]) == 1 assert len([s for s in recipes if s["kind"] == "image.generate" and not s["reuse"]]) == 0 story = deepcopy(m) story["spec"]["shots"][0]["duration_frames"] = 72 assert next( s for s in build_recipes(story, reusable, {"output_goal": "film"}, SimpleNamespace()) if s["key"] == "video_0001" )["reuse"] async def test_legacy_patch_and_run_require_editor(system): id, m = await editor(system) r = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "save"}, ) assert r.status_code == 200, r.text r = await system.client.patch( "/api/workflows/" + id, json={"name": "legacy"}, headers={"If-Match": "2"} ) assert r.status_code == 409 and r.json()["detail"]["code"] == "editor_required" r = await system.client.post( "/api/workflows/" + id + "/runs", json={"expected_version": 2, "draft_revision": 2}, headers={"Idempotency-Key": "legacy"}, ) assert r.status_code == 409 and r.json()["detail"]["code"] == "editor_required" def test_narration_typed_dag_and_models_are_frozen_before_video(): m = manifest(1) sid = m["shot_ids"][0] m["audio"] = { "mode": "generated_narration", "voice": "test", "speed": 1.2, "segments": [{"id": "f" * 32, "shot_id": sid, "text": ""}], } m["captions"]["mode"] = "ai_script" settings = SimpleNamespace(qwen_model="script-v1", tts_model="speech-v1") recipes = build_recipes(m, {}, {"output_goal": "film"}, settings) bykey = {r["key"]: r for r in recipes} assert bykey["script"]["kind"] == "text.script.generate" assert bykey["script"]["parameters"]["model"] == "script-v1" assert bykey["speech_0001"]["dependencies"] == ["script"] assert bykey["speech_0001"]["parameters"] == { "model": "speech-v1", "voice": "test", "speed": 1.2, } assert "speech_0001" in bykey["video_0001"]["dependencies"] assert bykey["assemble"]["dependencies"] == ["speech_0001"] assert {"assemble", "captions", "video_0001"} == set(bykey["compose"]["dependencies"]) def test_manual_frame_only_prepared_when_consumed_by_video(): m = manifest(1) sid = m["shot_ids"][0] frame = { "asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "manual", "_width": 16, "_height": 12, } only = build_recipes( m, {"frame:" + sid: frame}, {"output_goal": "media", "targets": ["frame:" + sid]}, SimpleNamespace(), ) assert only[0]["reuse"] and "_width" not in only[0]["reuse"] video = build_recipes(m, {"frame:" + sid: frame}, {"output_goal": "media"}, SimpleNamespace()) assert video[0]["kind"] == "image.prepare_frame" and video[0]["reuse"] is None assert video[0]["input"] == {"image_asset_id": "f"} @pytest.mark.parametrize("timeline_frames", [25, 120]) @pytest.mark.parametrize("source_kind", ["workflow", "story"]) async def test_film_script_speech_captions_assemble_compose_complete_cycle( system, monkeypatch, png_bytes, timeline_frames, source_kind ): """模型及FFmpeg探测为边界替身,真实DB/Job准入/冻结/应用全链路。""" import hashlib from uuid import uuid4 from unittest.mock import AsyncMock from sqlalchemy import select from app.models import WorkflowRun, WorkflowStep, WorkflowDraft, Job, Asset from app.services.orchestration.workflow_engine import advance_run monkeypatch.setattr("app.services.stories.candidates.validate_video", AsyncMock()) monkeypatch.setattr( "app.adapters.media.inspect_video_track", AsyncMock( return_value={"width": 1280, "height": 704, "fps": 24, "frames": 120, "duration": 5.0} ), ) system.settings.tts_base_url = "http://mock-tts" if source_kind == "story": response = await system.client.post( "/api/stories", json={ "name": "Auto story", "create_folder": False, "spec": { "schema_version": 3, "shots": [{"id": "a" * 32, "visual_prompt": "mountain"}], }, }, ) assert response.status_code == 201, response.text id = response.json()["id"] m = (await system.client.get("/api/editors/" + id)).json()["manifest"] else: id, m = await editor(system) sid = m["shot_ids"][0] segment = m["audio"]["segments"][0]["id"] m["audio"]["mode"] = "generated_narration" m["audio"]["voice"] = system.settings.tts_voices[0] m["captions"]["mode"] = "ai_script" if source_kind == "story": m["spec"]["shots"][0]["edit"]["duration_frames"] = timeline_frames else: m["spec"]["shots"][0]["duration_frames"] = timeline_frames response = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "narration"}, ) assert response.status_code == 200, response.text body = {"expected_version": 2, "output_goal": "film"} p = await system.client.post("/api/editors/" + id + "/plan", json=body) assert p.status_code == 200, p.text body["expected_plan_hash"] = p.json()["plan_hash"] response = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "film"} ) assert response.status_code == 202, response.text rid = response.json()["run"]["id"] seen = [] for tick in range(12): async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) r = await s.get(WorkflowRun, rid) assert r.state != "blocked", r.error_json jobs = ( await s.scalars(select(Job).where(Job.run_id == rid, Job.state != "succeeded")) ).all() for j in jobs: seen.append(j.task_type) if j.task_type == "video.generate": assert "audio.speech" in seen and j.input_json["image_asset_id"] if j.task_type == "audio.speech": assert j.input_json["prompt"] == "测试旁白" if j.task_type == "video.compose": assert (j.parameters.get("workflow_spec") or j.parameters["story_spec"])[ "render" ]["subtitles"][0]["text"] == "测试旁白" assert j.input_json["audio_asset_id"] key = "mock/" + uuid4().hex + ".bin" path = system.settings.asset_root / key path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(png_bytes) kind = { "image.generate": "image", "text.script.generate": "json", "audio.speech": "audio", "audio.assemble": "audio", "video.generate": "video", "video.compose": "video", }[j.task_type] duration = ( 0.5 if j.task_type == "audio.speech" else timeline_frames / 24 if j.task_type in {"audio.assemble", "video.compose"} else 5.0 ) a = Asset( owner_id=r.owner_id, name="mock output", storage_key=key, kind=kind, mime_type="application/octet-stream", size_bytes=len(png_bytes), sha256=hashlib.sha256(png_bytes).hexdigest(), width=1280, height=704, duration_seconds=duration if kind in {"audio", "video"} else None, source_job_id=j.id, source_output_index=0, ) s.add(a) j.state = "succeeded" if j.task_type == "text.script.generate": j.result_json = {"segments": [{"shot_id": sid, "text": "测试旁白"}]} await s.commit() if r.state == "succeeded": break async with system.app.state.db.session() as s: r = await s.get(WorkflowRun, rid) assert r.state == "succeeded" and r.apply_state == "applied" assert set(seen) == { "text.script.generate", "image.generate", "audio.speech", "video.generate", "audio.assemble", "video.compose", } assert r.result_manifest["audio"]["segments"][0]["text"] == "测试旁白" assert r.result_manifest["bindings"]["audio:" + segment]["duration_frames"] == 12 assert r.result_manifest["captions"]["cues"][0]["segment_id"] == segment assert (await s.get(WorkflowDraft, id)).current_run_id == rid compose = await s.scalar( select(WorkflowStep).where( WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose" ) ) assert compose.resolved_input_json["input_sha256"] assert ( r.spec_snapshot["render"]["audio"] is None and r.spec_snapshot["render"]["subtitles"] == [] ) # 后续仅编辑字幕:真实产物全部恢复,配音及镜头无新的模型任务。 current = (await system.client.get("/api/editors/" + id)).json() edited = current["manifest"] edited["captions"]["cues"][0].update(text="人工修改字幕", text_override=True) saved = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": current["version"], "manifest": edited}, headers={"Idempotency-Key": "caption-edit"}, ) assert saved.status_code == 200, saved.text body = {"expected_version": saved.json()["version"], "output_goal": "film"} p = await system.client.post("/api/editors/" + id + "/plan", json=body) assert p.status_code == 200, p.text assert all( x["status"] == "reuse" for x in p.json()["steps"] if x["kind"] in {"video.generate", "audio.speech"} ) body["expected_plan_hash"] = p.json()["plan_hash"] response = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "caption-film"} ) assert response.status_code == 202, response.text newrid = response.json()["run"]["id"] later = [] for tick in range(8): async with system.app.state.db.session() as s: await advance_run(s, newrid, system.settings) r = await s.get(WorkflowRun, newrid) assert r.state != "blocked", r.error_json jobs = ( await s.scalars(select(Job).where(Job.run_id == newrid, Job.state != "succeeded")) ).all() for j in jobs: later.append(j.task_type) assert j.task_type in {"audio.assemble", "video.compose"} if j.task_type == "video.compose": assert (j.parameters.get("workflow_spec") or j.parameters["story_spec"])[ "render" ]["subtitles"][0]["text"] == "人工修改字幕" key = "mock/" + uuid4().hex + ".bin" path = system.settings.asset_root / key path.write_bytes(png_bytes) s.add( Asset( owner_id=r.owner_id, name="mock reused film", storage_key=key, kind="audio" if j.task_type == "audio.assemble" else "video", mime_type="application/octet-stream", size_bytes=len(png_bytes), sha256=hashlib.sha256(png_bytes).hexdigest(), width=1280, height=704, duration_seconds=timeline_frames / 24, source_job_id=j.id, source_output_index=0, ) ) j.state = "succeeded" await s.commit() if r.state == "succeeded": break async with system.app.state.db.session() as s: r = await s.get(WorkflowRun, newrid) assert r.state == "succeeded" and r.apply_state == "applied" assert set(later) == {"audio.assemble", "video.compose"} assert (await s.get(WorkflowDraft, id)).current_run_id == newrid assert not any(k.startswith("_") for b in r.result_manifest["bindings"].values() for k in b) def test_forced_variant_reused_by_intent_but_actual_nonseed_parameters_checked(): from copy import deepcopy m = manifest(1) sid = m["shot_ids"][0] original = build_recipes( m, {}, {"output_goal": "media", "targets": ["frame:" + sid]}, SimpleNamespace() )[0] actual = deepcopy(original["parameters"]) actual["seed"] = 123456 b = { "asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "generated", "context_hash": original["context_hash"], "generation_parameters": actual, } assert build_recipes( m, {"frame:" + sid: b}, {"output_goal": "media", "targets": ["frame:" + sid]}, SimpleNamespace(), )[0]["reuse"] b["generation_parameters"]["guidance_scale"] = 99.0 assert not build_recipes( m, {"frame:" + sid: b}, {"output_goal": "media", "targets": ["frame:" + sid]}, SimpleNamespace(), )[0]["reuse"] async def test_cancel_waits_for_execution_cleanup_across_sessions(system): from sqlalchemy import select from app.models import WorkflowRun, WorkflowStep, Job, Execution from app.services.orchestration.workflow_engine import advance_run from app.services.workflows import control_run _, rid, _ = await start_frame(system) async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) step = await s.scalar(select(WorkflowStep).where(WorkflowStep.run_id == rid)) j = await s.get(Job, step.selected_job_id) e = Execution( job_id=j.id, ordinal=1, phase_key="gpu", resource_pool="gpu", fence_token="test", state="running", ) s.add(e) r = await s.get(WorkflowRun, rid) await control_run(s, r, "cancel") await s.commit() async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) r = await s.get(WorkflowRun, rid) assert r.state == "cancelling" e = await s.scalar( select(Execution).join(Job, Job.id == Execution.job_id).where(Job.run_id == rid) ) e.state = "exited" await s.commit() async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) r = await s.get(WorkflowRun, rid) assert r.state == "cancelled" def test_force_script_explicit_target_survives_silent_film_closure(): m = manifest(1) m["audio"]["segments"] = [{"id": "f" * 32, "shot_id": m["shot_ids"][0], "text": ""}] recipes = build_recipes(m, {}, {"output_goal": "film", "force": ["script"]}, SimpleNamespace()) assert "script" in {r["key"] for r in recipes} assert "compose" in {r["key"] for r in recipes} def test_frame_media_target_does_not_require_any_configured_tts_voice(): m = manifest(1) m["audio"].update( mode="generated_narration", voice="", segments=[{"id": "f" * 32, "shot_id": m["shot_ids"][0], "text": "words"}], ) recipes = build_recipes( m, {}, {"output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]}, SimpleNamespace(tts_voices=()), ) assert [r["key"] for r in recipes] == ["frame_0001"] async def test_missing_tts_voice_only_blocks_speech_target_plan(system): id, m = await editor(system) m["audio"]["mode"] = "generated_narration" m["audio"]["voice"] = "" saved = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "save-voice"}, ) assert saved.status_code == 200, saved.text system.settings.tts_voices = [] body = {"expected_version": 2, "output_goal": "media", "targets": ["frame:" + m["shot_ids"][0]]} frame = await system.client.post("/api/editors/" + id + "/plan", json=body) assert frame.status_code == 200 and frame.json()["issues"] == [], frame.text body["targets"] = ["audio:" + m["audio"]["segments"][0]["id"]] speech = await system.client.post("/api/editors/" + id + "/plan", json=body) assert speech.status_code == 200, speech.text assert any(i["code"] == "speech_unavailable" for i in speech.json()["issues"]) async def test_forced_script_materializes_only_missing_segment_text(system): import json, hashlib from sqlalchemy import select from app.models import Job, Asset, WorkflowRun from app.services.orchestration.workflow_engine import advance_run id, m = await editor(system, 2) m["audio"]["segments"][0]["text"] = "manual narration" saved = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "script-source"}, ) assert saved.status_code == 200, saved.text body = { "expected_version": 2, "output_goal": "media", "targets": ["script"], "force": ["script"], } plan = await system.client.post("/api/editors/" + id + "/plan", json=body) assert plan.status_code == 200, plan.text body["expected_plan_hash"] = plan.json()["plan_hash"] started = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "script"} ) assert started.status_code == 202, started.text rid = started.json()["run"]["id"] async with system.app.state.db.session() as s: await advance_run(s, rid, system.settings) job = await s.scalar(select(Job).where(Job.run_id == rid)) assert job.task_type == "text.script.generate" result = { "segments": [{"shot_id": sid, "text": "generated narration"} for sid in m["shot_ids"]] } data = json.dumps(result).encode() path = system.settings.asset_root / "script.json" path.write_bytes(data) s.add( Asset( owner_id=job.owner_id, name="script", storage_key="script.json", kind="json", mime_type="application/json", size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), source_job_id=job.id, source_output_index=0, ) ) job.result_json = result job.state = "succeeded" await advance_run(s, rid, system.settings) await s.commit() run = await s.get(WorkflowRun, rid) assert run.state == "succeeded" assert [x["text"] for x in run.result_manifest["audio"]["segments"]] == [ "manual narration", "generated narration", ] @pytest.mark.parametrize("change", ["context", "parameters", "unavailable"]) def test_locked_binding_requires_explicit_force_when_dependency_changed(change): from copy import deepcopy m = manifest(1) key = "frame:" + m["shot_ids"][0] original = build_recipes(m, {}, {"output_goal": "media", "targets": [key]}, SimpleNamespace())[ 0 ] binding = { "asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "generated", "locked": True, "context_hash": original["context_hash"], "generation_parameters": deepcopy(original["parameters"]), } m["bindings"][key] = binding valid = build_recipes( m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() )[0] assert valid["reuse"] and not valid.get("issue") reusable = {key: binding} if change == "context": m["spec"]["shots"][0]["prompt"] = "changed visual" elif change == "parameters": binding["generation_parameters"]["guidance_scale"] = 99 else: reusable = {} blocked = build_recipes( m, reusable, {"output_goal": "media", "targets": [key]}, SimpleNamespace() )[0] assert blocked["issue"]["code"] == "locked_dependency_changed" assert blocked["issue"]["unit_id"] == m["shot_ids"][0] forced = build_recipes( m, reusable, {"output_goal": "media", "targets": [key], "force": [key]}, SimpleNamespace() )[0] assert forced["reuse"] is None and not forced.get("issue") def test_locked_issue_only_in_selected_target_ancestor_closure(): m = manifest(2) first = "frame:" + m["shot_ids"][0] m["bindings"][first] = { "asset_id": "missing", "sha256": "a" * 64, "kind": "image", "source": "manual", "locked": True, } other = build_recipes( m, {}, {"output_goal": "media", "targets": ["frame:" + m["shot_ids"][1]]}, SimpleNamespace() ) assert not any(r.get("issue") for r in other) dependent = build_recipes( m, {}, {"output_goal": "media", "targets": ["video:" + m["shot_ids"][0]]}, SimpleNamespace() ) assert any(r.get("issue", {}).get("code") == "locked_dependency_changed" for r in dependent) async def test_locked_corrupt_asset_reports_issue_and_media_run_cannot_replace_it( system, png_bytes ): from app.models import Asset id, m = await editor(system) uploaded = await system.client.post( "/api/assets", files={"file": ("locked.png", png_bytes, "image/png")} ) aid = uploaded.json()["id"] key = "frame:" + m["shot_ids"][0] m["bindings"][key] = { "asset_id": aid, "sha256": "a" * 64, "kind": "image", "source": "manual", "locked": True, } saved = await system.client.post( "/api/editors/" + id + "/save", json={"expected_version": 1, "manifest": m}, headers={"Idempotency-Key": "locked"}, ) assert saved.status_code == 200, saved.text body = {"expected_version": 2, "output_goal": "media", "targets": [key]} valid = await system.client.post("/api/editors/" + id + "/plan", json=body) assert valid.status_code == 200 and not valid.json()["issues"], valid.text async with system.app.state.db.session() as s: asset = await s.get(Asset, aid) (system.settings.asset_root / asset.storage_key).write_bytes(b"corrupt") changed = await system.client.post("/api/editors/" + id + "/plan", json=body) assert changed.status_code == 200, changed.text assert any(i["code"] == "locked_dependency_changed" for i in changed.json()["issues"]) body["expected_plan_hash"] = changed.json()["plan_hash"] started = await system.client.post( "/api/editors/" + id + "/runs", json=body, headers={"Idempotency-Key": "locked-run"} ) assert started.status_code == 422, started.text def test_locked_manual_frame_cannot_be_implicitly_normalized_for_video(): m = manifest(1) key = "frame:" + m["shot_ids"][0] binding = { "asset_id": "f", "sha256": "a" * 64, "kind": "image", "source": "manual", "locked": True, "_width": 16, "_height": 12, } m["bindings"][key] = {k: v for k, v in binding.items() if not k.startswith("_")} direct = build_recipes( m, {key: binding}, {"output_goal": "media", "targets": [key]}, SimpleNamespace() ) assert direct[0]["reuse"] and not direct[0].get("issue") dependent = build_recipes( m, {key: binding}, {"output_goal": "media", "targets": ["video:" + m["shot_ids"][0]]}, SimpleNamespace(), ) assert dependent[0]["issue"]["code"] == "locked_dependency_changed"