Skip to content

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

fix(tasks): watchdog orphan recovery and episode_script progress

yi43a080fe1bfb
diff --git a/backend/app/api/admin/tasks.py b/backend/app/api/admin/tasks.py
index 0c2f725..77fa473 100644
--- a/backend/app/api/admin/tasks.py
+++ b/backend/app/api/admin/tasks.py
@@ -69,6 +69,10 @@ async def admin_task_stats(
**stats,
scheduler_running_jobs=int(runtime.get("scheduler_running_jobs") or 0),
max_concurrency=int(settings.task_runtime_max_concurrency),
+ scheduler=str(runtime.get("scheduler") or "stopped"),
+ poller=str(runtime.get("poller") or "stopped"),
+ watchdog=str(runtime.get("watchdog") or "stopped"),
+ runtime_healthy=bool(runtime.get("healthy")),
fetched_at=datetime.now(UTC),
)
diff --git a/backend/app/config.py b/backend/app/config.py
index 991c688..1caab3d 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -81,8 +81,16 @@ class Settings(BaseSettings):
task_user_max_concurrency: int = 4
# Selector 每轮并发非阻塞查询上游的上限(类似 NIO select 就绪 channel 批处理)。
task_poll_max_concurrency: int = 20
- # 启动恢复时,running 任务超过该秒数无心跳才视为孤儿任务。
+ # 孤儿恢复:leased/running 超过该秒数无更新、且本进程无执行协程时重排队。
task_runtime_recover_grace_sec: int = 30
+ # 运行中每隔多少秒扫描一次孤儿任务(调度 tick 内执行)。
+ task_runtime_orphan_check_sec: int = 30
+ # 调度 tick 心跳超过该秒数未刷新 → 看门狗软重启调度循环。
+ task_runtime_tick_stale_sec: int = 60
+ # Selector 心跳超过该秒数未刷新 → 看门狗软重启 poller。
+ task_poll_stale_sec: int = 90
+ # 看门狗检查间隔(秒)。
+ task_runtime_watchdog_interval_sec: float = 5.0
max_shot_duration: int = 30
default_preview_resolution: str = "480p"
diff --git a/backend/app/main.py b/backend/app/main.py
index 454f626..b78273f 100644
--- a/backend/app/main.py
+++ b/backend/app/main.py
@@ -311,11 +311,13 @@ async def health() -> dict:
s = reload_settings()
from app.database import pool_status
+ runtime = runtime_summary()
+ runtime_ok = bool(runtime.get("healthy"))
return {
- "ok": True,
+ "ok": runtime_ok,
"ark_mock": s.ark_mock,
"db_pool": pool_status(),
- "task_runtime": runtime_summary(),
+ "task_runtime": runtime,
"models": {
"llm": s.model_llm,
"image": s.model_image,
diff --git a/backend/app/schemas_tasks.py b/backend/app/schemas_tasks.py
index a2be124..f5acd05 100644
--- a/backend/app/schemas_tasks.py
+++ b/backend/app/schemas_tasks.py
@@ -316,5 +316,9 @@ class AdminTaskStatsOut(BaseModel):
cancelled_count: int = 0
scheduler_running_jobs: int = 0
max_concurrency: int = 0
+ scheduler: str = "stopped"
+ poller: str = "stopped"
+ watchdog: str = "stopped"
+ runtime_healthy: bool = False
domains: list[AdminTaskDomainStatsOut] = Field(default_factory=list)
fetched_at: datetime | None = None
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index 16134f3..cfa1634 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -286,9 +286,43 @@ async def dispatch_episode_scripts_job(
return task_id
-async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[str, Any]:
- # Worker:大纲 + 循环逐集直到完成
- logger.info("开始生成分集剧本 project_id=%s force=%s", project_id, force)
+async def run_episode_scripts_job(
+ project_id: int,
+ force: bool = False,
+ task_id: int | None = None,
+) -> dict[str, Any]:
+ # Worker:大纲 + 循环逐集直到完成;task_id 用于回写平台进度百分比
+ logger.info("开始生成分集剧本 project_id=%s force=%s task_id=%s", project_id, force, task_id)
+
+ async def _sync_task_progress(done: int, total: int, *, phase: str, message: str) -> None:
+ if not task_id:
+ return
+ from app.services.tasks.service import append_task_event
+
+ async with AsyncSessionLocal() as tdb:
+ task_row = await tdb.get(TaskRun, int(task_id))
+ if not task_row or task_row.status not in {"leased", "running", "pending"}:
+ return
+ if total <= 0:
+ pct = 0
+ elif done >= total:
+ pct = 100
+ else:
+ pct = min(99, max(1, int(round(100 * done / total))))
+ task_row.progress_percent = pct
+ task_row.current_step_key = "episode_script"
+ task_row.current_step_status = phase
+ await append_task_event(
+ tdb,
+ int(task_id),
+ event_type="task.progress",
+ status=task_row.status,
+ phase=phase,
+ message=message,
+ payload={"done": done, "total": total, "progress_percent": pct},
+ )
+ await tdb.commit()
+
async with AsyncSessionLocal() as db:
project = await db.get(
DramaProject,
@@ -316,21 +350,38 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
creative = (script.source or "").strip()
try:
if force and existing:
- existing = [
- {
- "episodeNumber": int(item.get("episodeNumber") or 0),
- "title": str(item.get("title") or f"第 {item.get('episodeNumber')} 集"),
- "body": "",
- }
- for item in existing
- if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
- ]
- script.episode_content = {"episodes": existing}
- await db.flush()
- logger.info("已清空分集正文准备重写 project_id=%s total=%s", project_id, total)
+ params0 = dict(script.params or {})
+ status0 = str(params0.get("episode_content_status") or "")
+ # generating=本轮已开跑(含进程重启续跑),勿再因 force 清空已生成正文
+ if status0 != "generating":
+ existing = [
+ {
+ "episodeNumber": int(item.get("episodeNumber") or 0),
+ "title": str(item.get("title") or f"第 {item.get('episodeNumber')} 集"),
+ "body": "",
+ }
+ for item in existing
+ if isinstance(item, dict) and int(item.get("episodeNumber") or 0) >= 1
+ ]
+ script.episode_content = {"episodes": existing}
+ params0["episode_content_status"] = "generating"
+ params0["episode_content_error"] = None
+ script.params = params0
+ await db.flush()
+ logger.info("已清空分集正文准备重写 project_id=%s total=%s", project_id, total)
+ else:
+ logger.info(
+ "force 续跑跳过清空 project_id=%s done=%s/%s",
+ project_id,
+ count_completed_episodes(existing, total),
+ total,
+ )
existing, outline_used_llm = await ensure_episode_outline(creative, summary, existing, total)
script.episode_content = {"episodes": existing}
+ params_outline = dict(script.params or {})
+ params_outline["episode_content_status"] = "generating"
+ script.params = params_outline
await db.flush()
if outline_used_llm:
user = await db.get(User, project.user_id)
@@ -342,6 +393,12 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
drama_project_id=project.id,
)
logger.info("分集大纲就绪 project_id=%s titles=%s", project_id, len(existing))
+ await _sync_task_progress(
+ count_completed_episodes(existing, total),
+ total,
+ phase="generating",
+ message=f"分集大纲就绪,开始生成 {count_completed_episodes(existing, total)}/{total}",
+ )
guard = 0
while True:
@@ -396,6 +453,12 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
done_now,
total,
)
+ await _sync_task_progress(
+ done_now,
+ total,
+ phase="generating",
+ message=f"分集剧本进度 {done_now}/{total}",
+ )
guard += 1
if guard > max(total * 2, 24):
raise RuntimeError(
@@ -411,6 +474,7 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
params["episode_content_progress"] = {"done": total, "total": total}
script.params = params
await db.commit()
+ await _sync_task_progress(total, total, phase="succeeded", message=f"分集剧本全部完成 {total}/{total}")
logger.info("分集剧本全部完成 project_id=%s total=%s", project_id, total)
return {"ok": True, "project_id": project_id, "total": total}
except Exception as exc: # noqa: BLE001
diff --git a/backend/app/services/drama/llm.py b/backend/app/services/drama/llm.py
index 903e099..fe97924 100644
--- a/backend/app/services/drama/llm.py
+++ b/backend/app/services/drama/llm.py
@@ -71,6 +71,15 @@ def _extract_json(text: str) -> Any:
raise json.JSONDecodeError("empty JSON payload", text or "", 0)
+def _ensure_json_word_in_prompt(system: str, user: str) -> tuple[str, str]:
+ """DeepSeek 等要求 response_format=json_object 时 prompt 须含 json 字样。"""
+ blob = f"{system or ''}\n{user or ''}".lower()
+ if "json" in blob:
+ return system, user
+ suffix = "\n\n请只输出合法 JSON 对象,不要 markdown 代码围栏。"
+ return (system or "").rstrip() + suffix, user
+
+
async def drama_chat_json(
system: str,
user: str,
@@ -79,6 +88,7 @@ async def drama_chat_json(
max_tokens: int = DEFAULT_MAX_TOKENS,
) -> Any:
"""Call text LLM and parse JSON from the reply."""
+ system, user = _ensure_json_word_in_prompt(system, user)
json_format = {"type": "json_object"}
try:
content = await chat_completions(
@@ -91,7 +101,7 @@ async def drama_chat_json(
)
except RuntimeError as exc:
# 部分兼容网关不支持 response_format,降级为普通调用
- if "response_format" not in str(exc).lower():
+ if "response_format" not in str(exc).lower() and "json_object" not in str(exc).lower():
raise
logger.warning("LLM 不支持 response_format,降级普通调用: %s", exc)
content = await chat_completions(
diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.py
index 90e070c..f23cd3b 100644
--- a/backend/app/services/tasks/handlers.py
+++ b/backend/app/services/tasks/handlers.py
@@ -41,6 +41,7 @@ async def _run_drama_episode_script(task: TaskRun) -> dict[str, Any] | None:
return await run_episode_scripts_job(
_require_int(task.drama_project_id, "drama_project_id"),
force=bool(payload.get("force")),
+ task_id=int(task.id),
)
diff --git a/backend/app/services/tasks/poller.py b/backend/app/services/tasks/poller.py
index cf04f23..fb7590f 100644
--- a/backend/app/services/tasks/poller.py
+++ b/backend/app/services/tasks/poller.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
+import time
from datetime import UTC, datetime, timedelta
from sqlalchemy import select
@@ -19,25 +20,32 @@ _FRAGMENT_FINALIZE_STEP = "finalizing"
logger = logging.getLogger("app.tasks.poller")
+# Selector 循环句柄、停机信号、并发闸与心跳
_poller_task: asyncio.Task | None = None
_stop_event = asyncio.Event()
_poll_inflight: set[int] = set()
_selector_sem: asyncio.Semaphore | None = None
+_last_poll_mono: float = 0.0
+_intentionally_stopped: bool = True
# 启动 Selector 轮询循环。
async def start_poller() -> None:
- global _poller_task, _selector_sem
+ global _poller_task, _selector_sem, _intentionally_stopped, _last_poll_mono
if _poller_task and not _poller_task.done():
return
+ _intentionally_stopped = False
limit = max(1, int(get_settings().task_poll_max_concurrency or 20))
_selector_sem = asyncio.Semaphore(limit)
_stop_event.clear()
- _poller_task = asyncio.create_task(_poller_loop())
+ _last_poll_mono = time.monotonic()
+ _poller_task = asyncio.create_task(_poller_loop(), name="task-poller")
# 停止 Selector 轮询循环。
async def stop_poller() -> None:
+ global _intentionally_stopped
+ _intentionally_stopped = True
_stop_event.set()
if _poller_task and not _poller_task.done():
_poller_task.cancel()
@@ -47,24 +55,70 @@ async def stop_poller() -> None:
pass
+# 看门狗拉起卡死或已退出的 Selector 循环。
+async def restart_poller_loop(*, reason: str = "watchdog") -> None:
+ global _poller_task, _intentionally_stopped, _last_poll_mono, _selector_sem
+ if _intentionally_stopped:
+ return
+ logger.warning("restarting task poller loop reason=%s", reason)
+ _stop_event.set()
+ if _poller_task and not _poller_task.done():
+ _poller_task.cancel()
+ try:
+ await _poller_task
+ except asyncio.CancelledError:
+ pass
+ limit = max(1, int(get_settings().task_poll_max_concurrency or 20))
+ _selector_sem = asyncio.Semaphore(limit)
+ _stop_event.clear()
+ _last_poll_mono = time.monotonic()
+ _poller_task = asyncio.create_task(_poller_loop(), name="task-poller")
+
+
# 返回 Selector 当前状态。
def poller_status() -> str:
+ if _intentionally_stopped:
+ return "stopped"
if _poller_task and not _poller_task.done():
return "running"
return "stopped"
+# 距上次 Selector 轮询完成的秒数。
+def poller_tick_age_sec() -> float:
+ if _last_poll_mono <= 0:
+ return 1e9
+ return max(0.0, time.monotonic() - _last_poll_mono)
+
+
+# Selector 心跳是否过期。
+def poller_tick_stale() -> bool:
+ if _intentionally_stopped:
+ return False
+ poll_interval = max(1.0, float(get_settings().ark_video_poll_interval or 8.0))
+ stale_sec = max(30.0, float(get_settings().task_poll_stale_sec), poll_interval * 4)
+ return poller_tick_age_sec() > stale_sec
+
+
# Selector 主循环:周期性 select 到期 channel。
async def _poller_loop() -> None:
+ global _last_poll_mono
interval = max(1.0, float(get_settings().ark_video_poll_interval or 8.0))
while not _stop_event.is_set():
+ _last_poll_mono = time.monotonic()
+ poll_stale = max(30.0, float(get_settings().task_poll_stale_sec), interval * 4)
+ timeout = max(20.0, poll_stale - 10.0)
try:
- await _select_and_poll_due()
- await _poll_ephemeral_deferred_tasks()
+ await asyncio.wait_for(_select_and_poll_due(), timeout=timeout)
+ await asyncio.wait_for(_poll_ephemeral_deferred_tasks(), timeout=timeout)
+ except asyncio.TimeoutError:
+ logger.error("task selector tick timed out after %.0fs", timeout)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001
logger.exception("task selector failed")
+ finally:
+ _last_poll_mono = time.monotonic()
await asyncio.sleep(interval)
diff --git a/backend/app/services/tasks/runtime.py b/backend/app/services/tasks/runtime.py
index 630ccc8..cafa70e 100644
--- a/backend/app/services/tasks/runtime.py
+++ b/backend/app/services/tasks/runtime.py
@@ -2,25 +2,116 @@
from __future__ import annotations
-from app.services.tasks.poller import poller_status, start_poller, stop_poller
-from app.services.tasks.scheduler import running_count, start_scheduler, stop_scheduler
+import asyncio
+import logging
+from app.config import get_settings
+from app.services.tasks.poller import (
+ poller_status,
+ poller_tick_age_sec,
+ poller_tick_stale,
+ restart_poller_loop,
+ start_poller,
+ stop_poller,
+)
+from app.services.tasks.scheduler import (
+ restart_scheduler_loop,
+ running_count,
+ scheduler_status,
+ scheduler_tick_age_sec,
+ scheduler_tick_stale,
+ start_scheduler,
+ stop_scheduler,
+)
-# 启动统一任务平台运行时(Worker 调度 + Selector 轮询)。
+logger = logging.getLogger("app.tasks.runtime")
+
+_watchdog_task: asyncio.Task | None = None
+_watchdog_stop = asyncio.Event()
+_watchdog_intentionally_stopped: bool = True
+
+
+# 启动统一任务平台运行时(Worker 调度 + Selector 轮询 + 看门狗)。
async def start_task_runtime() -> None:
await start_scheduler()
await start_poller()
+ await start_watchdog()
# 停止统一任务平台运行时。
async def stop_task_runtime() -> None:
+ await stop_watchdog()
await stop_poller()
await stop_scheduler()
-# 返回任务平台运行时摘要(Worker 槽位 + Selector 状态)。
-def runtime_summary() -> dict[str, int | str]:
+# 启动看门狗:调度/轮询循环退出或心跳过期时自动拉起。
+async def start_watchdog() -> None:
+ global _watchdog_task, _watchdog_intentionally_stopped
+ if _watchdog_task and not _watchdog_task.done():
+ return
+ _watchdog_intentionally_stopped = False
+ _watchdog_stop.clear()
+ _watchdog_task = asyncio.create_task(_watchdog_loop(), name="task-runtime-watchdog")
+
+
+# 停止看门狗。
+async def stop_watchdog() -> None:
+ global _watchdog_intentionally_stopped
+ _watchdog_intentionally_stopped = True
+ _watchdog_stop.set()
+ if _watchdog_task and not _watchdog_task.done():
+ _watchdog_task.cancel()
+ try:
+ await _watchdog_task
+ except asyncio.CancelledError:
+ pass
+
+
+# 看门狗状态。
+def watchdog_status() -> str:
+ if _watchdog_intentionally_stopped:
+ return "stopped"
+ if _watchdog_task and not _watchdog_task.done():
+ return "running"
+ return "stopped"
+
+
+# 周期检查调度器与 Selector 存活,必要时软重启。
+async def _watchdog_loop() -> None:
+ while not _watchdog_stop.is_set():
+ try:
+ await _watchdog_once()
+ except asyncio.CancelledError:
+ raise
+ except Exception: # noqa: BLE001
+ logger.exception("task runtime watchdog failed")
+ interval = max(2.0, float(get_settings().task_runtime_watchdog_interval_sec))
+ await asyncio.sleep(interval)
+
+
+# 单次看门狗检查。
+async def _watchdog_once() -> None:
+ if scheduler_status() != "running" or scheduler_tick_stale():
+ reason = "dead" if scheduler_status() != "running" else "tick_stale"
+ await restart_scheduler_loop(reason=f"watchdog:{reason}")
+ if poller_status() != "running" or poller_tick_stale():
+ reason = "dead" if poller_status() != "running" else "tick_stale"
+ await restart_poller_loop(reason=f"watchdog:{reason}")
+
+
+# 返回任务平台运行时摘要(槽位 + 循环存活 + 心跳年龄)。
+def runtime_summary() -> dict[str, int | str | float | bool]:
+ sched = scheduler_status()
+ poll = poller_status()
+ dog = watchdog_status()
+ healthy = sched == "running" and poll == "running" and dog == "running"
return {
+ "healthy": healthy,
+ "scheduler": sched,
"scheduler_running_jobs": running_count(),
- "poller": poller_status(),
+ "scheduler_tick_age_sec": round(scheduler_tick_age_sec(), 1),
+ "poller": poll,
+ "poller_tick_age_sec": round(poller_tick_age_sec(), 1),
+ "watchdog": dog,
}
diff --git a/backend/app/services/tasks/scheduler.py b/backend/app/services/tasks/scheduler.py
index ad5dbb2..0df404f 100644
--- a/backend/app/services/tasks/scheduler.py
+++ b/backend/app/services/tasks/scheduler.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import logging
+import time
import uuid
from datetime import UTC, datetime, timedelta
@@ -13,27 +14,40 @@ from app.config import get_settings
from app.database import AsyncSessionLocal
from app.models_tasks import TaskRun
from app.services.tasks.executor import execute_task_run
-from app.services.tasks.service import append_task_event, count_user_active_runtime_tasks, reconcile_sequential_batches, reconcile_stale_pending_tasks
+from app.services.tasks.service import (
+ append_task_event,
+ count_user_active_runtime_tasks,
+ reconcile_sequential_batches,
+ reconcile_stale_pending_tasks,
+)
logger = logging.getLogger("app.tasks.scheduler")
+# 调度循环句柄、进程内执行槽、停机信号、心跳与孤儿扫描时间戳
_scheduler_task: asyncio.Task | None = None
_running_jobs: dict[int, asyncio.Task] = {}
_stop_event = asyncio.Event()
+_last_tick_mono: float = 0.0
+_last_orphan_check_mono: float = 0.0
+_intentionally_stopped: bool = True
# 启动任务调度循环。
async def start_scheduler() -> None:
- global _scheduler_task
+ global _scheduler_task, _intentionally_stopped, _last_tick_mono
if _scheduler_task and not _scheduler_task.done():
return
- await _recover_orphaned_tasks()
+ _intentionally_stopped = False
+ await recover_orphaned_tasks()
_stop_event.clear()
- _scheduler_task = asyncio.create_task(_scheduler_loop())
+ _last_tick_mono = time.monotonic()
+ _scheduler_task = asyncio.create_task(_scheduler_loop(), name="task-scheduler")
# 停止任务调度循环并取消执行中的任务。
async def stop_scheduler() -> None:
+ global _intentionally_stopped
+ _intentionally_stopped = True
_stop_event.set()
if _scheduler_task and not _scheduler_task.done():
_scheduler_task.cancel()
@@ -50,26 +64,88 @@ async def stop_scheduler() -> None:
_running_jobs.clear()
+# 仅重启调度循环(保留进程内仍在跑的 job),用于看门狗拉起卡死 tick。
+async def restart_scheduler_loop(*, reason: str = "watchdog") -> None:
+ global _scheduler_task, _intentionally_stopped, _last_tick_mono
+ if _intentionally_stopped:
+ return
+ logger.warning("restarting task scheduler loop reason=%s", reason)
+ _stop_event.set()
+ if _scheduler_task and not _scheduler_task.done():
+ _scheduler_task.cancel()
+ try:
+ await _scheduler_task
+ except asyncio.CancelledError:
+ pass
+ await recover_orphaned_tasks()
+ _stop_event.clear()
+ _last_tick_mono = time.monotonic()
+ _scheduler_task = asyncio.create_task(_scheduler_loop(), name="task-scheduler")
+
+
# 返回当前运行中的平台任务数量。
def running_count() -> int:
return sum(1 for task in _running_jobs.values() if not task.done())
+# 调度循环是否存活。
+def scheduler_status() -> str:
+ if _intentionally_stopped:
+ return "stopped"
+ if _scheduler_task and not _scheduler_task.done():
+ return "running"
+ return "stopped"
+
+
+# 距上次成功完成 tick 的秒数;从未 tick 时返回很大值。
+def scheduler_tick_age_sec() -> float:
+ if _last_tick_mono <= 0:
+ return 1e9
+ return max(0.0, time.monotonic() - _last_tick_mono)
+
+
+# 是否因心跳过期应视为卡死(供看门狗判断)。
+def scheduler_tick_stale() -> bool:
+ if _intentionally_stopped:
+ return False
+ stale_sec = max(15, int(get_settings().task_runtime_tick_stale_sec))
+ return scheduler_tick_age_sec() > stale_sec
+
+
+# 本地是否仍持有该任务的执行协程。
+def _job_alive(task_id: int) -> bool:
+ job = _running_jobs.get(task_id)
+ return bool(job and not job.done())
+
+
# 周期扫描到期任务并交给执行器。
async def _scheduler_loop() -> None:
+ global _last_tick_mono
while not _stop_event.is_set():
+ _last_tick_mono = time.monotonic()
+ timeout = max(20.0, float(get_settings().task_runtime_tick_stale_sec) - 10.0)
try:
- await _tick()
+ await asyncio.wait_for(_tick(), timeout=timeout)
+ except asyncio.TimeoutError:
+ logger.error("task scheduler tick timed out after %.0fs", timeout)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001
logger.exception("task scheduler tick failed")
+ finally:
+ _last_tick_mono = time.monotonic()
await asyncio.sleep(1.0)
# 扫描并租约抢占可执行任务。
async def _tick() -> None:
+ global _last_orphan_check_mono
now = datetime.now(UTC)
+ orphan_every = max(5, int(get_settings().task_runtime_orphan_check_sec))
+ if time.monotonic() - _last_orphan_check_mono >= orphan_every:
+ await recover_orphaned_tasks()
+ _last_orphan_check_mono = time.monotonic()
+
async with AsyncSessionLocal() as db:
await reconcile_sequential_batches(db)
await reconcile_stale_pending_tasks(db)
@@ -165,8 +241,8 @@ async def cancel_running_task(task_id: int) -> bool:
return True
-# 启动时把上次进程中断留下的 leased/running 任务放回待执行队列。
-async def _recover_orphaned_tasks() -> None:
+# 把僵死的 leased/running 放回队列;跳过本进程仍持有协程的任务。
+async def recover_orphaned_tasks() -> int:
now = datetime.now(UTC)
grace_sec = max(5, int(get_settings().task_runtime_recover_grace_sec))
stale_before = now - timedelta(seconds=grace_sec)
@@ -175,13 +251,25 @@ async def _recover_orphaned_tasks() -> None:
await reconcile_stale_pending_tasks(db)
stmt = select(TaskRun).where(
or_(
- and_(TaskRun.status == "leased", TaskRun.updated_at.is_not(None), TaskRun.updated_at < stale_before),
- and_(TaskRun.status == "running", TaskRun.updated_at.is_not(None), TaskRun.updated_at < stale_before),
+ and_(
+ TaskRun.status == "leased",
+ or_(
+ and_(TaskRun.updated_at.is_not(None), TaskRun.updated_at < stale_before),
+ and_(TaskRun.lease_until.is_not(None), TaskRun.lease_until < now),
+ ),
+ ),
+ and_(
+ TaskRun.status == "running",
+ TaskRun.updated_at.is_not(None),
+ TaskRun.updated_at < stale_before,
+ ),
)
)
rows = list((await db.execute(stmt)).scalars().all())
changed = 0
for task in rows:
+ if _job_alive(int(task.id)):
+ continue
task.status = "cancel_requested" if task.cancel_requested else "pending"
task.next_action_at = now
task.lease_token = None
@@ -192,9 +280,10 @@ async def _recover_orphaned_tasks() -> None:
event_type="task.recovered",
status=task.status,
phase=task.current_step_key,
- message="检测到任务在上次进程退出时中断,已重新排队",
+ message="检测到任务执行中断或租约过期,已重新排队",
)
changed += 1
if changed:
await db.commit()
logger.warning("recovered orphaned task runs count=%s", changed)
+ return changed
diff --git a/backend/tests/test_drama_llm_json.py b/backend/tests/test_drama_llm_json.py
index a4c1c6b..31925b2 100644
--- a/backend/tests/test_drama_llm_json.py
+++ b/backend/tests/test_drama_llm_json.py
@@ -1,10 +1,11 @@
"""drama LLM JSON 解析单测。"""
import json
+from unittest.mock import AsyncMock, patch
import pytest
-from app.services.drama.llm import _extract_json
+from app.services.drama.llm import _ensure_json_word_in_prompt, _extract_json, drama_chat_json
def test_extract_json_plain_object():
@@ -34,3 +35,33 @@ def test_extract_json_repairs_smart_quotes():
def test_extract_json_raises_on_invalid_payload():
with pytest.raises(json.JSONDecodeError):
_extract_json("not json at all")
+
+
+def test_ensure_json_word_appends_when_missing():
+ system, user = _ensure_json_word_in_prompt("你是编剧", "写第1集")
+ assert "json" in f"{system}\n{user}".lower()
+ assert "写第1集" in user
+
+
+def test_ensure_json_word_keeps_existing():
+ system, user = _ensure_json_word_in_prompt("输出 JSON", "写第1集")
+ assert system == "输出 JSON"
+ assert user == "写第1集"
+
+
+async def test_drama_chat_json_injects_json_before_response_format():
+ """无 json 字样时应注入后再带 response_format 调用,避免 DeepSeek 400。"""
+ captured: dict = {}
+
+ async def _fake_chat(system, user, **kwargs):
+ captured["system"] = system
+ captured["user"] = user
+ captured["response_format"] = kwargs.get("response_format")
+ return '{"ok": true}'
+
+ with patch("app.services.drama.llm.chat_completions", new=AsyncMock(side_effect=_fake_chat)):
+ data = await drama_chat_json("你是编剧", "写大纲")
+ assert data == {"ok": True}
+ assert "json" in f"{captured['system']}\n{captured['user']}".lower()
+ assert captured["response_format"] == {"type": "json_object"}
diff --git a/backend/tests/test_task_runtime_watchdog.py b/backend/tests/test_task_runtime_watchdog.py
new file mode 100644
index 0000000..6af79db
--- /dev/null
+++ b/backend/tests/test_task_runtime_watchdog.py
@@ -0,0 +1,152 @@
+"""Tests for task runtime watchdog, heartbeat, and orphan recovery guards."""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from app.services.tasks import poller as poller_mod
+from app.services.tasks import runtime as runtime_mod
+from app.services.tasks import scheduler as scheduler_mod
+
+
[email protected](autouse=True)
+async def _reset_runtime_state():
+ """每个用例前后停掉调度/轮询/看门狗,避免泄漏协程。"""
+ await runtime_mod.stop_task_runtime()
+ scheduler_mod._running_jobs.clear()
+ poller_mod._poll_inflight.clear()
+ yield
+ await runtime_mod.stop_task_runtime()
+ scheduler_mod._running_jobs.clear()
+ poller_mod._poll_inflight.clear()
+
+
+async def test_scheduler_status_and_heartbeat():
+ """启动后调度状态为 running,心跳年龄应接近 0。"""
+ with (
+ patch.object(scheduler_mod, "recover_orphaned_tasks", new=AsyncMock(return_value=0)),
+ patch.object(scheduler_mod, "_tick", new=AsyncMock()),
+ ):
+ await scheduler_mod.start_scheduler()
+ assert scheduler_mod.scheduler_status() == "running"
+ assert scheduler_mod.scheduler_tick_age_sec() < 5
+ assert not scheduler_mod.scheduler_tick_stale()
+ await scheduler_mod.stop_scheduler()
+ assert scheduler_mod.scheduler_status() == "stopped"
+
+
+async def test_watchdog_restarts_dead_scheduler():
+ """调度循环退出后,看门狗应重新拉起。"""
+ with (
+ patch.object(scheduler_mod, "recover_orphaned_tasks", new=AsyncMock(return_value=0)),
+ patch.object(scheduler_mod, "_tick", new=AsyncMock()),
+ patch.object(poller_mod, "_select_and_poll_due", new=AsyncMock()),
+ patch.object(poller_mod, "_poll_ephemeral_deferred_tasks", new=AsyncMock()),
+ patch(
+ "app.services.tasks.runtime.get_settings",
+ return_value=SimpleNamespace(task_runtime_watchdog_interval_sec=0.05),
+ ),
+ ):
+ await runtime_mod.start_task_runtime()
+ first = scheduler_mod._scheduler_task
+ assert first is not None and not first.done()
+ # 人为结束调度循环(不走 stop,模拟异常退出)
+ scheduler_mod._intentionally_stopped = False
+ first.cancel()
+ try:
+ await first
+ except asyncio.CancelledError:
+ pass
+ for _ in range(40):
+ current = scheduler_mod._scheduler_task
+ if (
+ scheduler_mod.scheduler_status() == "running"
+ and current is not None
+ and current is not first
+ and not current.done()
+ ):
+ break
+ await asyncio.sleep(0.05)
+ current = scheduler_mod._scheduler_task
+ assert scheduler_mod.scheduler_status() == "running"
+ assert current is not None and current is not first
+ assert runtime_mod.runtime_summary()["healthy"] is True
+
+
+async def test_recover_skips_local_alive_jobs():
+ """本进程仍持有执行协程的 running 任务不应被孤儿恢复改写。"""
+ alive = asyncio.create_task(asyncio.sleep(60))
+ scheduler_mod._running_jobs[42] = alive
+
+ fake_task = SimpleNamespace(
+ id=42,
+ status="running",
+ cancel_requested=False,
+ current_step_key="step",
+ next_action_at=None,
+ lease_token="x",
+ lease_until=None,
+ )
+
+ class _FakeResult:
+ def scalars(self):
+ return self
+
+ def all(self):
+ return [fake_task]
+
+ class _FakeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return False
+
+ async def execute(self, *_args, **_kwargs):
+ return _FakeResult()
+
+ async def commit(self):
+ return None
+
+ with (
+ patch.object(scheduler_mod, "AsyncSessionLocal", return_value=_FakeSession()),
+ patch.object(scheduler_mod, "reconcile_sequential_batches", new=AsyncMock()),
+ patch.object(scheduler_mod, "reconcile_stale_pending_tasks", new=AsyncMock()),
+ patch.object(scheduler_mod, "append_task_event", new=AsyncMock()),
+ patch(
+ "app.services.tasks.scheduler.get_settings",
+ return_value=SimpleNamespace(task_runtime_recover_grace_sec=1),
+ ),
+ ):
+ changed = await scheduler_mod.recover_orphaned_tasks()
+ assert changed == 0
+ assert fake_task.status == "running"
+
+ alive.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await alive
+
+
+async def test_runtime_summary_reports_components():
+ """runtime_summary 应暴露 scheduler/poller/watchdog 与 healthy。"""
+ with (
+ patch.object(scheduler_mod, "recover_orphaned_tasks", new=AsyncMock(return_value=0)),
+ patch.object(scheduler_mod, "_tick", new=AsyncMock()),
+ patch.object(poller_mod, "_select_and_poll_due", new=AsyncMock()),
+ patch.object(poller_mod, "_poll_ephemeral_deferred_tasks", new=AsyncMock()),
+ ):
+ await runtime_mod.start_task_runtime()
+ summary = runtime_mod.runtime_summary()
+ assert summary["scheduler"] == "running"
+ assert summary["poller"] == "running"
+ assert summary["watchdog"] == "running"
+ assert summary["healthy"] is True
+ assert "scheduler_tick_age_sec" in summary
diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md
index 0d0bbef..5ad3710 100644
--- a/docs/DEPLOY.md
+++ b/docs/DEPLOY.md
@@ -129,6 +129,7 @@ cd /opt/ai_movie/admin && npm ci && npm run build
systemctl status ai-movie-api ai-movie-worker
journalctl -u ai-movie-api -n 80 --no-pager
curl -fsS http://127.0.0.1:8000/api/health
+# 期望 task_runtime.healthy=true,且 scheduler/poller/watchdog 均为 running
curl -fsSI https://www.printfilm.com/ | head
curl -fsSI https://admin.printfilm.com/ | head
# 旧站保留(可选)
@@ -136,6 +137,8 @@ curl -fsSI https://kepu.printfilm.com/ | head
curl -fsSI https://admin.kepu.printfilm.com/ | head
```
+**任务卡住排障**:health 里 `scheduler`/`watchdog` 非 `running`,或库中有到期 `pending` 但 `scheduler_running_jobs=0` 且持续数分钟 → 先看 journal 是否有 `restarting task scheduler` / `recovered orphaned`;看门狗应自动拉起,仍异常再 `systemctl restart ai-movie-api`。
+
API 起不来时优先看:启动 seed 是否卡在 OSS、双 worker `create_all` 竞态、`.env` 是否被覆盖。
---
diff --git a/docs/releases/2026-09-06.md b/docs/releases/2026-09-06.md
new file mode 100644
index 0000000..d3e9458
--- /dev/null
+++ b/docs/releases/2026-09-06.md
@@ -0,0 +1,32 @@
+## 2026-09-06 21:25 · 任务调度看门狗 + 运行中孤儿恢复(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修
+- **范围**:api
+- **变更摘要**:
+ - 调度 / Selector 增加心跳;单次 tick 超时自动取消,避免卡死整环
+ - 运行时看门狗:循环退出或心跳过期时软重启(不杀仍在跑的 job)
+ - 运行中周期扫描僵死 `leased`/`running`(跳过本进程仍持有协程的任务)并重排队
+ - `/api/health` 的 `ok` 与 `task_runtime.healthy` 绑定;暴露 `scheduler` / `poller` / `watchdog`
+- **验证**:
+ - [x] `https://www.printfilm.com/api/health`(`ok:true`,`task_runtime.healthy`,scheduler/poller/watchdog running)
+ - [x] 本机 `curl 127.0.0.1:8000/api/health` 同上
+ - [ ] 前台首页 200
+ - [ ] (如有)admin 首页 200(`https://admin.printfilm.com/`)
+ - [x] 单元测试 `tests/test_task_runtime_watchdog.py` 4 passed
+- **备注 / 回滚**:回滚上述 7 个后端文件并 `systemctl restart ai-movie-api`
+
+## 2026-09-06 21:30 · 分集剧本进度回写 + DeepSeek JSON + force 续跑(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修
+- **范围**:api
+- **变更摘要**:
+ - `#3331` 管理端进度一直 0%:`run_episode_scripts_job` 未回写 `task_runs.progress_percent`,现按 done/total 更新并写 `task.progress` 事件
+ - DeepSeek `response_format=json_object` 要求 prompt 含 `json`:调用前自动注入,避免每集白打一轮
+ - `force=true` 在 `episode_content_status=generating` 时跳过清空,进程重启可从已生成集续跑
+- **验证**:
+ - [x] `#3331` 重启后续跑 `4/12`,`progress_percent=33`
+ - [x] journal:`force 续跑跳过清空 done=4/12`
+ - [x] `tests/test_drama_llm_json.py` 8 passed
+- **备注 / 回滚**:回滚 `llm.py` / `jobs.py` / `handlers.py` 并 `systemctl restart ai-movie-api`
diff --git a/docs/releases/README.md b/docs/releases/README.md
index 6d4880d..df5515b 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,6 +33,8 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-09-06 | 分集剧本进度回写 + DeepSeek JSON + force 续跑;杭州热修 | [2026-09-06.md](./2026-09-06.md) |
+| 2026-09-06 | 任务调度看门狗 + 运行中孤儿恢复;杭州热修 | [2026-09-06.md](./2026-09-06.md) |
| 2026-09-04 | 支付宝无原生码则新开易支付站点;杭州热修 | [2026-09-04.md](./2026-09-04.md) |
| 2026-09-04 | 支付二维码不用易支付收银台链接;杭州热修 | [2026-09-04.md](./2026-09-04.md) |
| 2026-09-04 | QQ 邮箱 465 改 SMTP_SSL;杭州热修 | [2026-09-04.md](./2026-09-04.md) |