From 1f779d53c4312068513c2bd6d513f01a3c9f3caf Mon Sep 17 00:00:00 2001 From: leefer Date: Fri, 30 Oct 2026 00:20:48 +0800 Subject: [PATCH] HEL-892: fold pinned Primitive strings and project scoped subgraph boundaries Co-authored-by: multica-agent --- .../scripts/audit_reference_conversion.py | 73 +++- .../comfyui/serialization_reference.py | 183 +++++++++- .../calliope/comfyui/structure_reference.py | 288 +++++++++++++++ .../src/calliope/comfyui/ui2api.py | 41 ++- .../tests/test_structure_reference.py | 344 ++++++++++++++++++ 5 files changed, 915 insertions(+), 14 deletions(-) create mode 100644 calliope-backend/src/calliope/comfyui/structure_reference.py create mode 100644 calliope-backend/tests/test_structure_reference.py diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index c4fc12ba..9ba4437f 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -19,10 +19,12 @@ from calliope.comfyui.companions import load_companions from calliope.comfyui.delivery_scope import exclusion_for from calliope.comfyui.serialization_reference import ( AUX_PROFILE, + PRIMITIVE_PROFILE, PROFILE, resolve_reference_link, serialize_reference_widgets, ) +from calliope.comfyui.structure_reference import STRUCTURE_PROFILES from calliope.comfyui.ui2api import convert, convert_reference @@ -38,14 +40,32 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: assert hashlib.sha256(raw).hexdigest() == binding["source_sha256"] source, api = json.loads(raw), json.loads(record["raw"]) assert convert(api).prompt is not None - nodes = {str(n["id"]): n for n in source["nodes"]} - links = {str(link[0]): link for link in source.get("links", [])} - fields, edges, unsupported = [], [], [] + selected = profile + if profile == "structure-batch-reference": + version = source.get("extra", {}).get("frontendVersion") + structural = f"comfy-frontend-{version}-structure-reference" + selected = ( + structural + if (source.get("definitions") or {}).get("subgraphs") + and structural in STRUCTURE_PROFILES + else PRIMITIVE_PROFILE + if any(n.get("type") == "PrimitiveNode" for n in source["nodes"]) + else AUX_PROFILE + ) + candidate = convert_reference(source, selected) + projected = candidate.diagnostic_graph or source + nodes = {str(n["id"]): n for n in projected["nodes"]} + links = { + str(link[0]): link + for link in projected.get("links", []) + if isinstance(link, list) and len(link) == 6 + } + fields, edges, unsupported, metadata, node_types, api_only = [], [], [], [], [], [] for nid, node in nodes.items(): if node.get("type") in ("Reroute", "Note", "MarkdownNote"): continue try: - values = serialize_reference_widgets(node, profile) + values = serialize_reference_widgets(node, selected) except ValueError as exc: unsupported.append({"node_id": nid, "type": node["type"], "reason": str(exc)}) else: @@ -60,6 +80,28 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "differences": differences(expected, value), } ) + linked = {s["name"] for s in node.get("inputs", []) if s.get("link") is not None} + api_only.extend( + {"node_id": nid, "field": name, "api_value": value} + for name, value in api.get(nid, {}).get("inputs", {}).items() + if name not in values and name not in linked + ) + metadata.append( + { + "node_id": nid, + "differences": differences( + api.get(nid, {}).get("_meta"), {"title": node.get("title") or node["type"]} + ), + } + ) + node_types.append( + { + "node_id": nid, + "source_type": node["type"], + "api_type": api.get(nid, {}).get("class_type"), + "differences": differences(api.get(nid, {}).get("class_type"), node["type"]), + } + ) for socket in node.get("inputs", []): lid = socket.get("link") if lid is None: @@ -87,10 +129,10 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "differences": differences(expected, endpoint), } ) - candidate = convert_reference(source, profile) rows.append( { "id": binding["id"], + "selected_profile": selected, "source_path": path, "source_sha256": binding["source_sha256"], "api_sha256": binding["export_sha256"], @@ -105,6 +147,12 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "serialized_fields": fields, "topology_edges": edges, "unsupported_widget_nodes": unsupported, + "diagnostic_graph": candidate.diagnostic_graph, + "unresolved_boundaries": candidate.unresolved_boundaries, + "node_types": node_types, + "metadata": metadata, + "api_only_fields_for_supported_nodes": api_only, + "comparison_is_complete": candidate.prompt is not None, "executable": False, "execution_verified": False, } @@ -112,7 +160,8 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: return { "profile": profile, "authority": "public_reference_only_not_object_info", - "comparison_scope": "supported root scalar widgets and legacy root link endpoints only", + "comparison_scope": "explicit supported scalar widgets and projected endpoints only; " + "diagnostic structures never prove widget values, full equivalence or execution", "reference_conditions": { "unmodified_frontend_widgets_assumed": True, "ue_extension_serializer_match": "unknown", @@ -134,7 +183,17 @@ def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) - parser.add_argument("--profile", choices=(PROFILE, AUX_PROFILE), default=PROFILE) + parser.add_argument( + "--profile", + choices=( + PROFILE, + AUX_PROFILE, + PRIMITIVE_PROFILE, + *STRUCTURE_PROFILES, + "structure-batch-reference", + ), + default=PROFILE, + ) args = parser.parse_args() report = audit(args.repo, args.profile) args.output.parent.mkdir(parents=True, exist_ok=True) diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index 4f7c6fe6..385387b5 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -1,8 +1,9 @@ """Small, explicit public-reference contract, never a target object_info snapshot. Sources and limits: docs/hel-892/{serialization-evidence,controlnet-reference}/sources.json. -Only explicitly pinned scalar layouts are covered. No dynamic prompt, seed -controller, subgraph, bypass or custom serializeValue is inferred. +Only explicitly pinned scalar layouts are covered. The subtitle opt-in also +folds direct Primitive STRING bindings. No seed controller, bypass, dynamic +extension or target installation is inferred. """ from __future__ import annotations @@ -12,6 +13,30 @@ from typing import Any PROFILE = "comfy-frontend-1.37.11-core-reference" AUX_PROFILE = "comfy-frontend-1.37.11-controlnet-aux-e8b689a-reference" AUX_COMMIT = "e8b689a513c3e6b63edc44066560ca5919c0576e" +PRIMITIVE_PROFILE = "comfy-frontend-1.37.11-qwen-b037d7be-reference" +# Explicit earlier Qwen schema, not a claim about the installed plugin. Its +# 14 widgets differ from the newer reference's added normalize_text field. +_SUBTITLE_LAYOUT = tuple( + zip( + ( + "model", + "precision", + "attention", + "forced_aligner", + "language", + "hints", + "output_format", + "output_path", + "split_mode", + "max_gap_sec", + "max_chars", + "max_inference_batch_size", + "max_new_tokens", + "unload_models", + ), + (str, str, str, str, str, str, str, str, str, float, int, int, int, bool), + ) +) # pyproject declares 1.1.5 at AUX_COMMIT; registry artifact mapping and target # installation remain unknown. This opt-in profile assumes unmodified widgets, # including no UE serializer changes. It never verifies dynamic combo membership. @@ -52,7 +77,7 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: "output": outputs, } - if profile not in (PROFILE, AUX_PROFILE): + if profile not in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE): raise ValueError("未知参考版本") definitions = { "Canny": spec( @@ -80,13 +105,35 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: ["IMAGE"], {name: "INT" if kind is int else "COMBO" for name, kind in layout}, ) + if profile == PRIMITIVE_PROFILE: + definitions["LoadAudio"] = spec({"audio": "COMBO"}, ["AUDIO"], {"audioUI": "AUDIO_UI"}) + definitions["AILab_Qwen3ASRSubtitle"] = spec( + {"audio": "AUDIO"}, + ["STRING"] * 4, + { + name: ( + "FLOAT" + if kind is float + else "INT" + if kind is int + else "BOOLEAN" + if kind is bool + else "STRING" + if name in ("hints", "output_path") + else "COMBO" + ) + for name, kind in _SUBTITLE_LAYOUT + }, + ) return definitions def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]: """Apply only the pinned identity serializers; reject any extra/missing value.""" - if profile not in (PROFILE, AUX_PROFILE): + if profile not in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE): raise ValueError("未知参考版本") + if profile == PRIMITIVE_PROFILE and node.get("type") in ("LoadAudio", "AILab_Qwen3ASRSubtitle"): + return _serialize_subtitle(node) if profile == AUX_PROFILE and node.get("type") in _AUX_LAYOUTS: return _serialize_aux(node) if node.get("mode", 0) != 0: @@ -116,6 +163,134 @@ def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> return result +def _serialize_subtitle(node): + ct, properties = node["type"], node.get("properties") or {} + if node.get("mode", 0) != 0: + raise ValueError("静音/旁路不在字幕参考契约内") + if ct == "LoadAudio": + if properties.get("cnr_id") != "comfy-core" or properties.get("ver") != "0.11.0": + raise ValueError("LoadAudio 提供方/声明版本不匹配") + values = node.get("widgets_values") + if ( + not isinstance(values, list) + or len(values) != 3 + or type(values[0]) is not str + or (values[1:] != [None, None]) + ): + raise ValueError("LoadAudio 仅覆盖文件名及两个不序列化占位;不支持录音") + allowed = {"audio": "COMBO", "audioUI": "AUDIO_UI", "upload": "AUDIOUPLOAD"} + for s in node.get("inputs", []): + if ( + s.get("type") != allowed.get(s.get("name")) + or (s.get("widget") != {"name": s.get("name")}) + or (s["name"] != "audio" and s.get("link") is not None) + ): + raise ValueError("LoadAudio 输入绑定不在参考契约内") + # v1.37.11 graphToPrompt checks options.serialize, whereas the audio + # extension only sets widget.serialize=false. DOMWidget without getValue + # serializes an empty string. Keep this discrepancy with supplied API; + # do not silently equate the two flags or drop the resulting field. + return {"audio": values[0], "audioUI": ""} + # Source declares no provider/version. Opt-in assumption is the immutable + # b037d7be source; reject conflicting declarations rather than silently map. + if properties.get("cnr_id") is not None or properties.get("ver") is not None: + raise ValueError("字幕参考版本未知,不接受未经证明的提供方/版本声明") + values = node.get("widgets_values") + if not isinstance(values, list) or len(values) != len(_SUBTITLE_LAYOUT): + raise ValueError("字幕参考要求14个固定控件;normalize_text 不在此版本") + result = {} + for (name, kind), value in zip(_SUBTITLE_LAYOUT, values): + if (kind is float and type(value) not in (int, float)) or ( + kind is not float and type(value) is not kind + ): + raise ValueError(f"字幕字段 {name} 类型不符") + result[name] = value + types = reference_definitions(PRIMITIVE_PROFILE)[ct]["input"] + allowed = {**types["required"], **types["optional"]} + for s in node.get("inputs", []): + name = s.get("name") + if ( + name not in allowed + or s.get("type") != allowed[name][0] + or (name != "audio" and s.get("widget") != {"name": name}) + ): + raise ValueError("字幕具名输入绑定/类型不符") + return result + + +def fold_reference_primitives(source, profile): + """Copy direct STRING values to proven widget bindings, then remove virtuals. + + v1.37.11 applyToGraph only copies direct target widgets. Reroute mediation, + numerical/combo controls, replacement expressions and unknown callbacks are + deliberately rejected. Every fanout must be proved before any copy is made. + """ + from copy import deepcopy + + graph = deepcopy(source) + nodes = {str(n["id"]): n for n in graph["nodes"]} + if len(nodes) != len(graph["nodes"]): + raise ValueError("节点 ID 重复") + links = {} + for link in graph.get("links", []): + if not isinstance(link, list) or len(link) != 6 or str(link[0]) in links: + raise ValueError("Primitive 仅覆盖唯一六字段连线") + links[str(link[0])] = link + primitives = [n for n in nodes.values() if n.get("type") == "PrimitiveNode"] + if not primitives: + return graph + if profile != PRIMITIVE_PROFILE: + raise ValueError("Primitive 需要显式字幕/具名字符串参考契约") + # Validate all links before removing a virtual node or consuming a value. + for lid in links: + resolve_reference_link(nodes, links, lid) + removals, updates = set(), [] + for node in primitives: + values, outputs = node.get("widgets_values"), node.get("outputs", []) + if ( + node.get("mode", 0) != 0 + or node.get("inputs") + or len(outputs) != 1 + or (not isinstance(values, list) or len(values) != 1 or type(values[0]) is not str) + or (node.get("properties") or {}).get("Run widget replace on values", False) + ): + raise ValueError("Primitive 仅覆盖单字符串;额外seed/模式/替换规则未证明") + output = outputs[0] + if output.get("type") != "STRING" or not output.get("links"): + raise ValueError("Primitive 类型不符或孤儿输出") + first = links[str(output["links"][0])] + first_socket = nodes[str(first[3])]["inputs"][first[4]] + if output.get("widget") != first_socket.get("widget") or (output.get("widget") is None): + raise ValueError("Primitive 输出控件与首个具名目标绑定不符") + for lid in output["links"]: + link = links[str(lid)] + target = nodes[str(link[3])] + if str(link[1]) != str(node["id"]) or link[2] != 0: + raise ValueError("Primitive 出口记录不对应") + socket = target["inputs"][link[4]] + name = socket.get("name") + # Only these pinned ordinary STRING widgets have identity callbacks. + if ( + target.get("type") != "AILab_Qwen3ASRSubtitle" + or name not in ("hints", "output_path") + or socket.get("widget") != {"name": name} + or socket.get("type") != "STRING" + ): + raise ValueError("Primitive 目标无已证明具名字符串绑定(含Reroute/类型冲突)") + serialize_reference_widgets(target, profile) + if link[5] != "STRING": + raise ValueError("Primitive 连线类型不符") + index = next(i for i, (field, _) in enumerate(_SUBTITLE_LAYOUT) if field == name) + updates.append((target, index, socket, values[0])) + removals.add(str(lid)) + for target, index, socket, value in updates: + target["widgets_values"][index] = value + socket["link"] = None + graph["nodes"] = [n for n in graph["nodes"] if n.get("type") != "PrimitiveNode"] + graph["links"] = [link for lid, link in links.items() if lid not in removals] + return graph + + def _serialize_aux(node: dict[str, Any]) -> dict[str, Any]: """Pinned optional widget order; no defaults or guessed dynamic options. diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py new file mode 100644 index 00000000..37d38d91 --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/structure_reference.py @@ -0,0 +1,288 @@ +"""Pinned frontend structural projection, for diagnostics only. + +Sources: docs/hel-892/structure-reference/sources.json. Does not serialize +promoted widgets, interpret third-party nodes, or establish execution eligibility. +""" + +from __future__ import annotations + +from copy import deepcopy +from dataclasses import dataclass, field +from typing import Any +from uuid import UUID + +STRUCTURE_PROFILES = { + f"comfy-frontend-{version}-structure-reference": version + for version in ("1.48.7", "1.53.6", "1.48.6") +} + + +@dataclass +class Structure: + graph: dict[str, Any] | None + issues: list[dict[str, Any]] = field(default_factory=list) + # These are boundary inputs whose frontend widget store cannot be reconstructed. + unresolved: list[dict[str, Any]] = field(default_factory=list) + + +def _id(value): + if type(value) is not int or value < 0: + raise ValueError("结构参考只接受非负整数局部节点 ID") + return str(value) + + +def _uuid(value): + try: + UUID(value) + return True + except (ValueError, TypeError, AttributeError): + return False + + +def expand_reference_subgraphs(source: dict, profile: str) -> Structure: + """Expand scoped nodes/links without consuming positional boundary widgets. + + A returned graph is diagnostic data, never an executable prompt. Unbound + boundary widget values remain explicitly unresolved. Any malformed structure + returns no graph, including malformed unused branches/definitions. + """ + try: + return _expand(source, profile) + except (ValueError, TypeError, KeyError, AttributeError, IndexError, RecursionError) as exc: + return Structure(None, [{"code": "reference_structure_invalid", "message": str(exc)}]) + + +def _expand(source, profile): + version = STRUCTURE_PROFILES.get(profile) + if version is None or (source.get("extra") or {}).get("frontendVersion") != version: + raise ValueError("源前端声明与结构参考版本不符") + definitions = {} + for definition in (source.get("definitions") or {}).get("subgraphs", []): + key = definition["id"] + if not _uuid(key) or key in definitions: + raise ValueError("子图定义 ID 非法或重复") + if definition.get("inputNode", {}).get("id") != -10 or ( + definition.get("outputNode", {}).get("id") != -20 + ): + raise ValueError("未知子图边界节点契约") + definitions[key] = definition + + # Validate each local network before projecting it. Keep link IDs local. + def network(graph, boundary=False): + nodes, links = {}, {} + for node in graph["nodes"]: + key = _id(node["id"]) + if key in nodes: + raise ValueError("重复局部节点 ID") + nodes[key] = node + if _uuid(node.get("type")) and node["type"] not in definitions: + raise ValueError("子图缺少定义:" + node["type"]) + for raw in graph.get("links", []): + if isinstance(raw, dict): + raw = [ + raw[k] + for k in ("id", "origin_id", "origin_slot", "target_id", "target_slot", "type") + ] + if not isinstance(raw, list) or len(raw) != 6: + raise ValueError("未知连线格式") + lid, origin, oslot, target, tslot, _ = raw + if type(lid) is not int or str(lid) in links: + raise ValueError("重复/非法局部连线 ID") + if type(origin) is not int or type(target) is not int: + raise ValueError("连线端点必须为整数局部 ID") + if type(oslot) is not int or type(tslot) is not int or min(oslot, tslot) < 0: + raise ValueError("非法连线槽") + for nid, slot, direction in ((origin, oslot, "outputs"), (target, tslot, "inputs")): + if boundary and ( + (nid == -10 and direction == "outputs") + or (nid == -20 and direction == "inputs") + ): + sockets = graph["inputs" if nid == -10 else "outputs"] + if slot >= len(sockets) or sockets[slot].get("linkIds", []).count(lid) != 1: + raise ValueError("边界槽/连线记录不互相对应") + else: + node = nodes.get(str(nid)) + if node is None or slot >= len(node.get(direction, [])): + raise ValueError("悬空节点或连线槽") + socket = node[direction][slot] + if direction == "inputs" and socket.get("link") != lid: + raise ValueError("入口与连线不对应") + if direction == "outputs" and (socket.get("links") or []).count(lid) != 1: + raise ValueError("出口与连线不对应") + links[str(lid)] = raw + for nid, node in nodes.items(): + for direction in ("inputs", "outputs"): + for slot, socket in enumerate(node.get(direction, [])): + ids = ( + [socket["link"]] + if direction == "inputs" and (socket.get("link") is not None) + else (socket.get("links") or []) + if direction == "outputs" + else [] + ) + for lid in ids: + link = links.get(str(lid)) + offset = 3 if direction == "inputs" else 1 + if link is None or str(link[offset]) != nid or link[offset + 1] != slot: + raise ValueError( + f"节点{nid} {direction}[{slot}] 引用连线{lid}缺失或端点不对应" + ) + if node["type"] in definitions: + definition = definitions[node["type"]] + for direction in ("inputs", "outputs"): + a, b = node.get(direction, []), definition.get(direction, []) + if len(a) != len(b) or any( + x.get("name") != y.get("name") or x.get("type") != y.get("type") + for x, y in zip(a, b) + ): + raise ValueError("子图实例与定义槽不匹配") + if boundary: + for direction, endpoint, offset in (("inputs", -10, 1), ("outputs", -20, 3)): + for slot, socket in enumerate(graph.get(direction, [])): + ids = socket.get("linkIds", []) + if ( + not ids + or len(ids) != len(set(ids)) + or (direction == "outputs" and len(ids) != 1) + ): + raise ValueError("歧义或空子图出口") + for lid in ids: + link = links.get(str(lid)) + if link is None or link[offset : offset + 2] != [endpoint, slot]: + raise ValueError("边界引用悬空/不匹配") + # Validate even cycles feeding no leaf after expansion (e.g. an unused + # pass-through subgraph connected back to itself). + indegree = dict.fromkeys(nodes, 0) + outgoing = {nid: [] for nid in nodes} + for _, origin, _, target, _, _ in links.values(): + if str(origin) in nodes and str(target) in nodes: + outgoing[str(origin)].append(str(target)) + indegree[str(target)] += 1 + pending = [nid for nid, count in indegree.items() if count == 0] + processed = 0 + while pending: + nid = pending.pop() + processed += 1 + for target in outgoing[nid]: + indegree[target] -= 1 + if indegree[target] == 0: + pending.append(target) + if processed != len(nodes): + raise ValueError("局部网络包含连线循环") + return nodes, links + + networks = {None: network(source)} + for key, definition in definitions.items(): + networks[key] = network(definition, True) + + def check_recursion(key, stack): + if key in stack: + raise ValueError("递归子图定义") + for n in networks[key][0].values(): + if n["type"] in definitions: + check_recursion(n["type"], stack + (key,)) + + check_recursion(None, ()) + for key in definitions: + check_recursion(key, ()) + + contexts, flat, unresolved, issues = {}, {}, [], [] + + def instantiate(key, path=(), parent=None, instance=None): + ctx = (key, path, parent, instance) + contexts[path] = ctx + for nid, node in networks[key][0].items(): + full = ":".join((*path, nid)) + if node.get("mode", 0) != 0: + issues.append( + { + "code": "mode_requires_export", + "node_id": full, + "message": "结构参考不解释静音/旁路", + } + ) + if node["type"] in definitions: + instantiate(node["type"], (*path, nid), ctx, node) + else: + flat[full] = deepcopy(node) + flat[full]["id"] = full + return ctx + + instantiate(None) + + def resolve(ctx, nid, slot, seen): + key, path, parent, instance = ctx + marker = (path, str(nid), slot) + if marker in seen: + raise ValueError("子图边界连线循环") + seen = seen | {marker} + if nid == -10 and parent is not None: + socket = instance["inputs"][slot] + lid = socket.get("link") + if lid is None: + return { + "boundary_instance": ":".join(path), + "slot": slot, + "name": socket["name"], + "type": socket["type"], + } + link = networks[parent[0]][1][str(lid)] + return resolve(parent, link[1], link[2], seen) + node = networks[key][0][str(nid)] + if node["type"] in definitions: + child = contexts[(*path, str(nid))] + definition = definitions[node["type"]] + lid = definition["outputs"][slot]["linkIds"][0] + link = networks[node["type"]][1][str(lid)] + return resolve(child, link[1], link[2], seen) + return [":".join((*path, str(nid))), slot] + + projected = [] + for full, node in flat.items(): + path = tuple(full.split(":")) + ctx = contexts[path[:-1]] + for slot, socket in enumerate(node.get("inputs", [])): + lid = socket.get("link") + socket["link"] = None + if lid is None: + continue + original = networks[ctx[0]][1][str(lid)] + endpoint = resolve(ctx, original[1], original[2], set()) + if isinstance(endpoint, dict): + unresolved.append( + {"node_id": full, "input_slot": slot, "input_name": socket["name"], **endpoint} + ) + continue + new_id = len(projected) + 1 + projected.append([new_id, *endpoint, full, slot, original[5]]) + socket["link"] = new_id + for socket in node.get("outputs", []): + socket["links"] = [] + for lid, origin, oslot, _, _, _ in projected: + flat[origin]["outputs"][oslot]["links"].append(lid) + + # Cycles among ordinary nodes are also unsafe; do not hide unused branches. + adjacency = {nid: [] for nid in flat} + for _, origin, _, target, _, _ in projected: + adjacency[origin].append(target) + active, done = set(), set() + + def visit(nid): + if nid in active: + raise ValueError("展开图包含连线循环") + if nid in done: + return + active.add(nid) + for target in adjacency[nid]: + visit(target) + active.remove(nid) + done.add(nid) + + for nid in flat: + visit(nid) + graph = { + "nodes": list(flat.values()), + "links": projected, + "extra": deepcopy(source.get("extra", {})), + } + return Structure(graph, issues, unresolved) diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index b42cf08c..b8fae510 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -4,7 +4,8 @@ object_info does not define custom frontend widget serialization. Only named widgets pass. Even input_order cannot prove arbitrary frontend serialization. The separate convert_reference entry point supports a bounded public-source profile for offline comparison only; it never changes production eligibility. -Subgraphs, seed extra controls, mute and bypass remain unsupported. +Explicit structural profiles expose subgraph diagnostics only. Production +subgraphs, seed extra controls, mute and bypass remain unsupported. """ from __future__ import annotations @@ -14,12 +15,15 @@ from typing import Any from .serialization_reference import ( AUX_PROFILE, + PRIMITIVE_PROFILE, PROFILE, + fold_reference_primitives, reference_definitions, resolve_reference_link, serialize_reference_widgets, validate_reroute, ) +from .structure_reference import STRUCTURE_PROFILES, expand_reference_subgraphs @dataclass @@ -27,6 +31,8 @@ class Conversion: prompt: dict[str, Any] | None issues: list[dict[str, Any]] = field(default_factory=list) reference_only: bool = False + diagnostic_graph: dict[str, Any] | None = None + unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list) def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion: @@ -40,7 +46,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: Public reference definitions cannot establish target execution eligibility. """ if ( - profile not in (PROFILE, AUX_PROFILE) + profile not in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, *STRUCTURE_PROFILES) or not isinstance(source, dict) or "nodes" not in source ): @@ -50,9 +56,35 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: True, ) try: + if profile in STRUCTURE_PROFILES: + structure = expand_reference_subgraphs(source, profile) + if structure.graph is None: + return Conversion(None, structure.issues, True) + # Structural scope never supplies widget contracts for newer versions. + # List the concrete remaining node gaps instead of one subgraph error. + result = _convert(structure.graph, {}, reference=True, reference_profile=profile) + result.issues = structure.issues + result.issues + for boundary in structure.unresolved: + result.issues.append( + { + "code": "boundary_widget_unverified", + **boundary, + "message": "边界无外部连线;不按位置猜 promoted widget 值", + } + ) + result.prompt = None + result.reference_only = True + result.diagnostic_graph = structure.graph + result.unresolved_boundaries = structure.unresolved + return result + original = source + if profile == PRIMITIVE_PROFILE: + source = fold_reference_primitives(source, profile) result = _convert( source, reference_definitions(profile), reference=True, reference_profile=profile ) + if profile == PRIMITIVE_PROFILE and source != original: + result.diagnostic_graph = source except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc: return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True) result.reference_only = True @@ -109,7 +141,8 @@ def _convert(source, object_info=None, *, reference=False, reference_profile=PRO links[str(link[0])] = link if reference: frontend_version = (source.get("extra") or {}).get("frontendVersion") - if frontend_version is not None and frontend_version != "1.37.11": + expected_version = STRUCTURE_PROFILES.get(reference_profile, "1.37.11") + if frontend_version is not None and frontend_version != expected_version: fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致") # Validate every stored link, even unused branches: never silently drop # an unsupported connection to obtain a partial candidate. @@ -166,6 +199,8 @@ def _convert(source, object_info=None, *, reference=False, reference_profile=PRO raise ValueError("源输出槽不符合固定参考契约") names = [s.get("name") for s in node.get("inputs", [])] allowed = set(declared) | ({"upload"} if ct == "LoadImage" else set()) + if reference_profile == PRIMITIVE_PROFILE and ct == "LoadAudio": + allowed |= {"upload", "audioUI"} if len(names) != len(set(names)) or set(names) - allowed: raise ValueError("额外或重复输入槽不在固定参考契约内") except (ValueError, TypeError, AttributeError) as exc: diff --git a/calliope-backend/tests/test_structure_reference.py b/calliope-backend/tests/test_structure_reference.py new file mode 100644 index 00000000..2e7c3836 --- /dev/null +++ b/calliope-backend/tests/test_structure_reference.py @@ -0,0 +1,344 @@ +"""Synthetic mutation fixtures; no target execution or golden export claims.""" + +import json +from copy import deepcopy +from pathlib import Path + +import pytest + +from calliope.comfyui.serialization_reference import ( + PRIMITIVE_PROFILE, + fold_reference_primitives, + serialize_reference_widgets, +) +from calliope.comfyui.structure_reference import expand_reference_subgraphs +from calliope.comfyui.ui2api import convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +CASES = json.loads((REPO / "docs/hel-892/golden-cases.json").read_text())["cases"] +PROFILE = "comfy-frontend-1.48.7-structure-reference" +DEFINITION = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" +NESTED = "aaaaaaaa-bbbb-cccc-dddd-ffffffffffff" + + +def real(case): + row = next(c for c in CASES if c["id"] == case) + return json.loads((REPO / row["source_path"]).read_text()) + + +def subtitle_fixture(): + """Synthetic reduced graph derived from source02; not an original export.""" + graph = real("02") + graph["nodes"] = [n for n in graph["nodes"] if n["id"] in (6, 7, 9)] + graph["links"] = [x for x in graph["links"] if x[0] in (13, 14)] + subtitle = next(n for n in graph["nodes"] if n["id"] == 9) + for output in subtitle["outputs"]: + output["links"] = [] + return graph + + +def test_primitive_mutated_value_reaches_bound_field_without_mutating_source(): + graph = subtitle_fixture() + primitive = next(n for n in graph["nodes"] if n["id"] == 7) + primitive["widgets_values"] = ["new terminology\n保留大小写"] + before = deepcopy(graph) + result = convert_reference(graph, PRIMITIVE_PROFILE) + assert result.prompt["9"]["inputs"]["hints"] == primitive["widgets_values"][0] + assert result.prompt["9"]["inputs"]["output_path"] == "" + assert result.prompt["6"]["inputs"]["audioUI"] == "" + assert "7" not in result.prompt + assert graph == before + assert convert(graph).prompt is None + + +def test_primitive_fanout_by_name_not_widget_array_position(): + graph = subtitle_fixture() + target = next(n for n in graph["nodes"] if n["id"] == 9) + primitive = next(n for n in graph["nodes"] if n["id"] == 7) + target["inputs"][8]["link"] = 19 # output_path, not hints + primitive["outputs"][0]["links"].append(19) + graph["links"].append([19, 7, 0, 9, 8, "STRING"]) + primitive["widgets_values"] = ["mutated"] + result = convert_reference(graph, PRIMITIVE_PROFILE) + assert result.prompt["9"]["inputs"]["output_path"] == "mutated" + assert result.prompt["9"]["inputs"]["hints"] == "mutated" + + +@pytest.mark.parametrize( + "mutation", + [ + "type", + "binding", + "extra_seed", + "replacement", + "orphan", + "missing_widget", + "bad_port", + "mode", + "duplicate_link", + ], +) +def test_primitive_bad_contract_rejects_entire_graph(mutation): + graph = subtitle_fixture() + primitive = next(n for n in graph["nodes"] if n["id"] == 7) + target = next(n for n in graph["nodes"] if n["id"] == 9) + if mutation == "type": + target["inputs"][6]["type"] = "INT" + elif mutation == "binding": + target["inputs"][6]["widget"] = {"name": "output_path"} + elif mutation == "extra_seed": + primitive["widgets_values"].append("randomize") + elif mutation == "replacement": + primitive["properties"]["Run widget replace on values"] = True + elif mutation == "orphan": + primitive["outputs"][0]["links"] = [] + graph["links"] = [x for x in graph["links"] if x[0] != 14] + target["inputs"][6]["link"] = None + elif mutation == "missing_widget": + target["widgets_values"].pop() + elif mutation == "bad_port": + graph["links"][1][4] = 99 + elif mutation == "mode": + primitive["mode"] = 4 + else: + graph["links"].append(deepcopy(graph["links"][1])) + assert convert_reference(graph, PRIMITIVE_PROFILE).prompt is None + with pytest.raises((ValueError, IndexError)): + fold_reference_primitives(graph, PRIMITIVE_PROFILE) + + +def test_primitive_reroute_is_not_assumed_to_forward_widget_binding(): + graph = subtitle_fixture() + reroute = { + "id": 10, + "type": "Reroute", + "inputs": [{"name": "", "link": 14}], + "outputs": [{"type": "STRING", "links": [19]}], + } + graph["nodes"].append(reroute) + graph["links"][1] = [14, 7, 0, 10, 0, "STRING"] + graph["links"].append([19, 10, 0, 9, 6, "STRING"]) + next(n for n in graph["nodes"] if n["id"] == 9)["inputs"][6]["link"] = 19 + assert convert_reference(graph, PRIMITIVE_PROFILE).prompt is None + + +def test_primitive_output_binding_and_conflicting_fanout_reject(): + source = subtitle_fixture() + primitive = next(n for n in source["nodes"] if n["id"] == 7) + primitive["outputs"][0]["widget"] = {"name": "wrong"} + assert convert_reference(source, PRIMITIVE_PROFILE).prompt is None + primitive["outputs"][0]["widget"] = {"name": "hints"} + primitive["outputs"][0]["links"].append(19) + target = next(n for n in source["nodes"] if n["id"] == 9) + target["inputs"][-1]["link"] = 19 # BOOLEAN unload_models conflicts with STRING + source["links"].append([19, 7, 0, 9, len(target["inputs"]) - 1, "BOOLEAN"]) + assert convert_reference(source, PRIMITIVE_PROFILE).prompt is None + + +def graph_fixture(): + """Synthetic two instances with nonzero source/output slots and object links.""" + definition = { + "id": DEFINITION, + "inputNode": {"id": -10}, + "outputNode": {"id": -20}, + "inputs": [{"name": "in", "type": "IMAGE", "linkIds": [10]}], + "outputs": [{"name": "out", "type": "MASK", "linkIds": [11]}], + "nodes": [ + { + "id": 3, + "type": "SyntheticTransform", + "mode": 0, + "inputs": [{"name": "x", "type": "IMAGE", "link": 10}], + "outputs": [{"type": "IMAGE", "links": []}, {"type": "MASK", "links": [11]}], + } + ], + "links": [ + dict(id=10, origin_id=-10, origin_slot=0, target_id=3, target_slot=0, type="IMAGE"), + dict(id=11, origin_id=3, origin_slot=1, target_id=-20, target_slot=0, type="MASK"), + ], + } + nodes = [ + { + "id": 1, + "type": "SyntheticSource", + "outputs": [{"type": "MASK", "links": []}, {"type": "IMAGE", "links": [1, 2]}], + } + ] + for instance, incoming, outgoing in ((5, 1, 3), (6, 2, 4)): + nodes.append( + { + "id": instance, + "type": DEFINITION, + "inputs": [{"name": "in", "type": "IMAGE", "link": incoming}], + "outputs": [{"name": "out", "type": "MASK", "links": [outgoing]}], + } + ) + nodes.append( + { + "id": 9, + "type": "SyntheticSink", + "inputs": [ + {"name": "a", "type": "MASK", "link": 3}, + {"name": "b", "type": "MASK", "link": 4}, + ], + } + ) + return { + "nodes": nodes, + "links": [ + [1, 1, 1, 5, 0, "IMAGE"], + [2, 1, 1, 6, 0, "IMAGE"], + [3, 5, 0, 9, 0, "MASK"], + [4, 6, 0, 9, 1, "MASK"], + ], + "definitions": {"subgraphs": [definition]}, + "extra": {"frontendVersion": "1.48.7"}, + } + + +def endpoints(graph): + return {(x[3], x[4]): (x[1], x[2]) for x in graph["links"]} + + +def test_scope_isolation_and_nonzero_slot_preservation(): + source = graph_fixture() + before = deepcopy(source) + result = expand_reference_subgraphs(source, PROFILE) + assert result.issues == result.unresolved == [] + assert endpoints(result.graph) == { + ("5:3", 0): ("1", 1), + ("6:3", 0): ("1", 1), + ("9", 0): ("5:3", 1), + ("9", 1): ("6:3", 1), + } + assert source == before + assert convert_reference(source, PROFILE).prompt is None # unknown synthetic serializers + assert convert(source).prompt is None + + +def test_nested_scope_boundaries_in_both_directions(): + source = graph_fixture() + outer = source["definitions"]["subgraphs"][0] + inner = deepcopy(outer) + inner["id"] = NESTED + outer["nodes"][0] = { + "id": 3, + "type": NESTED, + "inputs": [{"name": "in", "type": "IMAGE", "link": 10}], + "outputs": [{"name": "out", "type": "MASK", "links": [11]}], + } + outer["links"][1]["origin_slot"] = 0 + source["definitions"]["subgraphs"].append(inner) + result = expand_reference_subgraphs(source, PROFILE) + assert result.graph is not None + assert endpoints(result.graph)[("9", 1)] == ("6:3:3", 1) + assert endpoints(result.graph)[("5:3:3", 0)] == ("1", 1) + + +@pytest.mark.parametrize( + "mutation", + [ + "missing_definition", + "duplicate_id", + "duplicate_definition", + "recursive", + "dangling", + "bad_boundary", + "ambiguous_output", + "wrong_instance", + "cycle", + "wrong_version", + "bad_link_format", + ], +) +def test_structure_corruption_never_returns_partial_graph(mutation): + source = graph_fixture() + definition = source["definitions"]["subgraphs"][0] + if mutation == "missing_definition": + source["definitions"]["subgraphs"] = [] + elif mutation == "duplicate_id": + definition["nodes"].append(deepcopy(definition["nodes"][0])) + elif mutation == "duplicate_definition": + source["definitions"]["subgraphs"].append(deepcopy(definition)) + elif mutation == "recursive": + definition["nodes"][0]["type"] = DEFINITION + definition["nodes"][0]["inputs"][0]["name"] = "in" + definition["nodes"][0]["outputs"] = [{"name": "out", "type": "MASK", "links": [11]}] + definition["links"][1]["origin_slot"] = 0 + elif mutation == "dangling": + source["links"][0][1] = 999 + elif mutation == "bad_boundary": + definition["inputs"][0]["linkIds"] = [999] + elif mutation == "ambiguous_output": + definition["outputs"][0]["linkIds"] = [11, 11] + elif mutation == "wrong_instance": + source["nodes"][1]["inputs"][0]["name"] = "wrong" + elif mutation == "cycle": + source["links"][0][1:3] = [5, 0] + source["nodes"][0]["outputs"][1]["links"] = [2] + source["nodes"][1]["outputs"][0]["links"].append(1) + elif mutation == "wrong_version": + source["extra"]["frontendVersion"] = "main" + else: + source["links"][0] = [1, 1] + result = expand_reference_subgraphs(source, PROFILE) + assert result.graph is None + assert convert_reference(source, PROFILE).prompt is None + + +def test_unbound_boundary_is_reported_without_guessing_positional_values(): + source = graph_fixture() + source["links"] = source["links"][1:] + source["nodes"][0]["outputs"][1]["links"] = [2] + source["nodes"][1]["inputs"][0]["link"] = None + source["nodes"][1]["widgets_values"] = ["must not be used"] + result = convert_reference(source, PROFILE) + assert result.diagnostic_graph is not None and result.prompt is None + assert result.unresolved_boundaries == [ + { + "node_id": "5:3", + "input_slot": 0, + "input_name": "x", + "boundary_instance": "5", + "slot": 0, + "name": "in", + "type": "IMAGE", + } + ] + + +def test_mode_is_a_concrete_blocker_even_after_structural_expansion(): + source = graph_fixture() + source["definitions"]["subgraphs"][0]["nodes"][0]["mode"] = 4 + result = convert_reference(source, PROFILE) + assert result.prompt is None + assert any(x["code"] == "mode_requires_export" and x["node_id"] == "5:3" for x in result.issues) + + +@pytest.mark.parametrize("case", ["03", "04"]) +def test_real_structure_preserves_composite_output_and_stays_nonexecutable(case): + source = real(case) + profile = "comfy-frontend-" + source["extra"]["frontendVersion"] + "-structure-reference" + result = convert_reference(source, profile) + assert result.prompt is None + assert result.diagnostic_graph is not None + ids = {str(n["id"]) for n in result.diagnostic_graph["nodes"]} + assert ("37:43" if case == "03" else "459:457") in ids + assert result.unresolved_boundaries + assert all(x["code"] != "subgraph_requires_export" for x in result.issues) + + +def test_real_primitive_keeps_preview_gap_and_source_vs_api_schema_difference(): + source = real("02") + result = convert_reference(source, PRIMITIVE_PROFILE) + assert result.prompt is None + assert {x["node_id"] for x in result.issues} == {"1", "2", "3", "4"} + target = next(n for n in result.diagnostic_graph["nodes"] if n["id"] == 9) + values = serialize_reference_widgets(target, PRIMITIVE_PROFILE) + assert "normalize_text" not in values + + +def test_real_case07_bad_reciprocal_link_is_rejected(): + result = convert_reference(real("07"), "comfy-frontend-1.48.6-structure-reference") + assert result.prompt is None and result.diagnostic_graph is None + assert result.issues[0]["code"] == "reference_structure_invalid"