HEL-892: add opt-in pinned root Set/Get reference projection

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 04:57:59 +08:00
co-authored by multica-agent
parent 8187064129
commit efe68ecd98
29 changed files with 19931 additions and 12 deletions
@@ -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: