404 lines
20 KiB
Python
404 lines
20 KiB
Python
"""「指令下了,项目却卡住不动」的根因回归(项目 9 自检实测)。
|
||
|
||
三条真实成因:
|
||
1. 任务收口后没人回写项目状态 —— 过去只有出图 handler 会 refresh,质检/配音/
|
||
合成跑完就走,守护线程的兜底又只刷「队列里还有活跃任务」的项目。于是项目
|
||
最后一条任务正好是质检时,画面早就出完,界面却永远停在「调用视频模型」。
|
||
2. 质检返工耗尽把整条计划就地判死 —— 放行 / 排时间线 / 导出全部轮不到,
|
||
成片停在上一版,用户看到的依然是「项目没有任何推进」。
|
||
3. 局部范围重建时间线会把已经合格的镜头从成片里删掉。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from types import SimpleNamespace
|
||
|
||
from sqlalchemy import select
|
||
|
||
from app.constants import ShotStatus, TaskKind, TaskStatus
|
||
from app.models import AgentRun, EventLog, ExportRecord, Project, ReviewRecord, Task
|
||
from app.jobs import handlers
|
||
from app.services import agent, dispatch, storage
|
||
from app.services import status as status_service
|
||
|
||
|
||
def _shots(db, pid):
|
||
project = db.get(Project, pid)
|
||
return sorted(project.shots or [], key=lambda row: (row.order_index, row.id))
|
||
|
||
|
||
def _imported(api, db, pid, script_text, make_image_png):
|
||
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"))])
|
||
|
||
|
||
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 _stuck(db, pid):
|
||
"""把项目摆回现场那个「一直在转圈」的样子。"""
|
||
project = db.get(Project, pid)
|
||
project.status, project.current_stage = "generating", "generate"
|
||
db.commit()
|
||
|
||
|
||
def _break(db, pid, index=0):
|
||
"""换掉某一镜的画面:技术指标当场不合格,返工也修不好它。"""
|
||
shot = _shots(db, pid)[index]
|
||
storage.to_absolute(shot.output_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 _fail_visual(db, pid, monkeypatch, index=0):
|
||
"""画面有瑕疵但文件是好的 —— 与项目 9 镜头03「三只手」完全同一种局面。
|
||
|
||
index 可以是下标或下标列表(整批都修不好的局面)。
|
||
返回 (镜头, 修复开关):按下开关后画面质检恢复正常,用来验证「这一轮真的
|
||
全合格」时旧的软放行标记会被作废。
|
||
"""
|
||
from app.services import quality
|
||
|
||
rows = _shots(db, pid)
|
||
picks = index if isinstance(index, (list, tuple)) else [index]
|
||
targets = [rows[i] for i in picks]
|
||
target_ids = {row.id for row in targets}
|
||
real = quality.run_visual_qc
|
||
state = {"broken": True}
|
||
|
||
def fake(session, project, shot, report):
|
||
outcome = real(session, project, shot, report)
|
||
if shot.id in target_ids and state["broken"]:
|
||
report.checks.append(quality.Check(
|
||
"visual_cast", "画面质检·人物分身", False, 0, "同一人物出现两个",
|
||
"画面里主角多出一个分身,与人物设定不符"))
|
||
report.probe["visual_score"] = 20.0
|
||
return outcome
|
||
|
||
monkeypatch.setattr(quality, "run_visual_qc", fake)
|
||
return targets[0], (lambda: state.update({"broken": False}))
|
||
|
||
|
||
def _actions(db, pid):
|
||
return [row.action for row in
|
||
db.scalars(select(EventLog).where(EventLog.project_id == pid))]
|
||
|
||
|
||
def _run(db, pid, steps, **kwargs):
|
||
run = AgentRun(project_id=pid, status="planned", request_text="重做不合格镜头并导出成片",
|
||
auto_approve=True, provider="fake", model="orchestrator",
|
||
timeout_seconds=600, steps_json=steps, **kwargs)
|
||
db.add(run)
|
||
db.commit()
|
||
return run
|
||
|
||
|
||
def test_qc_task_alone_moves_the_project_off_generating(api, db, studio, script_text,
|
||
make_image_png):
|
||
"""最后一条任务正好是质检:跑完之后项目必须离开「调用视频模型」。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
_generated(api, db, pid)
|
||
_stuck(db, pid)
|
||
shot = _shots(db, pid)[0]
|
||
|
||
task = dispatch.new_qc_task(db, db.get(Project, pid), shot)
|
||
db.commit()
|
||
handlers.run(TaskKind.QC_SHOT, task.id)
|
||
|
||
db.expire_all()
|
||
assert db.get(Task, task.id).status == TaskStatus.SUCCEEDED
|
||
left = db.scalars(select(Task).where(Task.project_id == pid,
|
||
Task.status.in_(TaskStatus.ACTIVE))).first()
|
||
assert left is None, "队列已经空了"
|
||
project = db.get(Project, pid)
|
||
assert (project.status, project.current_stage) != ("generating", "generate"), \
|
||
"质检收口后没人回写项目状态,界面上会一直转圈"
|
||
assert (project.status, project.current_stage) == ("reviewing", "review")
|
||
|
||
|
||
def test_reconcile_project_status_writes_back_from_its_own_session(api, db, studio):
|
||
"""计划收口用的独立会话回写:拿不到宿主事务也必须能自己算一遍。"""
|
||
pid = studio["project_id"]
|
||
_stuck(db, pid)
|
||
assert agent.reconcile_project_status(pid) is True
|
||
db.expire_all()
|
||
assert db.get(Project, pid).status != "generating"
|
||
# 空项目(还没导入分镜)回写成草稿,而不是继续挂着「生成中」
|
||
assert db.get(Project, pid).status == "draft"
|
||
|
||
|
||
def test_failed_plan_also_writes_project_status_back(api, db, studio, script_text,
|
||
make_image_png):
|
||
"""计划失败同样要收口:否则失败的项目和卡死的项目在界面上长得一模一样。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
_generated(api, db, pid)
|
||
_stuck(db, pid)
|
||
# 一个镜头都没放行 → build_timeline 必然报错
|
||
run = _run(db, pid, [{"action": "build_timeline", "status": "pending", "shot_ids": None}])
|
||
|
||
agent.execute_run(run.id, timeout_seconds=300)
|
||
|
||
db.expire_all()
|
||
assert db.get(AgentRun, run.id).status == "failed"
|
||
project = db.get(Project, pid)
|
||
assert project.status != "generating", project.current_stage
|
||
|
||
|
||
def test_rework_exhaustion_still_finishes_the_film(api, db, studio, script_text, make_image_png,
|
||
monkeypatch):
|
||
"""一镜修不好不能带走整条计划:其余镜头照常放行、排时间线、导出成片。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
rows = _generated(api, db, pid)
|
||
broken, heal = _fail_visual(db, pid, monkeypatch, 0)
|
||
# 返工重画首帧/重出视频不改产物 = 模型连着两轮都画不好同一镜
|
||
monkeypatch.setattr(agent, "_step_generate_keyframes",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但首帧没变"})
|
||
monkeypatch.setattr(agent, "_step_generate_shots",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
_stuck(db, pid)
|
||
run = _run(db, pid, [
|
||
{"action": "quality_check", "status": "pending", "shot_ids": None,
|
||
"rework_rounds": 1, "force": True},
|
||
{"action": "approve_passed", "status": "pending", "shot_ids": None},
|
||
{"action": "build_timeline", "status": "pending", "shot_ids": None},
|
||
{"action": "compose", "status": "pending", "shot_ids": None},
|
||
])
|
||
|
||
agent.execute_run(run.id, timeout_seconds=600)
|
||
|
||
db.expire_all()
|
||
run = db.get(AgentRun, run.id)
|
||
assert run.status == "succeeded", (run.status, run.error_message)
|
||
assert all(step["status"] in ("succeeded", "skipped") for step in run.steps_json), \
|
||
run.steps_json
|
||
# 缺陷镜头如实留痕:写进计划、写进警告、写进事件,不冒充质检通过
|
||
assert [row["shot_id"] for row in (run.plan_json or {}).get("qc_soft_pass") or []] \
|
||
== [broken.id], run.plan_json
|
||
assert any("质检仍未通过" in text for text in (run.warnings_json or [])), run.warnings_json
|
||
assert "agent.qc_soft_pass" in _actions(db, pid)
|
||
soft_event = db.scalars(select(EventLog).where(EventLog.project_id == pid,
|
||
EventLog.action == "agent.qc_soft_pass")).first()
|
||
assert soft_event.level == "warn" and broken.id in soft_event.data_json["shot_ids"]
|
||
|
||
db.expire_all()
|
||
assert all(row.status == ShotStatus.APPROVED for row in _shots(db, pid)), \
|
||
[row.status for row in _shots(db, pid)]
|
||
review = db.scalars(select(ReviewRecord).where(ReviewRecord.shot_id == broken.id,
|
||
ReviewRecord.kind == "agent")).first()
|
||
assert review is not None and review.checks_json.get("qc_soft_pass") is True
|
||
assert "人工复核" in review.notes and "不是人工审核" in review.notes
|
||
passed_review = db.scalars(select(ReviewRecord).where(
|
||
ReviewRecord.shot_id == rows[1].id, ReviewRecord.kind == "agent")).first()
|
||
assert passed_review.checks_json.get("qc_soft_pass") is False
|
||
|
||
timeline = status_service.current_timeline(db, db.get(Project, pid))
|
||
assert sorted(seg.shot_id for seg in timeline.segments or []) == sorted(r.id for r in rows)
|
||
exports = list(db.scalars(select(ExportRecord).where(ExportRecord.project_id == pid)))
|
||
assert len(exports) == 1 and exports[0].status == "succeeded", exports
|
||
assert api.get(f"/api/projects/{pid}")["summary"]["status"] == "delivered"
|
||
|
||
|
||
def test_direct_quality_check_call_still_hard_stops(db, studio, api, script_text,
|
||
make_image_png, monkeypatch):
|
||
"""不走计划(人工复查/自检)时没有 run 上下文,返工耗尽仍旧按原语义硬停。"""
|
||
import pytest
|
||
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
_generated(api, db, pid)
|
||
_break(db, pid, 0)
|
||
monkeypatch.setattr(agent, "_step_generate_shots",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
|
||
with pytest.raises(agent.AgentStepError) as caught:
|
||
agent._step_quality_check(db, db.get(Project, pid),
|
||
{"shot_ids": None, "rework_rounds": 1}, 240)
|
||
assert "自动返工 1 轮后自动质检仍未通过" in str(caught.value), str(caught.value)
|
||
assert "agent.qc_soft_pass" not in _actions(db, pid)
|
||
|
||
|
||
def test_a_fully_passing_batch_clears_the_stale_soft_pass(api, db, studio, script_text,
|
||
make_image_png, monkeypatch):
|
||
"""软放行标记必须跟着本轮质检结果作废,不能在下一次重跑时继续冤枉这个镜头。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
rows = _generated(api, db, pid)
|
||
broken, heal = _fail_visual(db, pid, monkeypatch, 0)
|
||
monkeypatch.setattr(agent, "_step_generate_keyframes",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但首帧没变"})
|
||
monkeypatch.setattr(agent, "_step_generate_shots",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
run = _run(db, pid, [{"action": "quality_check", "status": "pending", "shot_ids": None,
|
||
"rework_rounds": 1, "force": True},
|
||
{"action": "approve_passed", "status": "pending", "shot_ids": None}])
|
||
outcome = agent._step_quality_check(db, db.get(Project, pid),
|
||
{"shot_ids": None, "rework_rounds": 1, "force": True},
|
||
240, run)
|
||
assert outcome["result"]["rework_exhausted"] == [broken.id]
|
||
assert [row["shot_id"] for row in run.plan_json["qc_soft_pass"]] == [broken.id]
|
||
|
||
# 修好了:这一轮画面质检不再报瑕疵,整批合格后旧标记必须作废
|
||
heal()
|
||
broken.qc_json = {"passed": False, "issues": ["画面质检·人物分身:同一人物出现两个"]}
|
||
broken.qc_score = None
|
||
broken.status = ShotStatus.GENERATED
|
||
db.commit()
|
||
outcome = agent._step_quality_check(db, db.get(Project, pid),
|
||
{"shot_ids": None}, 240, run)
|
||
assert outcome["status"] == "succeeded", outcome
|
||
assert "qc_soft_pass" not in (run.plan_json or {}), run.plan_json
|
||
|
||
|
||
def test_partial_timeline_rebuild_never_thins_the_film(api, db, studio, script_text,
|
||
make_image_png):
|
||
"""只重做镜头02 时,成片不能塌成一镜:已合格的镜头必须留在时间线里。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
rows = _generated(api, db, pid)
|
||
for shot in rows:
|
||
shot.status = ShotStatus.APPROVED
|
||
db.commit()
|
||
fake = SimpleNamespace(id=1, provider="fake", model="orchestrator")
|
||
|
||
whole = agent._step_build_timeline(db, db.get(Project, pid), {"shot_ids": None}, fake)
|
||
assert whole["status"] == "succeeded", whole
|
||
db.expire_all()
|
||
partial = agent._step_build_timeline(db, db.get(Project, pid),
|
||
{"shot_ids": [rows[1].id]}, fake)
|
||
assert partial["status"] in ("succeeded", "skipped"), partial
|
||
|
||
db.expire_all()
|
||
timeline = status_service.current_timeline(db, db.get(Project, pid))
|
||
assert sorted(seg.shot_id for seg in timeline.segments or []) == sorted(r.id for r in rows), \
|
||
"局部重做把已经合格的镜头从成片里删掉了"
|
||
|
||
|
||
def test_undecodable_footage_is_never_soft_passed(api, db, studio, script_text, make_image_png,
|
||
monkeypatch):
|
||
"""画面文件解不开时不许软放行:那只把「质检不合格」挪成「导出失败」。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
_generated(api, db, pid)
|
||
_break(db, pid, 0) # 整个文件都是坏字节,ffprobe 读不出时长
|
||
monkeypatch.setattr(agent, "_step_generate_keyframes",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
monkeypatch.setattr(agent, "_step_generate_shots",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
_stuck(db, pid)
|
||
run = _run(db, pid, [
|
||
{"action": "quality_check", "status": "pending", "shot_ids": None,
|
||
"rework_rounds": 1, "force": True},
|
||
{"action": "approve_passed", "status": "pending", "shot_ids": None},
|
||
{"action": "build_timeline", "status": "pending", "shot_ids": None},
|
||
])
|
||
|
||
agent.execute_run(run.id, timeout_seconds=600)
|
||
|
||
db.expire_all()
|
||
run = db.get(AgentRun, run.id)
|
||
assert run.status == "failed", run.status
|
||
assert "无法解码" in run.error_message, run.error_message
|
||
assert "qc_soft_pass" not in (run.plan_json or {}), run.plan_json
|
||
assert "agent.qc_soft_pass" not in _actions(db, pid)
|
||
# 失败 ≠ 卡死:项目状态照样得被回写
|
||
assert db.get(Project, pid).status != "generating"
|
||
|
||
|
||
def test_an_all_defective_batch_still_delivers(api, db, studio, script_text, make_image_png,
|
||
monkeypatch):
|
||
"""整批镜头都返工耗尽也要出片(项目 9 run 42 实测:质检步骤里只剩一镜时
|
||
「无一合格」把整条计划判死,用户要的最终输出永远轮不到)。"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
rows = _generated(api, db, pid)
|
||
_fail_visual(db, pid, monkeypatch, [0, 1]) # 两镜都有画面瑕疵,模型连着两轮修不掉
|
||
monkeypatch.setattr(agent, "_step_generate_keyframes",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但首帧没变"})
|
||
monkeypatch.setattr(agent, "_step_generate_shots",
|
||
lambda *a, **k: {"status": "succeeded", "detail": "返工但产物没变"})
|
||
_stuck(db, pid)
|
||
run = _run(db, pid, [
|
||
{"action": "quality_check", "status": "pending", "shot_ids": None,
|
||
"rework_rounds": 1, "force": True},
|
||
{"action": "approve_passed", "status": "pending", "shot_ids": None},
|
||
{"action": "build_timeline", "status": "pending", "shot_ids": None},
|
||
{"action": "compose", "status": "pending", "shot_ids": None},
|
||
])
|
||
|
||
agent.execute_run(run.id, timeout_seconds=600)
|
||
|
||
db.expire_all()
|
||
run = db.get(AgentRun, run.id)
|
||
assert run.status == "succeeded", (run.status, run.error_message)
|
||
qc_step = [row for row in run.steps_json if row["action"] == "quality_check"][0]
|
||
assert "本步骤镜头全部未通过" in qc_step["detail"], qc_step["detail"]
|
||
assert sorted(row["shot_id"] for row in run.plan_json["qc_soft_pass"]) \
|
||
== sorted(r.id for r in rows), run.plan_json
|
||
assert all(row.status == ShotStatus.APPROVED for row in _shots(db, pid))
|
||
exports = list(db.scalars(select(ExportRecord).where(ExportRecord.project_id == pid)))
|
||
assert len(exports) == 1 and exports[0].status == "succeeded", exports
|
||
assert api.get(f"/api/projects/{pid}")["summary"]["status"] == "delivered"
|
||
|
||
|
||
def test_timeline_keeps_a_shot_the_plan_did_not_re_approve(api, db, studio, script_text,
|
||
make_image_png):
|
||
"""只重做部分分镜时,上一版成片里状态被打回的镜头必须留在成片里。
|
||
|
||
项目 9 run 42:指令只覆盖分镜1/2,分镜3 因上一轮返工被打回未放行,
|
||
重建时间线会排出一部两镜「成片」,界面却写着导出成功。
|
||
"""
|
||
pid = studio["project_id"]
|
||
_imported(api, db, pid, script_text, make_image_png)
|
||
rows = _generated(api, db, pid)
|
||
for shot in rows:
|
||
shot.status = ShotStatus.APPROVED
|
||
db.commit()
|
||
fake = SimpleNamespace(id=1, provider="fake", model="orchestrator", warnings_json=[])
|
||
assert agent._step_build_timeline(db, db.get(Project, pid), {"shot_ids": None},
|
||
fake)["status"] == "succeeded"
|
||
|
||
rows[1].status = ShotStatus.GENERATED # 重做把这一镜的审核状态打回了
|
||
db.commit()
|
||
step = agent._step_build_timeline(db, db.get(Project, pid),
|
||
{"shot_ids": [rows[0].id]}, fake)
|
||
|
||
assert step["status"] in ("succeeded", "skipped"), step
|
||
db.expire_all()
|
||
timeline = status_service.current_timeline(db, db.get(Project, pid))
|
||
assert sorted(seg.shot_id for seg in timeline.segments or []) == sorted(r.id for r in rows), \
|
||
"上一版成片里的镜头被静默丢掉了"
|
||
assert any("本轮计划没有放行" in text for text in fake.warnings_json), fake.warnings_json
|
||
assert "agent.timeline_keep" in _actions(db, pid)
|
||
|
||
|
||
def test_manual_retry_restores_the_auto_resume_budget(db, studio):
|
||
"""用户亲自点「执行」= 重新授权:自动续跑预算必须复位,否则被重启烧过 2 次的
|
||
计划从此再也不会自己接着跑,一重启就永远停在失败。"""
|
||
pid = studio["project_id"]
|
||
run = _run(db, pid, [{"action": "compose", "status": "pending", "shot_ids": None}],
|
||
error_code="agent_interrupted",
|
||
plan_json={"intent": "regenerate", "resume_attempts": 2})
|
||
run.status = "failed"
|
||
db.commit()
|
||
|
||
agent.start_run(db, db.get(AgentRun, run.id), timeout_seconds=600)
|
||
|
||
db.expire_all()
|
||
fresh = db.get(AgentRun, run.id)
|
||
assert fresh.status == "running"
|
||
assert "resume_attempts" not in (fresh.plan_json or {}), fresh.plan_json
|
||
assert fresh.plan_json["intent"] == "regenerate", fresh.plan_json
|