cmvr-visual/backend/tests/test_workflow_review_repairs.py

449 lines
17 KiB
Python
Raw Normal View History

"""Regression tests for independent workflow orchestration review findings."""
import httpx
import pytest
from sqlalchemy import select
from app.models import Asset, Job
from app.models import ApiToken, Batch, WorkflowRun, WorkflowStep
from test_workflows_v2 import wf, draft, run, publish_video
async def tick(wf):
from app.services.orchestration.workflow_engine import advance_workflows
await advance_workflows(wf.app.state.db, wf.settings, wf.provider)
async def workflow_batch(wf, key="batch", extra=()):
d = await draft(wf)
response = await wf.client.post(
"/api/batches",
json={
"items": [
{
"kind": "workflow",
"draft_id": d["id"],
"draft_revision": d["revision"],
"expected_version": d["version"],
},
*extra,
]
},
headers={"Idempotency-Key": key},
)
assert response.status_code == 202, response.text
return response.json()
@pytest.mark.asyncio
async def test_batch_cancel_before_children_reconciles_to_terminal(wf):
batch = await workflow_batch(wf)
response = await wf.client.post(
"/api/batches/" + batch["batch"]["id"] + "/control",
json={"desired_state": "cancel"},
headers={"Idempotency-Key": "cancel"},
)
assert response.status_code == 200
await tick(wf)
result = (await wf.client.get("/api/batches/" + batch["batch"]["id"])).json()
assert result["batch"]["state"] == "cancelled"
assert result["items"][0]["state"] == "cancelled"
@pytest.mark.asyncio
async def test_held_batch_reconciles_finished_compose_without_new_admission(wf):
batch = await workflow_batch(wf)
rid = batch["items"][0]["target_id"]
for _ in range(3):
await tick(wf)
async with wf.app.state.db.session() as s:
selected = await s.scalar(
select(Job.id).where(Job.run_id == rid, Job.state != "succeeded")
)
await publish_video(wf, selected)
await tick(wf)
async with wf.app.state.db.session() as s:
compose = await s.scalar(select(Job.id).where(Job.run_id == rid, Job.step_key == "compose"))
b = await s.get(Batch, batch["batch"]["id"])
b.desired_state = "pause"
b.hold_reasons = ["admin_suspend"]
await s.commit()
await publish_video(wf, compose, compose=True)
await tick(wf)
result = (await wf.client.get("/api/workflow-runs/" + rid)).json()
assert result["run"]["state"] == "succeeded"
assert len(result["jobs"]) == 4
@pytest.mark.asyncio
async def test_retry_inherits_pause_manual_and_admin_holds(wf):
snap = await run(wf, await draft(wf))
rid = snap["run"]["id"]
await tick(wf)
async with wf.app.state.db.session() as s:
job = await s.scalar(select(Job).where(Job.run_id == rid))
job.state = "failed"
jid = job.id
await s.commit()
await wf.client.post(
"/api/workflow-runs/" + rid + "/pause", json={}, headers={"Idempotency-Key": "pause"}
)
async with wf.app.state.db.session() as s:
r = await s.get(WorkflowRun, rid)
r.hold_reasons = ["manual", "admin_suspend"]
await s.commit()
snap = (await wf.client.get("/api/workflow-runs/" + rid)).json()
response = await wf.client.post(
f"/api/workflow-runs/{rid}/steps/shot_1/retry",
json={"expected_run_version": snap["run"]["version"], "target_job_id": jid},
headers={"Idempotency-Key": "retry"},
)
assert response.status_code == 202, response.text
async with wf.app.state.db.session() as s:
new = await s.get(
Job,
next(
x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1"
),
)
assert new.desired_state == "pause"
assert {"manual", "admin_suspend"} <= set(new.hold_reasons)
@pytest.mark.asyncio
async def test_retry_old_batch_member_can_coexist_with_later_member(wf):
batch = await workflow_batch(
wf, extra=[{"kind": "job", "task_type": "image.generate", "input": {"prompt": "later"}}]
)
rid = batch["items"][0]["target_id"]
later_id = batch["items"][1]["target_id"]
await tick(wf)
async with wf.app.state.db.session() as s:
job = await s.scalar(select(Job).where(Job.run_id == rid))
job.state = "failed"
jid = job.id
await s.commit()
await tick(wf)
snap = (await wf.client.get("/api/workflow-runs/" + rid)).json()
response = await wf.client.post(
f"/api/workflow-runs/{rid}/steps/shot_1/retry",
json={"expected_run_version": snap["run"]["version"], "target_job_id": jid},
headers={"Idempotency-Key": "retry"},
)
assert response.status_code == 202, response.text
new_id = next(
x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1"
)
for _ in range(2):
await tick(wf)
async with wf.app.state.db.session() as s:
assert "batch_wait" not in (await s.get(Job, new_id)).hold_reasons
assert "batch_wait" not in (await s.get(Job, later_id)).hold_reasons
async with wf.app.state.db.session() as s:
later = await s.get(Job, later_id)
later.state = "succeeded"
await s.commit()
await tick(wf)
async with wf.app.state.db.session() as s:
assert "batch_wait" not in (await s.get(Job, new_id)).hold_reasons
@pytest.mark.asyncio
async def test_two_accepted_batches_preserve_first_child_and_retry_quota_hold(wf):
wf.settings.max_owner_jobs = 1
one = await workflow_batch(wf, "one")
two = await workflow_batch(wf, "two")
await tick(wf)
async with wf.app.state.db.session() as s:
jobs = (await s.scalars(select(Job))).all()
assert len(jobs) == 1
held = await s.get(WorkflowRun, two["items"][0]["target_id"])
assert "quota" in held.hold_reasons and held.error_json["code"] == "quota_exceeded"
jobs[0].state = "failed"
await s.commit()
await tick(wf)
async with wf.app.state.db.session() as s:
assert await s.scalar(select(Job.id).where(Job.run_id == two["items"][0]["target_id"]))
assert "quota" in (await s.get(WorkflowRun, two["items"][0]["target_id"])).hold_reasons
admitted = await s.scalar(select(Job).where(Job.run_id == two["items"][0]["target_id"]))
assert "quota" not in admitted.hold_reasons
@pytest.mark.asyncio
async def test_retry_coexists_with_active_sibling_when_representative_finished(wf):
batch = await workflow_batch(
wf,
extra=[
{"kind": "job", "task_type": "image.generate", "input": {"prompt": "pair"}, "count": 2}
],
)
rid = batch["items"][0]["target_id"]
bid = batch["batch"]["id"]
await tick(wf)
async with wf.app.state.db.session() as s:
first = await s.scalar(select(Job).where(Job.run_id == rid))
first.state = "failed"
jid = first.id
representative = await s.get(Job, batch["items"][1]["target_id"])
representative.state = "cancelled"
await s.commit()
await tick(wf)
snap = (await wf.client.get("/api/workflow-runs/" + rid)).json()
response = await wf.client.post(
f"/api/workflow-runs/{rid}/steps/shot_1/retry",
json={"expected_run_version": snap["run"]["version"], "target_job_id": jid},
headers={"Idempotency-Key": "retry"},
)
assert response.status_code == 202, response.text
retried = next(
x["selected_job_id"] for x in response.json()["steps"] if x["step_key"] == "shot_1"
)
await tick(wf)
async with wf.app.state.db.session() as s:
assert "batch_wait" not in (await s.get(Job, retried)).hold_reasons
sibling = await s.scalar(
select(Job).where(
Job.batch_id == bid, Job.batch_item_index == 1, Job.state != "cancelled"
)
)
assert "batch_wait" not in sibling.hold_reasons
@pytest.mark.asyncio
async def test_storage_admission_failure_isolated_and_retried(wf, monkeypatch):
from app.services import workflows
from app.core.errors import fail
first = await workflow_batch(wf, "one")
second = await workflow_batch(wf, "two")
original = workflows.create_jobs
held_owner_run = first["items"][0]["target_id"]
calls = 0
async def storage_once(*args, **kwargs):
nonlocal calls
calls += 1
if calls == 1:
fail(503, "storage_insufficient", "Full")
return await original(*args, **kwargs)
monkeypatch.setattr(workflows, "create_jobs", storage_once)
await tick(wf)
async with wf.app.state.db.session() as s:
assert "storage" in (await s.get(WorkflowRun, held_owner_run)).hold_reasons
assert await s.scalar(select(Job.id).where(Job.run_id == second["items"][0]["target_id"]))
await tick(wf)
async with wf.app.state.db.session() as s:
assert await s.scalar(select(Job.id).where(Job.run_id == held_owner_run))
@pytest.mark.asyncio
async def test_interactive_retry_scope_checked_on_new_request_and_accepted_replay(wf):
snap = await run(wf, await draft(wf))
rid = snap["run"]["id"]
await tick(wf)
async with wf.app.state.db.session() as s:
job = await s.scalar(select(Job).where(Job.run_id == rid))
job.state = "failed"
jid = job.id
await s.commit()
await tick(wf)
snap = (await wf.client.get("/api/workflow-runs/" + rid)).json()
issued = await wf.client.post(
"/api/auth/tokens", json={"name": "retry", "scopes": ["workflows:write"]}
)
token = issued.json()["token"]
tid = issued.json()["record"]["id"]
body = {"expected_run_version": snap["run"]["version"], "target_job_id": jid}
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=wf.app),
base_url="http://test",
headers={"Authorization": "Bearer " + token},
) as client:
url = f"/api/workflow-runs/{rid}/steps/shot_1/retry"
rejected = await client.post(url, json=body, headers={"Idempotency-Key": "retry"})
assert rejected.status_code == 403
async with wf.app.state.db.session() as s:
row = await s.get(ApiToken, tid)
row.scopes = ["workflows:write", "interactive:write"]
await s.commit()
accepted = await client.post(url, json=body, headers={"Idempotency-Key": "retry"})
assert accepted.status_code == 202, accepted.text
async with wf.app.state.db.session() as s:
row = await s.get(ApiToken, tid)
row.scopes = ["workflows:write"]
await s.commit()
replay = await client.post(url, json=body, headers={"Idempotency-Key": "retry"})
assert replay.status_code == 403
@pytest.mark.asyncio
@pytest.mark.parametrize("task", ["math.solve", "media.structure", "audio.speech"])
async def test_cpu_only_batch_accepted_without_gpu_capabilities(wf, png_bytes, monkeypatch, task):
checks = []
async def offline():
checks.append(True)
raise RuntimeError("GPU offline")
monkeypatch.setattr(wf.provider, "upstream_capabilities", offline, raising=False)
wf.settings.tts_base_url = "http://tts/v1"
wf.settings.tts_model = "kokoro"
inputs = {"prompt": "hello"}
if task == "media.structure":
image = await wf.client.post(
"/api/assets", files={"file": ("ref.png", png_bytes, "image/png")}
)
inputs = {"asset_id": image.json()["id"]}
response = await wf.client.post(
"/api/batches",
json={"items": [{"kind": "job", "task_type": task, "input": inputs}]},
headers={"Idempotency-Key": "cpu"},
)
assert response.status_code == 202, response.text
assert checks == []
@pytest.mark.asyncio
async def test_admin_held_batch_propagates_to_standalone_and_run_members(wf):
batch = await workflow_batch(
wf, extra=[{"kind": "job", "task_type": "image.generate", "input": {"prompt": "later"}}]
)
async with wf.app.state.db.session() as s:
b = await s.get(Batch, batch["batch"]["id"])
b.hold_reasons = ["admin_suspend"]
await s.commit()
await tick(wf)
async with wf.app.state.db.session() as s:
r = await s.get(WorkflowRun, batch["items"][0]["target_id"])
assert not await s.scalar(select(Job.id).where(Job.run_id == r.id))
j = await s.get(Job, batch["items"][1]["target_id"])
assert "admin_suspend" in j.hold_reasons
result = (await wf.client.get("/api/batches/" + batch["batch"]["id"])).json()
assert result["batch"]["hold_reasons"] == ["admin_suspend"]
@pytest.mark.asyncio
@pytest.mark.parametrize(
"corruption", ["missing", "same_size", "wrong_size", "outside_root", "foreign_owner"]
)
async def test_reuse_requires_owned_verified_file(wf, corruption, tmp_path):
d = await draft(wf)
snap = await run(wf, d)
rid = snap["run"]["id"]
await tick(wf)
async with wf.app.state.db.session() as s:
jid = await s.scalar(select(Job.id).where(Job.run_id == rid))
aid = await publish_video(wf, jid)
await tick(wf)
await wf.client.post(
"/api/workflow-runs/" + rid + "/cancel", json={}, headers={"Idempotency-Key": "cancel"}
)
await tick(wf)
async with wf.app.state.db.session() as s:
a = await s.get(Asset, aid)
path = wf.settings.asset_root / a.storage_key
if corruption == "missing":
path.unlink(missing_ok=True)
elif corruption == "same_size":
path.write_bytes(b"x" * a.size_bytes)
elif corruption == "wrong_size":
path.write_bytes(b"bad size")
elif corruption == "outside_root":
escape = tmp_path / "outside.mp4"
escape.write_bytes(b"v")
a.storage_key = str(escape)
else:
from app.models import User
foreign = User(username="foreign", display_name="Other", password_hash="unused")
s.add(foreign)
await s.flush()
a.owner_id = foreign.id
await s.commit()
current = (await wf.client.get("/api/workflows/" + d["id"])).json()
response = await wf.client.post(
"/api/workflows/" + d["id"] + "/runs",
json={
"draft_revision": current["revision"],
"expected_version": current["version"],
"reuse_run_id": rid,
},
headers={"Idempotency-Key": "reuse"},
)
assert response.status_code == 202, response.text
shot = next(x for x in response.json()["steps"] if x["step_key"] == "shot_1")
assert shot["selected_job_id"] is None and shot["state"] == "waiting"
@pytest.mark.asyncio
async def test_source_sha_participates_in_shot_semantic_hash(wf, png_bytes):
from test_timeline_v2 import spec
upload = await wf.client.post(
"/api/assets", files={"file": ("ref.png", png_bytes, "image/png")}
)
aid = upload.json()["id"]
body = spec()
body["shots"][0]["image_asset_id"] = aid
d = (await wf.client.post("/api/workflows", json={"spec": body})).json()
first = await run(wf, d)
await wf.client.post(
"/api/workflow-runs/" + first["run"]["id"] + "/cancel",
json={},
headers={"Idempotency-Key": "cancel"},
)
await tick(wf)
async with wf.app.state.db.session() as s:
a = await s.get(Asset, aid)
a.sha256 = "b" * 64
await s.commit()
d = (await wf.client.get("/api/workflows/" + d["id"])).json()
second = await run(wf, d, "second")
hashes = lambda snap: {x["step_key"]: x["semantic_input_hash"] for x in snap["steps"]}
assert hashes(first)["shot_1"] != hashes(second)["shot_1"]
assert hashes(first)["shot_2"] == hashes(second)["shot_2"]
@pytest.mark.asyncio
async def test_compose_hash_changes_when_selected_output_bytes_change(wf):
batch = await workflow_batch(wf)
rid = batch["items"][0]["target_id"]
for _ in range(3):
await tick(wf)
async with wf.app.state.db.session() as s:
jid = await s.scalar(select(Job.id).where(Job.run_id == rid, Job.state != "succeeded"))
await publish_video(wf, jid)
await tick(wf)
async with wf.app.state.db.session() as s:
compose = await s.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == rid, WorkflowStep.step_key == "compose"
)
)
first = compose.semantic_input_hash
jid = compose.selected_job_id
job = await s.get(Job, jid)
job.state = "failed"
a = await s.scalar(
select(Asset).where(
Asset.source_job_id.in_(
select(Job.id).where(Job.run_id == rid, Job.step_key == "shot_2")
)
)
)
a.sha256 = "b" * 64
await s.commit()
await tick(wf)
snap = (await wf.client.get("/api/workflow-runs/" + rid)).json()
result = await wf.client.post(
f"/api/workflow-runs/{rid}/steps/compose/retry",
json={"expected_run_version": snap["run"]["version"], "target_job_id": jid},
headers={"Idempotency-Key": "retry"},
)
assert result.status_code == 202, result.text
assert first != next(
x["semantic_input_hash"] for x in result.json()["steps"] if x["step_key"] == "compose"
)