nex_animation/backend/tests/test_retry_resume.py

235 lines
12 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.

"""图2「生成失败 → 记录错误并重试」与「断点续跑」回路。
用 mock 适配器的 failure_rate 注入临时故障,验证:
重试退避 → 达到上限后落败 → 人工修复后一键重跑;
以及进程被杀(任务卡在 running)后的心跳租约与断点续跑。
"""
from __future__ import annotations
from datetime import timedelta
from app.db import SessionLocal
from app.models import Task, now_utc
def _setup(api, 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"))])
return pid
def _mock_video_spec(api):
rows = api.get("/api/providers")["providers"]
spec = next(r for r in rows if r["provider"] == "mock" and r["media_type"] == "video")
return spec["id"]
def _tasks(api, pid, kind=None):
rows = api.get("/api/tasks", params={"project_id": pid})["tasks"]
return [t for t in rows if kind is None or t["kind"] == kind]
def test_injected_failure_retries_backs_off_and_fails_then_recovers(api, studio, script_text, make_image_png):
pid = _setup(api, studio, script_text, make_image_png)
spec_id = _mock_video_spec(api)
api.patch(f"/api/providers/{spec_id}", json={"config": {"failure_rate": 1.0}})
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False, "actor": "测试导演"})
api.drain(pid)
gens = _tasks(api, pid, "generate_shot")
assert len(gens) == 2
for task in gens:
assert task["status"] == "failed", task
assert task["max_attempts"] == 3 and task["attempts"] == 3 # MAX_SHOT_RETRIES=2 → 共 3 次尝试
assert task["error_code"] == "mock_injected_failure"
assert "failure_rate" in task["error_message"]
assert [h["code"] for h in task["error_history"]] == ["mock_injected_failure"] * 3
assert [h["attempt"] for h in task["error_history"]] == [1, 2, 3]
assert task["finished_at"] and task["output_path"] in ("", None)
for shot in api.get(f"/api/projects/{pid}/shots")["shots"]:
assert shot["status"] == "failed" and shot["stage"] == "failed"
assert shot["error_code"] == "mock_injected_failure"
assert shot["output_path"] in ("", None)
workflow = {n["key"]: n for n in api.get(f"/api/projects/{pid}/summary")["result"]["workflow"]}
assert workflow["generate"]["state"] == "failed" and "失败" in workflow["generate"]["detail"]
assert workflow["save_output"]["state"] == "failed"
actions = {e["action"] for e in api.get(f"/api/projects/{pid}/events")["events"]}
assert {"task.retry_scheduled", "task.failed"} <= actions
# ---- 修好供应商配置 → 一键重试失败任务 → 正常出片 ----
api.patch(f"/api/providers/{spec_id}", json={"config": {"failure_rate": 0}})
requeued = api.post(f"/api/projects/{pid}/tasks/retry-failed", json={"reset_attempts": True})["result"]
assert requeued["count"] == 2 and sorted(requeued["requeued"]) == sorted(t["id"] for t in gens)
for task in _tasks(api, pid, "generate_shot"):
assert task["status"] == "queued" and task["attempts"] == 0 and task["error_code"] == ""
assert all(s["status"] == "queued" for s in api.get(f"/api/projects/{pid}/shots")["shots"])
api.drain(pid)
for task in _tasks(api, pid, "generate_shot"):
assert task["status"] == "succeeded" and task["attempts"] == 1
# 重试历史保留在 error_history 里,便于事后复盘
assert len(task["error_history"]) == 3
for shot in api.get(f"/api/projects/{pid}/shots")["shots"]:
assert shot["status"] in ("generated", "qc_passed") and shot["output_exists"] is True
assert shot["error_code"] in ("", None)
workflow = {n["key"]: n for n in api.get(f"/api/projects/{pid}/summary")["result"]["workflow"]}
assert workflow["generate"]["state"] == "done" and workflow["quality_check"]["state"] == "done"
def test_manual_retry_rejects_non_failed_tasks(api, studio, script_text, make_image_png):
pid = _setup(api, studio, script_text, make_image_png)
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False})
task = _tasks(api, pid, "generate_shot")[0]
api.post(f"/api/tasks/{task['id']}/retry", json={}, expect=409)
single = api.post(f"/api/projects/{pid}/tasks/retry-failed", json={})["result"]
assert single == {"requeued": [], "count": 0}
def test_running_task_keeps_lease_and_stale_task_is_resumed(api, studio, script_text, make_image_png):
pid = _setup(api, studio, script_text, make_image_png)
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False})
target = _tasks(api, pid, "generate_shot")[0]
def mark(*, seconds_ago: float, status: str = "running") -> None:
session = SessionLocal()
try:
task = session.get(Task, target["id"])
task.status = status
task.attempts = 1
task.started_at = now_utc() - timedelta(seconds=seconds_ago)
task.heartbeat_at = task.started_at
session.commit()
finally:
session.close()
# 1) 心跳新鲜(conftest 把 STALE_RUNNING_SECONDS 设为 2s)→ 仍在执行,不许回收
mark(seconds_ago=1.0)
alive = api.post(f"/api/projects/{pid}/resume")["result"]
assert alive["recovered_here"] == [] and alive["resume"]["count"] == 0
assert api.get(f"/api/tasks/{target['id']}")["task"]["status"] == "running"
# 2) 心跳过期(模拟进程被 kill)→ 断点续跑把它捞回队列并留下检查点
mark(seconds_ago=120)
resumed = api.post(f"/api/projects/{pid}/resume")["result"]
assert [x["task_id"] for x in resumed["resume"]["recovered"]] == [target["id"]]
assert [x["task_id"] for x in resumed["recovered_here"]] == [target["id"]]
assert resumed["resume"]["count"] == 1
back = api.get(f"/api/tasks/{target['id']}")["task"]
assert back["status"] in ("queued", "running", "succeeded")
assert back["checkpoint"]["recovered_from"] == "stale_running"
# 尝试次数累计不清零:手工置入的历史 1 次仍在;resume 端点随后重新派发,
# 派发即原子认领会再 +1,所以这里必然 >= 1(inline 执行器下为 2)。
assert back["attempts"] >= 1
events = api.get(f"/api/projects/{pid}/events")["events"]
assert any(e["action"] == "task.recovered" and e["task_id"] == target["id"] for e in events)
shot = next(s for s in api.get(f"/api/projects/{pid}/shots")["shots"] if s["id"] == target["shot_id"])
assert shot["status"] in ("queued", "running", "generated", "qc_passed")
api.drain(pid)
after = api.get(f"/api/tasks/{target['id']}")["task"]
assert after["status"] == "succeeded" and after["checkpoint"]["recovered_from"] == "stale_running"
shot = next(s for s in api.get(f"/api/projects/{pid}/shots")["shots"] if s["id"] == target["shot_id"])
assert shot["status"] in ("generated", "qc_passed") and shot["output_exists"] is True
def test_cancel_task_and_cancel_active(api, studio, script_text, make_image_png):
pid = _setup(api, studio, script_text, make_image_png)
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": True})
gens = _tasks(api, pid, "generate_shot")
assert len(gens) == 2 and len(_tasks(api, pid, "voiceover")) == 2
first = gens[0]
cancelled = api.post(f"/api/tasks/{first['id']}/cancel", json={"reason": "这个镜头先压后"})["result"]
assert cancelled["status"] == "cancelled" and cancelled["task_id"] == first["id"]
shot = next(s for s in api.get(f"/api/projects/{pid}/shots")["shots"] if s["id"] == first["shot_id"])
assert shot["status"] in ("ready", "draft") and shot["stage"] == "cancelled"
# 终态任务不可重复取消
api.post(f"/api/tasks/{first['id']}/cancel", json={}, expect=409)
# 已取消的任务可以人工重试
retried = api.post(f"/api/tasks/{first['id']}/retry", json={"reset_attempts": True})["result"]
assert retried["status"] == "queued"
bulk = api.post(f"/api/projects/{pid}/tasks/cancel-active", json={"reason": "暂停整个项目"})["result"]
assert bulk["count"] >= 1 and set(bulk["cancelled"]) >= {g["id"] for g in gens[1:]}
counts = api.get(f"/api/projects/{pid}/queue")["counts"]
assert not any(status in counts for status in ("queued", "running", "retrying"))
assert counts.get("cancelled", 0) >= 3
drained = api.drain(pid)["result"]["drained"]
assert drained["dispatched"] == 0 and drained["remaining"] == 0
summary = api.get(f"/api/projects/{pid}/summary")["summary"]
assert summary["stats"]["tasks_active"] == 0
def test_restarted_process_frees_the_model_slot_at_once(api, studio, script_text, make_image_png):
"""改代码热重载 / 进程崩溃只带走线程,不改数据库。
上一代进程遗留的 running 任务若只等心跳超时(生产配置 STALE_RUNNING_SECONDS=1800)
才回收,唯一的视频并发位就被僵尸占死:AI 总控台重新下达指令时报「并发已满」,
整条流水线原地卡住半小时。
"""
import os
import socket
import subprocess
import sys
pid = _setup(api, studio, script_text, make_image_png)
api.patch(f"/api/providers/{_mock_video_spec(api)}", json={"max_concurrency": 1})
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False})
zombie_id = _tasks(api, pid, "generate_shot")[0]["id"]
child = subprocess.Popen([sys.executable or "/bin/true", "-c", "pass"])
child.wait() # 一个确实已经消失的 pid
session = SessionLocal()
try:
task = session.get(Task, zombie_id)
task.status, task.attempts = "running", 1
task.execution_backend, task.worker_id = "inline", f"{socket.gethostname()}:{child.pid}"
task.started_at = task.heartbeat_at = now_utc() # 心跳新鲜:租约远未过期
session.commit()
finally:
session.close()
# 僵尸占满唯一的并发位 → 队列彻底派发不动,这正是总控台报错的现场
stuck = api.post(f"/api/projects/{pid}/dispatch", json={})["result"]["dispatched"]
assert stuck["count"] == 0
assert any("并发已满" in row["reason"] for row in stuck["blocked"]), stuck["blocked"]
resumed = api.post(f"/api/projects/{pid}/resume")["result"]
assert [x["task_id"] for x in resumed["recovered_here"]] == [zombie_id]
assert resumed["dispatched"]["count"] >= 1, "额度当场就要还回来,不用等租约过期"
back = api.get(f"/api/tasks/{zombie_id}")["task"]
assert back["checkpoint"]["recovered_from"] == "dead_runner"
events = api.get(f"/api/projects/{pid}/events")["events"]
assert any(e["action"] == "task.recovered" and "重启" in e["message"] for e in events)
api.drain(pid)
assert api.get(f"/api/tasks/{zombie_id}")["task"]["status"] == "succeeded"
def test_task_running_in_this_process_is_not_reclaimed(api, studio, script_text, make_image_png):
"""同进程内正在跑的任务(心跳新鲜)绝不能被当成僵尸,否则同一镜头会生成两遍。"""
import os
import socket
pid = _setup(api, studio, script_text, make_image_png)
api.post(f"/api/projects/{pid}/tasks", json={"with_voiceover": False})
target = _tasks(api, pid, "generate_shot")[0]["id"]
session = SessionLocal()
try:
task = session.get(Task, target)
task.status, task.attempts = "running", 1
task.execution_backend, task.worker_id = "inline", f"{socket.gethostname()}:{os.getpid()}"
task.started_at = task.heartbeat_at = now_utc()
session.commit()
finally:
session.close()
assert api.post(f"/api/projects/{pid}/resume")["result"]["resume"]["count"] == 0
assert api.get(f"/api/tasks/{target}")["task"]["status"] == "running"