Files
aigc-home/calliope-backend/src/calliope/queue/manager.py
T
leeferandmultica-agent c5aa575ac3 feat(workflows): UI→API 转换器 + 批量导入 + 元数据轻量列表 (HEL-681 S2)
- 新增 comfyui/ui_convert.py:离线确定性转换(reroute/bypass/mute 透传、
  子图展开为 packed:inner 限定 id、Set/Get 变量解析、控件三种映射来源,
  无法可靠映射的文件进入需人工确认,绝不静默猜测)
- 新增 convert / import-batch / import-scan 端点:dry-run 逐文件
  ok/warn/fail 报告 + 建议元数据;导入端冲突跳过、重复执行幂等
- workflows 表加列 category/model_family/media_io/tags/favorite/
  last_used_at/source/source_path(纯加列迁移,旧行为零影响)
- GET /api/workflows?view=meta 轻量列表不含全量 JSON;旧接口行为不变
- 元数据建议:分类/模型家族(主加载器加权+目录回退,规避 qwen_image_vae
  误标)/输入输出媒介/MarkdownNote 描述素材
- enqueue 时记录 last_used_at;PATCH 支持 favorite/tags 等字段
- 测试 23 项新增(转换语义单测+146 文件语料+对拍+端点/迁移/幂等)

Co-authored-by: multica-agent <github@multica.ai>
2026-10-11 11:20:23 +08:00

280 lines
9.9 KiB
Python

