229 lines
9.3 KiB
Python
229 lines
9.3 KiB
Python
"""Offline, fail-closed comparison against source-bound original frontend exports.
|
|
|
|
This command never imports a workflow, enables one, calls a service, or executes it.
|
|
An equal result only establishes equality to the supplied export, not its provenance.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from calliope.comfyui.delivery_scope import exclusion_for
|
|
from calliope.comfyui.library import load_snapshot
|
|
from calliope.comfyui.ui2api import convert
|
|
|
|
|
|
def differences(expected, actual, pointer=""):
|
|
"""Keep types, absent keys, list order and nonzero output slots significant."""
|
|
if type(expected) is not type(actual):
|
|
return [{"path": pointer, "expected": expected, "actual": actual, "kind": "type"}]
|
|
if isinstance(expected, dict):
|
|
rows = []
|
|
for key in sorted(expected.keys() | actual.keys()):
|
|
child = pointer + "/" + key.replace("~", "~0").replace("/", "~1")
|
|
if key not in expected or key not in actual:
|
|
rows.append(
|
|
{
|
|
"path": child,
|
|
"kind": "missing_key",
|
|
"expected_present": key in expected,
|
|
"actual_present": key in actual,
|
|
"expected": expected.get(key),
|
|
"actual": actual.get(key),
|
|
}
|
|
)
|
|
else:
|
|
rows.extend(differences(expected[key], actual[key], child))
|
|
return rows
|
|
if isinstance(expected, list):
|
|
rows = []
|
|
for index in range(max(len(expected), len(actual))):
|
|
child = pointer + "/" + str(index)
|
|
if index >= len(expected) or index >= len(actual):
|
|
rows.append(
|
|
{
|
|
"path": child,
|
|
"kind": "missing_item",
|
|
"expected_present": index < len(expected),
|
|
"actual_present": index < len(actual),
|
|
"expected": expected[index] if index < len(expected) else None,
|
|
"actual": actual[index] if index < len(actual) else None,
|
|
}
|
|
)
|
|
else:
|
|
rows.extend(differences(expected[index], actual[index], child))
|
|
return rows
|
|
return (
|
|
[]
|
|
if expected == actual
|
|
else [{"path": pointer, "kind": "value", "expected": expected, "actual": actual}]
|
|
)
|
|
|
|
|
|
def preserved_fields(expected, actual, pointer=""):
|
|
if type(expected) is not type(actual):
|
|
return []
|
|
if isinstance(expected, dict):
|
|
return [
|
|
row
|
|
for key in sorted(expected.keys() & actual.keys())
|
|
for row in preserved_fields(
|
|
expected[key],
|
|
actual[key],
|
|
pointer + "/" + key.replace("~", "~0").replace("/", "~1"),
|
|
)
|
|
]
|
|
if isinstance(expected, list):
|
|
return [
|
|
row
|
|
for index, (left, right) in enumerate(zip(expected, actual))
|
|
for row in preserved_fields(left, right, pointer + "/" + str(index))
|
|
]
|
|
return [{"path": pointer, "value": expected}] if expected == actual else []
|
|
|
|
|
|
def compare_case(repo, exports, case, snapshot=None):
|
|
row = {**case, "executable": False, "execution_verified": False}
|
|
excluded = exclusion_for(case["source_path"])
|
|
if excluded:
|
|
return {**row, "status": "user_excluded", "exclusion": excluded}
|
|
try:
|
|
raw = (repo / case["source_path"]).read_bytes()
|
|
if hashlib.sha1(raw).hexdigest() != case["source_sha"]:
|
|
return {**row, "status": "source_sha_mismatch"}
|
|
source = json.loads(raw.decode("utf-8-sig"))
|
|
missing = [
|
|
name
|
|
for name in (case["export_file"], case["binding_file"])
|
|
if not (exports / name).is_file()
|
|
]
|
|
if missing:
|
|
return {
|
|
**row,
|
|
"status": "missing_materials",
|
|
"missing": missing,
|
|
"cannot_check": case["comparison"],
|
|
"node_definitions_available": bool(snapshot),
|
|
"missing_definitions": []
|
|
if snapshot
|
|
else ["未提供可信节点定义;UI位置控件和插件行为不能仅凭源文件确认"],
|
|
}
|
|
export_raw = (exports / case["export_file"]).read_bytes()
|
|
binding = json.loads((exports / case["binding_file"]).read_text(encoding="utf-8"))
|
|
# Binding is an operator statement, not automatic authentication of provenance.
|
|
required = {
|
|
"source_path": case["source_path"],
|
|
"source_sha": case["source_sha"],
|
|
"export_sha256": hashlib.sha256(export_raw).hexdigest(),
|
|
"original_frontend_export": True,
|
|
}
|
|
if any(
|
|
type(binding.get(k)) is not type(v) or binding.get(k) != v for k, v in required.items()
|
|
) or not all(
|
|
isinstance(binding.get(k), str) and binding[k].strip()
|
|
for k in ("exported_at", "frontend_version", "node_versions", "origin")
|
|
):
|
|
return {**row, "status": "invalid_binding", "required": required}
|
|
expected = json.loads(export_raw.decode("utf-8-sig"))
|
|
# A UI file is not an original API export, even when convert could accept it.
|
|
if not isinstance(expected, dict) or "nodes" in expected:
|
|
return {**row, "status": "invalid_export", "issues": ["必须为原始API图"]}
|
|
checked = convert(expected)
|
|
if checked.prompt is None:
|
|
return {**row, "status": "invalid_export", "issues": checked.issues}
|
|
result = convert(source, (snapshot or {}).get("object_info"))
|
|
row.update(
|
|
export_sha256=required["export_sha256"],
|
|
binding=binding,
|
|
provenance="仅记录提供者声明;真实性仍需审核",
|
|
)
|
|
if result.prompt is None:
|
|
return {
|
|
**row,
|
|
"status": "conversion_blocked",
|
|
"issues": result.issues,
|
|
"cannot_check": "转换器未生成完整prompt,不能逐字段/连线对照",
|
|
}
|
|
|
|
def split(graph):
|
|
return (
|
|
{
|
|
nid: {k: v for k, v in node.items() if k != "_meta"}
|
|
for nid, node in graph.items()
|
|
},
|
|
{nid: node["_meta"] for nid, node in graph.items() if "_meta" in node},
|
|
)
|
|
|
|
expected_graph, expected_meta = split(expected)
|
|
actual_graph, actual_meta = split(result.prompt)
|
|
delta = differences(expected_graph, actual_graph)
|
|
metadata = differences(expected_meta, actual_meta)
|
|
return {
|
|
**row,
|
|
"status": "different" if delta or metadata else "equal",
|
|
"differences": delta,
|
|
"metadata_differences": metadata,
|
|
"preserved_fields": preserved_fields(expected_graph, actual_graph),
|
|
"preserved_node_ids": sorted(expected.keys() & result.prompt.keys()),
|
|
"comparison_scope": "全部字段、类型、值及连线槽;_meta单列也影响equal",
|
|
}
|
|
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
|
|
return {**row, "status": "invalid_materials", "error": f"{type(exc).__name__}: {exc}"}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--repo", type=Path, required=True)
|
|
parser.add_argument("--cases", type=Path, required=True)
|
|
parser.add_argument("--exports", type=Path, required=True)
|
|
parser.add_argument("--snapshot", type=Path)
|
|
parser.add_argument("--output", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
cases = json.loads(args.cases.read_text(encoding="utf-8"))["cases"]
|
|
try:
|
|
snapshot = load_snapshot(args.snapshot)
|
|
except (OSError, ValueError, AttributeError) as exc:
|
|
report = {
|
|
"status": "invalid_snapshot",
|
|
"error": str(exc),
|
|
"cases": [],
|
|
"execution_verified": False,
|
|
}
|
|
else:
|
|
rows = [compare_case(args.repo, args.exports, case, snapshot) for case in cases]
|
|
report = {
|
|
"status": "user_excluded"
|
|
if rows and all(r["status"] == "user_excluded" for r in rows)
|
|
else "equal"
|
|
if any(r["status"] != "user_excluded" for r in rows)
|
|
and all(r["status"] in ("equal", "user_excluded") for r in rows)
|
|
else "not_ready",
|
|
"cases": rows,
|
|
"active_cases": sum(r["status"] != "user_excluded" for r in rows),
|
|
"user_excluded": sum(r["status"] == "user_excluded" for r in rows),
|
|
"execution_verified": False,
|
|
"snapshot_source": (snapshot or {}).get("source_url"),
|
|
"snapshot_captured_at": (snapshot or {}).get("captured_at"),
|
|
}
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
args.output.write_text(
|
|
json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
|
)
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"status": report["status"],
|
|
"cases": [{"id": r["id"], "status": r["status"]} for r in report["cases"]],
|
|
},
|
|
ensure_ascii=False,
|
|
)
|
|
)
|
|
return 0 if report["status"] in ("equal", "user_excluded") else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|