- L2 连接核查: /object_info preflight (node existence + combo values) with
5-min cache + manual refresh; analyze accepts endpoint_id, saved workflows
get POST /{id}/check; unreachable degrades to 无法核查, never blocks saving
- 测试工作流: jobs.origin='workflow_test' rides the real queue → ComfyUI →
outputs pipeline; only a downloadable, correctly-typed output counts as a
pass; dry-run refused; repeat clicks reuse the in-flight job; artifacts
isolated under assets/_workflow_test/{id}; retention keeps newest 5;
clear-tests + delete-workflow cascade cleanup; tasks page shows a 测试 badge
- Media groups: Autogrow detection generalized to video/audio lists
(ref_videos/ref_audios etc.), patcher clones/rewires per media family,
validation per list kind; entries appear only for actually-wired slots;
MiniMax H3 Ref2VA official-limit hints keyed off the node class
- 25 new backend tests (preflight / workflow-test / media-groups) against the
fake ComfyUI; fake server gains /object_info + drop_outputs knobs
Co-authored-by: multica-agent <github@multica.ai>
181 lines
5.9 KiB
Python
181 lines
5.9 KiB
Python
"""Workflow-test job helpers (HEL-643).
|
|
|
|
A test job (jobs.origin = 'workflow_test') runs the FULL real pipeline —
|
|
queue → ComfyUI → outputs — but its artifacts are isolated from project
|
|
entities: files land under ``assets/_workflow_test/{workflow_id}/`` and are
|
|
never written back to characters/locations/scenes/clips.
|
|
|
|
This module owns the artifact directory, the retention policy (keep the
|
|
newest N records per workflow) and the purge paths used by "清除测试记录"
|
|
and workflow deletion.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from calliope import config
|
|
from calliope.db import get_db
|
|
|
|
logger = logging.getLogger("calliope.queue")
|
|
|
|
TEST_ORIGIN = "workflow_test"
|
|
TEST_SOURCE = "workflow_test"
|
|
# Records (and artifacts) kept per workflow before older ones are pruned.
|
|
TEST_KEEP = 5
|
|
|
|
|
|
def workflow_test_dir(workflow_id: int) -> Path:
|
|
return config.settings.assets_dir / "_workflow_test" / str(workflow_id)
|
|
|
|
|
|
def _safe_unlink(path_str: str) -> bool:
|
|
"""Delete a file if it resolves under assets_dir (missing = already gone)."""
|
|
try:
|
|
target = Path(path_str).resolve()
|
|
target.relative_to(config.settings.assets_dir.resolve())
|
|
except (ValueError, OSError):
|
|
return False
|
|
if not target.is_file():
|
|
return False
|
|
try:
|
|
target.unlink()
|
|
return True
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def _unlink_job_outputs(job: dict[str, Any]) -> None:
|
|
try:
|
|
paths = json.loads(job.get("output_paths_json") or "[]")
|
|
except (json.JSONDecodeError, TypeError):
|
|
return
|
|
if not isinstance(paths, list):
|
|
return
|
|
for p in paths:
|
|
if isinstance(p, str) and p.strip():
|
|
_safe_unlink(p)
|
|
|
|
|
|
def _remove_test_dir_if_empty(workflow_id: int) -> None:
|
|
d = workflow_test_dir(workflow_id)
|
|
try:
|
|
if d.is_dir() and not any(d.iterdir()):
|
|
d.rmdir()
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _test_job_public(job: dict[str, Any]) -> dict[str, Any]:
|
|
out = dict(job)
|
|
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
|
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
|
out.pop("payload_json", None)
|
|
out.pop("output_paths_json", None)
|
|
return out
|
|
|
|
|
|
def list_test_jobs(workflow_id: int, limit: int = 20) -> list[dict[str, Any]]:
|
|
conn = get_db(config.settings.db_path)
|
|
try:
|
|
rows = conn.execute(
|
|
"SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?"
|
|
" ORDER BY id DESC LIMIT ?",
|
|
(workflow_id, TEST_ORIGIN, limit),
|
|
).fetchall()
|
|
return [_test_job_public(dict(r)) for r in rows]
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def find_active_test_job(workflow_id: int, endpoint_id: str | None) -> dict[str, Any] | None:
|
|
"""The unfinished test job for (workflow, endpoint), if one exists.
|
|
|
|
Idempotency guard for the "测试工作流" button: a second click re-uses the
|
|
in-flight job instead of enqueuing a duplicate.
|
|
"""
|
|
conn = get_db(config.settings.db_path)
|
|
try:
|
|
rows = conn.execute(
|
|
"SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?"
|
|
" AND status IN ('pending', 'running') ORDER BY id DESC",
|
|
(workflow_id, TEST_ORIGIN),
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
for r in rows:
|
|
job = dict(r)
|
|
try:
|
|
payload = json.loads(job.get("payload_json") or "{}")
|
|
except (json.JSONDecodeError, TypeError):
|
|
payload = {}
|
|
snap = payload.get("endpoint") or {}
|
|
if not isinstance(snap, dict):
|
|
snap = {}
|
|
if (snap.get("id") or None) == (endpoint_id or None):
|
|
return _test_job_public(job)
|
|
return None
|
|
|
|
|
|
def prune_workflow_tests(workflow_id: int, keep: int = TEST_KEEP) -> int:
|
|
"""Keep only the newest ``keep`` test records (older rows + files go)."""
|
|
conn = get_db(config.settings.db_path)
|
|
try:
|
|
rows = conn.execute(
|
|
"SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?"
|
|
" ORDER BY id DESC LIMIT -1 OFFSET ?",
|
|
(workflow_id, TEST_ORIGIN, max(keep, 0)),
|
|
).fetchall()
|
|
removed = 0
|
|
for r in rows:
|
|
job = dict(r)
|
|
if job.get("status") in ("pending", "running"):
|
|
continue
|
|
_unlink_job_outputs(job)
|
|
conn.execute("DELETE FROM jobs WHERE id = ?", (job["id"],))
|
|
removed += 1
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
_remove_test_dir_if_empty(workflow_id)
|
|
if removed:
|
|
logger.info("Pruned %s old workflow-test records for workflow %s", removed, workflow_id)
|
|
return removed
|
|
|
|
|
|
def purge_workflow_tests(workflow_id: int, *, allow_active: bool = False) -> int:
|
|
"""Delete EVERY test record and artifact for a workflow.
|
|
|
|
Returns the removed row count; raises RuntimeError when an unfinished
|
|
test job is still in flight (unless ``allow_active``).
|
|
"""
|
|
conn = get_db(config.settings.db_path)
|
|
try:
|
|
if not allow_active:
|
|
active = conn.execute(
|
|
"SELECT COUNT(*) AS n FROM jobs WHERE workflow_id = ? AND origin = ?"
|
|
" AND status IN ('pending', 'running')",
|
|
(workflow_id, TEST_ORIGIN),
|
|
).fetchone()["n"]
|
|
if active:
|
|
raise RuntimeError(
|
|
f"该工作流还有 {active} 个进行中的测试任务,请先等待完成或取消,再清除测试记录"
|
|
)
|
|
rows = conn.execute(
|
|
"SELECT * FROM jobs WHERE workflow_id = ? AND origin = ?",
|
|
(workflow_id, TEST_ORIGIN),
|
|
).fetchall()
|
|
removed = 0
|
|
for r in rows:
|
|
_unlink_job_outputs(dict(r))
|
|
conn.execute("DELETE FROM jobs WHERE id = ?", (r["id"],))
|
|
removed += 1
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
shutil.rmtree(workflow_test_dir(workflow_id), ignore_errors=True)
|
|
return removed
|