nex_animation/backend/tests/test_agent_qc_rework.py

281 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""质检不过就自动返工 + 服务重启后计划自动从断点继续。
两条都是「LLM 总控台跑不完整个流程」的真实成因:
1. 图形质检上线后,明显镜头瑕疵一律判不合格,quality_check 一步 raise 就把
放行 / 排时间线 / 合成全部带走,项目停在「已暂停」;
2. inline 后端的计划在进程内线程里跑,进程一重启计划直接变 failed,
任务层有断点续跑、计划层没有,于是镜头出完图也没人去质检放行合成。
"""
from __future__ import annotations
import threading
from types import SimpleNamespace
import pytest
from sqlalchemy import select
from app.constants import ShotStatus
from app.models import AgentRun, EventLog, Project, Task
from app.services import agent, storage
def _shots(db, pid):
project = db.get(Project, pid)
return sorted(project.shots or [], key=lambda row: (row.order_index, row.id))
def _generated(api, db, pid):
"""走完一次真实生成,让两个镜头都有合格的画面产物与质检记录。"""
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False})
api.drain(pid)
db.expire_all()
rows = _shots(db, pid)
assert all(row.output_path for row in rows), [row.status for row in rows]
return rows
def _break(db, pid, index=0):
"""把某一镜的画面换成坏文件:技术指标当场不合格,质检必须判返工。"""
shot = _shots(db, pid)[index]
path = storage.to_absolute(shot.output_path)
path.write_bytes(b"not-a-video-at-all")
shot.qc_json = {"passed": False, "issues": ["画面质检·人物分身:同一人物出现两个"]}
shot.qc_score = None
shot.status = ShotStatus.GENERATED
db.commit()
return shot
def _actions(db, pid):
return [row.action for row in
db.scalars(select(EventLog).where(EventLog.project_id == pid))]
def test_quality_check_reworks_failing_shot_and_then_passes(api, db, studio, script_text,
make_image_png):
"""质检判不合格 → 把问题写回提示词重做一次 → 复检通过,计划继续往下走。"""
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
rows = _generated(api, db, pid)
broken = _break(db, pid)
before_output = broken.output_path
project = db.get(Project, pid)
outcome = agent._step_quality_check(db, project, {"shot_ids": None}, 240)
assert outcome["status"] == "succeeded", outcome
assert outcome["result"]["rework_rounds"] == 1, outcome
assert "自动返工 1 轮" in outcome["detail"], outcome["detail"]
db.expire_all()
fixed = _shots(db, pid)[0]
# 返工真的重新生成了画面,而不是拿旧文件再检一遍
assert fixed.output_path != before_output or storage.to_absolute(fixed.output_path).stat().st_size > 512
assert bool((fixed.qc_json or {}).get("passed")) is True, fixed.qc_json
# 返工时质检问题被写回风格备注(compose_prompt 把它拼进视频提示词,模型才知道上次哪里穿帮);
# 复检通过后必须抹掉——旧问题留在提示词里,会让以后每次重新生成都继续照旧账改
rework_log = outcome["result"].get("rework") or []
assert agent.QC_REWORK_MARK not in (fixed.style_note or ""), fixed.style_note
# 复检会重写 qc_json,所以写回的必须是这一轮质检真正查出来的硬伤:
# 坏文件的硬伤是 ffprobe 解析失败,不是测试预设的假问题
assert any(("媒体探测" in row or "ffprobe" in row) for row in rework_log), rework_log
# 返工话术确实进过视频提示词(sync_prompt 现场组装),而不是只写在库里没人看
assert "同一人物绝不能出现第二个分身" in (fixed.prompt or ""), (fixed.prompt or "")[:200]
assert "agent.qc_rework" in _actions(db, pid)
def test_qc_rework_note_does_not_stack_up(api, db, studio, script_text, make_image_png):
"""反复返工只留一条返工段落,不能越堆越长把原文案挤没。"""
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
shot = _shots(db, pid)[0]
shot.style_note = "冷蓝胶片质感"
db.commit()
shot.qc_json = {"passed": False, "issues": ["服装串装", "牌面乱码"]}
agent._write_qc_rework_notes([shot], round_no=1)
agent._write_qc_rework_notes([shot], round_no=2)
assert shot.style_note.count(agent.QC_REWORK_MARK) == 1
assert shot.style_note.startswith("冷蓝胶片质感")
assert "第2轮" in shot.style_note and "第1轮" not in shot.style_note
def test_quality_check_stops_after_rework_budget(api, db, studio, script_text,
make_image_png, monkeypatch):
"""重做一轮还是不过:明确报「返工后仍未通过」并交回人工,而不是无限烧 GPU。"""
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
_generated(api, db, pid)
_break(db, pid)
monkeypatch.setattr(agent, "_step_generate_shots",
lambda *args, **kwargs: {"status": "succeeded", "detail": "返工但产物没变"})
project = db.get(Project, pid)
with pytest.raises(agent.AgentStepError) as caught:
agent._step_quality_check(db, project, {"shot_ids": None, "rework_rounds": 1}, 240)
assert "自动返工 1 轮后自动质检仍未通过" in str(caught.value), str(caught.value)
def test_rework_rounds_zero_keeps_old_hard_stop(api, db, studio, script_text, make_image_png):
"""rework_rounds=0 时行为回到「不过就停」,留给编导完全可控的选择。"""
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
_generated(api, db, pid)
_break(db, pid)
project = db.get(Project, pid)
with pytest.raises(agent.AgentStepError) as caught:
agent._step_quality_check(db, project, {"shot_ids": None, "rework_rounds": 0}, 240)
assert "自动质检未通过" in str(caught.value) and "返工 1 轮" not in str(caught.value)
def _running_run(db, studio, **kwargs):
run = AgentRun(project_id=studio["project_id"], status="running", request_text="跑完整片",
timeout_seconds=120,
steps_json=[{"action": "quality_check", "status": "running"},
{"action": "compose", "status": "pending"}],
**kwargs)
db.add(run)
db.commit()
return run
def test_interrupted_run_resumes_itself_after_service_restart(db, studio, monkeypatch):
"""进程重启后计划自己从断点继续,不再停在「已暂停」等人点按钮。"""
calls = []
reached = threading.Event()
def fake_execute(run_id, *, timeout_seconds, prestarted=False):
calls.append((run_id, timeout_seconds, prestarted))
reached.set()
monkeypatch.setattr(agent, "execute_run", fake_execute)
run = _running_run(db, studio)
assert agent.recover_interrupted_runs(db, auto_resume=True, resume_delay=0) == 1
assert reached.wait(15), "重启后没有自动续跑"
db.expire_all()
assert run.status == "running" and run.error_code == "", (run.status, run.error_code)
assert run.plan_json.get("resume_attempts") == 1
assert calls == [(run.id, 120, True)]
assert "agent.run_resumed" in _actions(db, studio["project_id"])
# 断点续跑:中断那一步还没成功,剩下的步骤仍待执行
assert any(step["status"] != "succeeded" for step in run.steps_json)
def test_auto_resume_is_capped(db, studio):
"""反复重启不能无限续跑:超出预算就明确交回人工的「重试暂停步骤」。"""
run = _running_run(db, studio, plan_json={"resume_attempts": 2})
assert agent.recover_interrupted_runs(db, auto_resume=True, resume_delay=0) == 1
db.expire_all()
assert run.status == "failed" and run.error_code == "agent_interrupted"
assert run.plan_json.get("resume_attempts") == 2
assert "重试暂停步骤" in run.error_message
def test_planning_run_is_never_auto_resumed(db, studio):
"""规划中断时连计划都没有,不能假装能续跑。"""
run = AgentRun(project_id=studio["project_id"], status="planning", request_text="跑完整片")
db.add(run)
db.commit()
assert agent.recover_interrupted_runs(db, auto_resume=True, resume_delay=0) == 1
db.expire_all()
assert run.status == "failed" and "规划请求中断" in run.error_message
def test_rework_does_not_queue_a_second_render_of_the_same_shot(api, db, studio, script_text,
make_image_png):
"""队列里还没开跑的同类任务必须复用:一次重做排两条 = 同一镜头多烧一次 GPU。"""
from app.constants import TaskKind
from app.services import dispatch
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
project = db.get(Project, pid)
first = dispatch.create_generation_tasks(db, project, priority=4, with_voiceover=False)
ids = sorted(row["task_id"] for row in first["created"])
assert len(ids) == 2 and not any(row.get("reused") for row in first["created"])
again = dispatch.create_generation_tasks(
db, db.get(Project, pid),
dispatch.plan_task_list(db, db.get(Project, pid), force=True),
force=True, priority=4, with_voiceover=False)
assert sorted(row["task_id"] for row in again["created"]) == ids
assert all(row.get("reused") for row in again["created"]), again["created"]
assert db.query(Task).filter(Task.project_id == pid,
Task.kind == TaskKind.GENERATE_SHOT).count() == 2
def test_render_in_flight_is_not_reused(api, db, studio, script_text, make_image_png):
"""正在出图的那条用的是上一轮提示词,重做时必须排新任务,不能拿旧的下锅。"""
from app.constants import TaskKind, TaskStatus
from app.services import dispatch
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
first = dispatch.create_generation_tasks(db, db.get(Project, pid), priority=4,
with_voiceover=False)
running = db.get(Task, first["created"][0]["task_id"])
running.status = TaskStatus.RUNNING
db.commit()
again = dispatch.create_generation_tasks(
db, db.get(Project, pid),
dispatch.plan_task_list(db, db.get(Project, pid), force=True),
force=True, priority=4, with_voiceover=False)
fresh = [row for row in again["created"] if not row.get("reused")]
assert [row["shot_id"] for row in fresh] == [running.shot_id], again["created"]
assert db.query(Task).filter(Task.project_id == pid,
Task.kind == TaskKind.GENERATE_SHOT).count() == 3
def test_rework_note_keeps_the_script_supporting_role(api, db, studio, script_text,
make_image_png):
"""返工要求不能把剧本里的对手戏角色删掉:「只允许出现设定人物」曾经害得返工越改越错。"""
pid = studio["project_id"]
api.post(f"/api/projects/{pid}/import",
data={"script_text": script_text, "default_duration": 2},
files=[("images", ("s01.png", make_image_png(480, 270, "0x226699"), "image/png")),
("images", ("s02.png", make_image_png(480, 270, "0x993355"), "image/png"))])
shot = _shots(db, pid)[0]
shot.qc_json = {"passed": False, "issues": ["画面质检·人数超出设定:设定仅1人,画面多出一名男子"]}
agent._write_qc_rework_notes([shot], round_no=1)
assert "画面描述里点名的人物必须保留" in shot.style_note
assert "本镜只允许出现设定人物" not in shot.style_note
assert "定妆图" in shot.style_note
# ---------------------------------------------------------------- 返工得真的换一次骰子
def test_rework_rerolls_the_seed():
"""提示词变了(返工写回了质检问题)种子必须跟着变,否则是把同一镜重出两遍。"""
from app.providers import comfyui
def req(prompt: str):
return SimpleNamespace(seed=None, idempotency_key="shot-25", prompt=prompt)
first = comfyui.derive_video_seed(req("紫小慧跑到柜台前"))
assert comfyui.derive_video_seed(req("紫小慧跑到柜台前")) == first, "同一提示词要能复现"
assert comfyui.derive_video_seed(req("紫小慧跑到柜台前【返工要求第1轮】不要分身")) != first
# 人工锁了 seed 的镜头永远复现同一个结果,返工也不该偷偷换脸
assert comfyui.derive_video_seed(SimpleNamespace(seed=777, idempotency_key="shot-25",
prompt="任意")) == 777
def test_default_rework_budget_allows_a_second_attempt():
assert agent.QC_REWORK_ROUNDS >= 2