"""Background queue worker loop.""" from __future__ import annotations import asyncio import json import logging from typing import Any from pathlib import Path as _fs_path import httpx from calliope import config from calliope.comfyui.client import ComfyUIClient from calliope.comfyui.dry_run import write_placeholder_mp4, write_placeholder_png from calliope.comfyui.lint import blocking_problem from calliope.comfyui.parser import parse_dynamic_inputs from calliope.comfyui.patcher import patch_workflow from calliope.comfyui.roles import input_has_role from calliope.db import get_db from calliope.events.bus import event_bus from calliope.export.runner import run_export from calliope.queue.manager import queue_manager from calliope.queue.workflow_test import ( TEST_ORIGIN, prune_workflow_tests, workflow_test_dir, ) logger = logging.getLogger("calliope.worker") def _comfy_messages(messages: list[Any]) -> str: """Pull the readable part out of ComfyUI's history status messages.""" parts: list[str] = [] for msg in messages: if not (isinstance(msg, (list, tuple)) and len(msg) == 2): continue body = msg[1] if isinstance(msg[1], dict) else {} node = body.get("node_type") or body.get("node_id") or "?" if msg[0] == "execution_error": reason = body.get("exception_message") or body.get("exception_type") or "未知错误" parts.append(f"节点 {node}:{str(reason).strip()}") elif msg[0] == "execution_interrupted": parts.append(f"任务在节点 {node} 处被中断(在 ComfyUI 端被取消,或 ComfyUI 已重启)") return ";".join(parts) or "ComfyUI 未给出原因" # /queue lookups that must agree before a prompt counts as lost, and /history # or /queue request failures in a row before the job gives up. _MISSING_POLLS_LIMIT = 3 _POLL_ERRORS_LIMIT = 5 class _CancelledByUser(RuntimeError): """The job row was flipped to 'cancelled' out-of-band (Stop button). The row already carries the terminal state; the loop must not overwrite it with mark_failed (which would bump retry_count and emit job.failed).""" class QueueWorker: def __init__(self) -> None: self._task: asyncio.Task | None = None self._stop = asyncio.Event() async def start(self) -> None: reset = queue_manager.reset_stale_jobs() if reset: logger.info("Reset %s stale running jobs to pending", reset) self._stop.clear() self._task = asyncio.create_task(self._loop(), name="calliope-queue-worker") async def stop(self) -> None: self._stop.set() if self._task: await asyncio.wait([self._task], timeout=5) async def _loop(self) -> None: logger.info("Queue worker started") while not self._stop.is_set(): try: if queue_manager.paused: await asyncio.sleep(config.settings.queue_poll_interval_sec) continue job = queue_manager.claim_next() if not job: await asyncio.sleep(config.settings.queue_poll_interval_sec) continue await event_bus.publish( "job.started", { "job_id": job["id"], "kind": job["kind"], "project_id": job.get("project_id"), "message": self._job_label(job), }, ) try: outputs = await self._run_job(job) queue_manager.mark_done(job["id"], outputs) if job["kind"] == "export": self._mark_project_completed(job["project_id"]) # Prompt snippet for canvas artifact labels: users # compare multiple generations of the same scene # side by side and pick one to re-apply. Parse the # stored payload here — _run_job's parsed copy is not # in this scope. try: job_payload = json.loads(job["payload_json"] or "{}") except (json.JSONDecodeError, TypeError): job_payload = {} row = queue_manager.get_job(job["id"]) or {} await event_bus.publish( "job.completed", { "job_id": job["id"], "kind": job["kind"], "outputs": outputs, "project_id": job["project_id"], "prompt": str(job_payload.get("prompt") or "")[:120], # Source stamp lets the UI attribute sandbox jobs # to their enqueuer without racing the jobs poll. "source": job_payload.get("source"), "comfy_prompt_id": row.get("comfy_prompt_id"), # Placeholder output — ComfyUI was never called. "dry_run": row.get("phase") == "dry_run", "message": f"{self._job_label(job)} · {len(outputs)} file(s)", }, ) if outputs: await event_bus.publish( "asset.ready", { "job_id": job["id"], "kind": job["kind"], "paths": outputs, "project_id": job["project_id"], "message": f"Saved {self._job_label(job)}", }, ) except _CancelledByUser: # The row already carries status='cancelled' (Stop button # flipped it out-of-band). Do NOT mark_failed (that would # bump retry_count and overwrite the terminal state). # Emit job.failed with cancelled=True so the UI flips the # node card and the user sees the stop took effect. logger.info("Job %s cancelled by user", job["id"]) await event_bus.publish( "job.failed", { "job_id": job["id"], "kind": job["kind"], "error": "cancelled by user", "cancelled": True, "project_id": job.get("project_id"), "message": f"{self._job_label(job)} cancelled", }, ) except Exception as exc: logger.exception("Job %s failed", job["id"]) queue_manager.mark_failed(job["id"], str(exc)) await event_bus.publish( "job.failed", { "job_id": job["id"], "kind": job["kind"], "error": str(exc), "project_id": job.get("project_id"), "message": f"{self._job_label(job)} failed", }, ) if str(job.get("origin") or "") == TEST_ORIGIN and job.get("workflow_id"): # Retention: keep only the newest records (and their # artifacts) per workflow (HEL-643). try: prune_workflow_tests(int(job["workflow_id"])) except Exception: logger.exception( "Pruning workflow-test records for workflow %s failed", job["workflow_id"], ) except Exception: logger.exception("Worker loop error") await asyncio.sleep(config.settings.queue_poll_interval_sec) logger.info("Queue worker stopped") async def _run_job(self, job: dict[str, Any]) -> list[str]: payload = json.loads(job["payload_json"] or "{}") project_id = job["project_id"] kind = job["kind"] is_test = str(job.get("origin") or "") == TEST_ORIGIN use_dry = bool(config.settings.dry_run) if kind == "export": # Export stitches local clips with ffmpeg — never touches ComfyUI, # and dry-run writes an mp4 placeholder (not the default PNG). return await run_export(job, payload, event_bus, dry_run=use_dry) base_url, headers, endpoint_label = self._resolve_endpoint(payload) client = ComfyUIClient(base_url, headers=headers) try: # A workflow test must be a REAL run — a dry-run placeholder that # passes as "测试通过" is exactly the false positive HEL-643 bans. if use_dry and is_test: raise RuntimeError( "测试工作流必须真实运行:当前设置开启了 Dry-run(占位模式)," "请到「设置」关闭 Dry-run 后重新测试" ) if use_dry: queue_manager.set_phase(job["id"], "dry_run") return await self._dry_run(job, payload) queue_manager.set_phase(job["id"], "connecting") healthy = await client.health() if not healthy: raise RuntimeError( f"ComfyUI 不可达({endpoint_label})。请在「ComfyUI 连接」页测试并修正该连接," "或在设置中开启 Dry-run 做占位测试。" ) workflow_id = job.get("workflow_id") or payload.get("workflow_id") workflow_row = self._load_workflow_row(workflow_id) if not workflow_row: raise RuntimeError( "找不到该任务使用的工作流(可能已被删除),请重新选择工作流后再生成" ) workflow = workflow_row["workflow_json"] broken = blocking_problem(workflow) if broken: raise RuntimeError(broken) # HEL-638: harvest only the confirmed output nodes. A workflow # with unknown custom outputs and no user mapping must not run. node_kinds = self._output_node_kinds(workflow_row) if node_kinds is None: raise RuntimeError( "该工作流含无法识别的自定义输出节点,尚未指定输出节点及媒体类型," "请到「ComfyUI 连接」页确认后再生成" ) input_values = payload.get("input_values") or {} if payload.get("continue_source") and kind == "video": input_values = await self._resolve_continue_source( job, payload, workflow, dict(input_values) ) patched = patch_workflow(workflow, input_values) patched = await client.prepare_media_inputs(patched) prompt_id = await client.queue_prompt(patched) queue_manager.set_phase(job["id"], "comfy_queued", prompt_id) await event_bus.publish( "job.progress", { "job_id": job["id"], "prompt_id": prompt_id, "phase": "comfy_queued", "message": f"ComfyUI 已接收任务(ID {prompt_id})", }, ) history = await self._poll_history(client, prompt_id, job["id"]) if not history: if queue_manager.is_cancelled(job["id"]): raise _CancelledByUser() raise RuntimeError( f"等待 ComfyUI 出结果超时(任务 ID {prompt_id}):可在「设置 → 队列」调大超时," "或到 ComfyUI 检查该任务" ) status = history.get("status") or {} if status.get("status_str") == "error" or status.get("completed") is False: messages = status.get("messages") or [] raise RuntimeError( f"ComfyUI 执行出错(任务 ID {prompt_id}):{_comfy_messages(messages)}" ) outputs_meta = client.extract_outputs(history, node_kinds=node_kinds) saved = [m for m in outputs_meta if m.get("type") == "output"] outputs_meta = saved or outputs_meta if not outputs_meta: checked = "、".join(sorted(node_kinds)) raise RuntimeError( f"ComfyUI 显示任务已结束(任务 ID {prompt_id}),但没有返回任何图片或视频," "不算生成完成。已按输出映射检查节点:" f"{checked};" "请到 ComfyUI 历史中核对该任务,并确认所指定的输出节点正确。" ) mismatch = next( ( m for m in outputs_meta if m.get("media_kind") and m["media_kind"] != node_kinds.get(m["node_id"]) ), None, ) if mismatch: want = node_kinds.get(mismatch["node_id"]) raise RuntimeError( f"输出节点 {mismatch['node_id']} 的媒体类型与映射不符" f"(映射为{'视频' if want == 'video' else '图片'}," f"实际返回 {mismatch['filename']}),任务不算生成完成。" "请到「ComfyUI 连接」页修正该节点的媒体类型。" ) queue_manager.set_phase(job["id"], "saving") if is_test: # Test artifacts live in a scratch dir, isolated from project # media and never written back to entities (HEL-643). dest_dir = workflow_test_dir(int(workflow_id)) else: dest_dir = config.settings.assets_dir / str(project_id) / kind dest_dir.mkdir(parents=True, exist_ok=True) paths: list[str] = [] for meta in outputs_meta: filename = meta["filename"] dest = dest_dir / filename await client.download_image( filename, subfolder=meta.get("subfolder", ""), folder_type=meta.get("type", "output"), dest=dest, ) paths.append(str(dest)) if not is_test: self._apply_outputs_to_entities(job, payload, paths) queue_manager.set_phase(job["id"], "finished") return paths finally: await client.close() @staticmethod def _resolve_endpoint(payload: dict[str, Any]) -> tuple[str, dict[str, str], str]: """Pick the ComfyUI address for THIS job (HEL-611). Priority: the payload's endpoint snapshot id, still present in config (fresh URL + token win) → the snapshot's URL when the id was deleted (token lost — history still explains the address) → the active connection (snapshots from before multi-connection, or jobs enqueued without one). """ from calliope.comfyui.endpoints import build_auth_headers snapshot = payload.get("endpoint") or {} if isinstance(snapshot, dict) and snapshot.get("id"): endpoint = config.settings.resolve_comfyui_endpoint(str(snapshot["id"])) if endpoint is not None and endpoint.get("id") == snapshot.get("id"): base_url = str(endpoint.get("base_url") or "") label = f"{endpoint.get('name') or '连接'} · {base_url}" return base_url, build_auth_headers(endpoint), label if isinstance(snapshot, dict) and snapshot.get("base_url"): # Dangling id: run against the snapshotted address, no token. base_url = str(snapshot["base_url"]) label = f"{snapshot.get('name') or '已删除连接'} · {base_url}" return base_url, {}, label endpoint = config.settings.resolve_comfyui_endpoint(None) if endpoint is None: raise RuntimeError("没有可用的 ComfyUI 连接:请到「ComfyUI 连接」页添加。") base_url = str(endpoint.get("base_url") or "") label = f"{endpoint.get('name') or '默认连接'} · {base_url}" return base_url, build_auth_headers(endpoint), label async def _resolve_continue_source( self, job: dict[str, Any], payload: dict[str, Any], workflow: dict[str, Any], input_values: dict[str, Any], ) -> dict[str, Any]: """Fill the workflow's video input with the previous clip's file. Enqueue defers continue-clips whose earlier clip does not exist yet (batch generation); the queue is concurrency-1, so by the time this job runs the earlier clip has been rendered and attached to its clip row. The path is injected into ``input_values`` like any user-provided value — ``patch_workflow`` writes it onto the ``(Input:video)`` node and ``prepare_media_inputs`` uploads it to ComfyUI before queuing. """ project_id = job["project_id"] src = payload.get("continue_source") or {} scene_pos = src.get("scene_order_index") clip_pos = src.get("clip_order_index") if scene_pos is None: scene_pos = payload.get("scene_order_index") or 0 if clip_pos is None: clip_pos = 1 prev: tuple[int, int] | None = None # (scene_pos, clip_pos) of the donor prev_clip: str | None = None conn = get_db(config.settings.db_path) try: row = conn.execute( """ SELECT s.order_index AS s_pos, c.order_index AS c_pos, COALESCE(c.clip_path, s.video_path) AS clip_path FROM clips c JOIN scenes s ON s.id = c.scene_id WHERE c.project_id = ? AND (s.order_index < ? OR (s.order_index = ? AND c.order_index < ?)) ORDER BY s.order_index DESC, c.order_index DESC LIMIT 1 """, (project_id, scene_pos, scene_pos, clip_pos), ).fetchone() if row: prev = (row["s_pos"], row["c_pos"]) prev_clip = row["clip_path"] finally: conn.close() pos_label = f"{scene_pos}.{clip_pos}" if prev is None: raise RuntimeError( f"Continue clip {pos_label}: no earlier clip in this project to continue from." ) if not prev_clip or not _fs_path(prev_clip).exists(): raise RuntimeError( f"Continue clip {pos_label}: previous clip (scene {prev[0]}.{prev[1]}) has no " "video file — generate the earlier clip first." ) video_node: str | None = None for inp in parse_dynamic_inputs(workflow): if input_has_role(inp, "video"): video_node = str(inp["nodeId"]) break if video_node is None: raise RuntimeError( "Continue clip " f"{pos_label}: workflow has no (Input:video) node to receive the previous clip." ) input_values[video_node] = prev_clip await event_bus.publish( "job.progress", { "job_id": job["id"], "project_id": project_id, "message": f"Continuing from clip {prev[0]}.{prev[1]}", }, ) return input_values async def _dry_run(self, job: dict[str, Any], payload: dict[str, Any]) -> list[str]: project_id = job["project_id"] kind = job["kind"] dest_dir = config.settings.assets_dir / str(project_id) / kind dest_dir.mkdir(parents=True, exist_ok=True) label = f"job-{job['id']}-{kind}" if kind == "video": path = write_placeholder_mp4(dest_dir / f"{label}.mp4", label=label) else: path = write_placeholder_png(dest_dir / f"{label}.png", label=label) paths = [str(path)] self._apply_outputs_to_entities(job, payload, paths) await asyncio.sleep(0.3) return paths async def _poll_history( self, client: ComfyUIClient, prompt_id: str, job_id: int | None = None ) -> dict[str, Any] | None: interval = max(config.settings.queue_poll_interval_sec, 0.5) timeout = config.settings.queue_poll_timeout_sec # 0 (or negative) = keep polling until the job completes or is cancelled. # Long video workflows routinely exceed 10 minutes, so the cap is now # configurable (default 30 min) instead of a hardcoded 600 seconds. attempts = None if timeout <= 0 else int(timeout / interval) n = 0 phase = "comfy_queued" missing = 0 errors = 0 while attempts is None or n < attempts: n += 1 if self._stop.is_set(): return None # Stop button: the job row was flipped to 'cancelled' out-of-band. # Interrupt the running ComfyUI prompt so the GPU stops NOW, then # bail — the row already carries the terminal state. if queue_manager.is_cancelled(job_id): await client.interrupt() return None try: history = await client.get_history(prompt_id) if history: return history where, ahead = await client.locate_prompt(prompt_id) except httpx.HTTPError as exc: errors += 1 if errors >= _POLL_ERRORS_LIMIT: raise RuntimeError( f"连续 {errors} 次无法从 ComfyUI 查询任务状态(任务 ID {prompt_id}):" f"{exc or type(exc).__name__}" ) from exc await asyncio.sleep(interval) continue errors = 0 if where == "missing": missing += 1 if missing >= _MISSING_POLLS_LIMIT: raise RuntimeError( f"ComfyUI 的队列和历史里都找不到该任务(任务 ID {prompt_id})," "可能 ComfyUI 已重启或任务被清除,没有产出结果" ) else: missing = 0 if where == "running": phase = "comfy_running" message = f"ComfyUI 正在执行(任务 ID {prompt_id})" elif where == "pending": phase = "comfy_queued" message = f"ComfyUI 排队中,前面还有 {ahead} 个任务(任务 ID {prompt_id})" else: message = f"等待 ComfyUI 返回结果(任务 ID {prompt_id})" if job_id is not None: queue_manager.set_phase(job_id, phase) await event_bus.publish( "job.progress", { "job_id": job_id, "prompt_id": prompt_id, "phase": phase, "queue_ahead": ahead if where == "pending" else None, "message": message, }, ) await asyncio.sleep(interval) return None def _mark_project_completed(self, project_id: int) -> None: """A finished export closes the project lifecycle.""" conn = get_db(config.settings.db_path) try: conn.execute( "UPDATE projects SET status = 'completed' WHERE id = ? AND status != 'completed'", (project_id,), ) conn.commit() finally: conn.close() def _load_workflow_row(self, workflow_id: int | None) -> dict[str, Any] | None: if not workflow_id: return None conn = get_db(config.settings.db_path) try: row = conn.execute( "SELECT workflow_json, output_map, output_map_source FROM workflows" " WHERE id = ?", (workflow_id,), ).fetchone() if not row: return None return { "workflow_json": json.loads(row["workflow_json"]), "output_map": row["output_map"], "output_map_source": row["output_map_source"], } finally: conn.close() @staticmethod def _output_node_kinds(workflow_row: dict[str, Any]) -> dict[str, str] | None: """Confirmed {nodeId: image|video} for this workflow, or None when the outputs are not confirmed (unknown nodes, no user mapping).""" from calliope.comfyui.output_map import mapping_problem, resolve_output_map workflow = workflow_row["workflow_json"] problem = mapping_problem( workflow, workflow_row.get("output_map"), workflow_row.get("output_map_source") ) if problem: return None entries, _source = resolve_output_map( workflow_row.get("output_map"), workflow_row.get("output_map_source"), workflow, ) return {str(e["nodeId"]): str(e["kind"]) for e in entries} or None def _job_label(self, job: dict[str, Any]) -> str: payload = json.loads(job.get("payload_json") or "{}") kind = job.get("kind") or "job" if kind == "export": return "Export film" conn = get_db(config.settings.db_path) try: if payload.get("character_id"): row = conn.execute( "SELECT name FROM characters WHERE id = ?", (payload["character_id"],) ).fetchone() name = row["name"] if row else f"#{payload['character_id']}" target = payload.get("asset_target") or "sheet" return f"{name} · {target}" if payload.get("location_id"): row = conn.execute( "SELECT name FROM locations WHERE id = ?", (payload["location_id"],) ).fetchone() name = row["name"] if row else f"#{payload['location_id']}" return f"{name} · environment" if payload.get("item_id"): row = conn.execute( "SELECT name FROM items WHERE id = ?", (payload["item_id"],) ).fetchone() name = row["name"] if row else f"#{payload['item_id']}" return f"{name} · item" if job.get("clip_id"): row = conn.execute( """ SELECT s.heading, s.order_index AS s_pos, c.order_index AS c_pos FROM clips c JOIN scenes s ON s.id = c.scene_id WHERE c.id = ? """, (job["clip_id"],), ).fetchone() if row: heading = (row["heading"] or f"Scene {row['s_pos']}").strip() return f"#{row['s_pos']}.{row['c_pos']} · {heading}" return f"Clip #{job['clip_id']}" if job.get("scene_id"): row = conn.execute( "SELECT heading, order_index FROM scenes WHERE id = ?", (job["scene_id"],) ).fetchone() if row: heading = (row["heading"] or f"Scene {row['order_index']}").strip() return f"Scene · {heading}" return f"Scene #{job['scene_id']}" finally: conn.close() return f"{kind} #{job.get('id')}" def _apply_outputs_to_entities( self, job: dict[str, Any], payload: dict[str, Any], paths: list[str] ) -> None: if not paths: return primary = paths[0] character_id = payload.get("character_id") location_id = payload.get("location_id") item_id = payload.get("item_id") scene_id = job.get("scene_id") conn = get_db(config.settings.db_path) try: if character_id: target = payload.get("asset_target") or "sheet" if target == "portrait": # Legacy jobs only — UI no longer generates portraits conn.execute( "UPDATE characters SET portrait_path = ? WHERE id = ?", (primary, character_id), ) else: conn.execute( "UPDATE characters SET sheet_path = ? WHERE id = ?", (primary, character_id), ) if location_id: conn.execute( "UPDATE locations SET reference_image_path = ? WHERE id = ?", (primary, location_id), ) if item_id: conn.execute( "UPDATE items SET reference_image_path = ? WHERE id = ?", (primary, item_id), ) if job.get("clip_id") and job["kind"] == "video": conn.execute( "UPDATE clips SET clip_path = ? WHERE id = ?", (primary, job["clip_id"]), ) # Mirror onto the scene for legacy readers (canvas scene cards, # old queries). The clip row stays the source of truth. conn.execute( """ UPDATE scenes SET video_path = ? WHERE id = ( SELECT scene_id FROM clips WHERE id = ? ) """, (primary, job["clip_id"]), ) elif scene_id and job["kind"] == "video": # Legacy job (pre-clips schema): write the scene's default clip. conn.execute( """ UPDATE clips SET clip_path = ? WHERE id = ( SELECT c.id FROM clips c WHERE c.scene_id = ? ORDER BY c.order_index, c.id LIMIT 1 ) """, (primary, scene_id), ) conn.execute( "UPDATE scenes SET video_path = ? WHERE id = ?", (primary, scene_id), ) conn.commit() finally: conn.close() queue_worker = QueueWorker()