diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index cb1e4046..f3ccc698 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, + CASE04_PROFILE, PREVIEW_PROFILE, PRIMITIVE_PROFILE, PROFILE, resolve_reference_link, + serialize_case04_node, serialize_promoted_node, serialize_reference_widgets, ) @@ -30,6 +32,22 @@ from calliope.comfyui.structure_reference import PROMOTED_PROFILES, STRUCTURE_PR from calliope.comfyui.ui2api import convert, convert_reference +def saved_named_pointer(source, nid, name): + """Locate immutable original named bytes by scoped IDs, never API values.""" + graph, prefix = source, "" + definitions = (source.get("definitions") or {}).get("subgraphs", []) + parts = nid.split(":") + for depth, part in enumerate(parts): + index, node = next((i, n) for i, n in enumerate(graph["nodes"]) if str(n["id"]) == part) + if depth == len(parts) - 1: + if name in (node.get("widgets_values_named") or {}): + escaped = name.replace("~", "~0").replace("/", "~1") + return prefix + f"/nodes/{index}/widgets_values_named/" + escaped + return None + dindex, graph = next((i, d) for i, d in enumerate(definitions) if d["id"] == node["type"]) + prefix = f"/definitions/subgraphs/{dindex}" + + def audit(repo: Path, profile: str = PROFILE) -> dict: rows = [] records = load_companions(repo / "docs/hel-892/supplied-api/manifest.json") @@ -43,7 +61,11 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: source, api = json.loads(raw), json.loads(record["raw"]) assert convert(api).prompt is not None selected = profile - if profile in ("structure-batch-reference", "promoted-batch-reference"): + if profile in ( + "structure-batch-reference", + "promoted-batch-reference", + "case04-batch-reference", + ): version = source.get("extra", {}).get("frontendVersion") structural = f"comfy-frontend-{version}-structure-reference" selected = ( @@ -54,7 +76,7 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: if any(n.get("type") == "PrimitiveNode" for n in source["nodes"]) else AUX_PROFILE ) - if profile == "promoted-batch-reference": + if profile in ("promoted-batch-reference", "case04-batch-reference"): selected = ( selected.replace("-structure-reference", "-promoted-reference") if selected.replace("-structure-reference", "-promoted-reference") @@ -63,6 +85,8 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: if selected == PRIMITIVE_PROFILE else selected ) + if profile == "case04-batch-reference" and binding["id"] == "04": + selected = CASE04_PROFILE candidate = convert_reference(source, selected) projected = candidate.diagnostic_graph or source nodes = {str(n["id"]): n for n in projected["nodes"]} @@ -77,7 +101,9 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: continue try: values = ( - serialize_promoted_node(node, PROMOTED_PROFILES[selected]) + serialize_case04_node(node) + if selected == CASE04_PROFILE + else serialize_promoted_node(node, PROMOTED_PROFILES[selected]) if selected in PROMOTED_PROFILES else serialize_reference_widgets(node, selected) ) @@ -94,10 +120,26 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "node_id": nid, "field": name, "source_reference": value, + **( + { + "source_value_pointer": next( + ( + b["value_pointer"] + for b in candidate.resolved_boundaries + if b["node_id"] == nid and b["input_name"] == name + ), + saved_named_pointer(source, nid, name), + ), + "serializer_contract": "case04-reference/sources.json; " + "case04-reference/contracts.json", + } + if selected == CASE04_PROFILE + else {} + ), "api": expected, "differences": ( differences({}, {name: value}) - if selected in (PREVIEW_PROFILE, *PROMOTED_PROFILES) + if selected in (PREVIEW_PROFILE, CASE04_PROFILE, *PROMOTED_PROFILES) and name not in api.get(nid, {}).get("inputs", {}) else differences(expected, value) ), @@ -162,8 +204,9 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "source_frontend_version": source.get("extra", {}).get("frontendVersion"), "export_frontend_version": binding["frontend_version"], "whole_prompt_available": candidate.prompt is not None, + "serialization_stage": candidate.serialization_stage, "candidate_prompt": candidate.prompt - if profile == "promoted-batch-reference" + if profile in ("promoted-batch-reference", "case04-batch-reference", CASE04_PROFILE) else None, "whole_prompt_differences": differences(api, candidate.prompt) if candidate.prompt is not None @@ -201,7 +244,13 @@ def audit(repo: Path, profile: str = PROFILE) -> dict: "diagnostic structures never prove widget values, full equivalence or execution", "reference_conditions": { "unmodified_frontend_widgets_assumed": True, - "promoted_named_positional": "1.53.6 requires both representations to agree when named values exist; 1.48.7 ignores unknown named keys", + "promoted_named_positional": ( + "1.53.6 requires both representations to agree when named values exist; " + "1.48.7 ignores unknown named keys" + ), + "case04_stage": "restored_saved_state_before_queue_hooks; fixed controls only", + "case04_uncovered": "queue history/settings, non-fixed seed, other dynamic branches, " + "dynamic text/filename expressions, unknown extension overrides", "promoted_missing_or_null": "no silent default; typed scalar consumption rejects null", "primitive_inside_promoted_profile": "unsupported; whole prompt remains closed", "combo_availability": "not evaluated; fixed scalar constructor only", @@ -233,6 +282,8 @@ def main(): PREVIEW_PROFILE, *STRUCTURE_PROFILES, *PROMOTED_PROFILES, + CASE04_PROFILE, + "case04-batch-reference", "promoted-batch-reference", "structure-batch-reference", ), diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index 5283a006..f8420926 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -1,10 +1,11 @@ """Small, explicit public-reference contract, never a target object_info snapshot. Sources: docs/hel-892/{serialization-evidence,controlnet-reference, -promoted-reference,structure-reference}/sources.json. +promoted-reference,structure-reference,case04-reference}/sources.json. 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. +folds direct Primitive STRING bindings. The case04 opt-in covers fixed seed +controls in saved state only. No bypass, arbitrary extension or target +installation is inferred. """ from __future__ import annotations @@ -15,6 +16,7 @@ PROFILE = "comfy-frontend-1.37.11-core-reference" AUX_PROFILE = "comfy-frontend-1.37.11-controlnet-aux-e8b689a-reference" AUX_COMMIT = "e8b689a513c3e6b63edc44066560ca5919c0576e" PREVIEW_PROFILE = "comfy-frontend-1.37.11-preview-reference" +CASE04_PROFILE = "comfy-frontend-1.53.6-core-0.38.0-saved-state-reference" 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. @@ -547,3 +549,358 @@ def serialize_promoted_node(node, version): validate_direct_value(value, kind) result[name] = value return result + + +# Fixed core 0.38.0 / frontend 1.53.6 constructors. This profile reads restored +# saved state, before queue hooks. It does not simulate a browser or random RNG. +# Dotted DynamicCombo child names are constructed by dynamicWidgets.ts, not +# inferred from the supplied API. Unsupported branches stay closed. +_CASE04_LAYOUTS = { + **_SIMPLE_LAYOUTS, + "ResolutionSelector": ("aspect_ratio", "megapixels", "multiple"), + "SaveImageAdvanced": ( + "filename_prefix", + "format", + "format.bit_depth", + "format.input_color_space", + ), + "TextEncodeQwenImage21": ("prompt", "negative_prompt", "resolution"), + "VAEDecode": (), + "KSampler": ( + "seed", + "control_after_generate", + "steps", + "cfg", + "sampler_name", + "scheduler", + "denoise", + ), + "TextGenerate": ( + "prompt", + "max_length", + "sampling_mode", + "sampling_mode.temperature", + "sampling_mode.top_k", + "sampling_mode.top_p", + "sampling_mode.min_p", + "sampling_mode.repetition_penalty", + "sampling_mode.seed", + "sampling_mode.presence_penalty", + "thinking", + "use_default_template", + "mtp", + ), + "PreviewAny": (), + "ComfySwitchNode": ("switch",), +} +_CASE04_TYPES = { + **_DIRECT, + "ResolutionSelector": {"aspect_ratio": "COMBO", "megapixels": "FLOAT", "multiple": "INT"}, + "SaveImageAdvanced": { + "filename_prefix": "STRING", + "format": "COMFY_DYNAMICCOMBO_V3", + "format.bit_depth": "COMBO", + "format.input_color_space": "COMBO", + }, + "KSampler": { + **_DIRECT["KSampler"], + "seed": "INT", + "denoise": "FLOAT", + }, + "TextGenerate": { + **_DIRECT["TextGenerate"], + "max_length": "INT", + "sampling_mode": "COMFY_DYNAMICCOMBO_V3", + "sampling_mode.temperature": "FLOAT", + "sampling_mode.top_k": "INT", + "sampling_mode.top_p": "FLOAT", + "sampling_mode.min_p": "FLOAT", + "sampling_mode.repetition_penalty": "FLOAT", + "sampling_mode.seed": "INT", + "sampling_mode.presence_penalty": "FLOAT", + "use_default_template": "BOOLEAN", + "mtp": "COMBO", + }, + "VAEDecode": {}, + "PreviewAny": {}, +} +_CASE04_LINKS = { + "KSampler": { + "model": "MODEL", + "positive": "CONDITIONING", + "negative": "CONDITIONING", + "latent_image": "LATENT", + }, + "VAEDecode": {"samples": "LATENT", "vae": "VAE"}, + "TextEncodeQwenImage21": {"clip": "CLIP"}, + "TextGenerate": {"clip": "CLIP"}, + "SaveImageAdvanced": {"images": "IMAGE"}, + "PreviewAny": {"source": "*"}, + "QwenImage21Cache": {"model": "MODEL"}, +} +_CASE04_OPTIONAL = { + "TextGenerate": { + "image": "IMAGE", + "video": "IMAGE", + "audio": "AUDIO", + "system_prompt": "STRING", + }, + "TextEncodeQwenImage21": {"vae": "VAE", **{f"images.image_{i}": "IMAGE" for i in range(1, 17)}}, + # Bounded MatchType specialization: STRING/STRING -> STRING only. + "ComfySwitchNode": {"on_false": "STRING", "on_true": "STRING"}, + "ResolutionSelector": {"preview": "RESOLUTION_PREVIEW"}, +} +_CASE04_OUTPUTS = { + **_SIMPLE_OUTPUTS, + "ResolutionSelector": ["INT", "INT"], + "SaveImageAdvanced": ["IMAGE"], + "TextEncodeQwenImage21": ["CONDITIONING", "CONDITIONING", "LATENT"], + "VAEDecode": ["IMAGE"], + "KSampler": ["LATENT"], + "TextGenerate": ["STRING", "STRING"], + "PreviewAny": ["STRING"], + "ComfySwitchNode": ["STRING"], +} +# Bounds are static schema checks, not UI callbacks: no rounding or clamping. +_CASE04_BOUNDS = { + ("ResolutionSelector", "megapixels"): (0.1, 16), + ("ResolutionSelector", "multiple"): (8, 128), + ("KSampler", "seed"): (0, 0xFFFFFFFFFFFFFFFF), + ("KSampler", "steps"): (1, 10000), + ("KSampler", "cfg"): (0, 100), + ("KSampler", "denoise"): (0, 1), + ("TextGenerate", "max_length"): (1, 32768), + ("TextGenerate", "sampling_mode.temperature"): (0.01, 2), + ("TextGenerate", "sampling_mode.top_k"): (0, 1000), + ("TextGenerate", "sampling_mode.top_p"): (0, 1), + ("TextGenerate", "sampling_mode.min_p"): (0, 1), + ("TextGenerate", "sampling_mode.repetition_penalty"): (0, 5), + ("TextGenerate", "sampling_mode.seed"): (0, 0xFFFFFFFFFFFFFFFF), + ("TextGenerate", "sampling_mode.presence_penalty"): (0, 5), + ("TextEncodeQwenImage21", "resolution"): (0, 4096), + ("EmptyLatentImage", "width"): (16, 16384), + ("EmptyLatentImage", "height"): (16, 16384), + ("EmptyLatentImage", "batch_size"): (1, 4096), +} +_CASE04_ENUMS = { + ("ResolutionSelector", "aspect_ratio"): ( + "1:1 (Square)", + "2:3 (Portrait Photo)", + "3:2 (Photo)", + "3:4 (Portrait Standard)", + "4:3 (Standard)", + "9:16 (Portrait Widescreen)", + "16:9 (Widescreen)", + "21:9 (Ultrawide)", + ), + ("UNETLoader", "weight_dtype"): ("default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"), + ("CLIPLoader", "type"): ( + "stable_diffusion", + "stable_cascade", + "sd3", + "stable_audio", + "mochi", + "ltxv", + "pixart", + "cosmos", + "lumina2", + "wan", + "hidream", + "chroma", + "ace", + "omnigen2", + "qwen_image", + "hunyuan_image", + "flux2", + "ovis", + "longcat_image", + "cogvideox", + "lens", + "pixeldit", + "ideogram4", + "boogu", + "krea2", + "joyimage", + "mage", + "minimax", + "yue2", + ), + ("CLIPLoader", "device"): ("default", "cpu"), + ("QwenImage21Cache", "device"): ("auto", "gpu", "cpu", "off"), + ("QwenImage21Cache", "dtype"): ("default", "int8", "int4"), + ("TextGenerate", "mtp"): ("auto", "off", "2", "3", "4", "5"), +} +# Fixed lists copied from comfy/samplers.py at the recorded core commit. +_CASE04_ENUMS[("KSampler", "sampler_name")] = tuple( + ( + "euler euler_cfg_pp euler_ancestral euler_ancestral_cfg_pp heun heunpp2 exp_heun_2_x0 " + "exp_heun_2_x0_sde dpm_2 dpm_2_ancestral lms dpm_fast dpm_adaptive dpmpp_2s_ancestral " + "dpmpp_2s_ancestral_cfg_pp dpmpp_sde dpmpp_sde_gpu dpmpp_2m dpmpp_2m_cfg_pp dpmpp_2m_sde " + "dpmpp_2m_sde_gpu dpmpp_2m_sde_heun dpmpp_2m_sde_heun_gpu dpmpp_3m_sde dpmpp_3m_sde_gpu " + "ddpm lcm ipndm ipndm_v deis cfgpp_ud10_ab res_multistep res_multistep_cfg_pp " + "res_multistep_ancestral res_multistep_ancestral_cfg_pp gradient_estimation " + "gradient_estimation_cfg_pp er_sde seeds_2 seeds_3 sa_solver sa_solver_pece " + "ddim uni_pc uni_pc_bh2" + ).split() +) +_CASE04_ENUMS[("KSampler", "scheduler")] = ( + "simple", + "sgm_uniform", + "karras", + "exponential", + "ddim_uniform", + "beta", + "normal", + "linear_quadratic", + "kl_optimal", +) + + +def case04_definitions(): + """Static reference schemas only; model/file combo membership stays unknown.""" + return { + ct: { + "input": { + "required": { + k: [v] + for k, v in { + **_CASE04_TYPES[ct], + **_CASE04_LINKS.get(ct, {}), + }.items() + }, + "optional": {k: [v] for k, v in _CASE04_OPTIONAL.get(ct, {}).items()}, + }, + "output": _CASE04_OUTPUTS[ct], + } + for ct in _CASE04_LAYOUTS + } + + +def case04_widget_type(node, socket): + props = node.get("properties") or {} + if props.get("cnr_id") != "comfy-core" or props.get("ver") != "0.38.0": + raise ValueError("case04要求comfy-core/0.38.0声明;不证明目标版本") + name = socket.get("name") + kind = _CASE04_TYPES.get(node.get("type"), {}).get(name) + if kind is None or socket.get("type") != kind or socket.get("widget") != {"name": name}: + raise ValueError("case04未证明的具名控件绑定") + if node.get("mode", 0) != 0 or any(k in node for k in ("widgets", "serializeValue")): + raise ValueError("case04不接受模式/自定义serializer覆盖") + return kind + + +def validate_case04_value(node, name, value): + import math + + ct = node["type"] + kind = _CASE04_TYPES[ct][name] + validate_direct_value(value, "COMBO" if kind == "COMFY_DYNAMICCOMBO_V3" else kind) + if kind in ("FLOAT", "INT"): + if type(value) is float and not math.isfinite(value): + raise ValueError(f"{ct}.{name}不是有限数") + bounds = _CASE04_BOUNDS.get((ct, name)) + if bounds and not bounds[0] <= value <= bounds[1]: + raise ValueError(f"{ct}.{name}超出固定源码范围") + if kind == "INT" and abs(value) > 2**53 - 1: + raise ValueError("保存整数不能在JavaScript Number中精确恢复") + options = _CASE04_ENUMS.get((ct, name)) + if options is not None and value not in options: + raise ValueError(f"{ct}.{name}非法静态枚举") + + +def case04_seed_fanout(bound): + """Equal scalar domains, different control construction; only fixed is covered. + + KSampler requests a control explicitly. DynamicCombo prefixes the other + input as sampling_mode.seed, so useIntWidget's bare-name fallback does not + create a second controller. linkIds order selects the host's first source. + """ + pairs = {(node["type"], socket["name"]) for node, socket, _ in bound} + if pairs != {("KSampler", "seed"), ("TextGenerate", "sampling_mode.seed")}: + return False + for node, _, kind in bound: + if kind != "INT": + return False + serialize_case04_node(node) + return True + + +def serialize_case04_node(node): + """Bounded saved-state serializer, with no queue hooks or execution claim. + + DynamicCombo supports only TextGenerate.on and SaveImageAdvanced.png here. + Other branches, dynamic text/filename expressions and non-fixed controls + fail closed; they are never replaced by random or API-derived constants. + """ + ct = node.get("type") + if ct not in _CASE04_LAYOUTS: + raise ValueError("case04未覆盖完整节点serializer") + layout = _CASE04_LAYOUTS[ct] + values = node.get("widgets_values", []) + if not isinstance(values, list) or len(values) != len(layout): + raise ValueError("case04完整控件数/动态分支不符;不补默认值") + props = node.get("properties") or {} + if ( + props.get("cnr_id") != "comfy-core" + or props.get("ver") != "0.38.0" + or node.get("mode", 0) != 0 + or any(k in node for k in ("widgets", "serializeValue", "comfyDynamic")) + ): + raise ValueError("case04提供方/版本/模式或自定义覆盖不符") + named = node.get("widgets_values_named") + if named is not None and ( + not isinstance(named, dict) + or set(named) != set(layout) + or any(type(named[n]) is not type(v) or named[n] != v for n, v in zip(layout, values)) + ): + raise ValueError("case04具名/位置恢复冲突;开关未知") + result = {} + for name, value in zip(layout, values): + if name == "control_after_generate": + if value != "fixed": + raise ValueError("seed控制非fixed:保存态不证明beforeQueued/afterQueued实际种子") + continue + validate_case04_value(node, name, value) + result[name] = value + if ct == "TextGenerate" and result["sampling_mode"] != "on": + raise ValueError("仅覆盖sampling_mode.on动态分支") + if ct == "SaveImageAdvanced": + if ( + result["format"] != "png" + or result["format.bit_depth"] not in ("8-bit", "16-bit") + or result["format.input_color_space"] != "sRGB" + ): + raise ValueError("仅覆盖png的固定bit_depth/color_space分支") + if "%" in result["filename_prefix"]: + raise ValueError("filename_prefix替换依赖日期/图上下文;不生成常量") + if ct in ("TextGenerate", "TextEncodeQwenImage21"): + for name in ("prompt", "negative_prompt"): + value = result.get(name, "") + if any(token in value for token in ("{", "}", "/*", "//", "\\")): + raise ValueError("动态文本serializer不在字面量子集;不随机展开") + spec = case04_definitions()[ct]["input"] + allowed = {k: v[0] for k, v in {**spec["required"], **spec["optional"]}.items()} + names = [] + for socket in node.get("inputs", []): + name = socket.get("name") + if name not in allowed or socket.get("type") != allowed[name] or name in names: + raise ValueError("case04额外/重复/错误类型输入槽") + names.append(name) + widget = socket.get("widget") + expected = {"name": name} if name in result or name == "preview" else None + if widget != expected: + raise ValueError("case04输入控件绑定不符") + if name == "preview" and socket.get("link") is not None: + raise ValueError("非执行preview控件不能作为连线输入") + if set(spec["required"]) - set(names): + raise ValueError("case04缺少固定构造的输入槽") + if ct == "TextEncodeQwenImage21": + images = [s for s in node.get("inputs", []) if s["name"].startswith("images.")] + if ( + [s["name"] for s in images] != [f"images.image_{i}" for i in range(1, len(images) + 1)] + or not images + or any(s.get("link") is None for s in images[:-1]) + or images[-1].get("link") is not None + ): + raise ValueError("autogrow只覆盖连续已连接输入及末尾空槽") + return result diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py index af6e4655..596205ed 100644 --- a/calliope-backend/src/calliope/comfyui/structure_reference.py +++ b/calliope-backend/src/calliope/comfyui/structure_reference.py @@ -44,7 +44,9 @@ def _uuid(value): return False -def expand_reference_subgraphs(source: dict, profile: str, *, widgets: bool = False) -> Structure: +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 @@ -52,15 +54,17 @@ def expand_reference_subgraphs(source: dict, profile: str, *, widgets: bool = Fa returns no graph, including malformed unused branches/definitions. """ try: - return _expand(source, profile, widgets) + 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): +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"] @@ -244,7 +248,20 @@ def _expand(source, profile, widgets=False): resolved = [] if widgets: - from .serialization_reference import direct_widget_type, validate_direct_value + 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) @@ -260,7 +277,7 @@ def _expand(source, profile, widgets=False): found.extend(targets(target["type"], edge[4], stack + (marker,))) elif socket.get("widget") is not None: try: - kind = direct_widget_type(target, socket, version) + kind = widget_type(target, socket) except ValueError: kind = None found.append((target, socket, kind)) @@ -301,6 +318,8 @@ def _expand(source, profile, widgets=False): 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: @@ -357,8 +376,10 @@ def _expand(source, profile, widgets=False): value = values[slot] if not value["compatible"]: raise ValueError("多目标控件约束未知或不兼容") - kind = direct_widget_type(node, socket, version) + 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 diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index 17e0a229..b99727d0 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -15,13 +15,16 @@ from typing import Any from .serialization_reference import ( AUX_PROFILE, + CASE04_PROFILE, PREVIEW_PROFILE, PRIMITIVE_PROFILE, PROFILE, + case04_definitions, fold_reference_primitives, promoted_definitions, reference_definitions, resolve_reference_link, + serialize_case04_node, serialize_promoted_node, serialize_reference_widgets, validate_reroute, @@ -37,6 +40,7 @@ class Conversion: diagnostic_graph: dict[str, Any] | None = None 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 def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion: @@ -56,6 +60,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: AUX_PROFILE, PRIMITIVE_PROFILE, PREVIEW_PROFILE, + CASE04_PROFILE, *STRUCTURE_PROFILES, *PROMOTED_PROFILES, ) @@ -68,17 +73,24 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: True, ) try: - if profile in (*STRUCTURE_PROFILES, *PROMOTED_PROFILES): - promoted = profile in PROMOTED_PROFILES - structure_profile = profile.replace("-promoted-reference", "-structure-reference") - structure = expand_reference_subgraphs(source, structure_profile, widgets=promoted) + if profile in (*STRUCTURE_PROFILES, *PROMOTED_PROFILES, CASE04_PROFILE): + case04 = profile == CASE04_PROFILE + promoted = profile in PROMOTED_PROFILES or case04 + structure_profile = ( + "comfy-frontend-1.53.6-structure-reference" + if case04 + else profile.replace("-promoted-reference", "-structure-reference") + ) + structure = expand_reference_subgraphs( + source, structure_profile, widgets=promoted, case04=case04 + ) 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, - promoted_definitions() if promoted else {}, + case04_definitions() if case04 else promoted_definitions() if promoted else {}, reference=True, reference_profile=profile, boundary_values=structure.resolved, @@ -97,6 +109,8 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: if not promoted or result.issues: result.prompt = None result.reference_only = True + if case04: + result.serialization_stage = "restored_saved_state_before_queue_hooks" result.diagnostic_graph = structure.graph result.unresolved_boundaries = structure.unresolved result.resolved_boundaries = structure.resolved @@ -172,9 +186,11 @@ def _convert( links[str(link[0])] = link if reference: frontend_version = (source.get("extra") or {}).get("frontendVersion") - expected_version = {**STRUCTURE_PROFILES, **PROMOTED_PROFILES}.get( - reference_profile, "1.37.11" - ) + expected_version = { + **STRUCTURE_PROFILES, + **PROMOTED_PROFILES, + CASE04_PROFILE: "1.53.6", + }.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 @@ -228,7 +244,9 @@ def _convert( if reference: try: inputs.update( - serialize_promoted_node(node, PROMOTED_PROFILES[reference_profile]) + serialize_case04_node(node) + if reference_profile == CASE04_PROFILE + else serialize_promoted_node(node, PROMOTED_PROFILES[reference_profile]) if reference_profile in PROMOTED_PROFILES else serialize_reference_widgets(node, reference_profile) ) @@ -294,7 +312,7 @@ def _convert( # Custom unions/wildcards need frontend evidence; do not guess coercions. if expected != actual and not ( reference - and reference_profile == PREVIEW_PROFILE + and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE) and ct == "PreviewAny" and name == "source" and expected == "*" diff --git a/calliope-backend/tests/test_case04_saved_reference.py b/calliope-backend/tests/test_case04_saved_reference.py new file mode 100644 index 00000000..8a9367be --- /dev/null +++ b/calliope-backend/tests/test_case04_saved_reference.py @@ -0,0 +1,266 @@ +"""Real source/API comparison and synthetic mutations; no upstream code execution.""" + +import json +from copy import deepcopy +from pathlib import Path + +import pytest + +from calliope.comfyui.serialization_reference import CASE04_PROFILE +from calliope.comfyui.ui2api import convert, convert_reference +from tests.test_promoted_preview_reference import fixture, real + + +def node(source, nid): + rows = source["nodes"] + source["definitions"]["subgraphs"][0]["nodes"] + return next(n for n in rows if n["id"] == nid) + + +def edit(source, nid, name, value): + n = node(source, nid) + names = list(n["widgets_values_named"]) + n["widgets_values"][names.index(name)] = value + n["widgets_values_named"][name] = value + + +def candidate(source): + return convert_reference(source, CASE04_PROFILE) + + +def test_real_complete_saved_state_keeps_api_differences_and_all_types(): + source = real("04") + before = deepcopy(source) + result = candidate(source) + assert result.prompt is not None and result.reference_only + assert result.serialization_stage == "restored_saved_state_before_queue_hooks" + repo = Path(__file__).resolve().parents[2] + api = json.loads((repo / "docs/hel-892/supplied-api/04.api.json").read_bytes()) + assert result.prompt.keys() == api.keys() + for nid, expected in api.items(): + actual = result.prompt[nid] + assert actual["class_type"] == expected["class_type"] + assert actual["inputs"].keys() == expected["inputs"].keys() + for name, value in expected["inputs"].items(): + got = actual["inputs"][name] + assert type(got) is type(value) + if (nid, name) in (("459:451", "unet_name"), ("459:473", "clip_name")): + assert got != value and got.replace("\\", "/") == value + else: + assert got == value + assert "control_after_generate" not in result.prompt["459:458"]["inputs"] + assert set(result.prompt["459:472"]["inputs"]) == {"source"} + assert "preview" not in result.prompt["13"]["inputs"] + assert source == before and convert(source).prompt is None + assert convert_reference(source, "comfy-frontend-1.53.6-structure-reference").prompt is None + assert convert_reference(source, "comfy-frontend-1.53.6-promoted-reference").prompt is None + + +@pytest.mark.parametrize("value", [0, 1, 987654321, 2**53 - 1]) +def test_host_seed_changes_both_typed_targets_with_original_pointers(value): + source = real("04") + edit(source, 459, "seed", value) + # Internal seeds differ deliberately; the host is authoritative. + edit(source, 458, "seed", 111) + edit(source, 471, "sampling_mode.seed", 222) + result = candidate(source) + assert result.prompt is not None + assert result.prompt["459:458"]["inputs"]["seed"] == value + assert result.prompt["459:471"]["inputs"]["sampling_mode.seed"] == value + for row in result.resolved_boundaries: + if row["input_name"] in ("seed", "sampling_mode.seed"): + assert row["value_pointer"] == "/nodes/1/widgets_values/10" + assert row["named_value_pointer"] == "/nodes/1/widgets_values_named/seed" + + +@pytest.mark.parametrize("mode", ["increment", "decrement", "randomize", "bogus", None]) +def test_nonfixed_control_never_becomes_a_fabricated_queue_seed(mode): + source = real("04") + edit(source, 458, "control_after_generate", mode) + result = candidate(source) + assert result.prompt is None and result.issues + assert any("fixed" in x.get("message", "") for x in result.issues) + + +@pytest.mark.parametrize("value", [-1, 2**53, 2**64, 10**400, True, None, "10", 1.25]) +def test_host_seed_bad_domain_or_js_precision_closes_whole_graph(value): + source = real("04") + edit(source, 459, "seed", value) + result = candidate(source) + assert result.prompt is None and result.unresolved_boundaries + + +@pytest.mark.parametrize( + "nid,name,value", + [ + (13, "megapixels", 17), + (13, "aspect_ratio", "invented"), + (458, "steps", 0), + (458, "denoise", 2), + (458, "sampler_name", "invented"), + (471, "sampling_mode.top_k", True), + (471, "sampling_mode.temperature", 0), + (471, "sampling_mode.top_p", float("inf")), + (471, "max_length", 32769), + (471, "sampling_mode", "off"), + (471, "mtp", "invented"), + (461, "format", "avif"), + (461, "format.bit_depth", "32-bit float"), + (461, "filename_prefix", "%date:yyyy%"), + (452, "prompt", "{a|b}"), + (452, "negative_prompt", "// comment"), + (480, "dtype", "fp99"), + ], +) +def test_static_constraints_and_uncovered_dynamic_behaviors_fail_closed(nid, name, value): + source = real("04") + edit(source, nid, name, value) + assert candidate(source).prompt is None + + +@pytest.mark.parametrize( + "nid,name,value", + [ + (13, "megapixels", 2.5), + (458, "denoise", 0.25), + (471, "sampling_mode.temperature", 0.5), + (471, "sampling_mode.top_k", 77), + (461, "format.bit_depth", "16-bit"), + (461, "filename_prefix", "offline/changed"), + ], +) +def test_proven_scalar_changes_are_serialized_without_api_constants(nid, name, value): + source = real("04") + edit(source, nid, name, value) + result = candidate(source) + key = str(nid) if nid in (13, 461) else f"459:{nid}" + assert result.prompt[key]["inputs"][name] == value + assert type(result.prompt[key]["inputs"][name]) is type(value) + + +@pytest.mark.parametrize( + "mutation", + [ + "provider", + "version", + "extra_widget", + "missing_widget", + "named_conflict", + "bad_binding", + "missing_socket", + "serializer", + "duplicate_socket", + "extra_dynamic", + "extra_control", + "autogrow_name", + "frontend", + "fanout_conflict", + ], +) +def test_unknown_layout_bindings_and_fanout_configs_never_return_partial_graph(mutation): + source = real("04") + target = node(source, 471) + if mutation in ("provider", "version"): + target["properties"]["cnr_id" if mutation == "provider" else "ver"] = "unknown" + elif mutation == "extra_widget": + target["widgets_values"].append(None) + elif mutation == "missing_widget": + target["widgets_values"].pop() + elif mutation == "named_conflict": + target["widgets_values_named"]["max_length"] = 12 + elif mutation == "bad_binding": + target["inputs"][13]["widget"]["name"] = "seed" + elif mutation == "missing_socket": + target["inputs"].pop() + elif mutation == "serializer": + target["serializeValue"] = "unknown" + elif mutation == "duplicate_socket": + target["inputs"].append(deepcopy(target["inputs"][-1])) + elif mutation == "extra_dynamic": + target["inputs"].append({"name": "sampling_mode.fake", "type": "INT", "link": None}) + elif mutation == "extra_control": + target["widgets_values"].insert(9, "fixed") + elif mutation == "autogrow_name": + node(source, 452)["inputs"][1]["name"] = "images.image_17" + elif mutation == "frontend": + source["extra"]["frontendVersion"] = "1.53.7" + elif mutation == "fanout_conflict": + # Redirect seed's second binding to top_k (same INT, different range). + edge = next(e for e in source["definitions"]["subgraphs"][0]["links"] if e["id"] == 697) + target["inputs"][13]["link"] = None + target["inputs"][9]["link"] = 697 + edge["target_slot"] = 9 + result = candidate(source) + assert result.prompt is None and result.issues + + +def test_external_seed_link_wins_over_invalid_stored_host_scalar(): + source = real("04") + # ResolutionSelector.width is INT. This is a synthetic link, not generation. + source["links"].append([9999, 13, 0, 459, 10, "INT"]) + node(source, 13)["outputs"][0]["links"].append(9999) + node(source, 459)["inputs"][10]["link"] = 9999 + edit(source, 459, "seed", None) + result = candidate(source) + assert result.prompt["459:458"]["inputs"]["seed"] == ["13", 0] + assert result.prompt["459:471"]["inputs"]["sampling_mode.seed"] == ["13", 0] + + +def test_model_file_string_remains_dynamic_availability_unknown(): + source = real("04") + edit(source, 459, "unet_name", "not-installed.safetensors") + assert candidate(source).prompt["459:451"]["inputs"]["unet_name"] == "not-installed.safetensors" + edit(source, 451, "weight_dtype", "not-a-static-option") + assert candidate(source).prompt is None + + +def test_multiple_instance_host_values_do_not_cross(): + source = fixture("one") + second = deepcopy(source["nodes"][0]) + second["id"] = 6 + second["widgets_values"] = ["two"] + source["nodes"].append(second) + result = candidate(source) + assert result.prompt["5:3"]["inputs"]["value"] == "one" + assert result.prompt["6:3"]["inputs"]["value"] == "two" + + +def test_nested_hosts_and_same_name_root_keep_distinct_values(): + source = fixture("outer") + outer = source["definitions"]["subgraphs"][0] + nested = deepcopy(outer) + nested["id"] = "aaaaaaaa-bbbb-cccc-dddd-ffffffffffff" + host = deepcopy(source["nodes"][0]) + host.update(id=3, type=nested["id"], widgets_values=["inner"]) + host["inputs"][0]["link"] = 10 + host["outputs"][0]["links"] = [11] + outer["nodes"] = [host] + source["definitions"]["subgraphs"].append(nested) + root = deepcopy(nested["nodes"][0]) + root["id"] = 9 + root["inputs"][0]["link"] = None + root["outputs"][0]["links"] = [] + root["widgets_values"] = ["root"] + source["nodes"].append(root) + result = candidate(source) + assert result.prompt["5:3:3"]["inputs"]["value"] == "outer" + assert result.prompt["9"]["inputs"]["value"] == "root" + + +def test_boundary_raw_text_bypasses_internal_dynamic_serializer(): + source = real("04") + edit(source, 459, "negative_prompt", "{kept|raw}") + result = candidate(source) + assert result.prompt["459:452"]["inputs"]["negative_prompt"] == "{kept|raw}" + + +def test_seed_fanout_order_selects_source_without_equating_controller_construction(): + source = real("04") + definition = source["definitions"]["subgraphs"][0] + boundary = next(s for s in definition["inputs"] if s["name"] == "seed") + boundary["linkIds"].reverse() + edit(source, 459, "seed", 12345) + result = candidate(source) + assert result.prompt["459:458"]["inputs"]["seed"] == 12345 + assert result.prompt["459:471"]["inputs"]["sampling_mode.seed"] == 12345 + edit(source, 458, "control_after_generate", "randomize") + assert candidate(source).prompt is None # conservative even if non-first source