diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index c0e5169..a87365d 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -39,7 +39,12 @@ from calliope.comfyui.serialization_reference import ( serialize_promoted_node, serialize_reference_widgets, ) -from calliope.comfyui.structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES +from calliope.comfyui.structure_reference import ( + PROMOTED_PROFILES, + SETGET_COMMIT, + SETGET_PROFILES, + STRUCTURE_PROFILES, +) from calliope.comfyui.ui2api import convert, convert_reference @@ -293,6 +298,7 @@ REFERENCE_PROFILES = ( SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, ) @@ -495,6 +501,7 @@ def profile_attempt(source, profile): **PROMOTED_PROFILES, CASE04_PROFILE: "1.53.6", **VHS_PROFILES, + **SETGET_PROFILES, }.get(profile, "1.37.11") assumptions = { "frontend": expected, @@ -572,6 +579,38 @@ def profile_attempt(source, profile): "serialization-evidence/sources.json", ] base = {"profile": profile, "assumptions": assumptions} + if profile in SETGET_PROFILES: + assumptions["setget_reference"] = { + "commit": SETGET_COMMIT, + "missing_version": "explicit_fixed_reference_assumption_only", + "provider_policy": "exact_aux_id_required; missing/literal/conflict_rejected", + "scope": "root_only; nested_and_cross_boundary_rejected", + "name": "widgets_values/0 exact string; no normalization or previousName lookup", + "duplicates": "reject_all; frontend_first_match_is_not_emulated", + "unmodified_pinned_extensions": True, + "target_installation_and_UE_match": "unknown", + } + assumptions["reference_sources"] = [ + "setget-reference/sources.json", + "vhs-reference/sources.json", + "serialization-evidence/sources.json", + ] + base["verified_reference_facts"] = "setget-reference/contract.json" + base["source_declarations"] = [ + { + "pointer": f"/nodes/{i}", + **{k: (n.get("properties") or {}).get(k) for k in ("cnr_id", "aux_id", "ver")}, + } + for i, n in enumerate(source.get("nodes", [])) + ] + if not any(n.get("type") in ("SetNode", "GetNode") for n in source.get("nodes", [])): + return { + **base, + "status": "not_applicable", + "issues": [ + {"code": "setget_not_present", "message": "新profile仅覆盖包含Set/Get的根图"} + ], + } if profile in (*CROP_SPLIT_PROFILES, *VHS_PROFILES): base["source_declarations"] = [ { @@ -594,21 +633,29 @@ def profile_attempt(source, profile): else "requires_explicit_1.48.6" ) assumptions["missing_frontend_policy"] = ( - "explicit_media_reference_assumption" + "explicit_1.37.11_reference_assumption" + if profile in SETGET_PROFILES + else "explicit_media_reference_assumption" if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES) else "explicit_legacy_reference_assumption" if profile in (PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE) else "requires_explicit_declaration" ) - if profile in VHS_PROFILES and expected == "1.48.6": + if profile in (*VHS_PROFILES, *SETGET_PROFILES) and expected == "1.48.6": assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6" assumptions["missing_node_declarations"] = [ n["pointer"] - for n in node_inventory(source, include_aux=profile in CROP_SPLIT_PROFILES) + for n in node_inventory( + source, include_aux=profile in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES) + ) if n["type"] not in ("Note", "MarkdownNote", "Reroute", "PrimitiveNode") and (n["provider"] is None or n["version"] is None) ] - if (profile in VHS_PROFILES and expected == "1.48.6" and declared_frontend is None) or ( + if ( + profile in (*VHS_PROFILES, *SETGET_PROFILES) + and expected == "1.48.6" + and declared_frontend is None + ) or ( declared_frontend != expected and not ( declared_frontend is None @@ -621,6 +668,7 @@ def profile_attempt(source, profile): SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, ) ) ): @@ -644,6 +692,11 @@ def profile_attempt(source, profile): else "serializer_or_structure_rejected", "issues": result.issues, "unresolved_boundaries": result.unresolved_boundaries, + **( + {"virtual_resolutions": result.virtual_resolutions} + if profile in SETGET_PROFILES + else {} + ), } # Legacy core serializers explicitly assume absent declarations. Record # that assumption instead of implying that a type-name match proved it. @@ -655,6 +708,11 @@ def profile_attempt(source, profile): or "restored_saved_state_before_queue_hooks", "candidate_sha256": canonical_sha(result.prompt), "candidate_prompt": result.prompt, + **( + {"virtual_resolutions": result.virtual_resolutions} + if profile in SETGET_PROFILES + else {} + ), **( {"field_evidence": asr_field_evidence(source, result.prompt)} if profile == ASR_PROFILE @@ -740,7 +798,7 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= for issue in attempt["issues"]: gap_inventory = ( node_inventory(source, include_aux=True) - if attempt["profile"] in CROP_SPLIT_PROFILES + if attempt["profile"] in (*CROP_SPLIT_PROFILES, *SETGET_PROFILES) else inventory ) matches = [n for n in gap_inventory if n["node_id"] == issue.get("node_id")] @@ -766,7 +824,11 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= } if baseline_profiles is None: excluded_profiles = ( - VHS_PROFILES if any(p in VHS_PROFILES for p in profiles) else CROP_SPLIT_PROFILES + SETGET_PROFILES + if any(p in SETGET_PROFILES for p in profiles) + else VHS_PROFILES + if any(p in VHS_PROFILES for p in profiles) + else CROP_SPLIT_PROFILES ) baseline_profiles = tuple(p for p in profiles if p not in excluded_profiles) old_complete = { diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index b79a15d..4bb01e2 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -14,6 +14,8 @@ import json import math from typing import Any +from .structure_reference import SETGET_PROFILES + MP3_PROFILE = "comfy-frontend-1.37.11-mp3-core-0.11.0-reference" REEL_PROFILE = "comfy-frontend-1.37.11-layerstyle-mixed-core-0.4.0-reference" MEDIA_PROFILES = (MP3_PROFILE, REEL_PROFILE) @@ -100,6 +102,8 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: "output": outputs, } + if profile in SETGET_PROFILES: + return {**reference_definitions(PROFILE), **vhs_definitions()} if profile in VHS_PROFILES: return vhs_definitions() if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES): @@ -176,6 +180,16 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: 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 in SETGET_PROFILES: + if node.get("type") in vhs_definitions(): + return serialize_vhs_node(node) + if any( + k in container + for container in (node, node.get("properties") or {}) + for k in ("widgets", "widgets_values_named", "serializeValue", "comfyDynamic") + ): + raise ValueError("Set/Get组合核心参考不接受自定义serializer或额外控件") + return serialize_reference_widgets(node, PROFILE) if profile in VHS_PROFILES: return serialize_vhs_node(node) if profile in (*MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES): diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py index 596205e..e571b7b 100644 --- a/calliope-backend/src/calliope/comfyui/structure_reference.py +++ b/calliope-backend/src/calliope/comfyui/structure_reference.py @@ -7,11 +7,17 @@ node serializers, third-party behavior, target versions or execution eligibility from __future__ import annotations +import re from copy import deepcopy from dataclasses import dataclass, field from typing import Any from uuid import UUID +SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18" +SETGET_PROFILES = { + f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6") +} + STRUCTURE_PROFILES = { f"comfy-frontend-{version}-structure-reference": version for version in ("1.48.7", "1.53.6", "1.48.6") @@ -44,6 +50,292 @@ def _uuid(value): return False +def project_reference_setget(source: dict) -> Structure: + """Pinned KJ same-root saved-state projection, never a partial prompt. + + Diagnostics may retain literal, unique-name topology when provenance is + ambiguous. Such paths carry rejections and NEVER yield a projected graph. + Every virtual node, edge and dependency cycle is checked, including unused + branches. No subgraph scope, rename callback or type inference is emulated. + """ + from .serialization_reference import validate_reroute + + issues, resolved = [], [] + + def reject(message, nid=""): + issues.append({"code": "setget_reference_invalid", "node_id": str(nid), "message": message}) + + try: + if (source.get("definitions") or {}).get("subgraphs") or any( + _uuid(n.get("type")) for n in source["nodes"] + ): + reject("Set/Get仅覆盖根图;嵌套或跨边界名字作用域未证明") + if any((source.get("extra") or {}).get(k) for k in ("ue_links", "links_added_by_ue")): + raise ValueError("Set/Get不解释UE附加连线") + nodes, indices, links, link_indices = {}, {}, {}, {} + for i, n in enumerate(source["nodes"]): + nid = _id(n["id"]) + if nid in nodes: + raise ValueError("重复根图节点ID") + nodes[nid], indices[nid] = n, i + if n.get("type") not in ("Note", "MarkdownNote") and ( + type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0 + ): + reject("根图运行节点仅支持正常mode=0", nid) + if any( + k in container + for container in (n, n.get("properties") or {}) + for k in ( + "getInputLink", + "resolveInput", + "resolveOutput", + "onExecute", + "isVirtualNode", + "applyToGraph", + ) + ): + reject("根图含自定义执行/追线覆盖", nid) + for i, edge in enumerate(source.get("links", [])): + if not isinstance(edge, list) or len(edge) != 6: + raise ValueError("Set/Get仅接受六字段根图连线") + lid, a, oslot, b, islot, typ = edge + if type(lid) is not int or lid < 0 or lid in links: + raise ValueError("连线ID非法或重复") + a, b = _id(a), _id(b) + for nid, slot, direction in ((a, oslot, "outputs"), (b, islot, "inputs")): + if ( + nid not in nodes + or type(slot) is not int + or not (0 <= slot < len(nodes[nid].get(direction, []))) + ): + raise ValueError("连线端点/原槽缺失") + s = nodes[nid][direction][slot] + if direction == "outputs": + ids = s.get("links") or [] + if any(type(x) is not int for x in ids) or ids.count(lid) != 1: + raise ValueError("输出与连线不互指") + elif type(s.get("link")) is not int or s["link"] != lid: + raise ValueError("输入与连线不互指") + if s.get("type") != typ: + raise ValueError("每跳连线类型与两端槽必须精确一致") + if not isinstance(typ, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", typ): + raise ValueError("通配/联合/动态连线类型未证明") + links[lid], link_indices[lid] = edge, i + for nid, n in nodes.items(): + for direction in ("inputs", "outputs"): + for slot, s in enumerate(n.get(direction, [])): + ids = ( + [s["link"]] + if direction == "inputs" and s.get("link") is not None + else (s.get("links") or []) + if direction == "outputs" + else [] + ) + for lid in ids: + e = links.get(lid) + offset = 1 if direction == "outputs" else 3 + if e is None or [str(e[offset]), e[offset + 1]] != [nid, slot]: + raise ValueError("槽引用缺失连线或错误端点") + + setters, names, node_rejections = {}, {}, {} + virtual = { + nid for nid, n in nodes.items() if n.get("type") in ("SetNode", "GetNode", "Reroute") + } + for nid in sorted(virtual): + n = nodes[nid] + start = len(issues) + if type(n.get("mode", 0)) is not int or n.get("mode", 0) != 0: + reject("Set/Get/Reroute只支持正常mode=0", nid) + if n["type"] == "Reroute": + try: + validate_reroute(n) + except ValueError as exc: + reject(str(exc), nid) + types = [s.get("type") for s in n.get("inputs", []) + n.get("outputs", [])] + if ( + len(types) != 2 + or types[0] != types[1] + or not isinstance(types[0], str) + or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", types[0]) + ): + reject("Reroute仅支持已保存且精确相同的具体类型", nid) + else: + props = n.get("properties") or {} + if ( + props.get("aux_id") != "kijai/ComfyUI-KJNodes" + or props.get("cnr_id") is not None + ): + reject("Set/Get提供方歧义或冲突;类名字面aux_id不是来源证明", nid) + if props.get("ver") not in (None, SETGET_COMMIT): + reject("Set/Get显式版本不等于固定完整提交", nid) + values = n.get("widgets_values") + if ( + not isinstance(values, list) + or len(values) != 1 + or type(values[0]) is not str + or not values[0] + ): + reject("Set/Get要求唯一非空字符串名字控件", nid) + else: + names[nid] = values[0] + if n["type"] == "SetNode": + setters.setdefault(values[0], []).append(nid) + if ( + len(n.get("inputs", [])) != (1 if n["type"] == "SetNode" else 0) + or len(n.get("outputs", [])) != 1 + ): + reject("Set/Get有额外或缺失槽", nid) + sockets = n.get("inputs", []) + n.get("outputs", []) + types = [s.get("type") for s in sockets] + if ( + not types + or any( + not isinstance(t, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", t) + for t in types + ) + or len(set(types)) != 1 + ): + reject("Set/Get槽类型未知或不一致;不按名字推断类型", nid) + if any(s.get("name") != s.get("type") or s.get("widget") for s in sockets): + reject("Set/Get槽构造/绑定与固定形式不符", nid) + for container in (n, n.get("properties") or {}): + if any( + k in container + for k in ( + "widgets", + "widgets_values_named", + "serializeValue", + "comfyDynamic", + "getInputLink", + "onExecute", + "isVirtualNode", + ) + ): + reject("虚拟节点存在自定义覆盖或额外控件", nid) + props = n.get("properties") or {} + ue = props.get("ue_properties") or {} + if any( + props.get(k) or ue.get(k) + for k in ("widget_ue_connectable", "input_ue_unconnectable") + ): + reject("虚拟节点UE自定义绑定未证明", nid) + node_rejections[nid] = issues[start:] + for name, ids in setters.items(): + if len(ids) != 1: + reject(f"重名Set:{name!r};保守拒绝而非取首个") + + def trace(nid, slot, seen=()): + token = (nid, slot) + if token in seen: + raise ValueError("Set/Get逻辑环或链式自引用") + n = nodes[nid] + hop = { + "node_id": nid, + "output_slot": slot, + "node_pointer": f"/nodes/{indices[nid]}", + "output_pointer": f"/nodes/{indices[nid]}/outputs/{slot}", + } + if nid not in virtual: + return [nid, slot], [hop], [] + if slot != 0: + raise ValueError("虚拟节点出口必须为零槽") + rejection = list(node_rejections[nid]) + if nid in names: + hop.update(name=names[nid], name_pointer=hop["node_pointer"] + "/widgets_values/0") + if n["type"] == "GetNode": + ids = setters.get(names.get(nid), []) + if len(ids) != 1: + raise ValueError("Get缺少唯一精确名字Set;不使用previousName/标题或规范化") + sid = ids[0] + if n["outputs"][0]["type"] != nodes[sid]["outputs"][0]["type"]: + raise ValueError("Get与Set类型冲突") + endpoint, hops, errors = trace(sid, 0, (*seen, token)) + hop.update( + name=names[nid], + name_pointer=hop["node_pointer"] + "/widgets_values/0", + setter_id=sid, + ) + return endpoint, [hop, *hops], rejection + errors + lid = n.get("inputs", [{}])[0].get("link") + if lid not in links: + raise ValueError("Set/Reroute无上游实际输入") + e = links[lid] + hop.update(input_slot=0, link_pointer=f"/links/{link_indices[lid]}", original_link=e) + endpoint, hops, errors = trace(str(e[1]), e[2], (*seen, token)) + return endpoint, [hop, *hops], rejection + errors + + # Include logical binding edges when checking ALL cycles, including + # ordinary-node cycles containing a Set/Get hop and unused bad branches. + adjacency = {nid: [] for nid in nodes} + for e in links.values(): + adjacency[str(e[1])].append(str(e[3])) + for nid, n in nodes.items(): + if n.get("type") == "GetNode" and len(setters.get(names.get(nid), [])) == 1: + adjacency[setters[names[nid]][0]].append(nid) + indegree = dict.fromkeys(nodes, 0) + for targets in adjacency.values(): + for t in targets: + indegree[t] += 1 + pending = [k for k, v in indegree.items() if not v] + visited = 0 + while pending: + visited += 1 + for target in adjacency[pending.pop()]: + indegree[target] -= 1 + if not indegree[target]: + pending.append(target) + if visited != len(nodes): + reject("根图含物理或Set/Get逻辑依赖环") + # Resolve every virtual node, even if its output has no consumers. + for nid in sorted(virtual): + try: + trace(nid, 0) + except (ValueError, KeyError, IndexError, TypeError) as exc: + reject(str(exc), nid) + graph = deepcopy(source) + kept = {str(n["id"]): n for n in graph["nodes"] if str(n["id"]) not in virtual} + edges = [] + for e in links.values(): + if str(e[3]) in virtual: + continue + try: + endpoint, hops, errors = trace(str(e[1]), e[2]) + if str(e[1]) in virtual: + resolved.append( + { + "target_node_id": str(e[3]), + "target_input_slot": e[4], + "target_input_name": nodes[str(e[3])]["inputs"][e[4]]["name"], + "original_link_pointer": f"/links/{link_indices[e[0]]}", + "original_link": e, + "endpoint": endpoint, + "hops": hops, + "binding_rejections": errors, + "authority": "literal_topology_only" + if errors or issues + else "pinned_reference_assumption_only", + } + ) + edges.append([e[0], int(endpoint[0]), endpoint[1], *e[3:]]) + except (ValueError, KeyError, IndexError, TypeError) as exc: + reject(str(exc), e[3]) + if issues: + for resolution in resolved: + resolution["whole_graph_rejected"] = True + resolution["authority"] = "literal_topology_only" + return Structure(None, issues, resolved=resolved) + for n in kept.values(): + for s in n.get("outputs", []): + s["links"] = [] + for e in edges: + kept[str(e[1])]["outputs"][e[2]]["links"].append(e[0]) + graph["nodes"], graph["links"] = list(kept.values()), edges + return Structure(graph, resolved=resolved) + except (ValueError, TypeError, KeyError, IndexError, AttributeError, RecursionError) as exc: + reject(str(exc)) + return Structure(None, issues, resolved=resolved) + + def expand_reference_subgraphs( source: dict, profile: str, *, widgets: bool = False, case04: bool = False ) -> Structure: diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index 5dd00ff..bd20657 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -34,7 +34,13 @@ from .serialization_reference import ( serialize_reference_widgets, validate_reroute, ) -from .structure_reference import PROMOTED_PROFILES, STRUCTURE_PROFILES, expand_reference_subgraphs +from .structure_reference import ( + PROMOTED_PROFILES, + SETGET_PROFILES, + STRUCTURE_PROFILES, + expand_reference_subgraphs, + project_reference_setget, +) @dataclass @@ -46,6 +52,7 @@ class Conversion: unresolved_boundaries: list[dict[str, Any]] = field(default_factory=list) resolved_boundaries: list[dict[str, Any]] = field(default_factory=list) serialization_stage: str | None = None + virtual_resolutions: list[dict[str, Any]] = field(default_factory=list) def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion: @@ -67,6 +74,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, *VHS_PROFILES, + *SETGET_PROFILES, AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE, @@ -83,6 +91,27 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: True, ) try: + if profile in SETGET_PROFILES: + expected = SETGET_PROFILES[profile] + declared = (source.get("extra") or {}).get("frontendVersion") + if declared != expected and not (declared is None and expected == "1.37.11"): + raise ValueError("Set/Get前端声明不匹配;缺失仅显式选择1.37.11") + structure = project_reference_setget(source) + if structure.graph is None: + return Conversion( + None, structure.issues, True, virtual_resolutions=structure.resolved + ) + result = _convert( + structure.graph, + reference_definitions(profile), + reference=True, + reference_profile=profile, + ) + result.reference_only = True + result.virtual_resolutions = structure.resolved + result.diagnostic_graph = structure.graph + result.serialization_stage = "restored_saved_state_before_queue_hooks" + return result if ( profile in VHS_PROFILES and VHS_PROFILES[profile] == "1.48.6" @@ -226,6 +255,7 @@ def _convert( **PROMOTED_PROFILES, CASE04_PROFILE: "1.53.6", **VHS_PROFILES, + **SETGET_PROFILES, }.get(reference_profile, "1.37.11") if frontend_version is not None and frontend_version != expected_version: fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致") diff --git a/calliope-backend/tests/test_audio_separation_reference.py b/calliope-backend/tests/test_audio_separation_reference.py index c8d5a9e..22a0809 100644 --- a/calliope-backend/tests/test_audio_separation_reference.py +++ b/calliope-backend/tests/test_audio_separation_reference.py @@ -362,7 +362,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari profiles = tuple( p for p in audit.REFERENCE_PROFILES - if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES) + if p not in (*audit.CROP_SPLIT_PROFILES, *audit.VHS_PROFILES, *audit.SETGET_PROFILES) ) baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE) old = audit.audit_library(REPO, baseline) diff --git a/calliope-backend/tests/test_crop_split_reference.py b/calliope-backend/tests/test_crop_split_reference.py index dd9f46a..f41a9e7 100644 --- a/calliope-backend/tests/test_crop_split_reference.py +++ b/calliope-backend/tests/test_crop_split_reference.py @@ -351,7 +351,9 @@ def test_two_disjoint_instances_preserve_nodes_links_and_values(profile): def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged(): - historical_profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES) + historical_profiles = tuple( + p for p in audit.REFERENCE_PROFILES if p not in (*VHS_PROFILES, *audit.SETGET_PROFILES) + ) profiles = tuple(p for p in historical_profiles if p not in CROP_SPLIT_PROFILES) historical = json.loads((REPO / "docs/hel-892/separation-evidence/library.json").read_bytes()) baseline = audit.audit_library(REPO, profiles) diff --git a/calliope-backend/tests/test_setget_reference.py b/calliope-backend/tests/test_setget_reference.py new file mode 100644 index 0000000..8443015 --- /dev/null +++ b/calliope-backend/tests/test_setget_reference.py @@ -0,0 +1,423 @@ +"""Saved-state transformation tests; never execute upstream JS or a ComfyUI job.""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest +from scripts import audit_reference_conversion as audit +from scripts.verify_frontend_sources import verify + +from calliope.comfyui.structure_reference import ( + SETGET_PROFILES, + project_reference_setget, +) +from calliope.comfyui.ui2api import convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +PROFILE = next(iter(SETGET_PROFILES)) + + +def virtual(nid, kind, name, typ="IMAGE"): + return { + "id": nid, + "type": kind, + "mode": 0, + "properties": {"aux_id": "kijai/ComfyUI-KJNodes", "previousName": "old"}, + "widgets_values": [name], + "inputs": [{"name": typ, "type": typ, "link": None}] if kind == "SetNode" else [], + "outputs": [{"name": typ, "type": typ, "links": []}], + } + + +def connect(graph, lid, origin, oslot, target, tslot, typ="IMAGE"): + nodes = {n["id"]: n for n in graph["nodes"]} + nodes[origin]["outputs"][oslot].setdefault("links", []).append(lid) + nodes[target]["inputs"][tslot]["link"] = lid + graph["links"].append([lid, origin, oslot, target, tslot, typ]) + + +def synthetic(): + graph = { + "nodes": [ + { + "id": 1, + "type": "LoadImage", + "widgets_values": ["one.png", "image"], + "inputs": [], + "outputs": [{"type": "IMAGE", "links": []}, {"type": "MASK", "links": []}], + }, + virtual(2, "SetNode", "图片"), + virtual(3, "GetNode", "图片"), + { + "id": 4, + "type": "PreviewImage", + "widgets_values": [], + "inputs": [{"name": "images", "type": "IMAGE", "link": None}], + "outputs": [], + }, + ], + "links": [], + } + connect(graph, 1, 1, 0, 2, 0) + connect(graph, 2, 3, 0, 4, 0) + return graph + + +def test_fixed_originals_and_registration_call_chain(): + root = REPO / "docs/hel-892/setget-reference" + assert len(verify(root)["sources_verified"]) == 19 + js = (root / "web__js__setgetnodes.js").read_text() + for text in ( + 'LiteGraph.registerNodeType("SetNode", SetNode)', + 'LiteGraph.registerNodeType("GetNode", GetNode)', + "this.isVirtualNode = true", + "getInputLink(slot)", + "n.type === 'SetNode' && n.widgets[0].value === name", + "if (app.configuringGraph) return;", + "if (this._justAdded && !app.configuringGraph)", + "this.properties.previousName = this.widgets[0].value;", + ): + assert text in js + for v in SETGET_PROFILES.values(): + dto = (root / f"{v}__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts").read_text() + assert "const virtualLink = this.node.getInputLink(slot)" in dto + assert "return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)" in dto + node = (root / f"{v}__src__lib__litegraph__src__LGraphNode.ts").read_text() + assert "widget.value = info.widgets_values[i++]" in node + assert "getInputLink(slot: number)" in node + + +@pytest.mark.parametrize("profile", SETGET_PROFILES) +def test_complete_projection_and_production_stays_closed(profile): + g = synthetic() + g["extra"] = {"frontendVersion": SETGET_PROFILES[profile]} + original = copy.deepcopy(g) + result = convert_reference(g, profile) + assert result.prompt is not None, result.issues + assert set(result.prompt) == {"1", "4"} + assert result.prompt["4"]["inputs"]["images"] == ["1", 0] + assert result.prompt["1"]["inputs"]["image"] == "one.png" + assert [h["node_id"] for h in result.virtual_resolutions[0]["hops"]] == ["3", "2", "1"] + assert result.reference_only + assert convert(g).prompt is None + assert g == original + + +@pytest.mark.parametrize("name", ["图片", " A ", "a", "A", "e\u0301", "\u00e9", " "]) +def test_exact_names_rename_previous_name_and_upstream_changes(name): + g = synthetic() + g["nodes"][1]["widgets_values"] = [name] + g["nodes"][2]["widgets_values"] = [name] + g["nodes"][1]["properties"]["previousName"] = "图片" + result = convert_reference(g, PROFILE) + assert result.prompt is not None + assert result.virtual_resolutions[0]["hops"][0]["name"] == name + g["nodes"][0]["widgets_values"][0] = "changed.png" + assert convert_reference(g, PROFILE).prompt["1"]["inputs"]["image"] == "changed.png" + g["nodes"][2]["widgets_values"] = ["not_current"] + g["nodes"][1]["properties"]["previousName"] = "not_current" + g["nodes"][1]["title"] = "not_current" + assert convert_reference(g, PROFILE).prompt is None + + +@pytest.mark.parametrize("other", ["a", "A ", " A", "e\u0301"]) +def test_no_name_normalization(other): + g = synthetic() + g["nodes"][1]["widgets_values"] = ["A" if other != "e\u0301" else "\u00e9"] + g["nodes"][2]["widgets_values"] = [other] + assert convert_reference(g, PROFILE).prompt is None + + +def test_multiple_names_and_changing_binding_selects_correct_source(): + g = synthetic() + other = copy.deepcopy(g["nodes"][0]) + other["id"] = 11 + other["widgets_values"][0] = "two.png" + other["outputs"][0]["links"] = [] + g["nodes"] += [other, virtual(12, "SetNode", "second")] + connect(g, 11, 11, 0, 12, 0) + assert convert_reference(g, PROFILE).prompt["4"]["inputs"]["images"] == ["1", 0] + g["nodes"][2]["widgets_values"] = ["second"] + result = convert_reference(g, PROFILE) + assert result.prompt["4"]["inputs"]["images"] == ["11", 0] + assert result.prompt["11"]["inputs"]["image"] == "two.png" + + +def test_fanout_direct_set_and_multilevel_reroute_preserve_original_slot(): + g = synthetic() + g["nodes"][0]["outputs"][1]["type"] = "IMAGE" # topology fixture only + g["nodes"][0]["outputs"][0]["links"] = [] + g["nodes"][0]["outputs"][1]["links"] = [1] + g["links"][0][2] = 1 + g["nodes"] += [ + virtual(5, "GetNode", "图片"), + virtual(6, "SetNode", "next"), + virtual(7, "GetNode", "next"), + { + "id": 8, + "type": "Reroute", + "widgets_values": [], + "inputs": [{"name": "", "type": "IMAGE", "link": None}], + "outputs": [{"name": "", "type": "IMAGE", "links": []}], + }, + copy.deepcopy(g["nodes"][3]), + ] + g["nodes"][-1]["id"] = 9 + g["nodes"][-1]["inputs"][0]["link"] = None + connect(g, 3, 5, 0, 6, 0) + connect(g, 4, 7, 0, 8, 0) + connect(g, 5, 8, 0, 9, 0) + # Direct Set output feeds an additional sink; Get fanout is independent. + sink = copy.deepcopy(g["nodes"][3]) + sink["id"] = 10 + sink["inputs"][0]["link"] = None + g["nodes"].append(sink) + connect(g, 6, 2, 0, 10, 0) + projected = project_reference_setget(g) + assert projected.graph is not None, projected.issues + assert {tuple(e["endpoint"]) for e in projected.resolved} == {("1", 1)} + assert len(projected.resolved) == 3 + last = next(r for r in projected.resolved if r["target_node_id"] == "9") + assert [h["node_id"] for h in last["hops"]] == ["8", "7", "6", "5", "2", "1"] + assert [e[2] for e in projected.graph["links"]] == [1, 1, 1] + + +@pytest.mark.parametrize( + "mutation", + [ + "duplicate", + "missing_set", + "empty", + "bad_name", + "extra_widget", + "mapping_widget", + "bad_aux", + "missing_aux", + "literal_aux", + "bad_version", + "bad_cnr", + "extra_input", + "extra_output", + "bad_type", + "wildcard", + "union", + "mode", + "bool_mode", + "custom_serializer", + "custom_properties", + "custom_binding", + "bad_slot_name", + "bad_reciprocal", + "dangling", + "bool_slot", + "bool_link", + "wrong_edge_type", + "physical_cycle", + "logical_cycle", + "unused_bad_get", + "unused_bad_set", + "nested", + "uuid", + "ue_edges", + ], +) +def test_fail_closed_mutations_including_unused_branches(mutation): + g = synthetic() + s = g["nodes"][1] + get = g["nodes"][2] + if mutation == "duplicate": + extra = copy.deepcopy(s) + extra["id"] = 22 + extra["inputs"][0]["link"] = None + g["nodes"].append(extra) + elif mutation == "missing_set": + s["widgets_values"] = ["other"] + elif mutation == "empty": + get["widgets_values"] = [""] + elif mutation == "bad_name": + get["widgets_values"] = [True] + elif mutation == "extra_widget": + get["widgets_values"].append("extra") + elif mutation == "mapping_widget": + get["widgets_values"] = {"Constant": "图片"} + elif mutation == "bad_aux": + s["properties"]["aux_id"] = "rgthree/rgthree-comfy" + elif mutation == "missing_aux": + s["properties"].pop("aux_id") + elif mutation == "literal_aux": + s["properties"]["aux_id"] = "SetNode" + elif mutation == "bad_version": + s["properties"]["ver"] = "1.0.0" + elif mutation == "bad_cnr": + s["properties"]["cnr_id"] = "other" + elif mutation == "extra_input": + get["inputs"] = [{"name": "IMAGE", "type": "IMAGE", "link": None}] + elif mutation == "extra_output": + get["outputs"].append(copy.deepcopy(get["outputs"][0])) + elif mutation == "bad_type": + get["outputs"][0]["type"] = "FLOAT" + g["links"][1][5] = "FLOAT" + g["nodes"][3]["inputs"][0]["type"] = "FLOAT" + elif mutation in ("wildcard", "union"): + s["outputs"][0]["type"] = "*" if mutation == "wildcard" else "IMAGE,MASK" + elif mutation == "mode": + get["mode"] = 4 + elif mutation == "bool_mode": + get["mode"] = False + elif mutation == "custom_serializer": + get["serializeValue"] = "override" + elif mutation == "custom_properties": + s["properties"]["getInputLink"] = "override" + elif mutation == "custom_binding": + s["properties"]["ue_properties"] = {"widget_ue_connectable": {"Constant": True}} + elif mutation == "bad_slot_name": + s["inputs"][0]["name"] = "other" + elif mutation == "bad_reciprocal": + g["nodes"][0]["outputs"][0]["links"] = [] + elif mutation == "dangling": + g["links"][0][1] = 999 + elif mutation == "bool_slot": + g["links"][0][2] = False + elif mutation == "bool_link": + g["links"][0][0] = True + elif mutation == "wrong_edge_type": + g["links"][0][5] = "MASK" + elif mutation in ("physical_cycle", "logical_cycle"): + g["nodes"][0]["outputs"][0]["links"] = [] + g["links"].pop(0) + connect(g, 1, 2 if mutation == "physical_cycle" else 3, 0, 2, 0) + elif mutation == "unused_bad_get": + g["nodes"].append(virtual(99, "GetNode", "missing")) + elif mutation == "unused_bad_set": + g["nodes"].append(virtual(99, "SetNode", "unused")) + elif mutation == "nested": + g["definitions"] = {"subgraphs": [{"id": "any"}]} + elif mutation == "uuid": + g["nodes"].append({"id": 88, "type": "e61f4fd0-e251-4d58-bfa4-cf163fa86577"}) + elif mutation == "ue_edges": + g["extra"] = {"ue_links": [1]} + result = convert_reference(g, PROFILE) + assert result.prompt is None, mutation + assert result.issues, mutation + + +def test_unknown_ordinary_node_blocks_whole_graph_with_reference_trace_retained(): + g = synthetic() + g["nodes"][0]["type"] = "UnknownImageProducer" + result = convert_reference(g, PROFILE) + assert result.prompt is None + assert result.virtual_resolutions[0]["endpoint"] == ["1", 0] + assert any(i["code"] == "reference_node_unsupported" for i in result.issues) + + +def test_ambiguous_provider_trace_is_explicitly_untrusted(): + g = synthetic() + g["nodes"][1]["properties"]["aux_id"] = "SetNode" + result = convert_reference(g, PROFILE) + assert result.prompt is None and result.diagnostic_graph is None + trace = result.virtual_resolutions[0] + assert trace["endpoint"] == ["1", 0] + assert trace["authority"] == "literal_topology_only" and trace["binding_rejections"] + + +def test_wrong_frontend_missing_policy_and_profile_inventory(): + p1486 = list(SETGET_PROFILES)[1] + assert convert_reference(synthetic(), p1486).prompt is None + for v in ["1.48.7", "1.53.6", "1.37.11-other"]: + g = synthetic() + g["extra"] = {"frontendVersion": v} + assert convert_reference(g, PROFILE).prompt is None + assert len(audit.REFERENCE_PROFILES) == 20 + + +@pytest.mark.parametrize("profile", SETGET_PROFILES) +def test_vhs_composition_preserves_nonzero_audio_slot_and_exact_commits(profile): + prefix = "example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/" + source = json.loads((REPO / (prefix + "多视频合成分屏展示.json")).read_bytes()) + load = next(n for n in source["nodes"] if n["id"] == 17) + source = json.loads( + ( + REPO + / ( + "example_ComfyUI_workflows/4-视频生成/Minimax-h3/" + "Minimax_H3_T8双时钟采样_参考生视频-8步高质量极速版.json" + ) + ).read_bytes() + ) + combine = next(n for n in source["nodes"] if n["id"] == 12) + for n in (load, combine): + n.pop("widgets_values_named", None) + for s in n["inputs"]: + s["link"] = None + for s in n["outputs"]: + s["links"] = [] + graph = { + "nodes": [ + load, + combine, + virtual(900, "SetNode", "audio", "AUDIO"), + virtual(901, "GetNode", "audio", "AUDIO"), + ], + "links": [], + "extra": {"frontendVersion": SETGET_PROFILES[profile]}, + } + connect(graph, 1, 17, 0, 12, 0) + connect(graph, 2, 17, 2, 900, 0, "AUDIO") + connect(graph, 3, 901, 0, 12, 1, "AUDIO") + result = convert_reference(graph, profile) + assert result.prompt is not None, result.issues + assert result.prompt["12"]["inputs"]["audio"] == ["17", 2] + assert result.prompt["12"]["inputs"]["images"] == ["17", 0] + assert result.prompt["17"]["inputs"]["force_rate"] == 16 + load["widgets_values"]["force_rate"] = 20 + assert convert_reference(graph, profile).prompt["17"]["inputs"]["force_rate"] == 20 + load["properties"]["ver"] = "1.7.9" + assert convert_reference(graph, profile).prompt is None + + +@pytest.mark.parametrize( + "mutation", ["reroute_type", "ordinary_override", "ordinary_mode", "ordinary_cycle"] +) +def test_combined_structure_rejects_other_graph_overrides_and_cycles(mutation): + g = synthetic() + if mutation == "reroute_type": + g["nodes"][1] = { + "id": 2, + "type": "Reroute", + "widgets_values": [], + "inputs": [{"name": "", "type": "IMAGE", "link": 1}], + "outputs": [{"type": "MASK", "links": []}], + } + elif mutation == "ordinary_override": + g["nodes"][0]["resolveOutput"] = "custom" + elif mutation == "ordinary_mode": + g["nodes"][0]["mode"] = False + else: + # Ordinary producer feeds Set, Get feeds the same producer input. + g["nodes"][0]["inputs"] = [{"name": "images", "type": "IMAGE", "link": None}] + connect(g, 3, 3, 0, 1, 0) + assert convert_reference(g, PROFILE).prompt is None + + +def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): + old = json.loads((REPO / "docs/hel-892/vhs-evidence/library.json").read_bytes()) + baseline = tuple(p for p in audit.REFERENCE_PROFILES if p not in SETGET_PROFILES) + now = audit.audit_library(REPO, baseline_profiles=baseline) + actual_old = audit.audit_library(REPO, baseline) + assert len(baseline) == 18 + assert actual_old["gap_groups"] == old["gap_groups"] + for historical, previous, current in zip(old["cases"], actual_old["cases"], now["cases"]): + assert historical["source_path"] == previous["source_path"] == current["source_path"] + assert historical["attempts"] == previous["attempts"] == current["attempts"][:18] + assert ( + historical.get("comparisons") + == previous.get("comparisons") + == current.get("comparisons") + ) + assert now["coverage_delta"]["baseline_profiles"] == list(baseline) + assert audit.audit(REPO, "case04-batch-reference") == json.loads( + (REPO / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() + ) diff --git a/calliope-backend/tests/test_vhs_reference.py b/calliope-backend/tests/test_vhs_reference.py index 20d016d..42a0963 100644 --- a/calliope-backend/tests/test_vhs_reference.py +++ b/calliope-backend/tests/test_vhs_reference.py @@ -285,9 +285,13 @@ def test_real_five_load_instances_are_distinct_and_modes_not_dropped(): def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected(): old = json.loads((REPO / "docs/hel-892/crop-split-evidence/library.json").read_bytes()) - profiles = tuple(p for p in audit.REFERENCE_PROFILES if p not in VHS_PROFILES) + # Freeze this batch's 18-profile history; Set/Get has separate current protection. + historical_profiles = tuple( + p for p in audit.REFERENCE_PROFILES if p not in audit.SETGET_PROFILES + ) + profiles = tuple(p for p in historical_profiles if p not in VHS_PROFILES) baseline = audit.audit_library(REPO, profiles) - now = audit.audit_library(REPO, baseline_profiles=profiles) + now = audit.audit_library(REPO, historical_profiles, baseline_profiles=profiles) assert len(profiles) == 16 and len(now["profiles"]) == 18 assert old["gap_groups"] == baseline["gap_groups"] for previous, before, after in zip(old["cases"], baseline["cases"], now["cases"]):