"""SQLite-backed job queue manager."""
from __future__ import annotations
import json
import logging
from typing import Any
from calliope import config
from calliope.db import get_db, row_to_dict
logger = logging.getLogger("calliope.queue")
class QueueManager:
def __init__(self) -> None:
self.paused = False
def reset_stale_jobs(self) -> int:
conn = get_db(config.settings.db_path)
try:
cur = conn.execute(
"UPDATE jobs SET status = 'pending', started_at = NULL, phase = NULL, "
"comfy_prompt_id = NULL WHERE status = 'running'"
)
conn.commit()
return cur.rowcount
finally:
conn.close()
def enqueue(
self,
*,
project_id: int,
kind: str,
workflow_id: int | None = None,
scene_id: int | None = None,
clip_id: int | None = None,
payload: dict[str, Any] | None = None,
origin: str = "user",
) -> dict[str, Any]:
conn = get_db(config.settings.db_path)
try:
payload = self._stamp_endpoint(conn, workflow_id, dict(payload or {}))
cur = conn.execute(
"""
INSERT INTO jobs (project_id, scene_id, clip_id, kind, workflow_id,
status, payload_json, origin)
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)
""",
(project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload), origin),
)
# HEL-681: every enqueued job counts as a use (最近使用).
if workflow_id is not None:
conn.execute(
"UPDATE workflows SET last_used_at = CURRENT_TIMESTAMP WHERE id = ?",
(workflow_id,),
)
conn.commit()
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone()
return row_to_dict(row)
finally:
conn.close()
@staticmethod
def _stamp_endpoint(
conn, workflow_id: int | None, payload: dict[str, Any]
) -> dict[str, Any]:
"""Snapshot the target ComfyUI connection into the job payload (HEL-611).
Every generation path (flow video/assets, playground, agent tools)
funnels through here, so they all share one execution route.
Priority: an explicit payload ``endpoint_id`` → the workflow's
bound connection → the active connection. The snapshot carries
id/name/base_url only — the token is resolved server-side by
the worker at run time.
"""
from calliope.comfyui.endpoints import endpoint_snapshot
if payload.get("endpoint"):
return payload
endpoint_id = payload.get("endpoint_id")
if not endpoint_id and workflow_id:
try:
row = conn.execute(
"SELECT endpoint_id FROM workflows WHERE id = ?", (workflow_id,)
).fetchone()
endpoint_id = row["endpoint_id"] if row else None
except Exception:
endpoint_id = None # pre-migration DB: column may be missing
payload["endpoint"] = endpoint_snapshot(endpoint_id)
return payload
def claim_next(self) -> dict[str, Any] | None:
if self.paused:
return None
conn = get_db(config.settings.db_path)
try:
row = conn.execute(
"SELECT * FROM jobs WHERE status = 'pending' ORDER BY created_at ASC LIMIT 1"
).fetchone()
if not row:
return None
job_id = row["id"]
conn.execute(
"""
UPDATE jobs SET status = 'running', started_at = CURRENT_TIMESTAMP
WHERE id = ? AND status = 'pending'
""",
(job_id,),
)
conn.commit()
claimed = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
return row_to_dict(claimed) if claimed else None
finally:
conn.close()
def set_phase(self, job_id: int, phase: str, comfy_prompt_id: str | None = None) -> None:
conn = get_db(config.settings.db_path)
try:
if comfy_prompt_id:
conn.execute(
"UPDATE jobs SET phase = ?, comfy_prompt_id = ? WHERE id = ?",
(phase, comfy_prompt_id, job_id),
)
else:
conn.execute("UPDATE jobs SET phase = ? WHERE id = ?", (phase, job_id))
conn.commit()
finally:
conn.close()
def mark_done(self, job_id: int, output_paths: list[str]) -> None:
conn = get_db(config.settings.db_path)
try:
conn.execute(
"""
UPDATE jobs SET status = 'done', output_paths_json = ?, error = NULL,
completed_at = CURRENT_TIMESTAMP WHERE id = ?
""",
(json.dumps(output_paths), job_id),
)
conn.commit()
finally:
conn.close()
def mark_failed(self, job_id: int, error: str) -> None:
conn = get_db(config.settings.db_path)
try:
conn.execute(
"""
UPDATE jobs SET status = 'failed', error = ?, completed_at = CURRENT_TIMESTAMP,
retry_count = retry_count + 1 WHERE id = ?
""",
(error[:2000], job_id),
)
conn.commit()
finally:
conn.close()
def retry(self, job_id: int) -> dict[str, Any] | None:
conn = get_db(config.settings.db_path)
try:
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
if not row:
return None
conn.execute(
"""
UPDATE jobs SET status = 'pending', error = NULL, started_at = NULL,
completed_at = NULL, phase = NULL, comfy_prompt_id = NULL WHERE id = ?
""",
(job_id,),
)
conn.commit()
return row_to_dict(
conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
)
finally:
conn.close()
def cancel(self, job_id: int) -> bool:
conn = get_db(config.settings.db_path)
try:
cur = conn.execute(
"""
UPDATE jobs SET status = 'failed', error = 'cancelled',
completed_at = CURRENT_TIMESTAMP
WHERE id = ? AND status IN ('pending', 'running')
""",
(job_id,),
)
conn.commit()
return cur.rowcount > 0
finally:
conn.close()
def cancel_by_session(self, session_id: int) -> list[int]:
"""Cancel every pending/running job whose payload carries this
session_id (agent-enqueued jobs stamp it). Returns the cancelled ids."""
conn = get_db(config.settings.db_path)
try:
rows = conn.execute(
"SELECT id, payload_json FROM jobs WHERE status IN ('pending', 'running')"
).fetchall()
cancelled: list[int] = []
for r in rows:
try:
payload = json.loads(r["payload_json"] or "{}")
except (json.JSONDecodeError, TypeError):
continue
if payload.get("session_id") == session_id:
conn.execute(
"""
UPDATE jobs SET status = 'failed', error = 'cancelled',
completed_at = CURRENT_TIMESTAMP WHERE id = ?
""",
(r["id"],),
)
cancelled.append(r["id"])
conn.commit()
return cancelled
finally:
conn.close()
def is_cancelled(self, job_id: int) -> bool:
conn = get_db(config.settings.db_path)
try:
row = conn.execute(
"SELECT status FROM jobs WHERE id = ?", (job_id,)
).fetchone()
return bool(row) and row["status"] not in ("pending", "running")
finally:
conn.close()
def list_jobs(
self, project_id: int | None = None, status: str | None = None, limit: int = 100
) -> list[dict[str, Any]]:
conn = get_db(config.settings.db_path)
try:
clauses: list[str] = []
params: list[Any] = []
if project_id is not None:
clauses.append("project_id = ?")
params.append(project_id)
if status:
clauses.append("status = ?")
params.append(status)
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
params.append(limit)
rows = conn.execute(
f"SELECT * FROM jobs {where} ORDER BY created_at DESC LIMIT ?",
params,
).fetchall()
return [row_to_dict(r) for r in rows]
finally:
conn.close()
def get_job(self, job_id: int) -> dict[str, Any] | None:
conn = get_db(config.settings.db_path)
try:
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
return row_to_dict(row) if row else None
finally:
conn.close()
def delete_job(self, job_id: int) -> dict[str, Any] | None:
"""Remove job row. Returns the deleted job dict, or None if missing."""
conn = get_db(config.settings.db_path)
try:
row = conn.execute("SELECT * FROM jobs WHERE id = ?", (job_id,)).fetchone()
if not row:
return None
job = row_to_dict(row)
conn.execute("DELETE FROM jobs WHERE id = ?", (job_id,))
conn.commit()
return job
finally:
conn.close()
queue_manager = QueueManager()