HEL-892: add explicit PreviewAny and promoted scalar reference conversion

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 00:54:36 +08:00
co-authored by multica-agent
parent 5e5cc03395
commit 7d4e3941ed
5 changed files with 848 additions and 34 deletions
@@ -1,7 +1,8 @@
"""Pinned frontend structural projection, for diagnostics only.
"""Pinned frontend structure and opt-in direct promoted scalar projection.
Sources: docs/hel-892/structure-reference/sources.json. Does not serialize
promoted widgets, interpret third-party nodes, or establish execution eligibility.
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
@@ -17,12 +18,16 @@ STRUCTURE_PROFILES = {
}
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):
@@ -39,7 +44,7 @@ def _uuid(value):
return False
def expand_reference_subgraphs(source: dict, profile: str) -> Structure:
def expand_reference_subgraphs(source: dict, profile: str, *, widgets: bool = False) -> Structure:
"""Expand scoped nodes/links without consuming positional boundary widgets.
A returned graph is diagnostic data, never an executable prompt. Unbound
@@ -47,12 +52,12 @@ def expand_reference_subgraphs(source: dict, profile: str) -> Structure:
returns no graph, including malformed unused branches/definitions.
"""
try:
return _expand(source, profile)
return _expand(source, profile, widgets)
except (ValueError, TypeError, KeyError, AttributeError, IndexError, RecursionError) as exc:
return Structure(None, [{"code": "reference_structure_invalid", "message": str(exc)}])
def _expand(source, profile):
def _expand(source, profile, widgets=False):
version = STRUCTURE_PROFILES.get(profile)
if version is None or (source.get("extra") or {}).get("frontendVersion") != version:
raise ValueError("源前端声明与结构参考版本不符")
@@ -237,6 +242,152 @@ def _expand(source, profile):
return resolve(child, link[1], link[2], seen)
return [":".join((*path, str(nid))), slot]
resolved = []
if widgets:
from .serialization_reference import direct_widget_type, validate_direct_value
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 = direct_widget_type(target, socket, version)
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
)
# 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 = direct_widget_type(node, socket, version)
validate_direct_value(value["value"], kind)
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(":"))
@@ -249,9 +400,40 @@ def _expand(source, profile):
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}
)
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]])
@@ -285,4 +467,4 @@ def _expand(source, profile):
"links": projected,
"extra": deepcopy(source.get("extra", {})),
}
return Structure(graph, issues, unresolved)
return Structure(graph, issues, unresolved, resolved)