906 lines
40 KiB
Python
906 lines
40 KiB
Python
"""Pinned frontend structure and opt-in direct promoted scalar projection.
|
||
|
||
Sources: docs/hel-892/{structure-reference,promoted-reference}/sources.json.
|
||
Structure profiles remain diagnostic. Direct values never prove complete ordinary
|
||
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
|
||
|
||
GRID_PROFILE = "comfy-frontend-1.41.20-core-0.17.0-grid-reference"
|
||
H3_PROFILE = "comfy-frontend-1.53.10-h3-a59888df-core-0.30.0-reference"
|
||
|
||
SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18"
|
||
SETGET_PROFILES = {
|
||
f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6")
|
||
}
|
||
|
||
VIDEOINFO_PROFILES = {
|
||
f"comfy-frontend-{v}-videoinfo-537f3a02-kj-ab72eda7-vhs-core-reference": v
|
||
for v in ("1.37.11", "1.48.6")
|
||
}
|
||
|
||
VIDEOINFO_DELEGATES = {
|
||
profile: f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference"
|
||
for profile, v in VIDEOINFO_PROFILES.items()
|
||
}
|
||
|
||
# Explicit composition keys; frontend and delegate identities never depend on order.
|
||
SCAIL_LOAD_PROFILES = {
|
||
f"comfy-frontend-{v}-scail-load-8e4d7947-info-537f3a02-kj-ab72eda7-reference": v
|
||
for v in ("1.37.11", "1.48.6")
|
||
}
|
||
SCAIL_LOAD_DELEGATES = {
|
||
profile: f"comfy-frontend-{v}-videoinfo-537f3a02-kj-ab72eda7-vhs-core-reference"
|
||
for profile, v in SCAIL_LOAD_PROFILES.items()
|
||
}
|
||
|
||
|
||
STRUCTURE_PROFILES = {
|
||
f"comfy-frontend-{version}-structure-reference": version
|
||
for version in ("1.48.7", "1.53.6", "1.48.6")
|
||
}
|
||
|
||
|
||
PROMOTED_PROFILES = {f"comfy-frontend-{v}-promoted-reference": v for v in ("1.48.7", "1.53.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)
|
||
resolved: 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 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:
|
||
"""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, widgets, case04)
|
||
except (ValueError, TypeError, KeyError, AttributeError, IndexError, RecursionError) as exc:
|
||
return Structure(None, [{"code": "reference_structure_invalid", "message": str(exc)}])
|
||
|
||
|
||
def _expand(source, profile, widgets=False, case04=False):
|
||
version = STRUCTURE_PROFILES.get(profile)
|
||
if version is None or (source.get("extra") or {}).get("frontendVersion") != version:
|
||
raise ValueError("源前端声明与结构参考版本不符")
|
||
if case04 and version != "1.53.6":
|
||
raise ValueError("case04保存态只覆盖1.53.6参考")
|
||
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]
|
||
|
||
resolved = []
|
||
if widgets:
|
||
from .serialization_reference import (
|
||
case04_seed_fanout,
|
||
case04_widget_type,
|
||
direct_widget_type,
|
||
validate_case04_value,
|
||
validate_direct_value,
|
||
)
|
||
|
||
def widget_type(node, socket):
|
||
return (
|
||
case04_widget_type(node, socket)
|
||
if case04
|
||
else direct_widget_type(node, socket, version)
|
||
)
|
||
|
||
def targets(key, slot, stack=()):
|
||
marker = (key, slot)
|
||
if marker in stack:
|
||
raise ValueError("递归控件绑定")
|
||
definition = definitions[key]
|
||
found = []
|
||
for lid in definition["inputs"][slot]["linkIds"]:
|
||
edge = networks[key][1][str(lid)]
|
||
target = networks[key][0][str(edge[3])]
|
||
socket = target["inputs"][edge[4]]
|
||
if target["type"] in definitions:
|
||
found.extend(targets(target["type"], edge[4], stack + (marker,)))
|
||
elif socket.get("widget") is not None:
|
||
try:
|
||
kind = widget_type(target, socket)
|
||
except ValueError:
|
||
kind = None
|
||
found.append((target, socket, kind))
|
||
return found
|
||
|
||
host_cache = {}
|
||
|
||
def host_values(path):
|
||
if path in host_cache:
|
||
return host_cache[path]
|
||
key, _, parent, instance = contexts[path]
|
||
definition = definitions[key]
|
||
props = instance.get("properties") or {}
|
||
if (
|
||
props.get("proxyWidgetErrorQuarantine")
|
||
or props.get("proxyWidgets")
|
||
or any(k in instance for k in ("widgets", "serializeValue"))
|
||
):
|
||
raise ValueError("隔离/代理/自定义控件覆盖不在promoted参考契约内")
|
||
names = [s["name"] for s in definition["inputs"]]
|
||
if len(names) != len(set(names)):
|
||
raise ValueError("重名稳定输入标识")
|
||
bindings = []
|
||
for slot, socket in enumerate(instance.get("inputs", [])):
|
||
bound = targets(key, slot)
|
||
if not bound:
|
||
if socket.get("widget") is not None:
|
||
raise ValueError("实例控件缺少可证明的内部绑定")
|
||
continue
|
||
kind = bound[0][2]
|
||
if kind is None:
|
||
raise ValueError(
|
||
f"首个内部绑定 {bound[0][0]['type']}.{bound[0][1]['name']} "
|
||
"无固定构造契约;无法重建host控件顺序"
|
||
)
|
||
compatible = all(
|
||
t == kind
|
||
and (n["type"], s["name"]) == (bound[0][0]["type"], bound[0][1]["name"])
|
||
for n, s, t in bound
|
||
)
|
||
if case04 and not compatible:
|
||
compatible = case04_seed_fanout(bound)
|
||
# Differently constrained fanouts need their own compatibility
|
||
# proof; never propagate a value just because types coincide.
|
||
if socket.get("widget") != {"name": names[slot]} or socket.get("type") != kind:
|
||
raise ValueError("实例稳定widget.name或类型不符")
|
||
bindings.append((slot, kind, compatible))
|
||
values = instance.get("widgets_values", [])
|
||
if not isinstance(values, list) or len(values) != len(bindings):
|
||
raise ValueError("promoted控件数量不符;不静默回退内部默认值")
|
||
# Array offset is justified only after reconstructing every host
|
||
# widget via interior named bindings (SubgraphNode._resolveInputWidget).
|
||
result = {}
|
||
local_nodes = list(networks[parent[0]][0])
|
||
prefix = "/nodes/" + str(local_nodes.index(str(instance["id"])))
|
||
if parent[0] is not None:
|
||
prefix = (
|
||
"/definitions/subgraphs/" + str(list(definitions).index(parent[0])) + prefix
|
||
)
|
||
for index, (slot, kind, compatible) in enumerate(bindings):
|
||
value = values[index]
|
||
# Retain the persisted value for provenance. Type validation
|
||
# happens on scalar consumption; external links always win.
|
||
result[slot] = {
|
||
"value": value,
|
||
"value_pointer": prefix + "/widgets_values/" + str(index),
|
||
"binding_name": names[slot],
|
||
"binding_type": kind,
|
||
"compatible": compatible,
|
||
"boundary_instance": ":".join(path),
|
||
}
|
||
named = instance.get("widgets_values_named")
|
||
if version == "1.53.6" and named is not None:
|
||
if (
|
||
not isinstance(named, dict)
|
||
or set(named) != {v["binding_name"] for v in result.values()}
|
||
or any(
|
||
type(named[v["binding_name"]]) is not type(v["value"])
|
||
or named[v["binding_name"]] != v["value"]
|
||
for v in result.values()
|
||
)
|
||
):
|
||
raise ValueError("具名/位置host值不一致;namedValuesRestore开关未知")
|
||
for v in result.values():
|
||
name = v["binding_name"].replace("~", "~0").replace("/", "~1")
|
||
v["named_value_pointer"] = prefix + "/widgets_values_named/" + name
|
||
host_cache[path] = result
|
||
return result
|
||
|
||
def scalar(endpoint, node, socket):
|
||
path = tuple(endpoint["boundary_instance"].split(":"))
|
||
values = host_values(path)
|
||
slot = endpoint["slot"]
|
||
if slot not in values:
|
||
raise ValueError("无稳定promoted控件绑定;不采用内部现值")
|
||
value = values[slot]
|
||
if not value["compatible"]:
|
||
raise ValueError("多目标控件约束未知或不兼容")
|
||
kind = widget_type(node, socket)
|
||
validate_direct_value(value["value"], kind)
|
||
if case04:
|
||
validate_case04_value(node, socket["name"], value["value"])
|
||
if kind != value["binding_type"]:
|
||
raise ValueError("边界到内部字段类型不兼容")
|
||
return value
|
||
|
||
store_keys = {}
|
||
for path in contexts:
|
||
if not path:
|
||
continue
|
||
try:
|
||
values = host_values(path)
|
||
for value in values.values():
|
||
# Pinned store identity uses local instance ID, not the
|
||
# composite execution path. Conflicting nested definitions
|
||
# must not be advertised as isolated store values.
|
||
key = (path[-1], value["binding_name"])
|
||
previous = store_keys.get(key)
|
||
identity = (value["binding_type"], type(value["value"]), value["value"])
|
||
if previous is not None and previous != identity:
|
||
raise ValueError("嵌套host的局部widgetId冲突;存储值优先顺序未证明")
|
||
store_keys[key] = identity
|
||
except ValueError as exc:
|
||
issues.append(
|
||
{
|
||
"code": "promoted_host_unverified",
|
||
"node_id": ":".join(path),
|
||
"message": str(exc),
|
||
}
|
||
)
|
||
|
||
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):
|
||
boundary = {
|
||
"node_id": full,
|
||
"input_slot": slot,
|
||
"input_name": socket["name"],
|
||
**endpoint,
|
||
}
|
||
if widgets:
|
||
try:
|
||
value = scalar(endpoint, node, socket)
|
||
except ValueError as exc:
|
||
unresolved.append({**boundary, "reason": str(exc)})
|
||
else:
|
||
local = list(networks[ctx[0]][0]).index(full.split(":")[-1])
|
||
prefix = "/nodes/" + str(local)
|
||
if ctx[0] is not None:
|
||
prefix = (
|
||
"/definitions/subgraphs/"
|
||
+ str(list(definitions).index(ctx[0]))
|
||
+ prefix
|
||
)
|
||
resolved.append(
|
||
{
|
||
**boundary,
|
||
**deepcopy(value),
|
||
"target_pointer": prefix + "/inputs/" + str(slot),
|
||
"precedence": [
|
||
"external_link",
|
||
"promoted_value",
|
||
"internal_serializer",
|
||
],
|
||
}
|
||
)
|
||
else:
|
||
unresolved.append(boundary)
|
||
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, resolved)
|
||
|
||
|
||
def validate_grid_structure(source, *, frontend="1.41.20", preview_any=False):
|
||
"""Only direct root links under the pinned 1.41.20 reference premise.
|
||
|
||
IMAGE -> IMAGE,MASK is the single supported MatchType specialization.
|
||
No UE implementation identity is inferred from an empty saved mapping.
|
||
"""
|
||
scope = "四宫格" if frontend == "1.41.20" else "H3"
|
||
if (source.get("extra") or {}).get("frontendVersion") != frontend:
|
||
raise ValueError(
|
||
"四宫格参考需要显式前端1.41.20"
|
||
if frontend == "1.41.20"
|
||
else f"H3直接连线参考需要显式前端{frontend}"
|
||
)
|
||
if (source.get("definitions") or {}).get("subgraphs"):
|
||
raise ValueError(f"{scope}参考不覆盖子图")
|
||
extra = source.get("extra") or {}
|
||
if extra.get("workflowRendererVersion", "LG") != "LG":
|
||
raise ValueError(f"{scope}只覆盖LG保存态")
|
||
for key in ("ue_links", "links_added_by_ue"):
|
||
if key in extra and extra[key] != []:
|
||
raise ValueError(f"{scope}参考只覆盖空UE连线数组")
|
||
nodes = {}
|
||
for node in source["nodes"]:
|
||
nid = _id(node["id"])
|
||
if nid in nodes:
|
||
raise ValueError("重复节点ID")
|
||
nodes[nid] = node
|
||
if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0:
|
||
raise ValueError(f"{scope}仅正常mode=0")
|
||
if node.get("type") in ("Note", "MarkdownNote") and (
|
||
node.get("inputs") or node.get("outputs")
|
||
):
|
||
raise ValueError("虚拟说明节点不得带执行连线")
|
||
links = {}
|
||
for edge in source.get("links", []):
|
||
if not isinstance(edge, list) or len(edge) != 6:
|
||
raise ValueError(f"{scope}只接受六字段连线")
|
||
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("连线原槽缺失或非法")
|
||
origin, target = nodes[a]["outputs"][oslot], nodes[b]["inputs"][islot]
|
||
accepted = origin.get("type") == target.get("type") == typ
|
||
if preview_any and nodes[b].get("type") == "PreviewAny":
|
||
accepted = typ == origin.get("type") == "STRING" and target.get("type") == "*"
|
||
if nodes[b].get("type") == "ResizeImageMaskNode" and target.get("name") == "input":
|
||
accepted = typ == origin.get("type") == "IMAGE" and target.get("type") == "IMAGE,MASK"
|
||
if not accepted:
|
||
raise ValueError("连线类型与精确槽不符,未覆盖的MatchType分支")
|
||
ids = origin.get("links") or []
|
||
if any(type(x) is not int for x in ids) or ids.count(lid) != 1:
|
||
raise ValueError("输出与连线不互指")
|
||
if type(target.get("link")) is not int or target["link"] != lid:
|
||
raise ValueError("输入与连线不互指")
|
||
links[lid] = edge
|
||
for nid, n in nodes.items():
|
||
for direction in ("inputs", "outputs"):
|
||
for slot, socket in enumerate(n.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:
|
||
if type(lid) is not int or lid not in links:
|
||
raise ValueError("槽引用未知连线")
|
||
edge = links[lid]
|
||
offset = 1 if direction == "outputs" else 3
|
||
if [str(edge[offset]), edge[offset + 1]] != [nid, slot]:
|
||
raise ValueError("槽引用错误端点")
|
||
# graphToPrompt's execution ordering requires an acyclic direct graph here.
|
||
visiting, visited = set(), set()
|
||
|
||
def visit(nid):
|
||
if nid in visiting:
|
||
raise ValueError(f"{scope}参考不支持环")
|
||
if nid in visited:
|
||
return
|
||
visiting.add(nid)
|
||
for e in links.values():
|
||
if str(e[3]) == nid:
|
||
visit(str(e[1]))
|
||
visiting.remove(nid)
|
||
visited.add(nid)
|
||
|
||
for nid in nodes:
|
||
visit(nid)
|