diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index 6d816e4..b7b5f18 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -43,0 +44 @@ from calliope.comfyui.structure_reference import ( + H3_PROFILE, @@ -307,0 +309 @@ REFERENCE_PROFILES = ( + H3_PROFILE, @@ -342 +344,3 @@ def node_inventory(source, *, include_aux=False): - "widget_count": len(node.get("widgets_values", [])), + "widget_count": len(node["widgets_values"]) + if isinstance(node.get("widgets_values"), (list, dict)) + else 0, @@ -553,0 +558,46 @@ def grid_field_evidence(source, prompt): +def h3_field_evidence(source, prompt): + """Exact typed dual-save pointers or physical links; no generated text.""" + from calliope.comfyui.serialization_reference import H3_CHECK_LAYOUT, H3_WRITER_LAYOUT + + fields = [] + for i, node in enumerate(source["nodes"]): + nid = str(node["id"]) + layout = H3_WRITER_LAYOUT if node["type"] == "MiniMaxH3GuidedWriter" else H3_CHECK_LAYOUT + for name, value in prompt[nid]["inputs"].items(): + socket = next((s for s in node["inputs"] if s["name"] == name), {}) + pointers = [] + shadowed = [] + if socket.get("link") is not None: + j, edge = next( + (j, e) for j, e in enumerate(source["links"]) if e[0] == socket["link"] + ) + expected, pointer = [str(edge[1]), edge[2]], f"/links/{j}" + if name in layout and name in node.get("widgets_values_named", {}): + shadowed = [ + f"/nodes/{i}/widgets_values/{layout.index(name)}", + f"/nodes/{i}/widgets_values_named/{name}", + ] + else: + w = layout.index(name) + expected, pointer = node["widgets_values"][w], f"/nodes/{i}/widgets_values/{w}" + pointers = [f"/nodes/{i}/widgets_values_named/{name}"] + assert type(value) is type(expected) and value == expected + fields.append( + { + "node_id": nid, + "field": name, + "value": value, + "json_type": type(value).__name__, + "source_pointer": pointer, + "corroborating_pointers": pointers, + "shadowed_saved_pointers": shadowed, + "class_pointer": f"/nodes/{i}/type", + "title_pointer": f"/nodes/{i}/title" + if node.get("title") + else f"/nodes/{i}/type", + "contract_manifest": "h3-reference/sources.json", + } + ) + return fields + + @@ -559,0 +610 @@ def profile_attempt(source, profile): + H3_PROFILE: "1.53.10", @@ -739,0 +791,7 @@ def profile_attempt(source, profile): + if profile == H3_PROFILE: + assumptions["h3_contract"] = "h3-reference/sources.json" + assumptions["reference_sources"] = ["h3-reference/sources.json"] + assumptions["core_version"] = "0.30.0" + assumptions["h3_commit"] = "a59888df88a69385d429b6865ea441e7844f49c9" + assumptions["restoration_policy"] = "named_and_positional_exact_typed_agreement" + assumptions["model_library_and_inference"] = "not_checked_or_executed" @@ -841 +899,3 @@ def profile_attempt(source, profile): - {"field_evidence": grid_field_evidence(source, result.prompt)} + {"field_evidence": h3_field_evidence(source, result.prompt)} + if profile == H3_PROFILE + else {"field_evidence": grid_field_evidence(source, result.prompt)} @@ -959 +1019,3 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= - (GRID_PROFILE,) + (H3_PROFILE,) + if H3_PROFILE in profiles + else (GRID_PROFILE,) diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index 1e0b06a..862eab5 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -18,0 +19 @@ from .structure_reference import ( + H3_PROFILE, @@ -99,0 +101,185 @@ _LAYOUTS = { +H3_COMMIT = "a59888df88a69385d429b6865ea441e7844f49c9" +# INPUT_TYPES required then optional order, with the seed's linked control. +# Frontend1.53.10 separates widget.serialize (workflow) from options.serialize +# (prompt). Only the linked control is workflow-only in this saved layout. +H3_WRITER_LAYOUT = ( + "prompt", + "model", + "task", + "resolution", + "duration", + "greedy", + "seed", + "control_after_generate", + "keep_model_loaded", + "aspect_ratio", + "reference_material", + "bypass", + "system_prompt", + "repeat_last", + "library_pick", +) +H3_CHECK_LAYOUT = ("prompt", "task", "duration") + + +def h3_definitions(): + """Fixed sources in h3-reference; not a production node registration.""" + + def spec(required, optional, outputs): + return { + "input": { + "required": {k: [v] for k, v in required.items()}, + "optional": {k: [v] for k, v in optional.items()}, + }, + "output": outputs, + } + + return { + "MiniMaxH3GuidedWriter": spec( + dict( + prompt="STRING", + model="COMBO", + task="COMBO", + resolution="COMBO", + duration="INT", + greedy="BOOLEAN", + seed="INT", + keep_model_loaded="BOOLEAN", + ), + { + "aspect_ratio": "STRING,COMBO", + "reference_material": "STRING", + "options": "H3_REWRITER_OPTIONS", + "bypass": "BOOLEAN", + "system_prompt": "STRING", + "repeat_last": "BOOLEAN", + "library_pick": "STRING", + }, + ["STRING"] * 4, + ), + "MiniMaxH3PromptCheck": spec( + dict(prompt="STRING", task="COMBO", duration="FLOAT"), + {"options": "H3_REWRITER_OPTIONS", "references.ref_0": "IMAGE,VIDEO,AUDIO"}, + ["STRING"] * 9, + ), + "PreviewAny": spec({"source": "*"}, {}, ["STRING"]), + } + + +def serialize_h3_node(node): + """Conservative intersection of named/positional restoration, saved state. + + No dynamic model enumeration, library lookup, queue hook, check or inference + runs. Conflicting saves are rejected even if a particular named-restore + setting might choose one: that setting is not supplied by the source graph. + """ + ct, props = node.get("type"), node.get("properties") or {} + defs = h3_definitions() + if ct not in defs: + raise ValueError("H3固定参考未覆盖节点") + provider, version = ( + ("comfy-core", "0.30.0") + if ct == "PreviewAny" + else ("minimax-h3-prompt-rewriter", H3_COMMIT) + ) + if props.get("cnr_id") != provider or props.get("ver") != version or "aux_id" in props: + raise ValueError("H3需要精确提供方/完整提交或core0.30.0;身份声明冲突") + if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0: + raise ValueError("H3仅正常mode=0") + for container in (node, props): + if any( + k in container + for k in ( + "ue_properties", + "widget_ue_connectable", + "input_ue_unconnectable", + "widgets", + "serializeValue", + "comfyDynamic", + "onConfigure", + "onSerialize", + "getInputLink", + "resolveInput", + "resolveOutput", + "onExecute", + "isVirtualNode", + "applyToGraph", + "beforeQueued", + "afterQueued", + ) + ): + raise ValueError("H3不解释未知UE或序列化/恢复钩子覆盖") + layout = ( + H3_WRITER_LAYOUT + if ct == "MiniMaxH3GuidedWriter" + else (H3_CHECK_LAYOUT if ct == "MiniMaxH3PromptCheck" else ()) + ) + values, named = node.get("widgets_values"), node.get("widgets_values_named") + if not isinstance(values, list) or len(values) != len(layout): + raise ValueError("H3保存数组缺项/多项或布局未证明") + if not isinstance(named, dict) or set(named) != set(layout): + raise ValueError("H3要求完整具名保存;缺项/多项不能选择恢复路径") + for name, value in zip(layout, values): + if type(named[name]) is not type(value) or named[name] != value: + raise ValueError(f"H3具名与位置恢复冲突:{name}") + out = dict(zip(layout, values)) + strings = { + "prompt", + "model", + "task", + "resolution", + "aspect_ratio", + "reference_material", + "system_prompt", + "library_pick", + "control_after_generate", + } + for name, value in out.items(): + valid = ( + type(value) is str + if name in strings + else ( + type(value) is bool + if name in ("greedy", "keep_model_loaded", "bypass", "repeat_last") + else type(value) is int + if name in ("seed",) or (name == "duration" and ct == "MiniMaxH3GuidedWriter") + else type(value) in (int, float) and math.isfinite(value) + ) + ) + if not valid: + raise ValueError(f"H3保存类型不符:{name}") + if ct != "PreviewAny": + tasks = ("T2VA", "I2VA", "FL2VA", "L2VA") + if ct == "MiniMaxH3PromptCheck": + tasks += ("Ref2VA",) + if out["task"] not in tasks: + raise ValueError("H3 task枚举不符") + low, high = (4, 15) if ct == "MiniMaxH3GuidedWriter" else (0.1, 600) + if not low <= out["duration"] <= high: + raise ValueError("H3 duration超出固定schema范围") + if ct == "MiniMaxH3GuidedWriter": + if out["resolution"] not in ("48:9", "32:9", "21:9", "16:9", "4:3", "1:1", "3:4", "9:16"): + raise ValueError("H3 resolution枚举不符") + if not out["model"]: + raise ValueError("H3动态model只能保留非空显示字符串,选项与文件可用性未知") + if not 0 <= out["seed"] <= 0xFFFFFFFF or out["control_after_generate"] != "fixed": + raise ValueError("H3只证明fixed且范围内的seed不变保存态") + out.pop("control_after_generate") + declared = {**defs[ct]["input"]["required"], **defs[ct]["input"]["optional"]} + sockets = node.get("inputs", []) + names = [s.get("name") for s in sockets] + if len(names) != len(set(names)) or set(names) - set(declared): + raise ValueError("H3未知/重复输入或未覆盖的autogrow槽") + for socket in sockets: + expected = declared[socket["name"]][0] + if socket.get("type") != expected: + raise ValueError("H3输入类型/联合槽与schema不符") + widget = socket.get("widget") + if widget is not None and widget != {"name": socket["name"]}: + raise ValueError("H3控件绑定不符") + # socketless resolution cannot be converted to a wire under this schema. + if socket["name"] == "resolution": + raise ValueError("H3 resolution为socketless展示选择") + return out + + @@ -304,0 +491,2 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: + if profile == H3_PROFILE: + return h3_definitions() @@ -388,0 +577,2 @@ def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> + if profile == H3_PROFILE: + return serialize_h3_node(node) diff --git a/calliope-backend/src/calliope/comfyui/structure_reference.py b/calliope-backend/src/calliope/comfyui/structure_reference.py index 2e7512b..748ab47 100644 --- a/calliope-backend/src/calliope/comfyui/structure_reference.py +++ b/calliope-backend/src/calliope/comfyui/structure_reference.py @@ -16,0 +17 @@ 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" @@ -809 +810 @@ def _expand(source, profile, widgets=False, case04=False): -def validate_grid_structure(source): +def validate_grid_structure(source, *, frontend="1.41.20", preview_any=False): @@ -815,2 +816,7 @@ def validate_grid_structure(source): - if (source.get("extra") or {}).get("frontendVersion") != "1.41.20": - raise ValueError("四宫格参考需要显式前端1.41.20") + 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}" + ) @@ -818 +824 @@ def validate_grid_structure(source): - raise ValueError("四宫格参考不覆盖子图") + raise ValueError(f"{scope}参考不覆盖子图") @@ -821 +827 @@ def validate_grid_structure(source): - raise ValueError("四宫格只覆盖LG保存态") + raise ValueError(f"{scope}只覆盖LG保存态") @@ -824 +830 @@ def validate_grid_structure(source): - raise ValueError("四宫格参考只覆盖空UE连线数组") + raise ValueError(f"{scope}参考只覆盖空UE连线数组") @@ -832 +838 @@ def validate_grid_structure(source): - raise ValueError("四宫格仅正常mode=0") + raise ValueError(f"{scope}仅正常mode=0") @@ -840 +846 @@ def validate_grid_structure(source): - raise ValueError("四宫格只接受六字段连线") + raise ValueError(f"{scope}只接受六字段连线") @@ -853,0 +860,2 @@ def validate_grid_structure(source): + if preview_any and nodes[b].get("type") == "PreviewAny": + accepted = typ == origin.get("type") == "STRING" and target.get("type") == "*" @@ -886 +894 @@ def validate_grid_structure(source): - raise ValueError("四宫格参考不支持环") + raise ValueError(f"{scope}参考不支持环") diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index 43ce5bc..4993c95 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -39,0 +40 @@ from .structure_reference import ( + H3_PROFILE, @@ -77,0 +79 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: + H3_PROFILE, @@ -103,0 +106,13 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: + if profile == H3_PROFILE: + validate_grid_structure(source, frontend="1.53.10", preview_any=True) + if any(n.get("type") not in reference_definitions(H3_PROFILE) for n in source["nodes"]): + raise ValueError("H3只覆盖两类固定插件实体与core0.30.0 PreviewAny") + if any( + k in source or k in (source.get("extra") or {}) + for k in ( + "ue_properties", + "widget_ue_connectable", + "input_ue_unconnectable", + ) + ): + raise ValueError("H3未知整图UE覆盖") @@ -221 +236 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: - if profile == GRID_PROFILE: + if profile in (GRID_PROFILE, H3_PROFILE): @@ -225,0 +241 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: + H3_PROFILE, @@ -244 +260 @@ def _convert( - if reference and reference_profile == GRID_PROFILE: + if reference and reference_profile in (GRID_PROFILE, H3_PROFILE): @@ -303,0 +320 @@ def _convert( + H3_PROFILE: "1.53.10", @@ -452 +469 @@ def _convert( - and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE) + and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE, H3_PROFILE) diff --git a/calliope-backend/tests/test_audio_separation_reference.py b/calliope-backend/tests/test_audio_separation_reference.py index 324bd32..ee8b49c 100644 --- a/calliope-backend/tests/test_audio_separation_reference.py +++ b/calliope-backend/tests/test_audio_separation_reference.py @@ -372,0 +373 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari + audit.H3_PROFILE, diff --git a/calliope-backend/tests/test_crop_split_reference.py b/calliope-backend/tests/test_crop_split_reference.py index bdbed6f..e2a9715 100644 --- a/calliope-backend/tests/test_crop_split_reference.py +++ b/calliope-backend/tests/test_crop_split_reference.py @@ -363,0 +364 @@ def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged() + audit.H3_PROFILE, diff --git a/calliope-backend/tests/test_grid_reference.py b/calliope-backend/tests/test_grid_reference.py index 270f780..319af04 100644 --- a/calliope-backend/tests/test_grid_reference.py +++ b/calliope-backend/tests/test_grid_reference.py @@ -340,2 +340,6 @@ def test_fixed_sources_and_original_profile_cohorts_remain_identical(): - assert len(profiles) == 24 and tuple(audit.REFERENCE_PROFILES[:-1]) == profiles - current = audit.audit_library(REPO, baseline_profiles=profiles) + assert ( + len(profiles) == 24 + and tuple(p for p in audit.REFERENCE_PROFILES if p not in (GRID_PROFILE, audit.H3_PROFILE)) + == profiles + ) + current = audit.audit_library(REPO, (*profiles, GRID_PROFILE), baseline_profiles=profiles) diff --git a/calliope-backend/tests/test_h3_reference.py b/calliope-backend/tests/test_h3_reference.py new file mode 100644 index 0000000..ac681f8 --- /dev/null +++ b/calliope-backend/tests/test_h3_reference.py @@ -0,0 +1,330 @@ +"""Offline H3 saved-state contracts; never execute plugins or inspect local models.""" + +import copy +import hashlib +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.serialization_reference import H3_COMMIT, serialize_h3_node +from calliope.comfyui.structure_reference import H3_PROFILE +from calliope.comfyui.ui2api import convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +PATH = next((REPO / "example_ComfyUI_workflows").rglob("Minimax-H3提示词增强.json")) + + +def graph(): + return json.loads(PATH.read_bytes()) + + +def node(g, nid): + return next(n for n in g["nodes"] if n["id"] == nid) + + +def put(g, nid, field, value): + n = node(g, nid) + i = list(n["widgets_values_named"]).index(field) + n["widgets_values"][i] = value + n["widgets_values_named"][field] = value + + +def closed(g): + before = copy.deepcopy(g) + r = convert_reference(g, H3_PROFILE) + assert r.prompt is None and r.issues and r.reference_only and g == before + assert all(i.get("pointer") is not None for i in r.issues) + a = audit.profile_attempt(g, H3_PROFILE) + assert a["status"] in ("rejected", "not_applicable") + assert "candidate_prompt" not in a + + +def test_real_source_complete_four_entities_saved_state_only(): + assert hashlib.sha256(PATH.read_bytes()).hexdigest() == ( + "ffea53b27d52c63aa9ec9c60144489cc4f9e5a44d9478bcc297be9d9008f1a4c" + ) + g = graph() + before = copy.deepcopy(g) + r = convert_reference(g, H3_PROFILE) + assert r.prompt is not None, r.issues + assert r.reference_only and g == before and convert(g).prompt is None + assert set(r.prompt) == {"169", "170", "171", "172"} + assert r.serialization_stage == "restored_saved_state_before_queue_hooks" + writer = r.prompt["169"]["inputs"] + assert len(writer) == 14 and "control_after_generate" not in writer + assert writer["seed"] == 42 and writer["duration"] == 10 + assert writer["model"] == node(g, 169)["widgets_values_named"]["model"] + assert writer["prompt"] == node(g, 169)["widgets_values_named"]["prompt"] + assert r.prompt["170"]["inputs"] == {"prompt": ["169", 0], "task": "T2VA", "duration": 5} + assert r.prompt["171"]["inputs"] == {"source": ["170", 0]} + assert r.prompt["172"]["inputs"] == {"source": ["170", 8]} + fields = audit.h3_field_evidence(g, r.prompt) + assert len(fields) == 19 + assert sum(f["json_type"] == "list" for f in fields) == 3 + shadowed = next(f for f in fields if f["node_id"] == "170" and f["field"] == "prompt") + assert shadowed["shadowed_saved_pointers"] == [ + "/nodes/1/widgets_values/0", + "/nodes/1/widgets_values_named/prompt", + ] + assert all(f["corroborating_pointers"] for f in fields if f["json_type"] != "list") + a = audit.profile_attempt(g, H3_PROFILE) + assert a["candidate_sha256"] == audit.canonical_sha(r.prompt) + assert a["assumptions"]["target_version_match"] == "unknown" + + +@pytest.mark.parametrize( + "field,value", + [ + ("model", "opaque model display string, no file lookup"), + ("prompt", "opaque\ntext\u0000中文"), + ("system_prompt", "opaque-system"), + ("reference_material", "opaque-reference"), + ("aspect_ratio", "opaque-ratio"), + ("library_pick", '{"file":"not-read.json","id":"unresolved"}'), + ("repeat_last", True), + ("bypass", True), + ("keep_model_loaded", True), + ("greedy", False), + ("seed", 0), + ("seed", 4294967295), + ("duration", 4), + ("duration", 15), + ("task", "I2VA"), + ("task", "FL2VA"), + ("task", "L2VA"), + ("resolution", "9:16"), + ], +) +def test_writer_instance_changes_propagate_without_interpreting_text_or_running(field, value): + g = graph() + put(g, 169, field, value) + r = convert_reference(g, H3_PROFILE) + assert r.prompt is not None, r.issues + actual = r.prompt["169"]["inputs"][field] + assert type(actual) is type(value) and actual == value + assert r.prompt["170"]["inputs"]["prompt"] == ["169", 0] + + +@pytest.mark.parametrize( + "field,value", + [ + ("task", "Ref2VA"), + ("duration", 0.1), + ("duration", 600.0), + ("duration", 7.5), + ("prompt", "saved value overridden by physical edge"), + ], +) +def test_check_float_and_union_placeholder_are_not_synthetic_media(field, value): + g = graph() + put(g, 170, field, value) + r = convert_reference(g, H3_PROFILE) + assert r.prompt is not None, r.issues + assert r.prompt["170"]["inputs"][field] == (["169", 0] if field == "prompt" else value) + assert "options" not in r.prompt["170"]["inputs"] + assert "references.ref_0" not in r.prompt["170"]["inputs"] + + +@pytest.mark.parametrize( + "nid,field,value", + [ + (169, "seed", True), + (169, "seed", 42.0), + (169, "seed", -1), + (169, "seed", 4294967296), + (169, "greedy", 1), + (169, "bypass", "false"), + (169, "duration", 10.0), + (169, "duration", 3), + (169, "duration", 16), + (169, "duration", "10"), + (169, "model", ""), + (169, "model", None), + (169, "reference_material", []), + (169, "library_pick", {}), + (169, "task", "Ref2VA"), + (169, "resolution", "1920x1080"), + (169, "control_after_generate", "increment"), + (169, "control_after_generate", "decrement"), + (169, "control_after_generate", "randomize"), + (169, "control_after_generate", None), + (170, "task", "unknown"), + (170, "duration", 0), + (170, "duration", 600.1), + (170, "duration", True), + (170, "duration", float("inf")), + ], +) +def test_types_ranges_enums_and_unproved_queue_controls_close_whole_graph(nid, field, value): + g = graph() + put(g, nid, field, value) + closed(g) + + +@pytest.mark.parametrize("nid", [169, 170, 171, 172]) +@pytest.mark.parametrize( + "mutation", ["provider", "version", "aux", "mode", "ue", "hook", "extra-output"] +) +def test_registration_identity_modes_hooks_and_output_schemas_are_exact(nid, mutation): + g = graph() + n = node(g, nid) + if mutation == "provider": + n["properties"]["cnr_id"] = "same-named-other-plugin" + elif mutation == "version": + n["properties"]["ver"] = "0.18.6" if nid < 171 else "0.38.0" + elif mutation == "aux": + n["properties"]["aux_id"] = "pytraveler/MiniMax-H3-Prompt-Rewriter-ComfyUI" + elif mutation == "mode": + n["mode"] = 4 + elif mutation == "ue": + n["properties"]["ue_properties"] = {"version": "7.7"} + elif mutation == "hook": + n["serializeValue"] = "unknown" + else: + n["outputs"].append({"type": "STRING", "links": None}) + closed(g) + + +@pytest.mark.parametrize("nid", [169, 170, 171, 172]) +@pytest.mark.parametrize( + "mutation", ["short", "long", "named-missing", "named-extra", "missing-map"] +) +def test_dual_save_layout_is_required_even_for_empty_preview(nid, mutation): + g = graph() + n = node(g, nid) + if mutation == "short": + n["widgets_values"] = n["widgets_values"][:-1] if nid < 171 else None + elif mutation == "long": + n["widgets_values"].append("unexpected") + elif mutation == "named-missing": + if n["widgets_values_named"]: + n["widgets_values_named"].pop(next(iter(n["widgets_values_named"]))) + else: + n["widgets_values_named"] = None + elif mutation == "named-extra": + n["widgets_values_named"]["preview"] = "legacy" + else: + n.pop("widgets_values_named") + closed(g) + + +@pytest.mark.parametrize("field", ["prompt", "seed", "library_pick", "control_after_generate"]) +def test_named_positional_conflicts_are_not_resolved_by_precedence_guess(field): + g = graph() + node(g, 169)["widgets_values_named"][field] = "conflict" + closed(g) + + +def test_synthetic_instance_replacement_and_nonzero_check_slot_propagate(): + g = graph() + node(g, 169)["id"] = 900 + g["links"][0][1] = 900 + g["links"][2][2] = 7 + node(g, 170)["outputs"][8]["links"] = None + node(g, 170)["outputs"][7]["links"] = [338] + r = convert_reference(g, H3_PROFILE) + assert r.prompt is not None, r.issues + assert "169" not in r.prompt + assert r.prompt["170"]["inputs"]["prompt"] == ["900", 0] + assert r.prompt["172"]["inputs"]["source"] == ["170", 7] + + +@pytest.mark.parametrize( + "mutation", + [ + "frontend", + "missing-frontend", + "input-type", + "union-type", + "duplicate-input", + "bad-output-type", + "bad-slot", + "bad-edge-type", + "duplicate-link", + "dangling", + "cycle", + "subgraph", + "root-ue", + "unknown-node", + "unknown-ref", + "bad-widget", + ], +) +def test_unproven_structure_and_physical_types_fail_closed(mutation): + g = graph() + if mutation == "frontend": + g["extra"]["frontendVersion"] = "1.53.6" + elif mutation == "missing-frontend": + g["extra"].pop("frontendVersion") + elif mutation == "input-type": + node(g, 170)["inputs"][2]["type"] = "FLOAT" + elif mutation == "union-type": + node(g, 170)["inputs"][1]["type"] = "IMAGE" + elif mutation == "duplicate-input": + node(g, 170)["inputs"].append(copy.deepcopy(node(g, 170)["inputs"][0])) + elif mutation == "bad-output-type": + node(g, 170)["outputs"][8]["type"] = "FLOAT" + elif mutation == "bad-slot": + g["links"][2][2] = 9 + elif mutation == "bad-edge-type": + g["links"][2][5] = "FLOAT" + elif mutation == "duplicate-link": + g["links"].append(g["links"][0]) + elif mutation == "dangling": + g["links"][0][1] = 999 + elif mutation == "cycle": + node(g, 169)["inputs"].append({"name": "prompt", "type": "STRING", "link": 339}) + node(g, 170)["outputs"][0]["links"].append(339) + g["links"].append([339, 170, 0, 169, 1, "STRING"]) + elif mutation == "subgraph": + g["definitions"] = {"subgraphs": [{"id": "unproven"}]} + elif mutation == "root-ue": + g["extra"]["ue_links"] = [[1, 2, 3]] + elif mutation == "unknown-node": + node(g, 169)["type"] = "SameNameUnregistered" + elif mutation == "unknown-ref": + node(g, 170)["inputs"][1]["name"] = "references.ref_1" + else: + node(g, 170)["inputs"][2]["widget"]["name"] = "seed" + closed(g) + + +def test_options_and_reference_union_cannot_accept_string_output_by_name(): + for index in (0, 1): + g = graph() + node(g, 170)["inputs"][index]["link"] = 339 + node(g, 169)["outputs"][1]["links"] = [339] + g["links"].append([339, 169, 1, 170, index, "STRING"]) + closed(g) + + +def test_fixed_sources_are_cached_not_imported_and_include_registration(): + r = verify(REPO / "docs/hel-892/h3-reference") + assert r["target_version_match"] == "unknown" and not r["upstream_code_executed"] + assert len(r["sources_verified"]) >= 40 + assert H3_COMMIT in H3_PROFILE.replace("a59888df", H3_COMMIT) + assert serialize_h3_node(node(graph(), 171)) == {} + + +def test_full_library_old_25_attempts_gaps_eight_hashes_and_six_pairs_frozen(): + old = json.loads((REPO / "docs/hel-892/grid-evidence/library.json").read_bytes()) + baseline = tuple(old["profiles"]) + assert len(baseline) == 25 and baseline == audit.REFERENCE_PROFILES[:-1] + before = audit.audit_library(REPO, baseline) + now = audit.audit_library(REPO, baseline_profiles=baseline) + assert old["gap_groups"] == before["gap_groups"] + for a, b, c in zip(old["cases"], before["cases"], now["cases"]): + assert a["source_path"] == b["source_path"] == c["source_path"] + assert a["attempts"] == b["attempts"] == c["attempts"][:25] + assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") + if a["candidate_hashes"]: + assert a["candidate_hashes"] == c["candidate_hashes"] + target = PATH.relative_to(REPO).as_posix() + assert now["coverage_delta"]["new_complete_paths"] == [target] + assert len(now["coverage_delta"]["current_complete_paths"]) == 9 + assert sum(r["status"] == "blocked" for r in now["cases"]) == 136 + r = next(r for r in now["cases"] if r["source_path"] == target) + assert r["comparison_status"] == "comparison_unavailable" and not r["execution_verified"] diff --git a/calliope-backend/tests/test_scail_load_reference.py b/calliope-backend/tests/test_scail_load_reference.py index 5ebab09..349bc42 100644 --- a/calliope-backend/tests/test_scail_load_reference.py +++ b/calliope-backend/tests/test_scail_load_reference.py @@ -245 +245,6 @@ def test_exact_historical_emission_is_not_user_provenance(): - assert len([p for p in audit.REFERENCE_PROFILES if p != audit.GRID_PROFILE]) == 24 + assert ( + len( + [p for p in audit.REFERENCE_PROFILES if p not in (audit.GRID_PROFILE, audit.H3_PROFILE)] + ) + == 24 + ) diff --git a/calliope-backend/tests/test_setget_reference.py b/calliope-backend/tests/test_setget_reference.py index cc9f3cf..65bff83 100644 --- a/calliope-backend/tests/test_setget_reference.py +++ b/calliope-backend/tests/test_setget_reference.py @@ -339 +339,6 @@ def test_wrong_frontend_missing_policy_and_profile_inventory(): - not in (*audit.VIDEOINFO_PROFILES, *audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE) + not in ( + *audit.VIDEOINFO_PROFILES, + *audit.SCAIL_LOAD_PROFILES, + audit.GRID_PROFILE, + audit.H3_PROFILE, + ) @@ -425,0 +431 @@ def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): + audit.H3_PROFILE, @@ -428 +434,5 @@ def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): - now = audit.audit_library(REPO, baseline_profiles=baseline) + now = audit.audit_library( + REPO, + tuple(p for p in audit.REFERENCE_PROFILES if p != audit.H3_PROFILE), + baseline_profiles=baseline, + ) diff --git a/calliope-backend/tests/test_vhs_reference.py b/calliope-backend/tests/test_vhs_reference.py index 6953e49..3c09f1b 100644 --- a/calliope-backend/tests/test_vhs_reference.py +++ b/calliope-backend/tests/test_vhs_reference.py @@ -297,0 +298 @@ def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected(): + audit.H3_PROFILE, diff --git a/calliope-backend/tests/test_videoinfo_reference.py b/calliope-backend/tests/test_videoinfo_reference.py index d2e9790..9070345 100644 --- a/calliope-backend/tests/test_videoinfo_reference.py +++ b/calliope-backend/tests/test_videoinfo_reference.py @@ -283 +283 @@ def test_real_entities_strict_source_schema_and_old_profiles_stay_frozen(): - if p not in (*audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE) + if p not in (*audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE, audit.H3_PROFILE) diff --git a/docs/hel-892/h3-evidence/recompute.py b/docs/hel-892/h3-evidence/recompute.py new file mode 100644 index 0000000..bc9164b --- /dev/null +++ b/docs/hel-892/h3-evidence/recompute.py @@ -0,0 +1,377 @@ +"""Recompute H3 reference evidence and protections without services or upstream execution.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sqlite3 +import subprocess +import sys +import tarfile +import zipfile +from collections import Counter +from pathlib import Path + +BASE = "201ddf76221477ae75232819919869cb2695a6f8" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--db", type=Path, required=True) + parser.add_argument("--documents", type=Path, required=True) + args = parser.parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo / "calliope-backend")) + from calliope.comfyui.structure_reference import ( + H3_PROFILE, + ) + from scripts import audit_reference_conversion as audit + from scripts.audit_library_documents import audit as audit_docs + from scripts.verify_frontend_sources import verify + + out = repo / "docs/hel-892/h3-evidence" + + def write(name, value): + (out / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + + old = json.loads((repo / "docs/hel-892/grid-evidence/library.json").read_bytes()) + profiles = tuple(old["profiles"]) + assert len(profiles) == 25 + assert profiles == tuple(p for p in audit.REFERENCE_PROFILES if p != H3_PROFILE) + before = audit.audit_library(repo, profiles) + now = audit.audit_library(repo, baseline_profiles=profiles) + write("library.json", now) + for a, b, c in zip(old["cases"], before["cases"], now["cases"]): + assert a["source_path"] == b["source_path"] == c["source_path"] + assert a["attempts"] == b["attempts"] == c["attempts"][:25] + assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") + if a["candidate_hashes"]: + assert a["candidate_hashes"] == c["candidate_hashes"] + assert old["gap_groups"] == before["gap_groups"] + six = audit.audit(repo, "case04-batch-reference") + assert six == json.loads( + (repo / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() + ) + write( + "previous-protection.json", + { + "baseline_profiles": profiles, + "old_attempts_identical": True, + "old_gaps_identical": True, + "six_companion_differences_identical": True, + "old_candidate_hashes_identical": True, + }, + ) + + def groups(report): + return { + tuple( + g[k] + for k in ("type", "provider", "version", "profile", "code", "rule_gap") + ): Counter( + (o["source_path"], o["node_pointer"], o["node_id"]) + for o in g["occurrences"] + ) + for g in report["gap_groups"] + } + + def stats(report): + gs = groups(report) + return { + "groups": len(gs), + "raw_occurrences": sum(sum(c.values()) for c in gs.values()), + "unique_occurrences_per_group": sum(len(c) for c in gs.values()), + "unique_nodes": len({o for c in gs.values() for o in c}), + "unique_paths": len({o[0] for c in gs.values() for o in c}), + } + + def diffrows(a, b): + return [ + { + "key": list(k), + "occurrences": [ + { + "source_path": o[0], + "node_pointer": o[1], + "node_id": o[2], + "count": n, + } + for o, n in sorted((v - b.get(k, Counter())).items(), key=str) + ], + } + for k, v in sorted(a.items(), key=str) + if v - b.get(k, Counter()) + ] + + def unavailable(report): + return sorted( + r["source_path"] + for r in report["cases"] + if all(a["status"] == "not_applicable" for a in r["attempts"]) + ) + + removed_unavailable = sorted(set(unavailable(before)) - set(unavailable(now))) + added_unavailable = sorted(set(unavailable(now)) - set(unavailable(before))) + ga, gb = groups(before), groups(now) + added, removed = diffrows(gb, ga), diffrows(ga, gb) + write( + "coverage-delta.json", + { + "baseline_profiles": profiles, + "baseline": stats(before), + "current": stats(now), + "key_fields": [ + "type", + "provider", + "version", + "profile", + "code", + "rule_gap", + ], + "occurrence_key": ["source_path", "node_pointer", "node_id"], + "added_groups": added, + "removed_groups": removed, + "added_occurrences": sum( + o["count"] for g in added for o in g["occurrences"] + ), + "removed_occurrences": sum( + o["count"] for g in removed for o in g["occurrences"] + ), + "new_complete_paths": now["coverage_delta"]["new_complete_paths"], + "complete_paths": now["coverage_delta"]["current_complete_paths"], + "closed_paths": [ + r["source_path"] for r in now["cases"] if r["status"] == "blocked" + ], + "unavailable_frontend_before": unavailable(before), + "unavailable_frontend_after": unavailable(now), + "removed_unavailable_frontend_paths": removed_unavailable, + "added_unavailable_frontend_paths": added_unavailable, + "unavailable_frontend_change_reason": "new explicit 1.53.10 profile; applicability is not conversion success", + "attempt_counts": dict( + Counter(a["status"] for r in now["cases"] for a in r["attempts"]) + ), + "conflicts": sum(r["status"] == "candidate_conflict" for r in now["cases"]), + }, + ) + + from calliope.comfyui.ui2api import convert_reference + + target = next( + (repo / "example_ComfyUI_workflows").rglob("Minimax-H3提示词增强.json") + ) + source = json.loads(target.read_bytes()) + actual = convert_reference(source, H3_PROFILE) + assert actual.prompt is not None, actual.issues + row = next( + r + for r in now["cases"] + if r["source_path"] == target.relative_to(repo).as_posix() + ) + assert row["comparison_status"] == "comparison_unavailable" + fields = audit.h3_field_evidence(source, actual.prompt) + assert len(fields) == 19 and sum(f["json_type"] == "list" for f in fields) == 3 + write( + "actual-h3.json", + { + "authority": "offline_reference_only_not_API_export_or_execution_qualification", + "source_path": row["source_path"], + "source_sha256": row["source_sha256"], + "profile": H3_PROFILE, + "candidate_prompt": actual.prompt, + "candidate_sha256": audit.canonical_sha(actual.prompt), + "field_evidence": fields, + "comparison_status": row["comparison_status"], + "execution_verified": False, + "original_bytes_modified": False, + "metadata": [ + { + "node_id": str(n["id"]), + "class_pointer": f"/nodes/{i}/type", + "title_pointer": f"/nodes/{i}/title", + "value": actual.prompt[str(n["id"])]["_meta"], + } + for i, n in enumerate(source["nodes"]) + ], + "workflow_only_control": { + "node_id": "169", + "name": "control_after_generate", + "source_pointer": "/nodes/0/widgets_values/7", + "named_pointer": "/nodes/0/widgets_values_named/control_after_generate", + "value": "fixed", + "reason": "options.serialize=false; fixed changes no seed", + }, + "unconnected_optional_sockets": [ + "/nodes/0/inputs/0", + "/nodes/1/inputs/0", + "/nodes/1/inputs/1", + ], + "target_model_list_files_library_memory_and_inference": "unknown_not_read_or_run", + }, + ) + inventory = row["inventory"] + + dirs = [ + "serialization-evidence", + "structure-reference", + "controlnet-reference", + "promoted-reference", + "case04-reference", + "media-reference", + "separation-reference", + "crop-split-reference", + "vhs-reference", + "setget-reference", + "videoinfo-reference", + "scail-load-reference", + "grid-reference", + "h3-reference", + ] + entries = [] + counts = [] + for name in dirs: + directory = repo / "docs/hel-892" / name + verify(directory) + rows = json.loads((directory / "sources.json").read_bytes())["sources"] + for entry in rows: + lines = (directory / entry["local_file"]).read_text().splitlines() + locations = entry.get("rule_locations", {}) + for lo, hi in ( + locations.values() if isinstance(locations, dict) else locations + ): + assert 1 <= lo <= hi <= len(lines) + counts.append( + { + "manifest": name, + "entries": len(rows), + "unique_ids": len({r["id"] for r in rows}), + } + ) + entries.extend(rows) + write( + "cached-sources-check.json", + { + "manifests": counts, + "entries": len(entries), + "unique_ids_summed_per_manifest": sum(c["unique_ids"] for c in counts), + "global_distinct_id_strings": len({r["id"] for r in entries}), + "unique_url_and_hash": len({(r["raw_url"], r["sha256"]) for r in entries}), + "note": "ID counts are strings; URL+SHA256 is separately deduplicated; repeated frontend originals retained", + }, + ) + + originals = json.loads( + (repo / "docs/hel-892/media-evidence/original-bytes.json").read_bytes() + )["files"] + for row in originals: + raw = (repo / row["path"]).read_bytes() + assert raw == subprocess.check_output( + ["git", "show", f"{BASE}:{row['path']}"], cwd=repo + ) + assert len(originals) == 163 + write( + "original-bytes.json", + {"base": BASE, "count": 163, "all_unchanged": True, "files": originals}, + ) + production = json.loads( + (repo / "docs/hel-892/setget-evidence/production-protection.json").read_bytes() + )["files"] + for row in production: + raw = (repo / row["path"]).read_bytes() + assert raw == subprocess.check_output( + ["git", "show", f"{BASE}:{row['path']}"], cwd=repo + ) + assert hashlib.sha256(raw).hexdigest() == row["sha256"] + write("production-protection.json", {"base": BASE, "files": production}) + db = sqlite3.connect(args.db) + db.row_factory = sqlite3.Row + rows = db.execute( + "SELECT * FROM workflows WHERE source_repo_path IS NOT NULL" + ).fetchall() + assert len(rows) == 155 + assert not any( + r["is_enabled"] or r["doc_completed_at"] or r["exec_verified_at"] for r in rows + ) + issues = Counter(i["code"] for r in rows for i in json.loads(r["import_issues"])) + companion_values = sum( + p.get("value_origin") == "supplied_api_companion" + for r in rows + for p in json.loads(r["doc_json"])["params"] + ) + assert ( + companion_values == 294 + and issues["companion_unverified"] == 6 + and issues["environment_unchecked"] == 16 + ) + write( + "isolation.json", + { + "states": dict(Counter(r["import_state"] for r in rows)), + "count": 155, + "enabled_or_completed_or_executed": 0, + "issue_counts": dict(issues), + "companion_named_values": companion_values, + "reference_candidates_written_to_db": False, + "user_whole_row_protection": "executed affected tests", + }, + ) + db.close() + report = audit_docs(repo, args.documents.resolve()) + summary = {k: v for k, v in report.items() if k != "files"} + assert ( + summary["named_values_preserved"] == 1217 + and summary["unnamed_widget_nodes"] == 3660 + ) + assert summary["full_documents_completed"] == 0 and summary["real_executions"] == 0 + write("document-audit-summary.json", summary) + packages = [] + with ( + zipfile.ZipFile(next((repo / "calliope-backend/dist").glob("*.whl"))) as wh, + tarfile.open(next((repo / "calliope-backend/dist").glob("*.tar.gz"))) as sd, + ): + for name in [ + "structure_reference.py", + "serialization_reference.py", + "ui2api.py", + "protocol_references.json", + "source_reviews.json", + "delivery_scope.py", + "delivery_scope.json", + ]: + p = f"calliope-backend/src/calliope/comfyui/{name}" + raw = (repo / p).read_bytes() + assert wh.read(f"calliope/comfyui/{name}") == raw + member = next( + n for n in sd.getnames() if n.endswith(f"/src/calliope/comfyui/{name}") + ) + assert sd.extractfile(member).read() == raw + packages.append( + { + "path": p, + "sha256": hashlib.sha256(raw).hexdigest(), + "wheel_matches": True, + "sdist_matches": True, + } + ) + write("package-check.json", packages) + print( + json.dumps( + { + "ui": now["ui_total"], + "attempts": Counter( + a["status"] for r in now["cases"] for a in r["attempts"] + ), + "complete": len(now["coverage_delta"]["current_complete_paths"]), + "new_complete": now["coverage_delta"]["new_complete_paths"], + "inventory_nodes": len(inventory), + "inventory_paths": 1, + "gap_stats": stats(now), + }, + ensure_ascii=False, + ) + ) + + +if __name__ == "__main__": + main()