fix(gpu): #1970 MuseTalk worker 推理期心跳/超时 900/重试收敛/短视频前置失败
CI/CD Pipeline / Check push changed paths (pull_request) Has been skipped
CI/CD Pipeline / Dedup Check - skip PR tests when covered by push pipeline (pull_request) Successful in 0s
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 1s
CI/CD Pipeline / Frontend Lint (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / PR Build Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Retag skipped Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 1m23s
CI/CD Pipeline / Integration Tests (pull_request) Successful in 2m23s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 3m3s
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 3m0s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 3m1s
CI/CD Pipeline / Validate - Style (pull_request) Successful in 3m5s
CI/CD Pipeline / Validate - Python (mypy + alembic) (pull_request) Successful in 4m19s
AI Code Review / AI Code Review (pull_request) Successful in 6m27s
CI/CD Pipeline / Validate - Security (pull_request) Successful in 6m44s
CI/CD Pipeline / Unit Tests (pull_request) Failing after 8m42s
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been skipped
CI/CD Pipeline / CI Gate (pull_request) Failing after 1s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 5m54s

- GPU_TASK_TIMEOUT_SECONDS 默认 300→900(base.py + env 模板),worker
  REQUEST_TIMEOUT 默认同步 300→900,RTX2060 6G 处理 720p 长视频不再超时
- worker 新增 TaskHeartbeat daemon 线程:任务处理期间每 30s POST
  /gpu/register(task_id=...) 续任务心跳,服务端只在任务心跳真正停滞
  超过 900s(崩溃/断网)或 worker 明确上报 failed 时才回退 pending,
  长推理阻塞主循环不再导致误回退
- register schema/service 支持 task_id:_touch_task_heartbeat 只刷新
  属于该 worker 且仍 processing 的任务,已完成/已被回收重派的过期心跳忽略
- worker 本地 TASK_MAX_RETRY 2→1,且仅对瞬时错误(连接失败/超时/5xx)重试;
  4xx、结果过小等确定性失败不本地重试,服务端 MAX_ATTEMPTS=3 不变,
  消除 3×3=9 次推理放大
- <3s 输入视频(MuseTalk division by zero)下载后 ffprobe 前置校验,
  直接上报 failed"视频过短",不调用推理;ffprobe 不可用时不拦截
- 新增 11 个单测(worker 独立脚本按路径加载),全量 15839 passed
This commit is contained in:
xiaoxia
2026-09-19 14:29:22 +08:00
parent a1f25a4426
commit a8f1069cd2
12 changed files with 514 additions and 59 deletions
+1 -1
View File
@@ -258,4 +258,4 @@ APIZERO_API_KEY=${APIZERO_API_KEY}
# ==================== GPU MuseTalk Worker(反向轮询) ====================
GPU_WORKER_TOKEN=${GPU_WORKER_TOKEN}
GPU_TASK_TIMEOUT_SECONDS=300
GPU_TASK_TIMEOUT_SECONDS=900
+1 -1
View File
@@ -275,4 +275,4 @@ APIZERO_API_KEY=${APIZERO_API_KEY}
# ==================== GPU MuseTalk Worker(反向轮询) ====================
GPU_WORKER_TOKEN=${GPU_WORKER_TOKEN}
GPU_TASK_TIMEOUT_SECONDS=300
GPU_TASK_TIMEOUT_SECONDS=900
+8 -3
View File
@@ -19,7 +19,12 @@ MUSE_TALK_URL=http://127.0.0.1:7861
# 轮询/心跳/超时(秒)
POLL_INTERVAL=5
HEARTBEAT_INTERVAL=15
REQUEST_TIMEOUT=300
# 下载/推理/上传 HTTP 超时,需与服务端 GPU_TASK_TIMEOUT_SECONDS 对齐(默认 900)
REQUEST_TIMEOUT=900
# 单个任务本地最大重试次数(首次失败后再重试 N 次,默认 2)
TASK_MAX_RETRY=2
# 单个任务本地最大重试次数(仅网络/MuseTalk 瞬时错误才重试,默认 1)
TASK_MAX_RETRY=1
# 推理期间任务心跳间隔(秒,独立线程,无需改动)
TASK_HEARTBEAT_INTERVAL=30
# 输入视频最短时长(秒),小于则直接上报失败,不调用 MuseTalk
MIN_VIDEO_DURATION_SECONDS=3
+3 -2
View File
@@ -89,8 +89,9 @@ SaaS 后端部署完成后需配置:
| 日志 `MuseTalk 健康检查未通过` | 本地 MuseTalk 没启动,或端口不是 7861;`curl http://127.0.0.1:7861/health` 验证 |
| 任务长时间不被拉取 | Worker 和服务端连不上;检查 API_BASE_URL 是否可达、Token 是否正确 |
| 推理后上传 OSS 失败 | 本地出口网络被防火墙拦截 OSS 域名(oss-cn-hangzhou.aliyuncs.com) |
| 服务端看到任务回退到 pending 重试 | Worker 心跳超时(默认 5 分钟);Worker 进程崩溃或推理卡死超过 5 分钟 |
| 日志 `MuseTalk 推理超时` | 视频太长或显存不足;可临时调大 REQUEST_TIMEOUT,或限制输入视频时长 |
| 服务端看到任务回退到 pending 重试 | 任务心跳真正超时(默认 900s):Worker 进程崩溃/断网,或推理彻底卡死;正常长推理期间心跳线程每 30s 续期,不会回退 |
| 日志 `MuseTalk 推理超时或连接失败` | 视频太长或显存不足;可临时调大 REQUEST_TIMEOUT(服务端 GPU_TASK_TIMEOUT_SECONDS 需同步调大),或限制输入视频时长 |
| 日志 `视频过短(x.xxs < 3s)` | 输入视频不足 3s,MuseTalk 对短视频会 division by zero,已在本地直接上报失败;可用 MIN_VIDEO_DURATION_SECONDS 调整阈值 |
## 七、安全注意事项
+120 -45
View File
@@ -9,9 +9,12 @@
WORKER_ID 本机唯一 ID(默认 hostname+网卡MAC 后4位)
MUSE_TALK_URL 本地 MuseTalk 地址,默认 http://127.0.0.1:7861
POLL_INTERVAL 轮询间隔秒,默认 5
HEARTBEAT_INTERVAL 心跳间隔秒,默认 15
REQUEST_TIMEOUT HTTP 请求超时秒,默认 60
TASK_MAX_RETRY 单个任务最大重试次数(在 Worker 本地的重试),默认 2
HEARTBEAT_INTERVAL 空闲心跳间隔秒,默认 15
REQUEST_TIMEOUT HTTP 请求超时秒(下载/推理/上传统一使用),默认 900
需与服务端 GPU_TASK_TIMEOUT_SECONDS(默认 900)对齐
TASK_MAX_RETRY 单任务本地最大重试次数(仅对瞬时错误重试),默认 1
TASK_HEARTBEAT_INTERVAL 推理期间任务心跳间隔秒,默认 30
MIN_VIDEO_DURATION_SECONDS 最短输入视频时长秒,小于则直接上报失败,默认 3
用法:
python gpu_worker.py
@@ -26,6 +29,7 @@ import platform
import socket
import sys
import tempfile
import threading
import time
import uuid
from pathlib import Path
@@ -54,8 +58,17 @@ class Config:
muse_talk_url: str = _env("MUSE_TALK_URL", "http://127.0.0.1:7861").rstrip("/")
poll_interval: float = float(_env("POLL_INTERVAL", "5"))
heartbeat_interval: float = float(_env("HEARTBEAT_INTERVAL", "15"))
request_timeout: float = float(_env("REQUEST_TIMEOUT", "300"))
task_max_retry: int = int(_env("TASK_MAX_RETRY", "2"))
# #1970:RTX2060 6G 处理 720p 长视频可能 >5min;与服务端
# GPU_TASK_TIMEOUT_SECONDS 默认值对齐为 900,避免推理被本地/服务端先掐断。
request_timeout: float = float(_env("REQUEST_TIMEOUT", "900"))
# 本地只在网络/MuseTalk 瞬时错误时重试 1 次;服务端 MAX_ATTEMPTS=3
# 负责跨 worker/真正超时后的重派发,总尝试次数不再相乘放大。
task_max_retry: int = int(_env("TASK_MAX_RETRY", "1"))
# 推理期间任务心跳间隔(独立线程 POST /gpu/register 带 task_id)
task_heartbeat_interval: float = float(_env("TASK_HEARTBEAT_INTERVAL", "30"))
# 输入视频最短时长(秒):过短(如 1s)MuseTalk 会 division by zero,
# 本地前置拦截,直接上报 failed,不浪费 GPU 时间
min_video_duration_seconds: float = float(_env("MIN_VIDEO_DURATION_SECONDS", "3"))
worker_id: str = _env("WORKER_ID", "")
@classmethod
@@ -96,8 +109,12 @@ def _check_musetalk_health() -> tuple[bool, dict]:
return False, {"error": str(exc)}
def _register() -> bool:
"""向服务端注册 / 心跳,附带 GPU 信息."""
def _register(task_id: Optional[str] = None) -> bool:
"""向服务端注册 / 心跳,附带 GPU 信息。
推理期间的心跳线程传 task_id:服务端会同步刷新该 processing 任务的
last_heartbeat_at,防止长推理被误判超时回收。
"""
ok, info = _check_musetalk_health()
free_vram = int(info.get("free_vram_mb", 0) or 0) if isinstance(info, dict) else 0
gpu_name = info.get("gpu_name", "") if isinstance(info, dict) else ""
@@ -111,6 +128,8 @@ def _register() -> bool:
"free_vram_mb": free_vram,
"capabilities": "musetalk",
}
if task_id:
payload["task_id"] = task_id
try:
r = requests.post(
f"{Config.api_base_url}/api/v1/gpu/register",
@@ -181,11 +200,15 @@ def _download(url: str, path: Path) -> bool:
return False
def _call_musetalk(video_path: Path, audio_path: Path, out_path: Path) -> tuple[bool, float, str]:
def _call_musetalk(
video_path: Path, audio_path: Path, out_path: Path
) -> tuple[bool, float, str, bool]:
"""调用本地 MuseTalk /inference.
返回 (success, duration_seconds, error_msg).
返回 (success, duration_seconds, error_msg, retryable)。
duration 用 ffprobe 读结果视频,失败填 0。
retryable 仅对瞬时错误(连接失败/超时/5xx)为 True;HTTP 4xx、结果过小
等确定性失败不重试,直接上报服务端(服务端 MAX_ATTEMPTS 再决定是否重派发)。
"""
try:
with open(video_path, "rb") as vf, open(audio_path, "rb") as af:
@@ -199,17 +222,20 @@ def _call_musetalk(video_path: Path, audio_path: Path, out_path: Path) -> tuple[
timeout=Config.request_timeout,
)
if r.status_code != 200:
return False, 0.0, f"MuseTalk HTTP {r.status_code}: {r.text[:500]}"
retryable = r.status_code >= 500
return False, 0.0, f"MuseTalk HTTP {r.status_code}: {r.text[:500]}", retryable
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_bytes(r.content)
if out_path.stat().st_size < 1024:
return False, 0.0, f"MuseTalk 返回结果过小 ({out_path.stat().st_size} bytes)"
# 确定性失败(推理产物异常),本地重试大概率还是坏的,不重试
return False, 0.0, f"MuseTalk 返回结果过小 ({out_path.stat().st_size} bytes)", False
duration = _probe_duration(out_path)
return True, duration, ""
except requests.exceptions.Timeout:
return False, 0.0, f"MuseTalk 推理超时(>{Config.request_timeout}s)"
return True, duration, "", False
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
# 瞬时网络/超时错误,允许本地重试 1 次
return False, 0.0, f"MuseTalk 推理超时或连接失败(>{Config.request_timeout}s)", True
except Exception as exc:
return False, 0.0, f"MuseTalk 调用异常: {exc}"
return False, 0.0, f"MuseTalk 调用异常: {exc}", False
def _probe_duration(path: Path) -> float:
@@ -276,42 +302,91 @@ def _report_result(task_id: str, success: bool, duration: float = 0.0, error_msg
return False
class TaskHeartbeat(threading.Thread):
"""推理期间的任务心跳线程。
主循环的空闲心跳在 ``_handle_task`` 同步阻塞(下载/推理/上传最长 900s)
期间无法发送,服务端会因任务 last_heartbeat_at 停滞而误判超时回退 pending。
本线程每 task_heartbeat_interval 秒(默认 30s)POST /gpu/register 并
携带当前 task_id,让服务端持续续期任务心跳;任务处理结束 stop()。
"""
def __init__(self, task_id: str, interval: float):
super().__init__(daemon=True, name=f"hb-{task_id[:8]}")
self.task_id = task_id
self.interval = max(5.0, interval)
self._stop = threading.Event()
def run(self) -> None:
# 先立即发一次,再按间隔循环(首次心跳失败不影响主流程)
while not self._stop.is_set():
try:
if _register(self.task_id):
logger.debug("任务 %s 心跳已发送", self.task_id)
except Exception as exc: # noqa: BLE001
logger.warning("任务 %s 心跳异常(忽略): %s", self.task_id, exc)
self._stop.wait(self.interval)
def stop(self) -> None:
self._stop.set()
def _handle_task(task: dict) -> None:
"""处理一条任务(整个串行流程:下载→推理→上传→上报)."""
"""处理一条任务(整个串行流程:下载→时长校验→推理→上传→上报)。"""
task_id = task["task_id"]
logger.info("开始处理任务 %s", task_id)
with tempfile.TemporaryDirectory(prefix="musetalk_") as tmpdir:
tmp = Path(tmpdir)
video_path = tmp / "input.mp4"
audio_path = tmp / "input_audio.bin"
out_path = tmp / "output.mp4"
# 领取任务后立即启动任务级心跳线程,覆盖下载/推理/上报全过程
hb = TaskHeartbeat(task_id, Config.task_heartbeat_interval)
hb.start()
try:
with tempfile.TemporaryDirectory(prefix="musetalk_") as tmpdir:
tmp = Path(tmpdir)
video_path = tmp / "input.mp4"
audio_path = tmp / "input_audio.bin"
out_path = tmp / "output.mp4"
# 1. 下载
if not _download(task["video_url"], video_path):
_report_result(task_id, False, 0.0, "下载人物视频失败")
return
if not _download(task["audio_url"], audio_path):
_report_result(task_id, False, 0.0, "下载驱动音频失败")
return
# 1. 下载
if not _download(task["video_url"], video_path):
_report_result(task_id, False, 0.0, "下载人物视频失败")
return
if not _download(task["audio_url"], audio_path):
_report_result(task_id, False, 0.0, "下载驱动音频失败")
return
# 2. 推理(本地重试)
success = False
duration = 0.0
err = ""
for attempt in range(Config.task_max_retry + 1):
if attempt > 0:
logger.info("任务 %s 第 %d 次重试...", task_id, attempt + 1)
time.sleep(2)
success, duration, err = _call_musetalk(video_path, audio_path, out_path)
if success:
break
if not success:
logger.error("任务 %s 推理失败: %s", task_id, err)
_report_result(task_id, False, 0.0, err)
return
# 2. 输入时长前置校验:短视频 MuseTalk 会 division by zero,
# 直接上报 failed,不浪费 GPU 时间。ffprobe 不可用/读失败(0.0)
# 时不拦截,交给 MuseTalk 处理,避免误杀。
video_duration = _probe_duration(video_path)
if video_duration and video_duration < Config.min_video_duration_seconds:
msg = (
f"视频过短({video_duration:.2f}s < {Config.min_video_duration_seconds:.0f}s),"
"MuseTalk 无法处理"
)
logger.error("任务 %s %s", task_id, msg)
_report_result(task_id, False, 0.0, msg)
return
# 3. 上报结果(multipart 同时上传文件 → API 代为 PUT 到 OSS,逻辑最稳)
_report_success_with_file(task_id, duration, out_path)
# 3. 推理(本地仅对瞬时错误重试)
success = False
duration = 0.0
err = ""
retryable = False
for attempt in range(Config.task_max_retry + 1):
if attempt > 0:
logger.info("任务 %s 第 %d 次重试(瞬时错误)...", task_id, attempt + 1)
time.sleep(2)
success, duration, err, retryable = _call_musetalk(video_path, audio_path, out_path)
if success or not retryable:
break
if not success:
logger.error("任务 %s 推理失败: %s", task_id, err)
_report_result(task_id, False, 0.0, err)
return
# 4. 上报结果(multipart 同时上传文件 → API 代为 PUT 到 OSS,逻辑最稳)
_report_success_with_file(task_id, duration, out_path)
finally:
hb.stop()
def _report_success_with_file(task_id: str, duration: float, file_path: Path) -> None: