PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix(pipeline): 保留服务中断状态并修复取消后的恢复
yi5b1b7e67efd5
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.pyindex 3d96684..a3f6ffd 100644--- a/backend/app/services/pipeline.py+++ b/backend/app/services/pipeline.py@@ -180,6 +180,11 @@ def is_cancelled(project_id: int) -> bool:return project_id in _cancelled+def clear_pipeline_cancellation(project_id: int) -> None:+ """Only explicit resume paths clear a previous user-cancellation marker."""+ _cancelled.discard(project_id)++def _is_image_text(project: Project) -> bool:return (project.pipeline_mode or "full") == "image_text"@@ -589,12 +594,21 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:project_id,{"event": "done", "percent": 100, "video_url": await _final_url(project_id)},)- except (PipelineCancelled, asyncio.CancelledError):+ except (PipelineCancelled, asyncio.CancelledError) as exc:# 落项目态、推 SSE 后必须 re-raise:本函数由任务平台 executor 驱动,# 吞掉会让 TaskRun 误判 succeeded 扣费,并破坏 asyncio 任务取消语义。- logger.info("pipeline cancelled project=%s", project_id)async with AsyncSessionLocal() as db:project = await db.get(Project, project_id)+ requested = (+ isinstance(exc, PipelineCancelled)+ or is_cancelled(project_id)+ or (project is not None and project.status == ProjectStatus.CANCELLED)+ )+ if not requested:+ # 服务中断后调度器会重排同一任务,保留成功素材及可恢复状态。+ logger.info("pipeline interrupted; preserving resume state project=%s", project_id)+ raise+ logger.info("pipeline cancelled project=%s", project_id)if project and project.status != ProjectStatus.DONE:project.status = ProjectStatus.CANCELLEDproject.error_msg = "用户取消"@@ -629,7 +643,7 @@ async def run_pipeline(project_id: int, *, phase: str | None = None) -> None:"code": "CANCELLED",},)- return+ raise PipelineCancelled(f"project {project_id} cancelled") from exclogger.exception("pipeline failed project=%s", project_id)fail_msg = ("FFmpeg 被系统中断(signal 15),请点击重新拼接"diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex aab80e3..5b94673 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -166,10 +166,16 @@ async def _await_kepu(task: TaskRun, aw: Awaitable[Any], **extra: Any) -> dict[s# 执行科普分阶段流水线(严格按 payload.phase 预扣对应阶段)。async def _run_kepu_project_pipeline(task: TaskRun) -> dict[str, Any] | None:- from app.services.pipeline import run_pipeline+ from app.services.pipeline import clear_pipeline_cancellation, run_pipelinepayload = task.payload if isinstance(task.payload, dict) else {}phase = payload.get("phase")+ if task.cancel_requested:+ return {"cancelled": True, "project_id": task.project_id}+ # The previous task can have been cancelled before its pipeline ever ran,+ # leaving a process-local marker. Clear it in the executing worker only for+ # this fresh task; persistent CANCELLED checks still catch a new cancellation.+ clear_pipeline_cancellation(_require_int(task.project_id, "project_id"))return await _await_kepu(task,run_pipeline(@@ -234,8 +240,11 @@ async def _run_kepu_project_audio(task: TaskRun) -> dict[str, Any] | None:# 执行科普仅合成任务。async def _run_kepu_compose(task: TaskRun) -> dict[str, Any] | None:- from app.services.pipeline import compose_only+ from app.services.pipeline import clear_pipeline_cancellation, compose_only+ if task.cancel_requested:+ return {"cancelled": True, "project_id": task.project_id}+ clear_pipeline_cancellation(_require_int(task.project_id, "project_id"))return await _await_kepu(task,compose_only(_require_int(task.project_id, "project_id")),diff --git a/backend/tests/test_kepu_resume_cancel_marker.py b/backend/tests/test_kepu_resume_cancel_marker.pynew file mode 100644index 0000000..3e9dd67--- /dev/null+++ b/backend/tests/test_kepu_resume_cancel_marker.py@@ -0,0 +1,59 @@+"""A fresh wizard task can resume after an earlier task was cancelled before start."""+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from app.models import ProjectStatus+from app.services import pipeline+from app.services.tasks import handlers++[email protected]("handler_name,stage_name", [+ ("_run_kepu_project_pipeline", "run_pipeline"), ("_run_kepu_compose", "compose_only"),+])+async def test_fresh_task_clears_previous_marker_in_executing_worker(monkeypatch, handler_name, stage_name):+ task = SimpleNamespace(project_id=97110, cancel_requested=False, payload={"phase": "script"})+ pipeline.cancel_pipeline(task.project_id)++ async def stage(project_id, **_kwargs):+ assert not pipeline.is_cancelled(project_id)++ monkeypatch.setattr(pipeline, stage_name, stage)+ monkeypatch.setattr(handlers, "_kepu_output_snapshot", AsyncMock(return_value={}))+ result = await getattr(handlers, handler_name)(task)+ assert result["ok"]++[email protected]("handler_name,stage_name", [+ ("_run_kepu_project_pipeline", "run_pipeline"), ("_run_kepu_compose", "compose_only"),+])+async def test_current_cancellation_is_not_cleared_or_executed(monkeypatch, handler_name, stage_name):+ task = SimpleNamespace(project_id=97111, cancel_requested=True, payload={"phase": "script"})+ pipeline.cancel_pipeline(task.project_id)+ stage = AsyncMock()+ monkeypatch.setattr(pipeline, stage_name, stage)+ try:+ result = await getattr(handlers, handler_name)(task)+ assert result["cancelled"] and pipeline.is_cancelled(task.project_id)+ stage.assert_not_awaited()+ finally:+ pipeline.clear_pipeline_cancellation(task.project_id)+++async def test_db_cancellation_still_blocks_when_snapshot_predates_current_request(monkeypatch):+ task = SimpleNamespace(project_id=97112, cancel_requested=False, payload={})+ project = SimpleNamespace(status=ProjectStatus.CANCELLED)++ @asynccontextmanager+ async def factory():+ yield SimpleNamespace(get=AsyncMock(return_value=project))++ monkeypatch.setattr(pipeline, "AsyncSessionLocal", factory)+ try:+ with pytest.raises(pipeline.PipelineCancelled):+ await handlers._run_kepu_compose(task)+ assert project.status == ProjectStatus.CANCELLED+ finally:+ pipeline.clear_pipeline_cancellation(task.project_id)