Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
724 lines
28 KiB
Python
724 lines
28 KiB
Python
"""独立审查的可复现回归:引用生命周期、真实模型输入和共享接纳预算。"""
|
||
|
||
import copy
|
||
|
||
import httpx
|
||
import pytest
|
||
from sqlalchemy import select, func
|
||
|
||
from test_story_studio import prepare_manual_frame, story_spec
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_removed_shot_releases_selection_refs_without_losing_audit_or_other_refs(
|
||
system, monkeypatch
|
||
):
|
||
from app.models import AssetReference, ShotCandidate, ShotSelection, WorkflowDraft
|
||
|
||
spec = story_spec()
|
||
spec["shots"].append({"id": "2" * 32, "visual_prompt": "A river"})
|
||
c = system.client
|
||
d = (await c.post("/api/stories", json={"name": "Remove selected shot", "spec": spec})).json()
|
||
d, candidate, _ = await prepare_manual_frame(system, monkeypatch, d)
|
||
path = f"/api/stories/{d['id']}"
|
||
selected = await c.post(
|
||
path + "/selections",
|
||
headers={"Idempotency-Key": "select"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_id": "1" * 32,
|
||
"kind": "frame",
|
||
"candidate_id": candidate["id"],
|
||
},
|
||
)
|
||
assert selected.status_code == 200, selected.text
|
||
chosen = selected.json()["selections"][0]
|
||
actor = (await c.get("/api/auth/me")).json()["user"]["id"]
|
||
async with system.app.state.db.session() as s:
|
||
# 独立引用只用于断言PATCH不能笼统释放同素材的Run/候选/其他镜头保护。
|
||
for kind, id in (("run", "historical-run"), ("selection", "other-shot-selection")):
|
||
s.add(
|
||
AssetReference(
|
||
owner_id=actor, asset_id=candidate["asset"]["id"], ref_kind=kind, ref_id=id
|
||
)
|
||
)
|
||
await s.commit()
|
||
changed = copy.deepcopy(selected.json()["spec"])
|
||
changed["shots"].pop(0)
|
||
changed["render"]["total_frames"] = 120
|
||
patched = await c.patch(path, headers={"If-Match": "2"}, json={"spec": changed})
|
||
assert patched.status_code == 200, patched.text
|
||
# 即使客户端随后显式重加同一个稳定ID,也只能看见新的空选择,不能恢复旧审批。
|
||
restored = await c.patch(
|
||
path, headers={"If-Match": "3"}, json={"spec": selected.json()["spec"]}
|
||
)
|
||
assert restored.status_code == 200, restored.text
|
||
cleared = next(
|
||
x
|
||
for x in restored.json()["selections"]
|
||
if x["shot_id"] == "1" * 32 and x["kind"] == "frame"
|
||
)
|
||
assert cleared["candidate_id"] is None and cleared["asset"] is None
|
||
assert cleared["version"] == chosen["version"] + 1 and cleared["id"] != chosen["id"]
|
||
await system.app.state.coordinator.run_once()
|
||
assert (
|
||
next(x for x in (await c.get(path)).json()["selections"] if x["shot_id"] == "1" * 32)[
|
||
"candidate_id"
|
||
]
|
||
is None
|
||
)
|
||
removed_again = await c.patch(path, headers={"If-Match": "4"}, json={"spec": changed})
|
||
assert removed_again.status_code == 200
|
||
async with system.app.state.db.session() as s:
|
||
refs = (
|
||
await s.execute(
|
||
select(AssetReference.ref_kind, AssetReference.ref_id).where(
|
||
AssetReference.asset_id == candidate["asset"]["id"]
|
||
)
|
||
)
|
||
).all()
|
||
assert ("selection", chosen["id"]) not in refs
|
||
assert ("candidate", candidate["id"]) in refs
|
||
assert ("run", "historical-run") in refs
|
||
assert ("selection", "other-shot-selection") in refs
|
||
approval = await s.get(ShotSelection, chosen["id"])
|
||
assert (
|
||
approval.candidate_id == candidate["id"]
|
||
and approval.asset_id == candidate["asset"]["id"]
|
||
)
|
||
history = (
|
||
await s.scalars(
|
||
select(ShotSelection)
|
||
.where(
|
||
ShotSelection.draft_id == d["id"],
|
||
ShotSelection.shot_id == "1" * 32,
|
||
ShotSelection.kind == "frame",
|
||
)
|
||
.order_by(ShotSelection.version)
|
||
)
|
||
).all()
|
||
assert len(history) == 2 and history[-1].candidate_id is None
|
||
assert history[-1].decision_json["clear_reason"] == "shot_removed"
|
||
assert (await s.get(ShotCandidate, candidate["id"])).deleted_at is None
|
||
# 只撤掉本测试模拟的独立消费者,确认真实孤立产物此后可以释放。
|
||
from sqlalchemy import delete
|
||
|
||
await s.execute(
|
||
delete(AssetReference).where(
|
||
AssetReference.ref_id.in_(["historical-run", "other-shot-selection"])
|
||
)
|
||
)
|
||
await s.commit()
|
||
deleted = await c.delete(
|
||
path + "/candidates/" + candidate["id"], headers={"If-Match": str(candidate["version"])}
|
||
)
|
||
assert deleted.status_code == 200, deleted.text
|
||
assert (await c.delete("/api/assets/" + candidate["asset"]["id"])).status_code == 204
|
||
# 已完成旧Job的再次协调也不能恢复被删镜头或可信选择。
|
||
await system.app.state.coordinator.run_once()
|
||
current = (await c.get(path)).json()
|
||
assert [x["id"] for x in current["spec"]["shots"]] == ["2" * 32]
|
||
async with system.app.state.db.session() as s:
|
||
assert len((await s.get(WorkflowDraft, d["id"])).spec["shots"]) == 1
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize("distinct", [False, True])
|
||
async def test_reference_roles_preserved_but_model_inputs_are_ordered_unique(
|
||
system, png_bytes, monkeypatch, distinct
|
||
):
|
||
from app.models import ShotCandidate
|
||
from unittest.mock import AsyncMock
|
||
|
||
c = system.client
|
||
assets = [
|
||
(
|
||
await c.post("/api/assets", files={"file": (f"ref-{i}.png", png_bytes, "image/png")})
|
||
).json()["id"]
|
||
for i in range(3)
|
||
]
|
||
a, b, z = assets if distinct else [assets[0]] * 3
|
||
spec = story_spec()
|
||
spec["scenes"] = [{"id": "2" * 32, "reference_asset_ids": [a]}]
|
||
spec["entities"] = [
|
||
{
|
||
"id": "3" * 32,
|
||
"reference_asset_ids": [a, b] if distinct else [a],
|
||
"forms": [{"id": "4" * 32, "reference_asset_ids": [a]}],
|
||
"appearances": [
|
||
{"id": "5" * 32, "reference_asset_ids": [b, z, a] if distinct else [a]}
|
||
],
|
||
}
|
||
]
|
||
spec["shots"][0].update(
|
||
scene_id="2" * 32,
|
||
cast=[
|
||
{"id": "6" * 32, "entity_id": "3" * 32, "form_id": "4" * 32, "appearance_id": "5" * 32}
|
||
],
|
||
)
|
||
d = (await c.post("/api/stories", json={"name": "Reference roles", "spec": spec})).json()
|
||
path = f"/api/stories/{d['id']}"
|
||
preview = (await c.get(path + "/preview")).json()["shots"][0]
|
||
roles = preview["references"]
|
||
assert len(roles) == (7 if distinct else 4)
|
||
assert {x["role"] for x in roles} == {"scene", "entity", "form", "appearance"}
|
||
maximum = 3 if distinct else 1
|
||
system.settings.reference_generation_enabled = True
|
||
system.settings.reference_max_images = maximum
|
||
monkeypatch.setattr(
|
||
system.provider,
|
||
"upstream_capabilities",
|
||
AsyncMock(
|
||
return_value={
|
||
"reference_generation": {
|
||
"available": True,
|
||
"profile": system.settings.reference_generation_profile,
|
||
"max_reference_images": maximum,
|
||
}
|
||
}
|
||
),
|
||
raising=False,
|
||
)
|
||
response = await c.post(
|
||
path + "/candidates",
|
||
headers={"Idempotency-Key": "reference"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_id": "1" * 32,
|
||
"kind": "frame",
|
||
"reference_mode": "reference",
|
||
},
|
||
)
|
||
assert response.status_code == 202, response.text
|
||
candidate = response.json()["candidates"][0]
|
||
expected = [a, b, z] if distinct else [a]
|
||
assert candidate["input_summary"]["actual_reference_asset_ids"] == expected
|
||
async with system.app.state.db.session() as s:
|
||
plan = (await s.get(ShotCandidate, candidate["id"])).plan_json
|
||
assert plan["input"]["reference_asset_ids"] == expected
|
||
assert plan["input_snapshot"]["actual_image_refs"] == expected
|
||
assert plan["references"] == roles
|
||
assert candidate["context_hash"] == preview["context_hash"]
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_workflow_machine_scopes_cover_story_commands_and_recovery(system):
|
||
c = system.client
|
||
made = await c.post(
|
||
"/api/auth/tokens",
|
||
json={
|
||
"name": "Story machine",
|
||
"scopes": ["workflows:read", "workflows:write", "interactive:write"],
|
||
},
|
||
)
|
||
assert made.status_code == 201
|
||
async with httpx.AsyncClient(
|
||
transport=httpx.ASGITransport(app=system.app),
|
||
base_url="http://test",
|
||
headers={"Authorization": "Bearer " + made.json()["token"]},
|
||
) as machine:
|
||
assert (await machine.get("/api/stories/capabilities")).status_code == 200
|
||
created = await machine.post(
|
||
"/api/stories", json={"name": "Machine story", "spec": story_spec()}
|
||
)
|
||
assert created.status_code == 201, created.text
|
||
d = created.json()
|
||
assert (await machine.get("/api/stories")).json()["total"] == 1
|
||
path = f"/api/stories/{d['id']}"
|
||
accepted = await machine.post(
|
||
path + "/candidates",
|
||
headers={"Idempotency-Key": "machine-candidate"},
|
||
json={"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"},
|
||
)
|
||
assert accepted.status_code == 202, accepted.text
|
||
recovered = await machine.get(
|
||
"/api/submissions/machine-candidate?operation=story.candidate.create"
|
||
)
|
||
assert recovered.status_code == 200, recovered.text
|
||
assert recovered.json()["candidate_ids"] == [accepted.json()["candidates"][0]["id"]]
|
||
assert (await machine.get("/api/jobs")).status_code == 403
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_candidate_commands_share_creation_rate_and_replay_does_not_charge(system):
|
||
from app.models import QuotaReservation, ShotCandidate
|
||
from app.services.orchestration.workflow_engine import advance_workflows
|
||
|
||
c = system.client
|
||
d = (await c.post("/api/stories", json={"name": "Rate", "spec": story_spec()})).json()
|
||
path = f"/api/stories/{d['id']}"
|
||
body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "count": 4}
|
||
system.settings.max_creation_commands_per_minute = 1
|
||
first = await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-one"}, json=body)
|
||
assert first.status_code == 202, first.text
|
||
assert (
|
||
await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-one"}, json=body)
|
||
).json() == first.json()
|
||
blocked = await c.post(path + "/candidates", headers={"Idempotency-Key": "rate-two"}, json=body)
|
||
assert blocked.status_code == 429, blocked.text
|
||
assert (
|
||
await c.post(
|
||
"/api/jobs",
|
||
headers={"Idempotency-Key": "legacy-next"},
|
||
json={"task_type": "math.solve", "input": {"prompt": "2+2"}},
|
||
)
|
||
).status_code == 429
|
||
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(ShotCandidate)) == 4
|
||
assert (
|
||
await s.scalar(
|
||
select(func.count())
|
||
.select_from(QuotaReservation)
|
||
.where(QuotaReservation.operation.like("story.%"))
|
||
)
|
||
== 1
|
||
)
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize("kind", ["single", "batch"])
|
||
async def test_candidate_plans_cannot_bypass_parent_or_leaf_capacity(system, kind):
|
||
from app.models import ShotCandidate
|
||
|
||
c = system.client
|
||
d = (await c.post("/api/stories", json={"name": "Bounded", "spec": story_spec()})).json()
|
||
path = f"/api/stories/{d['id']}" + ("/candidates" if kind == "single" else "/candidate-batches")
|
||
body = {"expected_version": 1, "kind": "frame", "count": 2}
|
||
body.update(
|
||
{"shot_id": "1" * 32}
|
||
if kind == "single"
|
||
else {"shot_ids": ["1" * 32], "execution_mode": "batch"}
|
||
)
|
||
system.settings.max_owner_batches = 1
|
||
system.settings.max_owner_jobs = 1
|
||
system.settings.max_owner_story_candidates = 3
|
||
first = await c.post(path, headers={"Idempotency-Key": "plan-one"}, json=body)
|
||
assert first.status_code == 202, first.text
|
||
second = await c.post(path, headers={"Idempotency-Key": "plan-two"}, json=body)
|
||
assert second.status_code == 429, second.text
|
||
system.settings.max_owner_batches = 10
|
||
leaf_limited = await c.post(path, headers={"Idempotency-Key": "plan-three"}, json=body)
|
||
assert leaf_limited.status_code == 429, leaf_limited.text
|
||
assert (
|
||
await c.post(path, headers={"Idempotency-Key": "plan-one"}, json=body)
|
||
).status_code == 202
|
||
async with system.app.state.db.session() as s:
|
||
assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 2
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_running_candidate_batch_progress_changes_version_and_emits_event(system):
|
||
from app.models import BatchItem, Event, ShotCandidate
|
||
from app.services.orchestration.workflow_engine import advance_workflows
|
||
from app.services.stories.candidates import advance_candidate_batches
|
||
|
||
c = system.client
|
||
d = (await c.post("/api/stories", json={"name": "Progress", "spec": story_spec()})).json()
|
||
response = await c.post(
|
||
f"/api/stories/{d['id']}/candidate-batches",
|
||
headers={"Idempotency-Key": "progress"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_ids": ["1" * 32],
|
||
"kind": "frame",
|
||
"count": 2,
|
||
"execution_mode": "batch",
|
||
},
|
||
)
|
||
assert response.status_code == 202
|
||
bid = response.json()["batch_id"]
|
||
await advance_workflows(system.app.state.db, system.settings, system.provider)
|
||
before = (await c.get("/api/batches/" + bid)).json()["batch"]
|
||
assert before["state"] == "running" and before["completed_items"] == 0
|
||
async with system.app.state.db.session() as s:
|
||
rows = (
|
||
await s.scalars(
|
||
select(ShotCandidate)
|
||
.where(ShotCandidate.batch_id == bid)
|
||
.order_by(ShotCandidate.id)
|
||
)
|
||
).all()
|
||
rows[0].state, rows[1].state = "ready", "running"
|
||
assert (
|
||
await s.scalar(select(BatchItem).where(BatchItem.target_id == rows[0].id))
|
||
).state != "succeeded"
|
||
old_event = await s.scalar(select(func.max(Event.id)))
|
||
await advance_candidate_batches(s, system.settings)
|
||
await s.commit()
|
||
emitted = (
|
||
await s.scalars(
|
||
select(Event).where(Event.id > old_event, Event.event_type == "batch.updated")
|
||
)
|
||
).all()
|
||
after = (await c.get("/api/batches/" + bid)).json()["batch"]
|
||
assert after["state"] == "running" and after["completed_items"] == 1
|
||
assert after["version"] > before["version"]
|
||
assert len(emitted) == 1 and emitted[0].data["batch"]["completed_items"] == 1
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize("operation", ["single", "batch", "retry", "render"])
|
||
async def test_story_creation_zero_rate_rejects_new_intents_and_keeps_no_partial_records(
|
||
system, operation
|
||
):
|
||
from app.models import ShotCandidate, QuotaReservation
|
||
|
||
c = system.client
|
||
d = (await c.post("/api/stories", json={"name": "Zero budget", "spec": story_spec()})).json()
|
||
path = f"/api/stories/{d['id']}"
|
||
body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame"}
|
||
route = path + "/candidates"
|
||
previous = 0
|
||
if operation == "retry":
|
||
accepted = await c.post(route, headers={"Idempotency-Key": "original"}, json=body)
|
||
assert accepted.status_code == 202
|
||
cid = accepted.json()["candidates"][0]["id"]
|
||
async with system.app.state.db.session() as s:
|
||
(await s.get(ShotCandidate, cid)).state = "failed"
|
||
await s.commit()
|
||
route, body, previous = route + "/" + cid + "/retry", {"expected_version": 1}, 1
|
||
elif operation == "batch":
|
||
route, body = (
|
||
path + "/candidate-batches",
|
||
{"expected_version": 1, "shot_ids": ["1" * 32], "kind": "frame"},
|
||
)
|
||
elif operation == "render":
|
||
route, body = path + "/renders", {"expected_version": 1, "execution_mode": "interactive"}
|
||
system.settings.max_creation_commands_per_minute = 0
|
||
rejected = await c.post(route, headers={"Idempotency-Key": "zero"}, json=body)
|
||
assert rejected.status_code == 429, rejected.text
|
||
async with system.app.state.db.session() as s:
|
||
assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == previous
|
||
assert (
|
||
await s.scalar(
|
||
select(func.count())
|
||
.select_from(QuotaReservation)
|
||
.where(QuotaReservation.operation.like("story.%"))
|
||
)
|
||
== previous
|
||
)
|
||
|
||
|
||
def test_story_candidate_settings_limits_are_independent_and_environment_configurable(
|
||
monkeypatch, tmp_path
|
||
):
|
||
from app.core.config import Settings
|
||
|
||
monkeypatch.setenv("CMVR_MODE", "test")
|
||
monkeypatch.setenv("DATABASE_URL", "sqlite+aiosqlite:///:memory:")
|
||
monkeypatch.setenv("WORKSPACE_ROOT", str(tmp_path))
|
||
monkeypatch.setenv("MAX_OWNER_STORY_CANDIDATES", "4200")
|
||
monkeypatch.setenv("MAX_GLOBAL_STORY_CANDIDATES", "17000")
|
||
settings = Settings.from_env()
|
||
assert settings.max_owner_story_candidates == 4200
|
||
assert settings.max_global_story_candidates == 17000
|
||
assert (
|
||
Settings(
|
||
mode="test", database_url="sqlite+aiosqlite:///:memory:", workspace_root=tmp_path
|
||
).max_owner_story_candidates
|
||
== 4000
|
||
)
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize("shot_count", [126, 1000])
|
||
async def test_large_candidate_plan_is_accepted_before_any_jobs_despite_active_job_limit(
|
||
system, monkeypatch, shot_count
|
||
):
|
||
from app.models import Job, ShotCandidate
|
||
|
||
monkeypatch.setattr(
|
||
"app.services.stories.common.read_runtime_policy",
|
||
lambda settings: {"configuration_error": None, "workflow_max_shots": 1000},
|
||
)
|
||
system.settings.max_owner_jobs = 1
|
||
system.settings.max_owner_batches = 1
|
||
spec = {
|
||
"schema_version": 3,
|
||
"shots": [{"id": f"{i:032x}", "visual_prompt": "A tree"} for i in range(1, shot_count + 1)],
|
||
}
|
||
c = system.client
|
||
created = await c.post("/api/stories", json={"name": "Large plan", "spec": spec})
|
||
assert created.status_code == 201, created.text
|
||
d = created.json()
|
||
response = await c.post(
|
||
f"/api/stories/{d['id']}/candidate-batches",
|
||
headers={"Idempotency-Key": "large-plan"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_ids": [s["id"] for s in spec["shots"]],
|
||
"kind": "frame",
|
||
"count": 4,
|
||
"execution_mode": "batch",
|
||
},
|
||
)
|
||
assert response.status_code == 202, response.text
|
||
assert len(response.json()["candidates"]) == shot_count * 4
|
||
async with system.app.state.db.session() as s:
|
||
assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == shot_count * 4
|
||
assert await s.scalar(select(func.count()).select_from(Job)) == 0
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize(
|
||
"visual_prompt,source_seconds,source_frames,duration_frames",
|
||
[("A tree", 5, 48, 24), ("", 5, 48, 24), ("A tree", 1, 360, 240), ("A tree", 5, 360, 240)],
|
||
)
|
||
async def test_manual_video_only_can_confirm_and_render_without_unused_frame_dependencies(
|
||
system, monkeypatch, visual_prompt, source_seconds, source_frames, duration_frames
|
||
):
|
||
import asyncio
|
||
import shutil
|
||
from app.adapters.media import run_process
|
||
from app.adapters.provider.client import Provider
|
||
from app.models import ShotSelection
|
||
|
||
if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
|
||
pytest.skip("FFmpeg and ffprobe required for manual video composition")
|
||
system.settings.ffmpeg_bin, system.settings.ffprobe_bin = (
|
||
shutil.which("ffmpeg"),
|
||
shutil.which("ffprobe"),
|
||
)
|
||
c = system.client
|
||
spec = story_spec()
|
||
spec["shots"][0]["visual_prompt"] = visual_prompt
|
||
spec["shots"][0]["video_parameters"] = {"source_seconds": source_seconds}
|
||
spec["shots"][0]["edit"] = {"start_frame": 24, "duration_frames": duration_frames}
|
||
created = await c.post("/api/stories", json={"name": "Manual video only", "spec": spec})
|
||
assert created.status_code == 201, created.text
|
||
d = created.json()
|
||
path = f"/api/stories/{d['id']}"
|
||
source = system.settings.workspace_root / "manual-only.mp4"
|
||
await run_process(
|
||
[
|
||
system.settings.ffmpeg_bin,
|
||
"-v",
|
||
"error",
|
||
"-f",
|
||
"lavfi",
|
||
"-i",
|
||
"color=c=green:s=256x256:r=24",
|
||
"-frames:v",
|
||
str(source_frames),
|
||
"-c:v",
|
||
"libx264",
|
||
"-pix_fmt",
|
||
"yuv420p",
|
||
str(source),
|
||
]
|
||
)
|
||
uploaded = await c.post(
|
||
"/api/assets", files={"file": ("manual.mp4", source.read_bytes(), "video/mp4")}
|
||
)
|
||
assert uploaded.status_code == 201, uploaded.text
|
||
accepted = await c.post(
|
||
path + "/candidates",
|
||
headers={"Idempotency-Key": "manual-video"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_id": "1" * 32,
|
||
"kind": "video",
|
||
"source_kind": "manual",
|
||
"asset_id": uploaded.json()["id"],
|
||
},
|
||
)
|
||
assert accepted.status_code == 202, accepted.text
|
||
candidate = accepted.json()["candidates"][0]
|
||
confirmed = await c.post(
|
||
path + "/selections",
|
||
headers={"Idempotency-Key": "select-video"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_id": "1" * 32,
|
||
"kind": "video",
|
||
"candidate_id": candidate["id"],
|
||
},
|
||
)
|
||
assert confirmed.status_code == 200, confirmed.text
|
||
assert confirmed.json()["readiness"]["ready"], confirmed.json()["readiness"]
|
||
async with system.app.state.db.session() as s:
|
||
assert not await s.scalar(
|
||
select(ShotSelection.id).where(
|
||
ShotSelection.draft_id == d["id"], ShotSelection.kind == "frame"
|
||
)
|
||
)
|
||
# 人工片未使用Wan源长度/seed;修改这些参数或清除无关首帧不应使其过期。
|
||
changed = confirmed.json()["spec"]
|
||
changed["shots"][0]["video_parameters"].update(source_seconds=15, seed=987)
|
||
patched = await c.patch(path, headers={"If-Match": "2"}, json={"spec": changed})
|
||
assert patched.status_code == 200 and patched.json()["readiness"]["ready"]
|
||
cleared = await c.post(
|
||
path + "/selections/clear",
|
||
headers={"Idempotency-Key": "unused-frame"},
|
||
json={"expected_version": 3, "shot_id": "1" * 32, "kind": "frame"},
|
||
)
|
||
assert cleared.status_code == 200 and cleared.json()["readiness"]["ready"]
|
||
after = (await c.get(path + "/candidates")).json()["items"][0]
|
||
assert not after["stale"] and after["context_hash"] == candidate["context_hash"]
|
||
rendered = await c.post(
|
||
path + "/renders",
|
||
headers={"Idempotency-Key": "render-manual"},
|
||
json={"expected_version": 4, "execution_mode": "interactive"},
|
||
)
|
||
assert rendered.status_code == 202, rendered.text
|
||
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)
|
||
run = (await c.get("/api/workflow-runs/" + rendered.json()["run"]["id"])).json()["run"]
|
||
assert run["state"] == "succeeded" and run["result_assets"], run
|
||
changed["shots"][0]["motion_prompt"] = "Different action"
|
||
stale = await c.patch(path, headers={"If-Match": "5"}, json={"spec": changed})
|
||
assert stale.status_code == 200
|
||
video_selection = next(x for x in stale.json()["selections"] if x["kind"] == "video")
|
||
assert video_selection["stale"]
|
||
finally:
|
||
await real.aclose()
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_generated_video_readiness_keeps_approved_frame_dependency():
|
||
from types import SimpleNamespace
|
||
from app.domain.stories import StorySpecV3, compile_story
|
||
from app.models import Asset, ShotSelection
|
||
from app.services.stories.common import current_hash, readiness
|
||
|
||
parsed = StorySpecV3.model_validate(story_spec())
|
||
d = SimpleNamespace(id="story", owner_id="owner", spec=parsed.model_dump(mode="json"))
|
||
compiled = compile_story(parsed, {})
|
||
assets = {
|
||
"frame": Asset(
|
||
id="frame",
|
||
owner_id="owner",
|
||
kind="image",
|
||
name="Frame",
|
||
mime_type="image/png",
|
||
size_bytes=1,
|
||
sha256="a" * 64,
|
||
ready=True,
|
||
),
|
||
"video": Asset(
|
||
id="video",
|
||
owner_id="owner",
|
||
kind="video",
|
||
name="Video",
|
||
mime_type="video/mp4",
|
||
size_bytes=1,
|
||
sha256="b" * 64,
|
||
duration_seconds=5,
|
||
ready=True,
|
||
),
|
||
}
|
||
|
||
async def get(model, id):
|
||
return assets[id]
|
||
|
||
s = SimpleNamespace(get=get)
|
||
frame = ShotSelection(
|
||
id="sf",
|
||
draft_id=d.id,
|
||
shot_id="1" * 32,
|
||
kind="frame",
|
||
candidate_id="cf",
|
||
asset_id="frame",
|
||
context_hash=compiled["shots"][0]["context_hash"],
|
||
decision_json={"asset_sha256": "a" * 64},
|
||
version=1,
|
||
)
|
||
latest = {("1" * 32, "frame"): frame}
|
||
video_hash = await current_hash(s, d, "1" * 32, "video", compiled, latest)
|
||
latest[("1" * 32, "video")] = ShotSelection(
|
||
id="sv",
|
||
draft_id=d.id,
|
||
shot_id="1" * 32,
|
||
kind="video",
|
||
candidate_id="cv",
|
||
asset_id="video",
|
||
context_hash=video_hash,
|
||
decision_json={"asset_sha256": "b" * 64, "source_kind": "generated"},
|
||
version=1,
|
||
)
|
||
assert (await readiness(s, d, compiled, latest))["ready"]
|
||
without_frame = {key: value for key, value in latest.items() if key[1] != "frame"}
|
||
unavailable = await readiness(s, d, compiled, without_frame)
|
||
assert not unavailable["ready"]
|
||
assert {issue["code"] for issue in unavailable["issues"]} == {
|
||
"frame_selection_required",
|
||
"video_selection_stale",
|
||
}
|
||
d.spec["shots"][0]["video_parameters"]["source_seconds"] = 15
|
||
assert await current_hash(s, d, "1" * 32, "video", compiled, latest) != video_hash
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
async def test_global_standalone_parent_and_pending_candidate_limits_include_other_owners(
|
||
system, other_client
|
||
):
|
||
c = system.client
|
||
system.settings.max_global_batches = 1
|
||
system.settings.max_global_story_candidates = 3
|
||
stories = []
|
||
for client in (c, other_client):
|
||
response = await client.post("/api/stories", json={"name": "Private", "spec": story_spec()})
|
||
assert response.status_code == 201
|
||
stories.append(response.json())
|
||
body = {"expected_version": 1, "shot_id": "1" * 32, "kind": "frame", "count": 2}
|
||
first = await c.post(
|
||
f"/api/stories/{stories[0]['id']}/candidates",
|
||
headers={"Idempotency-Key": "first"},
|
||
json=body,
|
||
)
|
||
assert first.status_code == 202
|
||
second_path = f"/api/stories/{stories[1]['id']}/candidates"
|
||
assert (
|
||
await other_client.post(
|
||
second_path, headers={"Idempotency-Key": "global-parent"}, json=body
|
||
)
|
||
).status_code == 429
|
||
system.settings.max_global_batches = 20
|
||
assert (
|
||
await other_client.post(
|
||
second_path, headers={"Idempotency-Key": "global-pending"}, json=body
|
||
)
|
||
).status_code == 429
|
||
|
||
|
||
@pytest.mark.asyncio
|
||
@pytest.mark.parametrize("source_seconds", [1, 5])
|
||
async def test_generated_video_range_exceeding_generation_source_is_rejected_before_dispatch(
|
||
system, source_seconds
|
||
):
|
||
from app.models import Job, ShotCandidate
|
||
|
||
spec = story_spec()
|
||
spec["shots"][0].update(
|
||
video_parameters={"source_seconds": source_seconds},
|
||
edit={"start_frame": 24, "duration_frames": 240},
|
||
)
|
||
c = system.client
|
||
created = await c.post("/api/stories", json={"name": "Independent trim", "spec": spec})
|
||
assert created.status_code == 201, created.text
|
||
d = created.json()
|
||
response = await c.post(
|
||
f"/api/stories/{d['id']}/candidates",
|
||
headers={"Idempotency-Key": "too-short"},
|
||
json={
|
||
"expected_version": 1,
|
||
"shot_id": "1" * 32,
|
||
"kind": "video",
|
||
"source_kind": "generated",
|
||
},
|
||
)
|
||
assert (
|
||
response.status_code == 422
|
||
and response.json()["detail"]["code"] == "generation_source_too_short"
|
||
), response.text
|
||
async with system.app.state.db.session() as s:
|
||
assert await s.scalar(select(func.count()).select_from(ShotCandidate)) == 0
|
||
assert await s.scalar(select(func.count()).select_from(Job)) == 0
|