Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

refactor(tasks): harden execution and recovery

harry07036b4dd6f49829
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 28f75193..c8dfff11 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -8,8 +8,30 @@ on:
jobs:
tests:
- name: Python tests
+ name: Python ${{ matrix.python-version }} tests
runs-on: ubuntu-latest
+ timeout-minutes: 30
+
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.11", "3.13"]
+
+ services:
+ redis:
+ image: redis:7-alpine
+ ports:
+ - 6379:6379
+ options: >-
+ --health-cmd "redis-cli ping"
+ --health-interval 5s
+ --health-timeout 3s
+ --health-retries 10
+
+ env:
+ MPT_TEST_REDIS_HOST: 127.0.0.1
+ MPT_TEST_REDIS_PORT: 6379
+ MPT_TEST_REDIS_DB: 15
steps:
- name: Check out repository
@@ -18,7 +40,7 @@ jobs:
- name: Set up Python
uses: actions/setup-python@v5
with:
- python-version: "3.11"
+ python-version: ${{ matrix.python-version }}
- name: Install uv
uses: astral-sh/setup-uv@v6
@@ -26,15 +48,64 @@ jobs:
enable-cache: true
- name: Install dependencies
- run: uv sync --frozen
+ run: uv sync --frozen --python ${{ matrix.python-version }}
- name: Compile Python sources
- run: uv run python -m compileall app cli.py main.py webui test
+ run: uv run --no-sync python -m compileall app cli.py main.py webui test
+
+ - name: Lint Python sources
+ if: matrix.python-version == '3.11'
+ run: uv run --no-sync ruff check app cli.py main.py webui test
- name: Run unit tests with coverage
# pytest 兼容现有 unittest.TestCase,同时会收集仓库中的 pytest 风格
# 测试,避免测试文件已存在但 CI 没有真正执行。
- run: uv run python -X utf8 -m coverage run -m pytest -q test
+ run: uv run --no-sync python -X utf8 -m coverage run -m pytest -q test
- name: Report test coverage
- run: uv run python -m coverage report
+ run: uv run --no-sync python -m coverage report
+
+ - name: Export coverage report
+ run: uv run --no-sync python -m coverage xml
+
+ - name: Upload coverage report
+ uses: actions/upload-artifact@v4
+ with:
+ name: coverage-python-${{ matrix.python-version }}
+ path: coverage.xml
+ retention-days: 7
+
+ windows-smoke:
+ name: Windows smoke tests
+ runs-on: windows-latest
+ timeout-minutes: 30
+
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v6
+ with:
+ enable-cache: true
+
+ - name: Install dependencies
+ run: uv sync --frozen --python 3.11
+
+ - name: Compile Python sources
+ run: uv run --no-sync python -m compileall app cli.py main.py webui test
+
+ - name: Run core service smoke tests
+ run: >-
+ uv run --no-sync python -X utf8 -m pytest -q
+ test/services/test_config.py
+ test/services/test_state.py
+ test/services/test_task.py
+ test/services/test_task_manager.py
+ test/services/test_upload_post.py
+ test/services/test_controller_video.py
diff --git a/app/asgi.py b/app/asgi.py
index 01f8b7da..5ff21fa6 100644
--- a/app/asgi.py
+++ b/app/asgi.py
@@ -1,6 +1,7 @@
"""Application implementation - ASGI."""
import os
+from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
@@ -15,6 +16,22 @@ from app.router import root_api_router
from app.utils import utils
+@asynccontextmanager
+async def application_lifespan(_: FastAPI):
+ """集中处理 API 进程启动恢复和关闭日志。"""
+ logger.info("startup event")
+
+ # 跨平台发布由当前进程线程池执行,不会在服务重启后恢复。启动时把 Redis
+ # 中确认已失去执行进程的活动状态收敛为失败,避免任务永久无法删除。
+ from app.services import task as task_service
+
+ task_service.recover_interrupted_cross_posts()
+ try:
+ yield
+ finally:
+ logger.info("shutdown event")
+
+
def exception_handler(request: Request, e: HttpException):
return JSONResponse(
status_code=e.status_code,
@@ -43,6 +60,7 @@ def get_application() -> FastAPI:
description=config.project_description,
version=config.project_version,
debug=False,
+ lifespan=application_lifespan,
)
instance.include_router(root_api_router)
instance.add_exception_handler(HttpException, exception_handler)
@@ -70,13 +88,3 @@ app.mount(
public_dir = utils.public_dir()
app.mount("/", StaticFiles(directory=public_dir, html=True), name="")
-
-
[email protected]_event("shutdown")
-def shutdown_event():
- logger.info("shutdown event")
-
-
[email protected]_event("startup")
-def startup_event():
- logger.info("startup event")
diff --git a/app/config/__init__.py b/app/config/__init__.py
index dd468128..9792ba7d 100644
--- a/app/config/__init__.py
+++ b/app/config/__init__.py
@@ -4,7 +4,6 @@ import sys
from loguru import logger
from app.config import config
-from app.utils import utils
def __init_logger():
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.py
index af36e8d9..b73cadff 100644
--- a/app/controllers/v1/video.py
+++ b/app/controllers/v1/video.py
@@ -22,6 +22,7 @@ from app.models.schema import (
BgmUploadResponse,
SubtitleRequest,
TaskDeletionResponse,
+ TaskListResponse,
TaskQueryRequest,
TaskQueryResponse,
TaskResponse,
@@ -88,6 +89,14 @@ def _resolve_path_within_directory(base_dir: str, unsafe_path: str, request_id:
message=f"{request_id}: invalid file path",
)
+
+def _public_task_data(task: dict) -> dict:
+ """复制任务状态并移除仅用于服务端进程协调的内部字段。"""
+ public_task = dict(task)
+ public_task.pop("cross_post_owner", None)
+ return public_task
+
+
def _task_file_to_uri(file: str, endpoint: str, task_dir: str, request_id: str) -> str:
if not isinstance(file, str):
return file
@@ -213,12 +222,16 @@ def create_task(
task_id=task_id, status_code=400, message=f"{request_id}: {str(e)}"
)
[email protected]("/tasks", response_model=TaskQueryResponse, summary="Get all tasks")
-def get_all_tasks(request: Request, page: int = Query(1, ge=1), page_size: int = Query(10, ge=1)):
[email protected]("/tasks", response_model=TaskListResponse, summary="Get all tasks")
+def get_all_tasks(
+ request: Request,
+ page: int = Query(1, ge=1),
+ page_size: int = Query(10, ge=1),
+):
tasks, total = sm.state.get_all_tasks(page, page_size)
response = {
- "tasks": tasks,
+ "tasks": [_public_task_data(task) for task in tasks],
"total": total,
"page": page,
"page_size": page_size,
@@ -240,7 +253,7 @@ def get_task(
task = sm.state.get_task(task_id)
if task:
task_dir = utils.task_dir()
- response_task = dict(task)
+ response_task = _public_task_data(task)
if "videos" in task:
response_task["videos"] = [
@@ -268,6 +281,18 @@ def delete_video(request: Request, task_id: str = Path(..., description="Task ID
request_id = base.get_task_id(request)
task = sm.state.get_task(task_id)
if task:
+ if tm.is_task_busy(task):
+ logger.warning(
+ f"refuse to delete busy task, request_id: {request_id}, "
+ f"task_id: {task_id}, state: {task.get('state')}, "
+ f"cross_post_state: {task.get('cross_post_state')}"
+ )
+ raise HttpException(
+ task_id=task_id,
+ status_code=409,
+ message=f"{request_id}: task is still running",
+ )
+
tasks_dir = utils.task_dir()
current_task_dir = os.path.join(tasks_dir, task_id)
if os.path.exists(current_task_dir):
diff --git a/app/models/const.py b/app/models/const.py
index b5892740..cbeaa9d4 100644
--- a/app/models/const.py
+++ b/app/models/const.py
@@ -26,5 +26,10 @@ TASK_STATE_FAILED = -1
TASK_STATE_COMPLETE = 1
TASK_STATE_PROCESSING = 4
+CROSS_POST_STATE_PENDING = "pending"
+CROSS_POST_STATE_PROCESSING = "processing"
+CROSS_POST_STATE_COMPLETE = "complete"
+CROSS_POST_STATE_FAILED = "failed"
+
FILE_TYPE_VIDEOS = ["mp4", "mov", "mkv", "webm"]
FILE_TYPE_IMAGES = ["jpg", "jpeg", "png", "bmp"]
diff --git a/app/models/schema.py b/app/models/schema.py
index 97cfa463..58eb4959 100644
--- a/app/models/schema.py
+++ b/app/models/schema.py
@@ -1,9 +1,9 @@
import warnings
from enum import Enum
-from typing import Any, List, Optional, Union
+from typing import Any, List, Literal, Optional, Union
import pydantic
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field
from app.config import config
@@ -247,24 +247,100 @@ class TaskResponse(BaseResponse):
}
+class TaskStatusData(BaseModel):
+ """任务查询对外保证的稳定字段;历史和扩展字段继续原样透传。"""
+
+ model_config = ConfigDict(extra="allow")
+
+ task_id: str
+ state: int
+ progress: int = 0
+ videos: Optional[List[str]] = None
+ combined_videos: Optional[List[str]] = None
+ failed_stage: Optional[str] = None
+ error: Optional[str] = None
+ cross_post_state: Optional[
+ Literal["pending", "processing", "complete", "failed"]
+ ] = None
+ cross_post_results: Optional[List[dict[str, Any]]] = None
+ cross_post_error: Optional[str] = None
+
+
+class TaskListData(BaseModel):
+ """分页任务列表结构。"""
+
+ tasks: List[TaskStatusData]
+ total: int
+ page: int
+ page_size: int
+
+
class TaskQueryResponse(BaseResponse):
- class Config:
- json_schema_extra = {
+ """
+ 任务查询会返回生成状态和可选的跨平台发布状态。
+
+ 生成失败时包含 `failed_stage` 和 `error`;生成完成后如果启用了自动发布,
+ `cross_post_state` 会依次进入 pending、processing、complete 或 failed。
+ """
+
+ data: TaskStatusData
+
+ model_config = ConfigDict(
+ json_schema_extra={
+ "examples": [
+ {
+ "status": 200,
+ "message": "success",
+ "data": {
+ "task_id": "6c85c8cc-a77a-42b9-bc30-947815aa0558",
+ "state": 1,
+ "progress": 100,
+ "videos": ["/tasks/example/final-1.mp4"],
+ "cross_post_state": "complete",
+ "cross_post_results": [{"success": True}],
+ },
+ },
+ {
+ "status": 200,
+ "message": "success",
+ "data": {
+ "task_id": "6c85c8cc-a77a-42b9-bc30-947815aa0558",
+ "state": -1,
+ "progress": 30,
+ "failed_stage": "audio",
+ "error": "TTS request timed out",
+ },
+ },
+ ],
+ }
+ )
+
+
+class TaskListResponse(BaseResponse):
+ """任务列表使用独立响应模型,避免与单任务查询混用文档结构。"""
+
+ data: TaskListData
+
+ model_config = ConfigDict(
+ json_schema_extra={
"example": {
"status": 200,
"message": "success",
"data": {
- "state": 1,
- "progress": 100,
- "videos": [
- "http://127.0.0.1:8080/tasks/6c85c8cc-a77a-42b9-bc30-947815aa0558/final-1.mp4"
- ],
- "combined_videos": [
- "http://127.0.0.1:8080/tasks/6c85c8cc-a77a-42b9-bc30-947815aa0558/combined-1.mp4"
+ "tasks": [
+ {
+ "task_id": "6c85c8cc-a77a-42b9-bc30-947815aa0558",
+ "state": 4,
+ "progress": 50,
+ }
],
+ "total": 1,
+ "page": 1,
+ "page_size": 10,
},
- },
+ }
}
+ )
class TaskDeletionResponse(BaseResponse):
diff --git a/app/services/state.py b/app/services/state.py
index c34e9f83..30470963 100644
--- a/app/services/state.py
+++ b/app/services/state.py
@@ -7,6 +7,19 @@ from app.config import config
from app.models import const
+_PATCH_EXISTING_TASK_SCRIPT = """
+if redis.call("EXISTS", KEYS[1]) == 0 then
+ return 0
+end
+
+for index = 1, #ARGV, 2 do
+ redis.call("HSET", KEYS[1], ARGV[index], ARGV[index + 1])
+end
+
+return 1
+"""
+
+
# Base class for state management
class BaseState(ABC):
@abstractmethod
@@ -21,6 +34,11 @@ class BaseState(ABC):
def get_all_tasks(self, page: int, page_size: int):
pass
+ @abstractmethod
+ def patch_task(self, task_id: str, **kwargs) -> bool:
+ """只更新已有任务的指定字段;任务不存在时返回 False。"""
+ pass
+
# Memory state management
class MemoryState(BaseState):
@@ -60,6 +78,17 @@ class MemoryState(BaseState):
task = self._tasks.get(task_id, None)
return copy.deepcopy(task) if task is not None else None
+ def patch_task(self, task_id: str, **kwargs) -> bool:
+ # 异步发布只应补充发布状态,不能覆盖已经保存的视频、字幕等结果。
+ # 在同一把锁内完成存在性判断和字段合并,也可避免任务删除后
+ # 被后台线程重建。
+ with self._lock:
+ task = self._tasks.get(task_id)
+ if task is None:
+ return False
+ task.update(copy.deepcopy(kwargs))
+ return True
+
def delete_task(self, task_id: str):
with self._lock:
self._tasks.pop(task_id, None)
@@ -89,7 +118,14 @@ class RedisState(BaseState):
cursor = 0
total = 0
while True:
- cursor, keys = self._redis.scan(cursor, count=page_size)
+ # Redis 数据库中除了任务 Hash,还可能存在 RedisTaskManager 使用的
+ # List 队列。只扫描 Hash 可以避免对队列执行 HGETALL 时触发
+ # WRONGTYPE,同时保证 total 只统计真正的任务记录。
+ cursor, keys = self._redis.scan(
+ cursor,
+ count=page_size,
+ _type="HASH",
+ )
batch_start = total
batch_size = len(keys)
total += batch_size
@@ -146,6 +182,25 @@ class RedisState(BaseState):
}
return task
+ def patch_task(self, task_id: str, **kwargs) -> bool:
+ if not kwargs:
+ return False
+
+ arguments = []
+ for field, value in kwargs.items():
+ arguments.extend((field, str(value)))
+
+ # EXISTS 和 HSET 如果分成两条命令,后台发布线程与删除请求并发时,
+ # HSET 可能在删除后重新创建一条残缺任务。Lua 脚本由 Redis 原子执行,
+ # 可以保证任务不存在时不写入,且不会改变现有字段之外的数据。
+ updated = self._redis.eval(
+ _PATCH_EXISTING_TASK_SCRIPT,
+ 1,
+ task_id,
+ *arguments,
+ )
+ return bool(updated)
+
def delete_task(self, task_id: str):
self._redis.delete(task_id)
diff --git a/app/services/task.py b/app/services/task.py
index 210b1909..8a066241 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -1,7 +1,13 @@
import math
-import os.path
+import os
import re
+import socket
+import threading
+import time
+from concurrent.futures import CancelledError, Future, ThreadPoolExecutor
+from functools import partial
from os import path
+from uuid import uuid4
from loguru import logger
@@ -15,6 +21,208 @@ from app.services import state as sm
from app.utils import file_security, utils
+# 发布请求最长可等待数分钟,不能继续占用视频生成任务的并发名额。
+# 固定大小的线程池将发布吞吐限制在可控范围内,同时让视频产物生成后
+# 立即进入完成状态。
+_cross_post_executor = ThreadPoolExecutor(
+ max_workers=2,
+ thread_name_prefix="mpt-cross-post",
+)
+_cross_post_max_pending_tasks = max(
+ 1,
+ int(config.app.get("upload_post_max_pending_tasks", 10)),
+)
+_cross_post_slots = threading.BoundedSemaphore(_cross_post_max_pending_tasks)
+_cross_post_registry_lock = threading.RLock()
+_cross_post_futures: dict[str, Future] = {}
+_cross_post_process_owner = f"{socket.gethostname()}:{os.getpid()}:{uuid4().hex}"
+_ACTIVE_CROSS_POST_STATES = {
+ const.CROSS_POST_STATE_PENDING,
+ const.CROSS_POST_STATE_PROCESSING,
+}
+_CROSS_POST_STATE_WRITE_ATTEMPTS = 3
+_CROSS_POST_STATE_RETRY_DELAY_SECONDS = 0.1
+_INTERRUPTED_CROSS_POST_ERROR = (
+ "cross-posting was interrupted before the process completed"
+)
+
+
+def is_task_busy(task: dict | None) -> bool:
+ """判断任务是否仍在生成或发布,供所有删除入口复用。"""
+ if not task:
+ return False
+
+ state = task.get("state")
+ try:
+ state = int(state)
+ except (TypeError, ValueError):
+ pass
+
+ # 视频生成和跨平台发布都可能继续读取任务目录。统一视为忙碌状态,
+ # 可以避免 API 与 WebUI 分别维护规则后出现一个允许删除、另一个禁止
+ # 删除的不一致行为。
+ return (
+ state == const.TASK_STATE_PROCESSING
+ or task.get("cross_post_state") in _ACTIVE_CROSS_POST_STATES
+ )
+
+
+def _register_cross_post_future(task_id: str, future: Future) -> None:
+ """登记当前进程持有的发布 Future,供启动恢复和测试判断真实运行状态。"""
+ with _cross_post_registry_lock:
+ _cross_post_futures[task_id] = future
+
+
+def _unregister_cross_post_future(task_id: str, future: Future | None = None) -> None:
+ """仅移除匹配的 Future,避免旧回调误删同任务后续注册的新工作。"""
+ with _cross_post_registry_lock:
+ current = _cross_post_futures.get(task_id)
+ if current is None or (future is not None and current is not future):
+ return
+ _cross_post_futures.pop(task_id, None)
+
+
+def _is_cross_post_active_in_process(task_id: str) -> bool:
+ """判断当前进程是否仍持有未结束的发布任务。"""
+ with _cross_post_registry_lock:
+ future = _cross_post_futures.get(task_id)
+ return future is not None and not future.done()
+
+
+def _is_windows_process_alive(process_id: int) -> bool:
+ """通过只读 Win32 API 判断进程状态,避免用 os.kill 误终止进程。"""
+ import ctypes
+
+ process_query_limited_information = 0x1000
+ still_active = 259
+ error_access_denied = 5
+ error_invalid_parameter = 87
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ # ctypes 默认把未声明的返回值当作 32 位 int。Windows 64 位进程句柄可能
+ # 因此被截断,必须显式声明 Win32 函数签名后再调用。
+ kernel32.OpenProcess.argtypes = [ctypes.c_ulong, ctypes.c_int, ctypes.c_ulong]
+ kernel32.OpenProcess.restype = ctypes.c_void_p
+ kernel32.GetExitCodeProcess.argtypes = [
+ ctypes.c_void_p,
+ ctypes.POINTER(ctypes.c_ulong),
+ ]
+ kernel32.GetExitCodeProcess.restype = ctypes.c_int
+ kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+ kernel32.CloseHandle.restype = ctypes.c_int
+ handle = kernel32.OpenProcess(
+ process_query_limited_information,
+ False,
+ process_id,
+ )
+ if not handle:
+ error_code = ctypes.get_last_error()
+ if error_code == error_invalid_parameter:
+ return False
+ if error_code == error_access_denied:
+ # 进程存在但当前用户无查询权限时,必须保守地视为存活,避免错误
+ # 回收其它账户正在执行的发布任务。
+ return True
+ logger.warning(
+ "failed to open cross-post owner process on Windows, "
+ f"process_id: {process_id}, error_code: {error_code}"
+ )
+ return True
+
+ try:
+ exit_code = ctypes.c_ulong()
+ if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)):
+ error_code = ctypes.get_last_error()
+ logger.warning(
+ "failed to read cross-post owner process state on Windows, "
+ f"process_id: {process_id}, error_code: {error_code}"
+ )
+ return True
+ return exit_code.value == still_active
+ finally:
+ kernel32.CloseHandle(handle)
+
+
+def _is_cross_post_owner_alive(owner: str | None) -> bool:
+ """判断持久化发布任务的本机进程是否仍存在。"""
+ if not owner:
+ return False
+
+ try:
+ hostname, process_id_text, _ = owner.split(":", 2)
+ process_id = int(process_id_text)
+ except (TypeError, ValueError):
+ logger.warning(f"invalid cross-post owner metadata: {owner}")
+ return False
+
+ # 无法可靠探测其它主机上的进程。共享 Redis 的多主机部署中必须保守地
+ # 视为仍在运行,避免当前节点误删另一节点正在读取的视频文件。
+ if hostname != socket.gethostname():
+ return True
+
+ # 当前进程内是否仍有真实发布工作,已经由 Future 注册表准确判断。运行到
+ # 这里说明注册表中没有对应 Future,即使 owner 与当前进程完全一致,也应
+ # 视为已中断;这可以覆盖终态写入持续失败、Future 已结束的场景。
+ if process_id == os.getpid():
+ return False
+
+ # Windows 的 os.kill(pid, 0) 与 POSIX 语义不同,可能直接终止目标进程。
+ # 使用只申请查询权限的 Win32 API,不向目标进程发送任何信号。
+ if os.name == "nt":
+ return _is_windows_process_alive(process_id)
+
+ try:
+ os.kill(process_id, 0)
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ except OSError as exc:
+ logger.warning(
+ f"failed to inspect cross-post owner process, owner: {owner}, error: {exc}"
+ )
+ return True
+ return True
+
+
+def _mark_task_failed(task_id: str, stage: str, error: str) -> dict:
+ """记录结构化失败信息,并保留任务失败前已经到达的进度。"""
+ existing_task = None
+ try:
+ existing_task = sm.state.get_task(task_id)
+ except Exception as exc:
+ logger.warning(f"failed to read task state before failure update: {exc}")
+
+ # 具体服务函数通常比编排层拥有更准确的错误原因。后续的空结果检查
+ # 不能再用通用文案覆盖它,否则 API 调用方仍然只能看到模糊信息。
+ if (
+ existing_task
+ and existing_task.get("state") == const.TASK_STATE_FAILED
+ and existing_task.get("error")
+ ):
+ return existing_task
+
+ message = str(error or "unknown task error").strip()
+ progress = int((existing_task or {}).get("progress", 0) or 0)
+ logger.error(
+ f"task failed, task_id: {task_id}, stage: {stage}, error: {message}"
+ )
+ failure = {
+ "task_id": task_id,
+ "state": const.TASK_STATE_FAILED,
+ "progress": progress,
+ "failed_stage": stage,
+ "error": message,
+ }
+ sm.state.update_task(
+ task_id,
+ state=failure["state"],
+ progress=failure["progress"],
+ failed_stage=failure["failed_stage"],
+ error=failure["error"],
+ )
+ return failure
+
+
def generate_script(task_id, params):
logger.info("\n\n## generating video script")
video_script = params.video_script.strip()
@@ -30,8 +238,7 @@ def generate_script(task_id, params):
logger.debug(f"video script: \n{video_script}")
if not video_script:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error("failed to generate video script.")
+ _mark_task_failed(task_id, "script", "failed to generate video script")
return None
return video_script
@@ -61,8 +268,11 @@ def generate_terms(task_id, params, video_script):
logger.debug(f"video terms: {utils.to_json(video_terms)}")
if not video_terms:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error("failed to generate video terms.")
+ _mark_task_failed(
+ task_id,
+ "terms",
+ "failed to generate video search terms",
+ )
return None
# 可选的 TwelveLabs Marengo 语义重排:未启用时返回原顺序,无任何副作用。
@@ -147,11 +357,11 @@ def generate_audio(task_id, params, video_script):
task_id, requested_custom_audio_file
)
except ValueError as exc:
- logger.error(
- "custom audio file is invalid, "
- f"task_id: {task_id}, path: {requested_custom_audio_file}, error: {str(exc)}"
+ _mark_task_failed(
+ task_id,
+ "audio",
+ f"invalid custom audio file: {exc}",
)
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
return None, None, None
if not custom_audio_file:
@@ -164,26 +374,26 @@ def generate_audio(task_id, params, video_script):
voice_file=audio_file,
)
if sub_maker is None:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error(
- """failed to generate audio:
-1. check if the language of the voice matches the language of the video script.
-2. check if the network is available. If you are in China, it is recommended to use a VPN and enable the global traffic mode.
- """.strip()
+ _mark_task_failed(
+ task_id,
+ "audio",
+ "failed to synthesize audio; verify the selected voice and TTS connectivity",
)
return None, None, None
audio_duration = math.ceil(voice.get_audio_duration(sub_maker))
if audio_duration == 0:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error("failed to get audio duration.")
+ _mark_task_failed(task_id, "audio", "generated audio duration is zero")
return None, None, None
return audio_file, audio_duration, sub_maker
else:
logger.info(f"using custom audio file: {custom_audio_file}")
audio_duration = voice.get_audio_duration(custom_audio_file)
if audio_duration == 0:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error("failed to get audio duration from custom audio file.")
+ _mark_task_failed(
+ task_id,
+ "audio",
+ "custom audio duration is zero",
+ )
return None, None, None
return custom_audio_file, audio_duration, None
@@ -252,9 +462,10 @@ def get_video_materials(task_id, params, video_terms, audio_duration):
materials=params.video_materials, clip_duration=params.video_clip_duration
)
if not materials:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error(
- "no valid materials found, please check the materials and try again."
+ _mark_task_failed(
+ task_id,
+ "materials",
+ "no valid local video materials were found",
)
return None
return [material_info.url for material_info in materials]
@@ -277,9 +488,10 @@ def get_video_materials(task_id, params, video_terms, audio_duration):
match_script_order=params.match_materials_to_script,
)
if not downloaded_videos:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- logger.error(
- "failed to download videos, maybe the network is not available. if you are in China, please use a VPN."
+ _mark_task_failed(
+ task_id,
+ "materials",
+ f"failed to download video materials from {params.video_source}",
)
return None
return downloaded_videos
@@ -385,7 +597,335 @@ def generate_final_videos(
return final_video_paths, combined_video_paths, warnings
-def start(task_id, params: VideoParams, stop_at: str = "video"):
+def _patch_cross_post_state(task_id: str, **kwargs) -> bool | None:
+ """安全更新发布字段;短暂状态后端故障时有限重试。"""
+ for attempt in range(1, _CROSS_POST_STATE_WRITE_ATTEMPTS + 1):
+ try:
+ return sm.state.patch_task(task_id, **kwargs)
+ except Exception as exc:
+ # Redis 短暂断连不应让任务永久停留在 pending/processing。发布状态
+ # 写入频率很低,这里使用固定次数和短等待即可覆盖瞬时故障,同时
+ # 避免后台线程无限阻塞。最后一次失败保留完整堆栈便于定位。
+ if attempt >= _CROSS_POST_STATE_WRITE_ATTEMPTS:
+ logger.exception(
+ f"failed to update cross-post state after retries, "
+ f"task_id: {task_id}, fields: {', '.join(kwargs)}, "
+ f"attempts: {attempt}, error: {exc}"
+ )
+ return None
+
+ logger.warning(
+ f"retry cross-post state update, task_id: {task_id}, "
+ f"fields: {', '.join(kwargs)}, attempt: {attempt}, error: {exc}"
+ )
+ time.sleep(_CROSS_POST_STATE_RETRY_DELAY_SECONDS)
+
+ return None
+
+
+def _record_cross_post_failure(
+ task_id: str,
+ error: Exception,
+ results: list[dict] | None = None,
+) -> None:
+ """尽最大努力保存发布失败;状态后端不可用时由日志保留诊断信息。"""
+ updated = _patch_cross_post_state(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_FAILED,
+ cross_post_results=results or None,
+ cross_post_error=str(error),
+ cross_post_owner=None,
+ )
+ if updated is False:
+ logger.warning(f"discard cross-post failure for missing task: {task_id}")
+
+
+def _ensure_cross_post_terminal_state(task_id: str) -> None:
+ """Future 结束后把仍处于活动态的任务收敛为失败。"""
+ try:
+ task = sm.state.get_task(task_id)
+ except Exception as exc:
+ # 此处已经是 Future 的最终回调,没有后续同步调用方可以处理异常。
+ # 状态后端恢复后,下一次进程启动仍会通过恢复逻辑处理遗留状态。
+ logger.exception(
+ f"failed to verify final cross-post state, task_id: {task_id}, error: {exc}"
+ )
+ return
+
+ if not task or task.get("cross_post_state") not in _ACTIVE_CROSS_POST_STATES:
+ return
+
+ logger.warning(
+ f"cross-post worker ended without terminal state, task_id: {task_id}, "
+ f"state: {task.get('cross_post_state')}"
+ )
+ _record_cross_post_failure(
+ task_id,
+ RuntimeError("cross-post worker ended without persisting a terminal state"),
+ task.get("cross_post_results"),
+ )
+
+
+def recover_interrupted_cross_posts(page_size: int = 100) -> int | None:
+ """
+ 将进程重启后无法恢复的发布任务标记为失败。
+
+ 跨平台发布使用当前进程内的线程池,不是持久化任务队列。进程启动时,
+ Redis 中残留的 pending/processing 不会自动继续执行;如果继续把它们视为
+ 运行中,用户将永久无法删除任务。这里分页扫描状态,只处理当前进程没有
+ 对应 Future 的活动记录,并保留已经生成的视频结果。
+ """
+ recovered = 0
+ page = 1
+
+ while True:
+ try:
+ tasks, total = sm.state.get_all_tasks(page, page_size)
+ except Exception as exc:
+ logger.exception(f"failed to recover interrupted cross-post tasks: {exc}")
+ return None
+
+ for task in tasks:
+ task_id = str(task.get("task_id") or "")
+ if (
+ not task_id
+ or task.get("cross_post_state") not in _ACTIVE_CROSS_POST_STATES
+ or _is_cross_post_active_in_process(task_id)
+ or _is_cross_post_owner_alive(task.get("cross_post_owner"))
+ ):
+ continue
+
+ updated = _patch_cross_post_state(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_FAILED,
+ cross_post_error=_INTERRUPTED_CROSS_POST_ERROR,
+ cross_post_owner=None,
+ )
+ if updated is True:
+ recovered += 1
+
+ if page * page_size >= total or not tasks:
+ break
+ page += 1
+
+ if recovered:
+ logger.warning(f"recovered interrupted cross-post tasks: {recovered}")
+ return recovered
+
+
+def _run_cross_post(
+ task_id: str,
+ video_paths: tuple[str, ...],
+ video_subject: str,
+ video_script: str,
+ video_language: str,
+ platforms: tuple[str, ...],
+ youtube_privacy_status: str,
+) -> None:
+ """后台执行跨平台发布,并只补充发布相关的任务字段。"""
+ results = []
+ try:
+ state_updated = _patch_cross_post_state(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_PROCESSING,
+ cross_post_error=None,
+ cross_post_owner=_cross_post_process_owner,
+ )
+ if state_updated is not True:
+ # False 表示任务已删除,None 表示状态后端暂时不可用。两种情况都
+ # 不应继续调用第三方接口,否则用户无法查询或控制这次发布。
+ if state_updated is False:
+ logger.warning(f"skip cross-post for missing task: {task_id}")
+ else:
+ _record_cross_post_failure(
+ task_id,
+ RuntimeError("failed to persist cross-post processing state"),
+ )
+ return
+
+ logger.info(
+ f"cross-post started, task_id: {task_id}, platforms: {', '.join(platforms)}"
+ )
+ youtube_extra = None
+ if any(platform.startswith("youtube") for platform in platforms):
+ metadata = llm.generate_social_metadata(
+ video_subject=video_subject,
+ video_script=video_script,
+ language=video_language or "",
+ platform="youtube_shorts",
+ )
+ youtube_extra = {
+ "youtube_title": metadata.get("title", video_subject),
+ "youtube_description": metadata.get("caption", ""),
+ "tags": metadata.get("hashtags", []),
+ "privacyStatus": youtube_privacy_status,
+ "containsSyntheticMedia": True,
+ }
+
+ for video_path in video_paths:
+ result = upload_post.cross_post_video(
+ video_path=video_path,
+ title=video_subject or "Check out this video! #shorts #viral",
+ platforms=list(platforms),
+ youtube_extra=youtube_extra,
+ )
+ if not isinstance(result, dict):
+ result = {
+ "success": False,
+ "error": "Upload-Post returned an invalid response",
+ }
+ results.append(result)
+
+ failures = [result for result in results if not result.get("success")]
+ if failures:
+ error_messages = [
+ str(
+ result.get("error")
+ or result.get("message")
+ or "unknown upload error"
+ )
+ for result in failures
+ ]
+ cross_post_state = const.CROSS_POST_STATE_FAILED
+ cross_post_error = "; ".join(error_messages)
+ logger.warning(
+ f"cross-post completed with failures, task_id: {task_id}, "
+ f"failed: {len(failures)}, total: {len(results)}"
+ )
+ else:
+ cross_post_state = const.CROSS_POST_STATE_COMPLETE
+ cross_post_error = None
+ logger.success(
+ f"cross-post completed, task_id: {task_id}, videos: {len(results)}"
+ )
+
+ state_updated = _patch_cross_post_state(
+ task_id,
+ cross_post_state=cross_post_state,
+ cross_post_results=results,
+ cross_post_error=cross_post_error,
+ cross_post_owner=None,
+ )
+ if state_updated is False:
+ logger.warning(f"discard cross-post result for missing task: {task_id}")
+ elif state_updated is None:
+ # 上传已经结束但结果没有持久化时,不能继续保留 processing。
+ # 失败状态写入会再次经过有限重试,至少让调用方得到明确终态。
+ _record_cross_post_failure(
+ task_id,
+ RuntimeError("failed to persist final cross-post result"),
+ results,
+ )
+ except Exception as exc:
+ # 发布失败只影响发布状态,不能反向覆盖已经完成的视频任务。
+ # 异常原文写入任务状态,API 调用方无需访问服务端日志也能定位问题。
+ logger.exception(f"cross-post failed, task_id: {task_id}, error: {exc}")
+ _record_cross_post_failure(task_id, exc, results)
+
+
+def _run_cross_post_with_slot(*args) -> None:
+ """执行发布任务,并确保成功、失败或异常时都会归还队列容量。"""
+ try:
+ _run_cross_post(*args)
+ except Exception as exc:
+ # _run_cross_post 已处理预期异常;这里是最后一道保护,避免未来新增
+ # 逻辑抛出的异常只保存在无人读取的 Future 中。
+ task_id = str(args[0]) if args else "unknown"
+ logger.exception(
+ f"cross-post worker crashed, task_id: {task_id}, error: {exc}"
+ )
+ if args:
+ _record_cross_post_failure(task_id, exc)
+ finally:
+ _cross_post_slots.release()
+
+
+def _finalize_cross_post_future(task_id: str, future: Future) -> None:
+ """清理 Future 注册,并确保取消、异常和状态写入失败都能收敛。"""
+ _unregister_cross_post_future(task_id, future)
+
+ try:
+ error = future.exception()
+ except CancelledError:
+ logger.warning(f"cross-post future was cancelled, task_id: {task_id}")
+ # Future 在开始执行前被取消时,worker 的 finally 不会运行,因此需要
+ # 在回调中归还队列容量,并把持久化状态改为失败。
+ _cross_post_slots.release()
+ _record_cross_post_failure(
+ task_id,
+ RuntimeError("cross-post job was cancelled before execution"),
+ )
+ return
+ except Exception as exc:
+ logger.exception(
+ f"failed to inspect cross-post future, task_id: {task_id}, error: {exc}"
+ )
+ _ensure_cross_post_terminal_state(task_id)
+ return
+
+ if error is not None:
+ logger.error(
+ f"cross-post future failed, task_id: {task_id}, "
+ f"error: {type(error).__name__}: {error}"
+ )
+
+ _ensure_cross_post_terminal_state(task_id)
+
+
+def _schedule_cross_post(
+ task_id: str,
+ video_paths: list[str],
+ params: VideoParams,
+ video_script: str,
+ platforms: list[str],
+ youtube_privacy_status: str,
+) -> str | None:
+ """提交后台发布任务;成功返回 None,调度失败返回可查询的错误原因。"""
+ if not _cross_post_slots.acquire(blocking=False):
+ error = "cross-post queue is full; publishing was skipped"
+ logger.warning(
+ f"skip cross-post because queue is full, task_id: {task_id}, "
+ f"capacity: {_cross_post_max_pending_tasks}"
+ )
+ _patch_cross_post_state(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_FAILED,
+ cross_post_error=error,
+ cross_post_owner=None,
+ )
+ return error
+
+ try:
+ future = _cross_post_executor.submit(
+ _run_cross_post_with_slot,
+ task_id,
+ tuple(video_paths),
+ params.video_subject or "",
+ video_script,
+ params.video_language or "",
+ tuple(platforms),
+ youtube_privacy_status,
+ )
+ _register_cross_post_future(task_id, future)
+ future.add_done_callback(partial(_finalize_cross_post_future, task_id))
+ except RuntimeError as exc:
+ _unregister_cross_post_future(task_id)
+ _cross_post_slots.release()
+ logger.exception(
+ f"failed to schedule cross-post, task_id: {task_id}, error: {exc}"
+ )
+ _patch_cross_post_state(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_FAILED,
+ cross_post_error=f"failed to schedule cross-post: {exc}",
+ cross_post_owner=None,
+ )
+ return f"failed to schedule cross-post: {exc}"
+
+ return None
+
+
+def _run_pipeline(task_id, params: VideoParams, stop_at: str = "video"):
logger.info(f"start task: {task_id}, stop_at: {stop_at}")
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=5)
@@ -397,15 +937,21 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
and not sonilo.is_enabled()
):
- logger.error("Sonilo background music requires an API key")
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ "Sonilo background music requires an API key",
+ )
# 1. Generate script
video_script = generate_script(task_id, params)
if not video_script or "Error: " in video_script:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ error = (
+ video_script.removeprefix("Error: ").strip()
+ if isinstance(video_script, str) and "Error: " in video_script
+ else "failed to generate video script"
+ )
+ return _mark_task_failed(task_id, "script", error)
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=10)
@@ -420,8 +966,11 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
if params.video_source != "local":
video_terms = generate_terms(task_id, params, video_script)
if not video_terms:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ return _mark_task_failed(
+ task_id,
+ "terms",
+ "failed to generate video search terms",
+ )
save_script_data(task_id, video_script, video_terms, params)
@@ -438,8 +987,11 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
task_id, params, video_script
)
if not audio_file:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ return _mark_task_failed(
+ task_id,
+ "audio",
+ "failed to prepare narration audio",
+ )
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=30)
@@ -473,8 +1025,11 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
task_id, params, video_terms, audio_duration
)
if not downloaded_videos:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ return _mark_task_failed(
+ task_id,
+ "materials",
+ "failed to prepare video materials",
+ )
if stop_at == "materials":
sm.state.update_task(
@@ -503,46 +1058,33 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
)
if not final_video_paths:
- sm.state.update_task(task_id, state=const.TASK_STATE_FAILED)
- return
+ return _mark_task_failed(
+ task_id,
+ "video",
+ "failed to generate final video",
+ )
logger.success(
f"task {task_id} finished, generated {len(final_video_paths)} videos."
)
- # 7. Cross-post to social platforms (if enabled)
- cross_post_results = []
- if upload_post.upload_post_service.is_configured() and upload_post.upload_post_service.auto_upload:
- platforms = upload_post.upload_post_service.platforms
- logger.info(f"\n\n## cross-posting videos to {', '.join(platforms)}")
-
- youtube_extra = None
- if any(p.startswith("youtube") for p in platforms):
- metadata = llm.generate_social_metadata(
- video_subject=params.video_subject,
- video_script=video_script,
- language=params.video_language or "",
- platform="youtube_shorts",
- )
- youtube_extra = {
- "youtube_title": metadata.get("title", params.video_subject),
- "youtube_description": metadata.get("caption", ""),
- "tags": metadata.get("hashtags", []),
- "privacyStatus": upload_post.upload_post_service.youtube_privacy_status,
- "containsSyntheticMedia": True,
- }
-
- for video_path in final_video_paths:
- result = upload_post.cross_post_video(
- video_path=video_path,
- title=params.video_subject or "Check out this video! #shorts #viral",
- youtube_extra=youtube_extra,
- )
- cross_post_results.append(result)
- if result.get('success'):
- logger.info(f"✅ Cross-posted: {video_path}")
- else:
- logger.warning(f"⚠️ Failed to cross-post: {video_path} - {result.get('error', 'Unknown error')}")
+ # 7. 先完成视频生成任务,再按需提交跨平台发布。第三方上传可能耗时
+ # 数分钟,不应阻塞视频结果返回,也不能反向影响已经生成的成片。
+ cross_post_enabled = (
+ upload_post.upload_post_service.is_configured()
+ and upload_post.upload_post_service.auto_upload
+ )
+ platforms = (
+ list(upload_post.upload_post_service.platforms)
+ if cross_post_enabled
+ else []
+ )
+ should_cross_post = cross_post_enabled and bool(platforms)
+ if cross_post_enabled and not platforms:
+ logger.warning(
+ f"skip cross-post because no platforms are configured, task_id: {task_id}"
+ )
+ cross_post_state = const.CROSS_POST_STATE_PENDING if should_cross_post else None
kwargs = {
"videos": final_video_paths,
@@ -553,15 +1095,52 @@ def start(task_id, params: VideoParams, stop_at: str = "video"):
"audio_duration": audio_duration,
"subtitle_path": subtitle_path,
"materials": downloaded_videos,
- "cross_post_results": cross_post_results if cross_post_results else None,
+ "cross_post_state": cross_post_state,
+ "cross_post_results": None,
+ "cross_post_error": None,
+ "cross_post_owner": _cross_post_process_owner if should_cross_post else None,
"warnings": generation_warnings or None,
}
sm.state.update_task(
task_id, state=const.TASK_STATE_COMPLETE, progress=100, **kwargs
)
+
+ if should_cross_post:
+ scheduling_error = _schedule_cross_post(
+ task_id=task_id,
+ video_paths=final_video_paths,
+ params=params,
+ video_script=video_script,
+ platforms=platforms,
+ youtube_privacy_status=(
+ upload_post.upload_post_service.youtube_privacy_status
+ ),
+ )
+ # 队列满或线程池关闭属于同步可知的调度失败。任务状态已经由调度函数
+ # 更新,这里同步修正返回快照,避免调用方收到与后续查询不一致的 pending。
+ if scheduling_error:
+ kwargs["cross_post_state"] = const.CROSS_POST_STATE_FAILED
+ kwargs["cross_post_error"] = scheduling_error
+ kwargs["cross_post_owner"] = None
+
return kwargs
+def start(task_id, params: VideoParams, stop_at: str = "video"):
+ """执行任务流水线,并确保未预期异常也会转换成可查询的失败状态。"""
+ try:
+ return _run_pipeline(task_id, params, stop_at=stop_at)
+ except Exception as exc:
+ logger.exception(
+ f"unexpected task pipeline failure, task_id: {task_id}, error: {exc}"
+ )
+ return _mark_task_failed(
+ task_id,
+ "pipeline",
+ f"{type(exc).__name__}: {exc}",
+ )
+
+
if __name__ == "__main__":
task_id = "task_id"
params = VideoParams(
diff --git a/app/services/video.py b/app/services/video.py
index 3a44eb58..548ffc53 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -1,4 +1,3 @@
-import glob
import itertools
import io
import os
diff --git a/cli.py b/cli.py
index 9a94a1f9..afa1c0f7 100644
--- a/cli.py
+++ b/cli.py
@@ -12,7 +12,7 @@ from uuid import UUID, uuid4
from loguru import logger
if TYPE_CHECKING:
- from app.models.schema import VideoParams
+ from app.models.schema import MaterialInfo, VideoParams
DEFAULT_VOICE_NAME = "zh-CN-XiaoxiaoNeural-Female"
@@ -779,8 +779,13 @@ def run_cli(argv: Sequence[str] | None = None) -> int:
f"CLI task failed with an unexpected error: task_id={task_id}, error={exc}"
)
return 1
- if not result:
- logger.error(f"CLI task failed: task_id={task_id}, stop_at={args.stop_at}")
+ if not result or result.get("state") == tm.const.TASK_STATE_FAILED:
+ failed_stage = result.get("failed_stage", "unknown") if result else "unknown"
+ error = result.get("error", "unknown task error") if result else "empty result"
+ logger.error(
+ f"CLI task failed: task_id={task_id}, stop_at={args.stop_at}, "
+ f"stage={failed_stage}, error={error}"
+ )
return 1
print(json.dumps({"task_id": task_id, "result": result}, ensure_ascii=False))
diff --git a/config.example.toml b/config.example.toml
index 763fbe40..032f2f38 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -266,6 +266,11 @@ upload_post_platforms = ["tiktok", "instagram"]
upload_post_auto_upload = false
# YouTube privacy: "public", "unlisted", or "private".
upload_post_youtube_privacy_status = "public"
+# Maximum number of running and queued cross-post jobs per process. When the
+# limit is reached, video generation still succeeds and only cross-posting is
+# rejected.
+# Cross-post jobs run in the current process and are not resumed after restart.
+upload_post_max_pending_tasks = 10
# =============================================================================
# Whisper Subtitles / Whisper 字幕
diff --git a/pyproject.toml b/pyproject.toml
index eac8501d..c79e7a0b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,8 +47,13 @@ twelvelabs = [
dev = [
"coverage==7.15.1",
"pytest==9.1.1",
+ "ruff==0.15.21",
]
+[tool.ruff.lint.per-file-ignores]
+# WebUI 需要先把项目根目录加入 sys.path,随后才能导入 app 包。
+"webui/Main.py" = ["E402"]
+
[tool.coverage.run]
# 统计分支覆盖率可以识别“代码行执行了,但条件的另一条分支从未验证”的情况,
# 比只统计行覆盖率更适合作为 CI 质量基线。CLI 和 WebUI 都属于生产入口,
@@ -58,10 +63,10 @@ branch = true
source = ["app", "cli", "webui", "main", "docs/skill"]
[tool.coverage.report]
-# 当前 pytest 完整测试的实测分支覆盖率为 68.19%。以 67% 作为稳定底线,
-# 既能把本次新增覆盖固化为 CI 质量门槛,也为 macOS、Windows 和 Linux
-# 之间少量平台分支差异保留余量;后续增加测试后可继续逐步提高该阈值。
-fail_under = 67
+# Python 3.11 和 3.13 完整测试的实测分支覆盖率均超过 70.4%。以 70%
+# 作为稳定底线,可以固化失败状态、异步发布恢复和 Redis 原子更新测试,
+# 同时为不同 Python 版本与操作系统的少量分支差异保留余量。
+fail_under = 70
show_missing = true
skip_covered = true
diff --git a/test/services/test_cli.py b/test/services/test_cli.py
index 6d074859..9311ad70 100644
--- a/test/services/test_cli.py
+++ b/test/services/test_cli.py
@@ -80,6 +80,28 @@ class TestCli(unittest.TestCase):
self.assertEqual(code, 1)
log_error.assert_called_once()
+ def test_run_cli_returns_error_for_structured_task_failure(self):
+ """任务服务返回结构化失败信息时,CLI 仍必须以非零状态退出。"""
+ failure = {
+ "task_id": "task-structured-failure",
+ "state": -1,
+ "progress": 30,
+ "failed_stage": "audio",
+ "error": "TTS request timed out",
+ }
+
+ with patch("app.services.task.start", return_value=failure), patch(
+ "app.utils.utils.get_uuid", return_value="task-structured-failure"
+ ), patch.object(cli.logger, "error") as log_error, patch(
+ "builtins.print"
+ ) as print_mock:
+ code = cli.run_cli(["--video-subject", "失败场景"])
+
+ self.assertEqual(code, 1)
+ print_mock.assert_not_called()
+ self.assertIn("stage=audio", log_error.call_args.args[0])
+ self.assertIn("TTS request timed out", log_error.call_args.args[0])
+
def test_subtitle_enabled_by_default(self):
args = cli.parse_args(["--video-subject", "test"])
params = cli.build_video_params(args)
@@ -231,7 +253,6 @@ class TestCli(unittest.TestCase):
def test_local_material_filename_resolved_to_absolute_path(self):
"""After preprocess_video, material.url should be an absolute path, not a bare filename."""
import os
- import tempfile
from app.utils import utils
from app.services import video as vd
from app.models.schema import MaterialInfo
diff --git a/test/services/test_config.py b/test/services/test_config.py
index 6b6e94ce..7ad627c2 100644
--- a/test/services/test_config.py
+++ b/test/services/test_config.py
@@ -50,6 +50,7 @@ class TestConfigPersistence:
"upload_post_platforms",
"upload_post_auto_upload",
"upload_post_youtube_privacy_status",
+ "upload_post_max_pending_tasks",
}
assert upload_post_keys <= example_config["app"].keys()
diff --git a/test/services/test_controller_video.py b/test/services/test_controller_video.py
index c5b1263d..e7c9982b 100644
--- a/test/services/test_controller_video.py
+++ b/test/services/test_controller_video.py
@@ -13,6 +13,7 @@ from app.controllers.manager.base_manager import TaskQueueFullError
from app.controllers.v1 import video as video_controller
from app.models import const
from app.models.exception import HttpException
+from app.models.schema import TaskListResponse, TaskQueryResponse
from app.services import state as sm
from app.utils import utils
@@ -39,6 +40,22 @@ class TestVideoControllerHelpers(unittest.TestCase):
expected,
)
+ def test_fastapi_startup_recovers_interrupted_cross_posts(self):
+ """API 进程启动时必须执行一次发布遗留状态恢复。"""
+ from app import asgi
+ from app.services import task as task_service
+
+ with patch.object(
+ task_service, "recover_interrupted_cross_posts"
+ ) as recover:
+ async def run_lifespan():
+ async with asgi.application_lifespan(asgi.app):
+ pass
+
+ asyncio.run(run_lifespan())
+
+ recover.assert_called_once_with()
+
def test_sanitize_upload_filename_rejects_empty_name(self):
"""空文件名和目录占位符不能进入服务端存储路径。"""
for filename in ("", ".", "..", "/"):
@@ -161,7 +178,7 @@ class TestVideoControllerTasks(unittest.TestCase):
with patch.object(
video_controller.sm.state,
"get_all_tasks",
- return_value=([{"id": "task-1"}], 21),
+ return_value=([{"id": "task-1", "cross_post_owner": "internal"}], 21),
) as get_all:
response = video_controller.get_all_tasks(
self._request(), page=2, page_size=10
@@ -194,6 +211,7 @@ class TestVideoControllerTasks(unittest.TestCase):
state=const.TASK_STATE_COMPLETE,
videos=[video_path],
combined_videos=[video_path],
+ cross_post_owner="localhost:123:internal",
)
with patch.dict(config.app, {"endpoint": ""}):
response = video_controller.get_task(
@@ -204,11 +222,109 @@ class TestVideoControllerTasks(unittest.TestCase):
response["data"]["videos"],
[f"/tasks/{task_id}/final-1.mp4"],
)
+ self.assertNotIn("cross_post_owner", response["data"])
+ self.assertIn("cross_post_owner", sm.state.get_task(task_id))
self.assertEqual(sm.state.get_task(task_id)["videos"], [video_path])
finally:
sm.state.delete_task(task_id)
shutil.rmtree(task_dir, ignore_errors=True)
+ def test_task_query_preserves_structured_failure_details(self):
+ """失败阶段和错误信息必须通过任务查询接口原样返回。"""
+ failed_task = {
+ "task_id": "failed-task",
+ "state": const.TASK_STATE_FAILED,
+ "progress": 30,
+ "failed_stage": "audio",
+ "error": "TTS request timed out",
+ }
+
+ with patch.object(
+ video_controller.sm.state,
+ "get_task",
+ return_value=failed_task,
+ ):
+ response = video_controller.get_task(
+ self._request(), task_id="failed-task", query=MagicMock()
+ )
+
+ self.assertEqual(response["data"], failed_task)
+
+ def test_task_query_schema_documents_success_and_failure_states(self):
+ """OpenAPI 模型示例必须覆盖发布成功和生成失败两种状态。"""
+ examples = TaskQueryResponse.model_json_schema()["examples"]
+
+ self.assertEqual(examples[0]["data"]["cross_post_state"], "complete")
+ self.assertEqual(examples[1]["data"]["failed_stage"], "audio")
+ self.assertTrue(examples[1]["data"]["error"])
+
+ task_data_schema = TaskQueryResponse.model_json_schema()["$defs"][
+ "TaskStatusData"
+ ]
+ self.assertIn("failed_stage", task_data_schema["properties"])
+ self.assertIn("cross_post_state", task_data_schema["properties"])
+
+ list_schema = TaskListResponse.model_json_schema()
+ self.assertIn("TaskListData", list_schema["$defs"])
+ self.assertIn("TaskStatusData", list_schema["$defs"])
+
+ def test_delete_rejects_generation_and_cross_posting_tasks(self):
+ """生成中和发布中的任务都在读取目录,删除接口必须返回 409。"""
+ busy_tasks = (
+ {
+ "task_id": "generating-task",
+ "state": const.TASK_STATE_PROCESSING,
+ "progress": 30,
+ },
+ {
+ "task_id": "publishing-task",
+ "state": const.TASK_STATE_COMPLETE,
+ "progress": 100,
+ "cross_post_state": const.CROSS_POST_STATE_PROCESSING,
+ },
+ )
+
+ for task in busy_tasks:
+ with self.subTest(task_id=task["task_id"]), patch.object(
+ video_controller.sm.state,
+ "get_task",
+ return_value=task,
+ ), patch.object(video_controller.sm.state, "delete_task") as delete_task:
+ with self.assertRaises(HttpException) as raised:
+ video_controller.delete_video(
+ self._request(), task_id=task["task_id"]
+ )
+
+ self.assertEqual(raised.exception.status_code, 409)
+ delete_task.assert_not_called()
+
+ def test_delete_allows_completed_task(self):
+ """普通已完成任务仍应保持原有删除行为。"""
+ completed_task = {
+ "task_id": "completed-task",
+ "state": const.TASK_STATE_COMPLETE,
+ "progress": 100,
+ "cross_post_state": const.CROSS_POST_STATE_COMPLETE,
+ }
+
+ with patch.object(
+ video_controller.sm.state,
+ "get_task",
+ return_value=completed_task,
+ ), patch.object(
+ video_controller.utils,
+ "task_dir",
+ return_value="/tmp/mpt-completed-task-test",
+ ), patch.object(
+ video_controller.os.path, "exists", return_value=False
+ ), patch.object(video_controller.sm.state, "delete_task") as delete_task:
+ response = video_controller.delete_video(
+ self._request(), task_id="completed-task"
+ )
+
+ self.assertEqual(response["status"], 200)
+ delete_task.assert_called_once_with("completed-task")
+
def test_get_and_delete_missing_task_return_404(self):
"""查询或删除未知任务都应返回一致的 404,而不是空成功响应。"""
with patch.object(video_controller.sm.state, "get_task", return_value=None):
diff --git a/test/services/test_state.py b/test/services/test_state.py
index 5cd8a9f4..05347b01 100644
--- a/test/services/test_state.py
+++ b/test/services/test_state.py
@@ -1,6 +1,9 @@
+import os
import sys
import threading
import unittest
+import uuid
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
@@ -12,6 +15,7 @@ from app.services.state import MemoryState, RedisState
class _FakeRedis:
def __init__(self, batches):
self.batches = batches
+ self.scan_types = []
self.data = {}
for key in [key for batch in batches for key in batch]:
index = int(key.decode("utf-8").split(":")[-1])
@@ -21,7 +25,8 @@ class _FakeRedis:
b"progress": str(index).encode("utf-8"),
}
- def scan(self, cursor, count):
+ def scan(self, cursor, count, _type=None):
+ self.scan_types.append(_type)
batch_index = int(cursor)
next_cursor = batch_index + 1
if next_cursor >= len(self.batches):
@@ -29,8 +34,42 @@ class _FakeRedis:
return next_cursor, self.batches[batch_index]
def hgetall(self, key):
+ if isinstance(key, str):
+ key = key.encode("utf-8")
return self.data[key]
+ def exists(self, key):
+ if isinstance(key, str):
+ key = key.encode("utf-8")
+ return key in self.data
+
+ def hset(self, key, field=None, value=None, mapping=None):
+ if isinstance(key, str):
+ key = key.encode("utf-8")
+ target = self.data.setdefault(key, {})
+ if mapping:
+ target.update(
+ {
+ str(item_key).encode("utf-8"): str(item_value).encode("utf-8")
+ for item_key, item_value in mapping.items()
+ }
+ )
+ elif field is not None:
+ target[str(field).encode("utf-8")] = str(value).encode("utf-8")
+
+ def eval(self, script, numkeys, key, *arguments):
+ if isinstance(key, str):
+ key = key.encode("utf-8")
+ if key not in self.data:
+ return 0
+
+ target = self.data[key]
+ for index in range(0, len(arguments), 2):
+ field = str(arguments[index]).encode("utf-8")
+ value = str(arguments[index + 1]).encode("utf-8")
+ target[field] = value
+ return 1
+
class TestMemoryState(unittest.TestCase):
def test_get_task_and_get_all_tasks_return_isolated_snapshots(self):
@@ -78,6 +117,36 @@ class TestMemoryState(unittest.TestCase):
self.assertEqual(total, thread_count * tasks_per_thread)
self.assertEqual(len(tasks), total)
+ def test_patch_task_preserves_generated_outputs(self):
+ """异步发布更新不能覆盖已经完成的视频任务字段。"""
+ state = MemoryState()
+ state.update_task(
+ "task-1",
+ state=const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ )
+
+ patched = state.patch_task(
+ "task-1",
+ cross_post_state=const.CROSS_POST_STATE_COMPLETE,
+ cross_post_results=[{"success": True}],
+ )
+
+ self.assertTrue(patched)
+ self.assertEqual(
+ state.get_task("task-1"),
+ {
+ "task_id": "task-1",
+ "state": const.TASK_STATE_COMPLETE,
+ "progress": 100,
+ "videos": ["final.mp4"],
+ "cross_post_state": const.CROSS_POST_STATE_COMPLETE,
+ "cross_post_results": [{"success": True}],
+ },
+ )
+ self.assertFalse(state.patch_task("missing", value="ignored"))
+
class TestRedisState(unittest.TestCase):
def _build_state(self, batch_sizes):
@@ -117,6 +186,100 @@ class TestRedisState(unittest.TestCase):
[task["task_id"] for task in second_page],
[f"task:{i}" for i in range(10, 18)],
)
+ self.assertTrue(state._redis.scan_types)
+ self.assertEqual(set(state._redis.scan_types), {"HASH"})
+
+ @unittest.skipUnless(
+ os.getenv("MPT_TEST_REDIS_HOST"),
+ "MPT_TEST_REDIS_HOST not set",
+ )
+ def test_real_redis_get_all_tasks_ignores_queue_keys(self):
+ """真实 Redis 中的 List 队列不能被任务列表误当作 Hash 读取。"""
+ state = RedisState(
+ host=os.environ["MPT_TEST_REDIS_HOST"],
+ port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
+ db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
+ )
+ suffix = uuid.uuid4()
+ task_ids = [f"ci-list-{suffix}-{index}" for index in range(3)]
+ queue_key = f"ci-queue-{suffix}"
+
+ try:
+ for task_id in task_ids:
+ state.update_task(
+ task_id,
+ state=const.TASK_STATE_COMPLETE,
+ progress=100,
+ )
+ state._redis.rpush(queue_key, *task_ids)
+
+ tasks, _ = state.get_all_tasks(page=1, page_size=1000)
+ returned_ids = {task["task_id"] for task in tasks}
+
+ self.assertTrue(set(task_ids).issubset(returned_ids))
+ self.assertNotIn(queue_key, returned_ids)
+ finally:
+ state._redis.delete(queue_key, *task_ids)
+
+ def test_patch_task_updates_only_existing_redis_task(self):
+ state = self._build_state([1])
+
+ self.assertTrue(
+ state.patch_task(
+ "task:0",
+ cross_post_state=const.CROSS_POST_STATE_FAILED,
+ cross_post_error="upload failed",
+ )
+ )
+ task = state.get_task("task:0")
+ self.assertEqual(task["progress"], 0)
+ self.assertEqual(task["cross_post_state"], const.CROSS_POST_STATE_FAILED)
+ self.assertEqual(task["cross_post_error"], "upload failed")
+ self.assertFalse(state.patch_task("missing", value="ignored"))
+
+ @unittest.skipUnless(
+ os.getenv("MPT_TEST_REDIS_HOST"),
+ "MPT_TEST_REDIS_HOST not set",
+ )
+ def test_real_redis_patch_and_delete_are_atomic(self):
+ """真实 Redis 中并发删除和局部更新不能重新创建残缺任务。"""
+ state = RedisState(
+ host=os.environ["MPT_TEST_REDIS_HOST"],
+ port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
+ db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
+ )
+
+ for _ in range(50):
+ task_id = f"ci-atomic-{uuid.uuid4()}"
+ state.update_task(
+ task_id,
+ state=const.TASK_STATE_COMPLETE,
+ progress=100,
+ )
+ barrier = threading.Barrier(2)
+
+ def patch_task():
+ barrier.wait()
+ state.patch_task(
+ task_id,
+ cross_post_state=const.CROSS_POST_STATE_COMPLETE,
+ )
+
+ def delete_task():
+ barrier.wait()
+ state.delete_task(task_id)
+
+ # Future.result() 会把工作线程异常重新抛到测试线程,避免 Redis
+ # 命令实际失败但仅打印线程异常、最终仍被误判为测试通过。
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ futures = [
+ executor.submit(patch_task),
+ executor.submit(delete_task),
+ ]
+ for future in futures:
+ future.result(timeout=5)
+
+ self.assertIsNone(state.get_task(task_id))
if __name__ == "__main__":
diff --git a/test/services/test_task.py b/test/services/test_task.py
index af477d4a..364d46b1 100644
--- a/test/services/test_task.py
+++ b/test/services/test_task.py
@@ -3,14 +3,17 @@ import os
import shutil
import sys
import tempfile
+from concurrent.futures import Future
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
+from uuid import uuid4
# add project root to python path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from app.services import task as tm
from app.models.schema import MaterialInfo, VideoParams
+from app.services.state import MemoryState, RedisState
from app.utils import utils
resources_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "resources")
@@ -22,10 +25,41 @@ RUN_INTEGRATION_TESTS = os.environ.get("MPT_RUN_INTEGRATION_TESTS", "").lower()
class TestTaskService(unittest.TestCase):
def setUp(self):
- pass
+ # 发布 Future 注册表是进程级状态。测试间清理可以避免某个模拟 Future
+ # 影响后续恢复测试,同时不会触碰真正线程池中的生产任务。
+ with tm._cross_post_registry_lock:
+ tm._cross_post_futures.clear()
def tearDown(self):
- pass
+ with tm._cross_post_registry_lock:
+ tm._cross_post_futures.clear()
+
+ def test_is_task_busy_covers_generation_and_cross_posting(self):
+ """删除入口必须同时识别视频生成和跨平台发布的活跃状态。"""
+ busy_tasks = (
+ {"state": tm.const.TASK_STATE_PROCESSING},
+ {
+ "state": tm.const.TASK_STATE_COMPLETE,
+ "cross_post_state": tm.const.CROSS_POST_STATE_PENDING,
+ },
+ {
+ "state": tm.const.TASK_STATE_COMPLETE,
+ "cross_post_state": tm.const.CROSS_POST_STATE_PROCESSING,
+ },
+ )
+ for task in busy_tasks:
+ with self.subTest(task=task):
+ self.assertTrue(tm.is_task_busy(task))
+
+ self.assertFalse(
+ tm.is_task_busy(
+ {
+ "state": tm.const.TASK_STATE_COMPLETE,
+ "cross_post_state": tm.const.CROSS_POST_STATE_COMPLETE,
+ }
+ )
+ )
+ self.assertFalse(tm.is_task_busy(None))
def test_generate_script_forwards_advanced_prompt_options(self):
"""
@@ -206,22 +240,24 @@ class TestTaskService(unittest.TestCase):
def test_start_rejects_missing_sonilo_key_before_costly_pipeline_steps(self):
"""完整任务缺少 Sonilo Key 时不能先调用 LLM、TTS 或素材服务。"""
params = VideoParams(video_subject="test", bgm_type="sonilo")
+ state = MemoryState()
with (
patch.object(tm.sonilo, "is_enabled", return_value=False),
patch.object(tm, "generate_script") as generate_script,
patch.object(tm, "generate_audio") as generate_audio,
patch.object(tm, "get_video_materials") as get_materials,
- patch.object(tm.sm.state, "update_task") as update_task,
+ patch.object(tm.sm, "state", state),
):
result = tm.start("missing-sonilo-key", params)
- self.assertIsNone(result)
generate_script.assert_not_called()
generate_audio.assert_not_called()
get_materials.assert_not_called()
- update_task.assert_any_call(
- "missing-sonilo-key", state=tm.const.TASK_STATE_FAILED
- )
+ failed_task = state.get_task("missing-sonilo-key")
+ self.assertEqual(result, failed_task)
+ self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(failed_task["failed_stage"], "preflight")
+ self.assertIn("API key", failed_task["error"])
def test_start_does_not_require_sonilo_key_when_volume_is_zero(self):
"""0 音量不会使用 Sonilo,因此缺少 Key 时仍应进入正常任务流水线。"""
@@ -230,15 +266,16 @@ class TestTaskService(unittest.TestCase):
bgm_type="sonilo",
bgm_volume=0.0,
)
+ state = MemoryState()
with (
patch.object(tm.sonilo, "is_enabled", return_value=False),
patch.object(tm, "generate_script", return_value="") as generate_script,
- patch.object(tm.sm.state, "update_task"),
+ patch.object(tm.sm, "state", state),
):
result = tm.start("zero-volume-without-key", params)
- self.assertIsNone(result)
generate_script.assert_called_once_with("zero-volume-without-key", params)
+ self.assertEqual(result["failed_stage"], "script")
def test_generate_terms_uses_script_order_mode_when_enabled(self):
"""
@@ -273,6 +310,7 @@ class TestTaskService(unittest.TestCase):
video_subject="startup story",
video_script="A short startup story.",
)
+ state = MemoryState()
with (
patch.object(
@@ -282,17 +320,17 @@ class TestTaskService(unittest.TestCase):
),
patch.object(tm, "generate_audio") as generate_audio,
patch.object(tm, "get_video_materials") as get_video_materials,
- patch.object(tm.sm.state, "update_task") as update_task,
+ patch.object(tm.sm, "state", state),
):
result = tm.start("term-provider-error", params)
- self.assertIsNone(result)
generate_audio.assert_not_called()
get_video_materials.assert_not_called()
- update_task.assert_any_call(
- "term-provider-error",
- state=tm.const.TASK_STATE_FAILED,
- )
+ failed_task = state.get_task("term-provider-error")
+ self.assertEqual(result, failed_task)
+ self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(failed_task["failed_stage"], "terms")
+ self.assertTrue(failed_task["error"])
def test_generate_audio_uses_custom_file_inside_task_directory(self):
task_id = "test-custom-audio-safe"
@@ -364,11 +402,12 @@ class TestTaskService(unittest.TestCase):
custom_audio_file=missing_audio_file,
voice_name="test-voice",
)
+ state = MemoryState()
try:
with (
patch.object(tm.voice, "tts") as tts,
- patch.object(tm.sm.state, "update_task") as update_task,
+ patch.object(tm.sm, "state", state),
):
audio_file, audio_duration, result_sub_maker = tm.generate_audio(
task_id, params, "script"
@@ -380,7 +419,9 @@ class TestTaskService(unittest.TestCase):
self.assertIsNone(audio_duration)
self.assertIsNone(result_sub_maker)
tts.assert_not_called()
- update_task.assert_called_with(task_id, state=tm.const.TASK_STATE_FAILED)
+ failed_task = state.get_task(task_id)
+ self.assertEqual(failed_task["failed_stage"], "audio")
+ self.assertIn("does not exist", failed_task["error"])
def test_generate_subtitle_uses_whisper_for_custom_audio_without_sub_maker(self):
"""
@@ -637,6 +678,7 @@ class TestTaskService(unittest.TestCase):
with self.subTest(stage=stage):
audio_result, materials_result, videos_result = failure_results
params = VideoParams(video_subject="Coffee")
+ state = MemoryState()
with (
patch.object(tm, "generate_script", return_value="generated script"),
patch.object(tm, "generate_terms", return_value=["coffee"]),
@@ -653,14 +695,39 @@ class TestTaskService(unittest.TestCase):
"generate_final_videos",
return_value=videos_result,
),
- patch.object(tm.sm.state, "update_task") as update_task,
+ patch.object(tm.sm, "state", state),
):
result = tm.start(f"failed-{stage}", params)
- self.assertIsNone(result)
- update_task.assert_any_call(
- f"failed-{stage}", state=tm.const.TASK_STATE_FAILED
- )
+ failed_task = state.get_task(f"failed-{stage}")
+ self.assertEqual(result, failed_task)
+ self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(failed_task["failed_stage"], stage)
+ self.assertTrue(failed_task["error"])
+
+ def test_start_records_unexpected_pipeline_exception(self):
+ """未预期异常也必须结束任务,并向 API 暴露原始异常类型和信息。"""
+ params = VideoParams(video_subject="Coffee")
+ state = MemoryState()
+
+ with (
+ patch.object(
+ tm,
+ "generate_script",
+ side_effect=RuntimeError("provider connection reset"),
+ ),
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("unexpected-failure", params)
+
+ failed_task = state.get_task("unexpected-failure")
+ self.assertEqual(result, failed_task)
+ self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(failed_task["failed_stage"], "pipeline")
+ self.assertEqual(
+ failed_task["error"],
+ "RuntimeError: provider connection reset",
+ )
def test_start_generates_youtube_metadata_for_each_cross_post(self):
"""
@@ -677,6 +744,17 @@ class TestTaskService(unittest.TestCase):
"hashtags": ["coffee", "shorts"],
}
service = tm.upload_post.upload_post_service
+ state = MemoryState()
+
+ def run_immediately(function, *args):
+ future = Future()
+ try:
+ function(*args)
+ except Exception as exc:
+ future.set_exception(exc)
+ else:
+ future.set_result(None)
+ return future
with (
patch.object(tm, "generate_script", return_value="generated script"),
@@ -719,7 +797,12 @@ class TestTaskService(unittest.TestCase):
{"success": False, "error": "upload failed"},
],
) as cross_post,
- patch.object(tm.sm.state, "update_task"),
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm._cross_post_executor,
+ "submit",
+ side_effect=run_immediately,
+ ),
):
result = tm.start("youtube-cross-post", params)
@@ -739,13 +822,575 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(cross_post.call_count, 2)
for call in cross_post.call_args_list:
self.assertEqual(call.kwargs["youtube_extra"], expected_extra)
+ self.assertEqual(call.kwargs["platforms"], ["youtube"])
+
+ # start() 返回的是视频完成时的稳定快照;后台发布结果通过任务查询获取。
+ self.assertEqual(
+ result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING
+ )
+ self.assertIsNone(result["cross_post_results"])
+ published_task = state.get_task("youtube-cross-post")
+ self.assertEqual(published_task["state"], tm.const.TASK_STATE_COMPLETE)
self.assertEqual(
- result["cross_post_results"],
+ published_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
+ )
+ self.assertEqual(
+ published_task["cross_post_results"],
[
{"success": True},
{"success": False, "error": "upload failed"},
],
)
+ self.assertEqual(published_task["cross_post_error"], "upload failed")
+
+ def test_start_returns_before_cross_post_worker_runs(self):
+ """视频任务完成时只提交发布工作,不能在生成线程中同步上传。"""
+ params = VideoParams(video_subject="Coffee")
+ service = tm.upload_post.upload_post_service
+ state = MemoryState()
+ submitted = []
+
+ def capture_submission(function, *args):
+ submitted.append((function, args))
+ return MagicMock(spec=Future)
+
+ with (
+ patch.object(tm, "generate_script", return_value="generated script"),
+ patch.object(tm, "generate_terms", return_value=["coffee"]),
+ patch.object(tm, "save_script_data"),
+ patch.object(
+ tm,
+ "generate_audio",
+ return_value=("audio.mp3", 5, object()),
+ ),
+ patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
+ patch.object(tm, "get_video_materials", return_value=["clip.mp4"]),
+ patch.object(
+ tm,
+ "generate_final_videos",
+ return_value=(["final.mp4"], ["combined.mp4"], []),
+ ),
+ patch.object(service, "is_configured", return_value=True),
+ patch.object(service, "auto_upload", True),
+ patch.object(service, "platforms", ["tiktok"]),
+ patch.object(service, "youtube_privacy_status", "private"),
+ patch.object(tm.upload_post, "cross_post_video") as cross_post,
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm._cross_post_executor,
+ "submit",
+ side_effect=capture_submission,
+ ) as submit,
+ ):
+ result = tm.start("deferred-cross-post", params)
+
+ submit.assert_called_once()
+ cross_post.assert_not_called()
+ self.assertEqual(result["videos"], ["final.mp4"])
+ self.assertEqual(result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING)
+ completed_task = state.get_task("deferred-cross-post")
+ self.assertEqual(completed_task["state"], tm.const.TASK_STATE_COMPLETE)
+ self.assertEqual(completed_task["progress"], 100)
+
+ worker, worker_args = submitted[0]
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm.upload_post,
+ "cross_post_video",
+ return_value={"success": True, "request_id": "upload-1"},
+ ),
+ ):
+ worker(*worker_args)
+
+ published_task = state.get_task("deferred-cross-post")
+ self.assertEqual(published_task["videos"], ["final.mp4"])
+ self.assertEqual(
+ published_task["cross_post_state"], tm.const.CROSS_POST_STATE_COMPLETE
+ )
+
+ def test_cross_post_worker_failure_does_not_change_video_completion(self):
+ """发布线程异常只能更新发布状态,不能破坏已完成的视频结果。"""
+ state = MemoryState()
+ state.update_task(
+ "cross-post-worker-failure",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm.llm,
+ "generate_social_metadata",
+ side_effect=RuntimeError("metadata provider unavailable"),
+ ),
+ patch.object(tm.upload_post, "cross_post_video") as cross_post,
+ ):
+ tm._run_cross_post(
+ "cross-post-worker-failure",
+ ("final.mp4",),
+ "Coffee",
+ "A short coffee story.",
+ "en",
+ ("youtube",),
+ "private",
+ )
+
+ cross_post.assert_not_called()
+ task = state.get_task("cross-post-worker-failure")
+ self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
+ self.assertEqual(task["videos"], ["final.mp4"])
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("metadata provider unavailable", task["cross_post_error"])
+
+ def test_start_returns_cross_post_scheduling_failure(self):
+ """同步调度失败必须同时体现在任务状态和 start() 返回快照中。"""
+ params = VideoParams(video_subject="Coffee")
+ service = tm.upload_post.upload_post_service
+ state = MemoryState()
+
+ with (
+ patch.object(tm, "generate_script", return_value="generated script"),
+ patch.object(tm, "generate_terms", return_value=["coffee"]),
+ patch.object(tm, "save_script_data"),
+ patch.object(
+ tm,
+ "generate_audio",
+ return_value=("audio.mp3", 5, object()),
+ ),
+ patch.object(tm, "generate_subtitle", return_value="subtitle.srt"),
+ patch.object(tm, "get_video_materials", return_value=["clip.mp4"]),
+ patch.object(
+ tm,
+ "generate_final_videos",
+ return_value=(["final.mp4"], ["combined.mp4"], []),
+ ),
+ patch.object(service, "is_configured", return_value=True),
+ patch.object(service, "auto_upload", True),
+ patch.object(service, "platforms", ["tiktok"]),
+ patch.object(service, "youtube_privacy_status", "private"),
+ patch.object(tm.sm, "state", state),
+ patch.object(tm._cross_post_slots, "acquire", return_value=False),
+ patch.object(tm._cross_post_executor, "submit") as submit,
+ ):
+ result = tm.start("cross-post-queue-full-result", params)
+
+ submit.assert_not_called()
+ self.assertEqual(
+ result["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
+ )
+ self.assertIn("queue is full", result["cross_post_error"])
+ persisted_task = state.get_task("cross-post-queue-full-result")
+ self.assertEqual(
+ persisted_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
+ )
+ self.assertEqual(
+ persisted_task["cross_post_error"],
+ result["cross_post_error"],
+ )
+
+ def test_cross_post_schedule_failure_is_recorded_separately(self):
+ """线程池拒绝新任务时应保留成片,并提供可查询的发布错误。"""
+ state = MemoryState()
+ slots = MagicMock()
+ slots.acquire.return_value = True
+ state.update_task(
+ "cross-post-schedule-failure",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(tm, "_cross_post_slots", slots),
+ patch.object(
+ tm._cross_post_executor,
+ "submit",
+ side_effect=RuntimeError("executor is shutting down"),
+ ),
+ ):
+ scheduling_error = tm._schedule_cross_post(
+ task_id="cross-post-schedule-failure",
+ video_paths=["final.mp4"],
+ params=VideoParams(video_subject="Coffee"),
+ video_script="A short coffee story.",
+ platforms=["tiktok"],
+ youtube_privacy_status="private",
+ )
+
+ slots.release.assert_called_once_with()
+ self.assertIn("executor is shutting down", scheduling_error)
+ task = state.get_task("cross-post-schedule-failure")
+ self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
+ self.assertEqual(task["videos"], ["final.mp4"])
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("executor is shutting down", task["cross_post_error"])
+
+ def test_cross_post_worker_always_releases_queue_slot(self):
+ """发布工作异常退出时也必须归还容量,避免后续发布永久被拒绝。"""
+ slots = MagicMock()
+ state = MemoryState()
+ state.update_task(
+ "task-id",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+
+ with (
+ patch.object(tm, "_cross_post_slots", slots),
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm,
+ "_run_cross_post",
+ side_effect=RuntimeError("worker crashed"),
+ ),
+ ):
+ tm._run_cross_post_with_slot("task-id")
+
+ slots.release.assert_called_once_with()
+ task = state.get_task("task-id")
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("worker crashed", task["cross_post_error"])
+
+ def test_cross_post_state_backend_failure_is_logged_and_skips_upload(self):
+ """首次状态写入失败时不能静默退出,也不能继续消耗发布额度。"""
+ state = MagicMock()
+ state.patch_task.side_effect = RuntimeError("redis unavailable")
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(tm.upload_post, "cross_post_video") as cross_post,
+ patch.object(tm.logger, "exception") as log_exception,
+ patch.object(tm.time, "sleep") as sleep,
+ ):
+ tm._run_cross_post(
+ "state-backend-failure",
+ ("final.mp4",),
+ "Coffee",
+ "A short coffee story.",
+ "en",
+ ("tiktok",),
+ "private",
+ )
+
+ cross_post.assert_not_called()
+ self.assertEqual(state.patch_task.call_count, 6)
+ self.assertEqual(sleep.call_count, 4)
+ self.assertEqual(log_exception.call_count, 2)
+ self.assertTrue(
+ all("redis unavailable" in call.args[0] for call in log_exception.call_args_list)
+ )
+
+ def test_cross_post_state_update_retries_transient_backend_failure(self):
+ """状态后端短暂失败一次后应继续发布,并最终保存完成状态。"""
+
+ class FlakyMemoryState(MemoryState):
+ def __init__(self):
+ super().__init__()
+ self.patch_calls = 0
+
+ def patch_task(self, task_id, **kwargs):
+ self.patch_calls += 1
+ if self.patch_calls == 1:
+ raise RuntimeError("temporary redis outage")
+ return super().patch_task(task_id, **kwargs)
+
+ state = FlakyMemoryState()
+ state.update_task(
+ "transient-state-failure",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm.upload_post,
+ "cross_post_video",
+ return_value={"success": True, "request_id": "upload-1"},
+ ) as cross_post,
+ patch.object(tm.time, "sleep") as sleep,
+ ):
+ tm._run_cross_post(
+ "transient-state-failure",
+ ("final.mp4",),
+ "Coffee",
+ "A short coffee story.",
+ "en",
+ ("tiktok",),
+ "private",
+ )
+
+ sleep.assert_called_once_with(tm._CROSS_POST_STATE_RETRY_DELAY_SECONDS)
+ cross_post.assert_called_once()
+ task = state.get_task("transient-state-failure")
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_COMPLETE)
+ self.assertIsNone(task["cross_post_error"])
+
+ def test_recover_interrupted_cross_posts_preserves_active_future(self):
+ """启动恢复只处理遗留状态,当前进程仍持有的发布任务不能被误伤。"""
+ state = MemoryState()
+ for task_id in (
+ "stale-pending",
+ "active-processing",
+ "inactive-current-owner",
+ "remote-processing",
+ "already-complete",
+ ):
+ cross_post_state = {
+ "stale-pending": tm.const.CROSS_POST_STATE_PENDING,
+ "active-processing": tm.const.CROSS_POST_STATE_PROCESSING,
+ "inactive-current-owner": tm.const.CROSS_POST_STATE_PROCESSING,
+ "remote-processing": tm.const.CROSS_POST_STATE_PROCESSING,
+ "already-complete": tm.const.CROSS_POST_STATE_COMPLETE,
+ }[task_id]
+ state.update_task(
+ task_id,
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=cross_post_state,
+ cross_post_owner=(
+ "another-host:123:remote"
+ if task_id == "remote-processing"
+ else (
+ tm._cross_post_process_owner
+ if task_id == "inactive-current-owner"
+ else None
+ )
+ ),
+ )
+
+ active_future = Future()
+ tm._register_cross_post_future("active-processing", active_future)
+ with patch.object(tm.sm, "state", state):
+ recovered = tm.recover_interrupted_cross_posts(page_size=1)
+
+ self.assertEqual(recovered, 2)
+ stale_task = state.get_task("stale-pending")
+ self.assertEqual(stale_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertEqual(stale_task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
+ self.assertEqual(
+ state.get_task("active-processing")["cross_post_state"],
+ tm.const.CROSS_POST_STATE_PROCESSING,
+ )
+ self.assertEqual(
+ state.get_task("inactive-current-owner")["cross_post_state"],
+ tm.const.CROSS_POST_STATE_FAILED,
+ )
+ self.assertEqual(
+ state.get_task("remote-processing")["cross_post_state"],
+ tm.const.CROSS_POST_STATE_PROCESSING,
+ )
+ self.assertEqual(
+ state.get_task("already-complete")["cross_post_state"],
+ tm.const.CROSS_POST_STATE_COMPLETE,
+ )
+ active_future.set_result(None)
+
+ def test_cross_post_owner_uses_future_registry_for_current_process(self):
+ """当前进程无活动 Future 时,同 PID 的新旧 owner 都应视为中断。"""
+ stale_owner = f"{tm.socket.gethostname()}:{tm.os.getpid()}:old-instance"
+
+ self.assertFalse(tm._is_cross_post_owner_alive(stale_owner))
+ self.assertFalse(tm._is_cross_post_owner_alive(tm._cross_post_process_owner))
+
+ def test_cross_post_owner_detection_handles_process_boundaries(self):
+ """所有者探测应覆盖旧记录、其它主机和本机进程异常边界。"""
+ hostname = tm.socket.gethostname()
+
+ self.assertFalse(tm._is_cross_post_owner_alive(None))
+ self.assertFalse(tm._is_cross_post_owner_alive("invalid-owner"))
+ self.assertTrue(tm._is_cross_post_owner_alive("another-host:123:instance"))
+
+ with (
+ patch.object(tm.os, "name", "posix"),
+ patch.object(tm.os, "kill", side_effect=ProcessLookupError),
+ ):
+ self.assertFalse(
+ tm._is_cross_post_owner_alive(f"{hostname}:987654:dead-instance")
+ )
+ with (
+ patch.object(tm.os, "name", "posix"),
+ patch.object(tm.os, "kill", side_effect=PermissionError),
+ ):
+ self.assertTrue(
+ tm._is_cross_post_owner_alive(f"{hostname}:987654:restricted")
+ )
+ with (
+ patch.object(tm.os, "name", "posix"),
+ patch.object(tm.os, "kill", side_effect=OSError("inspection failed")),
+ patch.object(tm.logger, "warning") as log_warning,
+ ):
+ self.assertTrue(
+ tm._is_cross_post_owner_alive(f"{hostname}:987654:unknown")
+ )
+ self.assertIn("inspection failed", log_warning.call_args.args[0])
+
+ with (
+ patch.object(tm.os, "name", "nt"),
+ patch.object(tm, "_is_windows_process_alive", return_value=True) as probe,
+ ):
+ self.assertTrue(
+ tm._is_cross_post_owner_alive(f"{hostname}:987654:windows")
+ )
+ probe.assert_called_once_with(987654)
+
+ @unittest.skipUnless(os.name == "nt", "Windows process API test")
+ def test_windows_process_probe_is_read_only_and_detects_liveness(self):
+ """Windows CI 应真实验证只读进程探测,不允许回退到 os.kill。"""
+ self.assertTrue(tm._is_windows_process_alive(os.getpid()))
+ self.assertFalse(tm._is_windows_process_alive(2_147_483_647))
+
+ def test_cross_post_terminal_check_converts_active_state_to_failure(self):
+ """worker 已结束但状态仍活动时,最终回调必须补写失败终态。"""
+ state = MemoryState()
+ state.update_task(
+ "unfinished-cross-post",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PROCESSING,
+ )
+
+ with patch.object(tm.sm, "state", state):
+ tm._ensure_cross_post_terminal_state("unfinished-cross-post")
+
+ task = state.get_task("unfinished-cross-post")
+ self.assertEqual(task["videos"], ["final.mp4"])
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("without persisting", task["cross_post_error"])
+
+ def test_cross_post_recovery_reports_state_backend_failure(self):
+ """启动恢复读取状态失败时应返回 None,允许 WebUI 后续 rerun 重试。"""
+ state = MagicMock()
+ state.get_all_tasks.side_effect = RuntimeError("redis unavailable")
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(tm.logger, "exception") as log_exception,
+ ):
+ recovered = tm.recover_interrupted_cross_posts()
+
+ self.assertIsNone(recovered)
+ self.assertIn("redis unavailable", log_exception.call_args.args[0])
+
+ def test_cancelled_cross_post_future_releases_slot_and_records_failure(self):
+ """排队 Future 被取消时也必须释放容量并写入失败终态。"""
+ state = MemoryState()
+ state.update_task(
+ "cancelled-cross-post",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+ slots = MagicMock()
+ future = Future()
+ tm._register_cross_post_future("cancelled-cross-post", future)
+ self.assertTrue(future.cancel())
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(tm, "_cross_post_slots", slots),
+ ):
+ tm._finalize_cross_post_future("cancelled-cross-post", future)
+
+ slots.release.assert_called_once_with()
+ self.assertFalse(tm._is_cross_post_active_in_process("cancelled-cross-post"))
+ task = state.get_task("cancelled-cross-post")
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("cancelled", task["cross_post_error"])
+
+ @unittest.skipUnless(
+ os.getenv("MPT_TEST_REDIS_HOST"),
+ "MPT_TEST_REDIS_HOST not set",
+ )
+ def test_real_redis_recovers_interrupted_cross_post_state(self):
+ """真实 Redis 中的遗留发布状态必须在恢复后保留视频并进入失败终态。"""
+ state = RedisState(
+ host=os.environ["MPT_TEST_REDIS_HOST"],
+ port=int(os.getenv("MPT_TEST_REDIS_PORT", "6379")),
+ db=int(os.getenv("MPT_TEST_REDIS_DB", "15")),
+ )
+ task_id = f"ci-cross-post-recovery-{uuid4()}"
+ state.update_task(
+ task_id,
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PROCESSING,
+ cross_post_owner="",
+ )
+
+ try:
+ with patch.object(tm.sm, "state", state):
+ recovered = tm.recover_interrupted_cross_posts(page_size=10)
+
+ self.assertGreaterEqual(recovered, 1)
+ task = state.get_task(task_id)
+ self.assertEqual(task["videos"], ["final.mp4"])
+ self.assertEqual(
+ task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
+ )
+ self.assertEqual(task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
+ finally:
+ state.delete_task(task_id)
+
+ def test_cross_post_future_exception_is_observed(self):
+ """线程池自身抛出的异常必须进入日志,不能留在无人读取的 Future 中。"""
+ future = Future()
+ future.set_exception(RuntimeError("executor worker failed"))
+
+ with patch.object(tm.logger, "error") as log_error:
+ tm._finalize_cross_post_future("future-failure", future)
+
+ log_error.assert_called_once()
+ self.assertIn("executor worker failed", log_error.call_args.args[0])
+
+ def test_cross_post_queue_full_rejects_only_publishing(self):
+ """发布队列满载时必须保留成片,并且不能继续向线程池提交任务。"""
+ state = MemoryState()
+ state.update_task(
+ "cross-post-queue-full",
+ state=tm.const.TASK_STATE_COMPLETE,
+ progress=100,
+ videos=["final.mp4"],
+ cross_post_state=tm.const.CROSS_POST_STATE_PENDING,
+ )
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm._cross_post_slots,
+ "acquire",
+ return_value=False,
+ ),
+ patch.object(tm._cross_post_executor, "submit") as submit,
+ ):
+ scheduling_error = tm._schedule_cross_post(
+ task_id="cross-post-queue-full",
+ video_paths=["final.mp4"],
+ params=VideoParams(video_subject="Coffee"),
+ video_script="A short coffee story.",
+ platforms=["tiktok"],
+ youtube_privacy_status="private",
+ )
+
+ submit.assert_not_called()
+ self.assertIn("queue is full", scheduling_error)
+ task = state.get_task("cross-post-queue-full")
+ self.assertEqual(task["state"], tm.const.TASK_STATE_COMPLETE)
+ self.assertEqual(task["videos"], ["final.mp4"])
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
+ self.assertIn("queue is full", task["cross_post_error"])
@unittest.skipUnless(
RUN_INTEGRATION_TESTS,
diff --git a/test/services/test_voice.py b/test/services/test_voice.py
index 46b32e7d..23126e46 100644
--- a/test/services/test_voice.py
+++ b/test/services/test_voice.py
@@ -1006,7 +1006,6 @@ class TestElevenLabsVoice(unittest.TestCase):
mock_config.elevenlabs.get.return_value = "fake-api-key"
mock_post.return_value.status_code = 200
mock_post.return_value.content = b"fake-mp3-bytes"
- mock_clip = mock_clip_cls.return_value.__enter__.return_value
mock_clip_cls.return_value.duration = 3.0
mock_clip_cls.return_value.close = lambda: None
diff --git a/uv.lock b/uv.lock
index 22403977..ce454c01 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1532,6 +1532,7 @@ twelvelabs = [
dev = [
{ name = "coverage" },
{ name = "pytest" },
+ { name = "ruff" },
]
[package.metadata]
@@ -1564,6 +1565,7 @@ provides-extras = ["twelvelabs"]
dev = [
{ name = "coverage", specifier = "==7.15.1" },
{ name = "pytest", specifier = "==9.1.1" },
+ { name = "ruff", specifier = "==0.15.21" },
]
[[package]]
@@ -2735,6 +2737,31 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/b7/b95708304cd49b7b6f82fdd039f1748b66ec2b21d6a45180910802f1abf1/rpds_py-0.30.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:ac37f9f516c51e5753f27dfdef11a88330f04de2d564be3991384b2f3535d02e", size = 562191 },
]
+[[package]]
+name = "ruff"
+version = "0.15.21"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0f/36/6f65aa9989acdec45d417192d8f4e7921931d8a6cf87ac74bce3eed98a8e/ruff-0.15.21.tar.gz", hash = "sha256:d0cfc841c572283c36548f82664a54ce6565567f1b0d5b4cf2caac693d8b7500", size = 4769401 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d0/c6/ede15cac6839f3dbce52565c8f5164a8210e669c7bc4decb03e5bdf47d0d/ruff-0.15.21-py3-none-linux_armv6l.whl", hash = "sha256:63ea0e965e5d73c90e95b2434beeafc70820536717f561b32ab6e777cb9bdf5d", size = 10854342 },
+ { url = "https://files.pythonhosted.org/packages/28/9d/d825b07ee7ea9e2d61df92a860033c94e06e7300d50a1c2653aac27d24fe/ruff-0.15.21-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:0f212c5d7d54c01bbfe6dcab02b724a39300f3e34ed7acbe995ccb320a2c58bd", size = 11139539 },
+ { url = "https://files.pythonhosted.org/packages/f5/de/3b107712e642f063c7a9e0887c427b22cb44097de5aab36c05f2e280670c/ruff-0.15.21-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e6312e41bc96791299614995ea3a977c5857c3b5662b1ecef6755b02b87cb646", size = 10595437 },
+ { url = "https://files.pythonhosted.org/packages/9a/6f/b4523cc90ba239ede441447a19d0c968846a3012e5a0b0c5b62831a3d5e3/ruff-0.15.21-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:01d65b4831c6b2a4ba8ee6faa84049d44d982b7a706e622c4094c509e51673be", size = 10990053 },
+ { url = "https://files.pythonhosted.org/packages/92/cc/c6a9872a5375f0628875481cf2f66b13d7d865bf3ca2e57f91c7e762d976/ruff-0.15.21-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2c5a913a589120ce67933d5d05fd6ddbcc2481c6a054980ee767f7414c72b4fd", size = 10666096 },
+ { url = "https://files.pythonhosted.org/packages/ab/97/c621f7a17e097f1790fa3af6374138823b330b2d03fc38337945daca212c/ruff-0.15.21-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5ef04b681d02ad4dc9620f00f83ac5c22f652d0e9a9cfe431d219b16ad5ccc41", size = 11537011 },
+ { url = "https://files.pythonhosted.org/packages/ea/51/d928727e476e25ccc57c6f449ffd80241a651a973ad949d39cfb2a771d28/ruff-0.15.21-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:16d090c0740916594157e75b80d666eab8e78083b39b3b0e1d698f4670a17b86", size = 12347101 },
+ { url = "https://files.pythonhosted.org/packages/1e/88/8cd62026802b16018ad06931d87997cf795ba2a6239ab659606c87d96bf0/ruff-0.15.21-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3a10e74757dd65004d779b73e2f3c5210156d9980b41224d50d2ebcf1db51e67", size = 11572001 },
+ { url = "https://files.pythonhosted.org/packages/b2/97/f63084cf55444fc110e8cb985ebfcc592af47f597d44453d778cb81bc156/ruff-0.15.21-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bab0905d2f29e0d9fbc3c373ed23db0095edaa3f71f1f4f519ec15134d9e85c8", size = 11549239 },
+ { url = "https://files.pythonhosted.org/packages/9d/77/f107da4a2874b7715914b03f09ba9c54424de3ff8a1cc5d015d3ee2ce0ac/ruff-0.15.21-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:00eca240af5789fec6fe7df74c088cc1f9644ed83027113468efba7c92b94075", size = 11535340 },
+ { url = "https://files.pythonhosted.org/packages/d5/e9/601deb322d3303a7bf212b0100ead6f2ee3f6a044d89c30f2f92bf83c731/ruff-0.15.21-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:262ab31557a75141325e32d3357f3597645a7f084e732b6b054dde428ecd9341", size = 10964048 },
+ { url = "https://files.pythonhosted.org/packages/ea/2e/0f2176d1e99c15192caea19c8c3a0a955246b4cb4de795042eeb616345cd/ruff-0.15.21-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:659c4e7a4212f83306045ec7c5e5a356d16d9a6ef4ae0c7a4d872914fc655d9d", size = 10667055 },
+ { url = "https://files.pythonhosted.org/packages/48/60/abd74a02e0c4214f12a68becfd30af7165cfdcb0e661ecdc60bbb949c09a/ruff-0.15.21-py3-none-musllinux_1_2_i686.whl", hash = "sha256:9e866eab611a5f959d36df2d10e446973a3610bc42b0c15b31dc27977d59c233", size = 11242043 },
+ { url = "https://files.pythonhosted.org/packages/b2/c6/583075d8ccabb4b229345edcaf1545eb3d8d6be90f686a479d7e94088bbf/ruff-0.15.21-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e89bc93c0d3803ba870b55c29671bad9dc6d94bb1eb181b056b52eb05b52854f", size = 11648064 },
+ { url = "https://files.pythonhosted.org/packages/3a/3c/37d0ecb729a7cc2d393ea7dce316fc585680f35d93b8d62139d7d0a3700c/ruff-0.15.21-py3-none-win32.whl", hash = "sha256:01f8d5be84823c172b389e123174f781f9daf86d6c58719d603f941932195cdd", size = 10896555 },
+ { url = "https://files.pythonhosted.org/packages/c0/b8/e43466b2a6067ce91e669068f6e28d6c719a920f014b070d5c8731725de3/ruff-0.15.21-py3-none-win_amd64.whl", hash = "sha256:d4b8d9a2f0f12b816b50447f6eccb9f4bb01a6b82c86b50fb3b5354b458dc6d3", size = 12038772 },
+ { url = "https://files.pythonhosted.org/packages/dd/75/e90ab9aeece218a9fc5a5bc3ec97d0ee6bb3c4ff95869463c1de58e29a1c/ruff-0.15.21-py3-none-win_arm64.whl", hash = "sha256:6e83115d4b9377c1cbc13abf0e051f069fab0ef815ea0504a8a008cee24dd0a8", size = 11375265 },
+]
+
[[package]]
name = "setuptools"
version = "82.0.1"
diff --git a/webui/Main.py b/webui/Main.py
index c062c82d..f9524f21 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -210,6 +210,13 @@ def _build_uploaded_file_path(uploaded_file, target_dir, allowed_extensions, pre
def _initialize_session_state():
"""集中初始化跨 rerun 保留的页面状态。"""
+ if not st.session_state.get("cross_post_recovery_checked"):
+ # WebUI 可以不经过 FastAPI 独立运行,因此也需要在首次会话初始化时处理
+ # 进程重启留下的发布状态。恢复失败时不写标记,后续 rerun 会再次尝试。
+ recovered = tm.recover_interrupted_cross_posts()
+ if recovered is not None:
+ st.session_state["cross_post_recovery_checked"] = True
+
saved_ui_language = config.ui.get("language", "")
browser_locale = st.context.locale
initial_ui_language = utils.resolve_ui_language(
@@ -533,6 +540,7 @@ def _collect_task_summaries(limit=20):
"task_id": task_id,
"subject": subject,
"state": task.get("state"),
+ "cross_post_state": task.get("cross_post_state"),
"progress": int(task.get("progress", 0) or 0),
"mtime": os.path.getmtime(task_path)
if os.path.isdir(task_path)
@@ -610,15 +618,12 @@ def _delete_task(task_id, task_path, task_state=None):
logger.exception(f"failed to verify task state before deletion: {task_id}, {e}")
return False
- current_state = current_task.get("state") if current_task else None
- is_processing = (
- any(
- _normalize_task_state(state) == const.TASK_STATE_PROCESSING
- for state in (task_state, current_state)
- )
- or task_id in _active_generation_tasks()
- )
- if is_processing:
+ task_snapshot = dict(current_task or {})
+ task_snapshot.setdefault("state", task_state)
+ if task_id in _active_generation_tasks():
+ task_snapshot["state"] = const.TASK_STATE_PROCESSING
+
+ if tm.is_task_busy(task_snapshot):
logger.warning(f"refused to delete running task: {task_id}")
return False
@@ -681,6 +686,7 @@ def _render_task_table(filtered_tasks, key_prefix):
task_id = task["task_id"]
has_video = bool(task["video_file"] and os.path.isfile(task["video_file"]))
is_processing = _task_state_filter_key(task) == "processing"
+ is_busy = is_processing or tm.is_task_busy(task)
has_restore_data = os.path.isfile(
os.path.join(task["task_path"], "script.json")
)
@@ -745,7 +751,7 @@ def _render_task_table(filtered_tasks, key_prefix):
delete_label = tr("Delete Task")
delete_help = (
f"{delete_label} ({tr('Task Status Processing')})"
- if is_processing
+ if is_busy
else delete_label
)
if st.button(
@@ -754,7 +760,7 @@ def _render_task_table(filtered_tasks, key_prefix):
use_container_width=True,
icon=":material/delete:",
help=delete_help,
- disabled=is_processing,
+ disabled=is_busy,
):
if _delete_task(task_id, task["task_path"], task["state"]):
st.toast(tr("Task Deleted"))
@@ -2434,7 +2440,7 @@ def _render_background_music_settings(params):
cached_validation["error"]
)
raise bgm_service.BgmUploadError(cached_validation["error"])
- except bgm_service.BgmUploadError as exc:
+ except bgm_service.BgmUploadError:
# 非法文件不能沿用上一次有效上传的名称,否则任务参数可能仍指向
# 历史 BGM。保留 UploadedFile 返回值,让用户点击生成时仍会被最终
# 服务端校验拦截,而不是静默生成一条没有背景音乐的视频。