HEL-892: bind supplied API companions with provenance and fail-closed import
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
"""Explicit source-bound supplied API companions; never evidence of general conversion.
|
||||
|
||||
Hashes bind the reviewed pair, not the historical export environment. Source/API
|
||||
comparisons retain positional values as unnamed rather than guessing widget order.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from calliope.comfyui.ui2api import convert
|
||||
|
||||
|
||||
def load_companions(path: Path) -> dict:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
if data.get("schema_version") != 1 or not isinstance(data.get("cases"), list):
|
||||
raise ValueError("配套清单格式错误")
|
||||
records = {}
|
||||
for entry in data["cases"]:
|
||||
key = entry["source_path"]
|
||||
if not all(
|
||||
isinstance(entry.get(k), str) and entry[k].strip()
|
||||
for k in (
|
||||
"source_path",
|
||||
"source_sha",
|
||||
"source_sha256",
|
||||
"export_sha256",
|
||||
"provider",
|
||||
"attachment_id",
|
||||
"received_at",
|
||||
"provenance",
|
||||
"instruction",
|
||||
)
|
||||
):
|
||||
raise ValueError("配套清单缺少来源、哈希或说明;未知导出版本应明确记为null")
|
||||
if not all(k in entry for k in ("exported_at", "frontend_version", "node_versions")):
|
||||
raise ValueError("必须明确记录导出时间/版本的未知状态")
|
||||
if key in records:
|
||||
raise ValueError("配套源路径重复")
|
||||
# Store bytes, not a live path: the same bytes are hashed and imported.
|
||||
relative = Path(entry["export_file"])
|
||||
if relative.is_absolute() or ".." in relative.parts:
|
||||
raise ValueError("配套文件必须在清单目录内")
|
||||
raw = (path.parent / relative).read_bytes()
|
||||
json.loads(raw.decode("utf-8-sig")) # Reject malformed JSON before any database write.
|
||||
records[key] = {"binding": entry, "raw": raw.decode("utf-8")}
|
||||
if hashlib.sha256(raw).hexdigest() != entry["export_sha256"]:
|
||||
raise ValueError("配套API文件哈希不符")
|
||||
return records
|
||||
|
||||
|
||||
def _same(left, right):
|
||||
# bool/int and int/float distinctions matter, including nested values.
|
||||
return type(left) is type(right) and (
|
||||
left.keys() == right.keys() and all(_same(left[k], right[k]) for k in left)
|
||||
if isinstance(left, dict)
|
||||
else len(left) == len(right) and all(_same(a, b) for a, b in zip(left, right))
|
||||
if isinstance(left, list)
|
||||
else left == right
|
||||
)
|
||||
|
||||
|
||||
def source_comparison(source: dict, api: dict) -> dict:
|
||||
"""Compare every exported field with explicit source evidence, never equal-by-default."""
|
||||
definitions = {s["id"]: s for s in (source.get("definitions") or {}).get("subgraphs", [])}
|
||||
indexed = {}
|
||||
|
||||
def walk(graph, prefix="", ancestry=()):
|
||||
for node in graph.get("nodes", []):
|
||||
nid = prefix + str(node["id"])
|
||||
indexed[nid] = (node, graph, prefix)
|
||||
sub = definitions.get(node.get("type"))
|
||||
if sub and sub["id"] not in ancestry:
|
||||
walk(sub, nid + ":", (*ancestry, sub["id"]))
|
||||
|
||||
walk(source)
|
||||
nodes = []
|
||||
for nid, exported in api.items():
|
||||
item = {"api_id": nid, "api_node": exported, "fields": []}
|
||||
inputs = exported.get("inputs")
|
||||
inputs = inputs if isinstance(inputs, dict) else {}
|
||||
found = indexed.get(nid)
|
||||
if not found:
|
||||
item["status"] = "api_only_source_changed_or_expansion_unresolved"
|
||||
item["fields"] = [
|
||||
{
|
||||
"field": field,
|
||||
"api_value": value,
|
||||
"api_type": type(value).__name__,
|
||||
"status": "source_node_unresolved",
|
||||
}
|
||||
for field, value in inputs.items()
|
||||
]
|
||||
nodes.append(item)
|
||||
continue
|
||||
original, graph, prefix = found
|
||||
item.update(
|
||||
source_node=original,
|
||||
status="type_match"
|
||||
if original.get("type") == exported.get("class_type")
|
||||
else "type_difference",
|
||||
metadata={
|
||||
"source_title": original.get("title", original.get("type")),
|
||||
"api_meta": exported.get("_meta"),
|
||||
"title_equal": _same(
|
||||
original.get("title", original.get("type")),
|
||||
(
|
||||
exported["_meta"].get("title")
|
||||
if isinstance(exported.get("_meta"), dict)
|
||||
else None
|
||||
),
|
||||
),
|
||||
},
|
||||
)
|
||||
links = {}
|
||||
for link in graph.get("links", []):
|
||||
if isinstance(link, dict):
|
||||
link = [
|
||||
link.get(k)
|
||||
for k in ("id", "origin_id", "origin_slot", "target_id", "target_slot", "type")
|
||||
]
|
||||
if isinstance(link, list) and len(link) >= 6:
|
||||
links[str(link[0])] = link
|
||||
sockets = {s["name"]: s for s in original.get("inputs", []) if "name" in s}
|
||||
widgets = original.get("widgets_values_named", original.get("widgets_values", []))
|
||||
for field, value in inputs.items():
|
||||
row = {"field": field, "api_value": value, "api_type": type(value).__name__}
|
||||
if isinstance(widgets, dict) and field in widgets:
|
||||
row["named_evidence"] = {
|
||||
"source_value": widgets[field],
|
||||
"source_type": type(widgets[field]).__name__,
|
||||
"status": "equal" if _same(widgets[field], value) else "different",
|
||||
}
|
||||
socket = sockets.get(field, {})
|
||||
link = links.get(str(socket.get("link")))
|
||||
if link and len(link) >= 6:
|
||||
expected = [prefix + str(link[1]), link[2]]
|
||||
row.update(
|
||||
source_link=link,
|
||||
source_expected=expected,
|
||||
status="link_equal" if _same(expected, value) else "link_difference",
|
||||
)
|
||||
elif isinstance(widgets, dict) and field in widgets:
|
||||
row.update(
|
||||
source_value=widgets[field],
|
||||
status="named_equal" if _same(widgets[field], value) else "named_difference",
|
||||
)
|
||||
else:
|
||||
row["status"] = "unnamed_or_virtual_boundary_unverified"
|
||||
item["fields"].append(row)
|
||||
nodes.append(item)
|
||||
return {
|
||||
"equivalent": False,
|
||||
"scope": "逐节点/字段保留API值和类型;直接连线比较ID及槽;位置控件不按顺序猜名",
|
||||
"nodes": nodes,
|
||||
"source_only_nodes": [
|
||||
{"source_id": nid, "node": node}
|
||||
for nid, (node, _, _) in indexed.items()
|
||||
if nid not in api
|
||||
],
|
||||
"unconfirmed": [
|
||||
"虚拟节点、子图边界、开关与循环展开语义需独立核查",
|
||||
"未有可信节点定义;单位、范围、环境和实际产物未验证",
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def resolve_companion(record: dict, source_path: str, raw: bytes, source: dict):
|
||||
binding = record["binding"]
|
||||
problem = None
|
||||
if (
|
||||
binding.get("source_path") != source_path
|
||||
or binding.get("source_sha") != hashlib.sha1(raw).hexdigest()
|
||||
or binding.get("source_sha256") != hashlib.sha256(raw).hexdigest()
|
||||
):
|
||||
problem = "源文件路径或哈希变化,配套API失效"
|
||||
text = record["raw"]
|
||||
if hashlib.sha256(text.encode()).hexdigest() != binding.get("export_sha256"):
|
||||
problem = "配套API哈希变化"
|
||||
api = json.loads(text.lstrip("\ufeff"))
|
||||
invalid = (
|
||||
[
|
||||
nid
|
||||
for nid, node in api.items()
|
||||
if not isinstance(node, dict)
|
||||
or not isinstance(node.get("class_type"), str)
|
||||
or not node["class_type"].strip()
|
||||
or not isinstance(node.get("inputs"), dict)
|
||||
or ("_meta" in node and not isinstance(node["_meta"], dict))
|
||||
]
|
||||
if isinstance(api, dict)
|
||||
else ["*"]
|
||||
)
|
||||
if invalid:
|
||||
problem = "API缺少节点类型或inputs:" + ",".join(invalid)
|
||||
checked = convert(api)
|
||||
if checked.prompt is None:
|
||||
problem = problem or "API连线或结构不合法"
|
||||
audit = {
|
||||
"binding": binding,
|
||||
"adopted": not problem,
|
||||
"method": "supplied_api_companion",
|
||||
"general_conversion_verified": False,
|
||||
"execution_verified": False,
|
||||
}
|
||||
if isinstance(api, dict) and all(isinstance(n, dict) for n in api.values()):
|
||||
audit["comparison"] = source_comparison(source, api)
|
||||
if problem:
|
||||
return None, audit, [{"code": "companion_invalid", "message": problem}, *checked.issues]
|
||||
# Always a blocker: no snapshot or output heuristic may promote this pair to executable.
|
||||
return (
|
||||
api,
|
||||
audit,
|
||||
[
|
||||
{
|
||||
"code": "companion_unverified",
|
||||
"message": "采用提供的配套API;源图差异、导出版本与真实执行尚未核验,保持停用",
|
||||
}
|
||||
],
|
||||
)
|
||||
@@ -11,6 +11,7 @@ from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from calliope.comfyui.companions import resolve_companion
|
||||
from calliope.comfyui.lint import workflow_warnings
|
||||
from calliope.comfyui.output_map import auto_output_map, needs_user_output_map
|
||||
from calliope.comfyui.parser import classify_usage, parse_dynamic_inputs, parse_dynamic_outputs
|
||||
@@ -300,7 +301,12 @@ def build_document(
|
||||
|
||||
|
||||
def import_library(
|
||||
conn: sqlite3.Connection, root: Path, *, source_commit: str, snapshot: dict | None = None
|
||||
conn: sqlite3.Connection,
|
||||
root: Path,
|
||||
*,
|
||||
source_commit: str,
|
||||
snapshot: dict | None = None,
|
||||
companions: dict | None = None,
|
||||
) -> dict:
|
||||
"""Caller supplies a migrated local DB. Single transaction; no network or jobs."""
|
||||
batch = str(uuid.uuid4())
|
||||
@@ -319,6 +325,11 @@ def import_library(
|
||||
"SELECT * FROM workflows WHERE source_repo_path=?", (relative,)
|
||||
).fetchone()
|
||||
record = {"path": relative, "source_sha": sha}
|
||||
companion = (companions or {}).get(relative)
|
||||
# Version companion documentation separately from the immutable received bytes.
|
||||
companion_sha = hashlib.sha256(
|
||||
_json({"record": companion, "doc_version": 1} if companion else None).encode()
|
||||
).hexdigest()
|
||||
if existing and fingerprint(dict(existing)) != existing["library_fingerprint"]:
|
||||
report["files"].append(
|
||||
{
|
||||
@@ -345,6 +356,8 @@ def import_library(
|
||||
if (
|
||||
old_doc.get("snapshot_sha") == snapshot_sha
|
||||
and old_doc.get("source_review_sha") == review_sha
|
||||
and old_doc.get("companion_sha", hashlib.sha256(b"null").hexdigest())
|
||||
== companion_sha
|
||||
):
|
||||
report["files"].append(
|
||||
{
|
||||
@@ -357,11 +370,16 @@ def import_library(
|
||||
)
|
||||
continue
|
||||
source = None
|
||||
companion_audit = None
|
||||
try:
|
||||
text = raw.decode("utf-8-sig")
|
||||
source = json.loads(text)
|
||||
result = convert(source, info)
|
||||
prompt, issues = result.prompt, result.issues
|
||||
if companion:
|
||||
prompt, companion_audit, issues = resolve_companion(
|
||||
companion, relative, raw, source
|
||||
)
|
||||
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
text = raw.hex()
|
||||
prompt, issues = (
|
||||
@@ -388,6 +406,37 @@ def import_library(
|
||||
else "pending_test"
|
||||
)
|
||||
doc = build_document(relative, source, prompt, snapshot, issues, review)
|
||||
doc["companion_sha"] = companion_sha
|
||||
if companion_audit:
|
||||
doc["api_companion"] = companion_audit
|
||||
if prompt:
|
||||
api_doc = build_document(relative, prompt, prompt, None, [], None)
|
||||
# Retain source inventory/reviews separately from supplied API evidence.
|
||||
doc["params"].extend(
|
||||
{
|
||||
**p,
|
||||
"node_id": "配套API:" + p["node_id"],
|
||||
"api_node_id": p["node_id"],
|
||||
"value_origin": "supplied_api_companion",
|
||||
"default_source": "supplied_api_companion",
|
||||
"effect": (
|
||||
f"配套API节点{p['node_id']}("
|
||||
f"{prompt[p['node_id']]['class_type']})的具名输入{p['field']};"
|
||||
"现值由导出保留,含义/单位/范围仍待定义。"
|
||||
),
|
||||
}
|
||||
for p in api_doc["params"]
|
||||
)
|
||||
doc["dependencies"]["models"] = sorted(
|
||||
set(doc["dependencies"]["models"] + api_doc["dependencies"]["models"])
|
||||
)
|
||||
doc["dependencies"]["node_types"] = sorted(
|
||||
set(
|
||||
doc["dependencies"]["node_types"]
|
||||
+ api_doc["dependencies"]["node_types"]
|
||||
)
|
||||
)
|
||||
doc["steps"].insert(0, companion_audit["binding"]["instruction"])
|
||||
doc["snapshot_sha"] = snapshot_sha
|
||||
doc["source_review_sha"] = review_sha
|
||||
judgment = classify_usage(prompt or {})
|
||||
|
||||
@@ -11,6 +11,7 @@ from pathlib import Path
|
||||
|
||||
import httpx
|
||||
|
||||
from calliope.comfyui.companions import load_companions
|
||||
from calliope.comfyui.library import import_library, load_snapshot, rollback_batch
|
||||
from calliope.db import get_db, migrate_db
|
||||
|
||||
@@ -36,6 +37,7 @@ def main() -> None:
|
||||
sub.add_argument("--root", type=Path, required=True)
|
||||
sub.add_argument("--source-commit", required=True)
|
||||
sub.add_argument("--snapshot", type=Path)
|
||||
sub.add_argument("--companions", type=Path)
|
||||
else:
|
||||
sub.add_argument("--batch-id", required=True)
|
||||
args = parser.parse_args()
|
||||
@@ -61,12 +63,19 @@ def main() -> None:
|
||||
if args.command == "import" and not args.root.is_dir():
|
||||
parser.error("--root 必须为存在的目录,避免误报空库成功")
|
||||
snapshot = load_snapshot(args.snapshot) if args.command == "import" else None
|
||||
companions = (
|
||||
load_companions(args.companions) if args.command == "import" and args.companions else None
|
||||
)
|
||||
asyncio.run(migrate_db(args.db))
|
||||
conn = get_db(args.db)
|
||||
try:
|
||||
if args.command == "import":
|
||||
report = import_library(
|
||||
conn, args.root, source_commit=args.source_commit, snapshot=snapshot
|
||||
conn,
|
||||
args.root,
|
||||
source_commit=args.source_commit,
|
||||
snapshot=snapshot,
|
||||
companions=companions,
|
||||
)
|
||||
documents = []
|
||||
for row in conn.execute(
|
||||
|
||||
Reference in New Issue
Block a user