Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

Prevent duplicate Celery pipelines for the same project.

yi793843d3507a
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index ba5020e..3b083c7 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -62,8 +62,21 @@ def start_pipeline(project_id: int) -> str:
_cancelled.discard(project_id)
settings = get_settings()
if settings.use_celery and _redis_ok():
+ from app.workers.queue_dedupe import clear_pipeline_run_lock, purge_pipeline_queue_for_project
from app.workers.tasks import run_pipeline_task
+ # Drop stale queued copies + revoke last known task so continue never double-runs
+ old_id = _celery_task_ids.pop(project_id, None)
+ if old_id and old_id != "in-process":
+ try:
+ from app.workers.celery_app import celery_app
+
+ celery_app.control.revoke(old_id, terminate=True, signal="SIGTERM")
+ except Exception: # noqa: BLE001
+ logger.warning("revoke previous task failed project=%s task=%s", project_id, old_id)
+ purge_pipeline_queue_for_project(project_id)
+ clear_pipeline_run_lock(project_id)
+
async_result = run_pipeline_task.apply_async(args=[project_id], queue="pipeline")
task_id = str(async_result.id)
_celery_task_ids[project_id] = task_id
@@ -95,6 +108,15 @@ def cancel_pipeline(project_id: int) -> bool:
except Exception: # noqa: BLE001
logger.warning("celery revoke failed project=%s task=%s", project_id, celery_id)
+ try:
+ from app.workers.queue_dedupe import clear_pipeline_run_lock, purge_pipeline_queue_for_project
+
+ if purge_pipeline_queue_for_project(project_id):
+ stopped = True
+ clear_pipeline_run_lock(project_id)
+ except Exception: # noqa: BLE001
+ logger.exception("queue purge on cancel failed project=%s", project_id)
+
return stopped
diff --git a/backend/app/workers/queue_dedupe.py b/backend/app/workers/queue_dedupe.py
new file mode 100644
index 0000000..8aaf1ea
--- /dev/null
+++ b/backend/app/workers/queue_dedupe.py
@@ -0,0 +1,145 @@
+"""Celery Redis queue helpers — purge duplicate pipeline tasks per project."""
+
+from __future__ import annotations
+
+import base64
+import json
+import logging
+import re
+from typing import Any
+
+import redis
+
+from app.config import get_settings
+
+logger = logging.getLogger(__name__)
+
+PIPELINE_QUEUE = "pipeline"
+_ARGS_RE = re.compile(r"\[(\d+)\]|\((\d+),?\)")
+
+
+def _redis_client(*, decode: bool = True) -> redis.Redis:
+ return redis.Redis.from_url(
+ get_settings().redis_url,
+ decode_responses=decode,
+ socket_connect_timeout=3,
+ socket_timeout=5,
+ )
+
+
+def project_id_from_celery_message(msg: dict[str, Any]) -> int | None:
+ """Extract project_id from a Celery Redis broker message."""
+ headers = msg.get("headers") or {}
+ argsrepr = str(headers.get("argsrepr") or "")
+ m = _ARGS_RE.search(argsrepr)
+ if m:
+ return int(m.group(1) or m.group(2))
+
+ body = msg.get("body")
+ if not body:
+ return None
+ try:
+ if isinstance(body, bytes):
+ body = body.decode("utf-8", errors="replace")
+ raw = base64.b64decode(body)
+ payload = json.loads(raw.decode("utf-8"))
+ # Celery JSON: [[args...], kwargs, embed]
+ args = payload[0] if isinstance(payload, (list, tuple)) and payload else None
+ if isinstance(args, (list, tuple)) and args:
+ return int(args[0])
+ if isinstance(args, int):
+ return args
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def purge_pipeline_queue_for_project(project_id: int, *, queue: str = PIPELINE_QUEUE) -> int:
+ """Remove pending broker messages for project_id from the pipeline queue.
+
+ Returns number of removed messages. Best-effort; never raises to callers.
+ """
+ try:
+ r = _redis_client(decode=True)
+ items = r.lrange(queue, 0, -1) or []
+ if not items:
+ return 0
+
+ kept: list[str] = []
+ removed_ids: list[str] = []
+ for raw in items:
+ try:
+ msg = json.loads(raw)
+ except Exception: # noqa: BLE001
+ kept.append(raw)
+ continue
+ pid = project_id_from_celery_message(msg)
+ if pid == int(project_id):
+ tid = str((msg.get("headers") or {}).get("id") or "")
+ if tid:
+ removed_ids.append(tid)
+ continue
+ kept.append(raw)
+
+ removed = len(items) - len(kept)
+ if removed <= 0:
+ return 0
+
+ pipe = r.pipeline()
+ pipe.delete(queue)
+ if kept:
+ pipe.rpush(queue, *kept)
+ pipe.execute()
+
+ if removed_ids:
+ try:
+ from app.workers.celery_app import celery_app
+
+ for tid in removed_ids:
+ celery_app.control.revoke(tid, terminate=False)
+ except Exception: # noqa: BLE001
+ logger.warning("revoke purged tasks failed project=%s", project_id)
+
+ logger.info(
+ "purged %s queued pipeline task(s) for project=%s (left=%s)",
+ removed,
+ project_id,
+ len(kept),
+ )
+ return removed
+ except Exception: # noqa: BLE001
+ logger.exception("purge_pipeline_queue_for_project failed project=%s", project_id)
+ return 0
+
+
+def pipeline_run_lock_key(project_id: int) -> str:
+ return f"ai_movie:pipeline:run:{int(project_id)}"
+
+
+def acquire_pipeline_run_lock(project_id: int, owner: str, *, ttl_sec: int = 7200) -> bool:
+ """NX lock so only one worker runs a project pipeline at a time."""
+ try:
+ r = _redis_client(decode=True)
+ return bool(r.set(pipeline_run_lock_key(project_id), owner, nx=True, ex=max(60, ttl_sec)))
+ except Exception: # noqa: BLE001
+ logger.exception("acquire pipeline lock failed project=%s", project_id)
+ return True # fail open so work still proceeds
+
+
+def release_pipeline_run_lock(project_id: int, owner: str) -> None:
+ try:
+ r = _redis_client(decode=True)
+ key = pipeline_run_lock_key(project_id)
+ cur = r.get(key)
+ if cur is None or cur == owner:
+ r.delete(key)
+ except Exception: # noqa: BLE001
+ logger.exception("release pipeline lock failed project=%s", project_id)
+
+
+def clear_pipeline_run_lock(project_id: int) -> None:
+ try:
+ r = _redis_client(decode=True)
+ r.delete(pipeline_run_lock_key(project_id))
+ except Exception: # noqa: BLE001
+ logger.exception("clear pipeline lock failed project=%s", project_id)
diff --git a/backend/app/workers/tasks.py b/backend/app/workers/tasks.py
index 03a3d65..5934b98 100644
--- a/backend/app/workers/tasks.py
+++ b/backend/app/workers/tasks.py
@@ -42,9 +42,19 @@ def run_pipeline_task(self, project_id: int) -> dict:
from app.config import reload_settings
from app.services.ark import reset_ark
from app.services.pipeline import PipelineCancelled, is_cancelled, run_pipeline
+ from app.workers.queue_dedupe import (
+ acquire_pipeline_run_lock,
+ release_pipeline_run_lock,
+ )
reload_settings()
reset_ark()
+
+ owner = str(getattr(getattr(self, "request", None), "id", "") or f"worker-{project_id}")
+ if not acquire_pipeline_run_lock(project_id, owner):
+ logger.warning("skip duplicate pipeline project=%s task=%s", project_id, owner)
+ return {"ok": False, "skipped": "duplicate", "project_id": project_id}
+
try:
_run(run_pipeline(project_id))
return {"ok": True, "project_id": project_id}
@@ -90,6 +100,8 @@ def run_pipeline_task(self, project_id: int) -> dict:
return {"ok": False, "project_id": project_id, "error": msg[:500]}
logger.exception("celery pipeline failed project=%s", project_id)
raise self.retry(exc=exc, countdown=10)
+ finally:
+ release_pipeline_run_lock(project_id, owner)
@celery_app.task(name="app.workers.tasks.regen_image_task")
diff --git a/docs/PLACEHOLDER_BACKLOG.md b/docs/PLACEHOLDER_BACKLOG.md
index cd38baa..95d8216 100644
--- a/docs/PLACEHOLDER_BACKLOG.md
+++ b/docs/PLACEHOLDER_BACKLOG.md
@@ -133,7 +133,7 @@
| ID | 项 | 现状 | 优先级 | 备注 |
|----|----|------|--------|------|
| X-01 | `generate` 续跑勿标 SCRIPTING | 部分完成 | P0 | API 已热更;需确认 worker 与前端一并部署 |
-| X-02 | Celery `pipeline` 队列去重 / 项目级互斥 | 待开发 | P0 | 同项目多次 continue 会堆积任务 |
+| X-02 | Celery `pipeline` 队列去重 / 项目级互斥 | 已完成待部署 | P0 | `queue_dedupe.py`:入队前 purge + Redis run lock |
| X-03 | 取消中途视频失败错误信息为空 | 待开发 | P1 | `RuntimeError('')` 日志难排查 |
| X-04 | 帮助中心 / 状态文案前端上线 | 已完成待部署 | P0 | `npm run build` + 静态发布 |
| X-05 | 视频阶段卡住时允许「仅补缺镜」 | 待开发 | P1 | 可走 `regen-video` + `compose`,避免整管线重入队 |