"""All saved scopes, bound overrides and rejection of forged editorial trust.""" from __future__ import annotations import copy import hashlib import json from pathlib import Path import pytest from calliope.comfyui.fixed_document import DEFINITIONS, canonical from calliope.comfyui.library import build_document from calliope.comfyui.source_reviews import review_for REPO = Path(__file__).resolve().parents[2] OUT = REPO / "docs/hel-892/qwen-edit-document-evidence" PATH = next(p for p in DEFINITIONS if p.endswith("Qwen_image2.1_图像编辑_提示词增强.json")) RAW = (REPO / PATH).read_bytes() SOURCE = json.loads(RAW) REVIEW = review_for(PATH, hashlib.sha1(RAW).hexdigest()) BLOCK = REVIEW["fixed_version_document"] def doc(source=None, review=None, path=PATH): return build_document( path, SOURCE if source is None else source, None, None, [], REVIEW if review is None else review, ) def pointer(obj, path): for part in path.strip("/").split("/"): part = part.replace("~1", "/").replace("~0", "~") obj = obj[int(part)] if isinstance(obj, list) else obj[part] return obj @pytest.mark.parametrize("index", range(70)) def test_every_saved_position_scope_and_citation(index): f = BLOCK["fields"][index] v = pointer(SOURCE, f["pointer"]) assert canonical(v) == canonical(f["value"]) and type(v).__name__ == f["json_type"] named = pointer(SOURCE, f["named_pointer"]) if f["node_id"] == "501": assert named == {"images": [{**item, "img": {}} for item in v]} assert named != v else: assert canonical(named) == canonical(v) prefix = f["pointer"].split("/widgets_values/")[0] n = pointer(SOURCE, prefix) assert str(n["id"]) == f["definition_node_id"] and n["type"] == f["class_type"] assert f["node_id"] == ("459:" if f["scope"] == "definition" else "") + str(n["id"]) assert all( f[k] for k in [ "effect", "label", "schema_default", "unit", "limits", "execution_note", "evidence", ] ) if f["type"] in ("INT", "FLOAT"): assert "UI编辑步进step2=" in f["limits"] for i in f["evidence"]: e = BLOCK["sources"][i] raw = (OUT / e["local_file"]).read_bytes() assert hashlib.sha256(raw).hexdigest() == e["sha256"] assert len(e["commit"]) == 40 and e["commit"] in e["url"] assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines()) @pytest.mark.parametrize("index", range(70)) @pytest.mark.parametrize("kind", ["value", "type", "pointer", "named"]) def test_saved_and_named_mutations_cannot_rebind_document(index, kind): s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW) f = r["fixed_version_document"]["fields"][index] if kind == "pointer": f["pointer"] = "/definitions/subgraphs/999/nodes/999/widgets_values/0" else: p = f["named_pointer"] if kind == "named" else f["pointer"] parent, _, key = p.rpartition("/") target = pointer(s, parent) target[int(key) if isinstance(target, list) else key] = ( {"forged": True} if kind != "type" else str(f["value"]) + "tampered" ) r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest() r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest() fixed = doc(s, r)["fixed_version"] assert not fixed["matched"] and "fields" not in fixed @pytest.mark.parametrize("index", range(18)) def test_host_bindings_are_scoped_named_and_have_physical_provenance(index): b = BLOCK["bindings"][index] assert b["value_pointer"] == f"/nodes/0/widgets_values/{index}" assert canonical(pointer(SOURCE, b["named_pointer"])) == canonical( pointer(SOURCE, b["value_pointer"]) ) boundary = pointer(SOURCE, b["boundary_pointer"]) assert boundary["id"] == b["boundary_id"] and boundary["name"] == b["name"] for t in b["targets"]: socket = pointer(SOURCE, t["target_pointer"]) edge = pointer(SOURCE, t["link_pointer"]) assert socket["name"] == t["field"] and socket["link"] == edge["id"] assert edge["origin_slot"] == index and edge["target_id"] == int(t["definition_node_id"]) assert "widgetId(rootGraph.id, 459," in b["widget_id_rule"] @pytest.mark.parametrize( "location", [f["pointer"] for f in BLOCK["fields"]] + [f["named_pointer"] for f in BLOCK["fields"]] + [c["pointer"] for c in BLOCK["comments"]] + [b["boundary_pointer"] for b in BLOCK["bindings"]] + [ "/definitions/subgraphs/0/id", "/nodes/0/type", "/nodes/0/inputs/22/name", "/extra/frontendVersion", "/nodes/6/properties/comparer_mode", "/nodes/6/widgets_values/0/0/url", "/nodes/6/widgets_values_named/rgthree_comparer/images/1/selected", "/definitions/subgraphs/0/nodes/0/properties/ver", "/links/3", "/definitions/subgraphs/0/links/0/target_slot", ], ) def test_recomputed_caller_digest_cannot_extend_trust(location): s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW) parent, _, key = location.rpartition("/") target = pointer(s, parent) target[int(key) if isinstance(target, list) else key] = ( "forged" if location == "/nodes/0/type" else {"tampered": True} ) r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest() r["fixed_version_document"]["subgraph_sha256"] = hashlib.sha256( canonical(s["definitions"]["subgraphs"][0]) ).hexdigest() r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest() assert not doc(s, r)["fixed_version"]["matched"] @pytest.mark.parametrize( "key", [ "source_path", "source_sha1", "source_sha256", "canonical_sha256", "subgraph_sha256", "sources", "versions", "bindings", "flow", "comments", "counts", "fields", ], ) def test_editorial_or_source_identity_forgery(key): r = copy.deepcopy(REVIEW) r["fixed_version_document"][key] = "forged" r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest() assert not doc(review=r)["fixed_version"]["matched"] def test_exact_counts_topology_and_distinct_frontend_state(): b = doc()["fixed_version"] assert b["matched"] saved = set() for prefix, g in [ ("", SOURCE), ("/definitions/subgraphs/0", SOURCE["definitions"]["subgraphs"][0]), ]: for i, n in enumerate(g["nodes"]): if n["type"] in ("MarkdownNote", "Note"): continue saved.update( f"{prefix}/nodes/{i}/widgets_values/{j}" for j, _ in enumerate(n.get("widgets_values") or []) ) assert saved == {f["pointer"] for f in b["fields"]} and len(saved) == 70 assert sum(f["scope"] == "root" for f in b["fields"]) == 30 assert len(b["comments"]) == 3 and all( pointer(SOURCE, c["pointer"]) == c["text"] for c in b["comments"] ) fs = {(f["node_id"], f["field"]): f for f in b["fields"]} assert fs["459", "prompt"]["value"] == "为角色更换服装" assert fs["459", "resolution"]["value"] == 0 and fs["459:474", "resolution"]["value"] == 1024 assert fs["459", "seed"]["value"] == 1054732230873463 for nid, name in [("459:458", "seed"), ("459:500", "sampling_mode.seed")]: assert fs[nid, name]["value"] == 0 assert fs[nid, name]["binding"]["value_pointer"] == "/nodes/0/widgets_values/11" assert fs["459:458", "control_after_generate"]["value"] == "randomize" assert fs["459:500", "thinking"]["value"] is True assert fs["459:500", "use_default_template"]["value"] is False assert "不采用" in fs["459:479", "value"]["execution_note"] for name, nid in [("switch", "459:468"), ("switch_1", "459:484")]: assert fs["459", name]["value"] is True and fs[nid, "switch"]["value"] is False assert fs[nid, "switch"]["binding"]["name"] == name for name, target in [("scheduler", "sampler_name"), ("scheduler_1", "scheduler")]: assert fs["459", name]["binding"]["targets"][0]["field"] == target assert b["counts"]["final_scalars"] == 0 assert b["counts"]["final_prompt_constructed"] is False assert b["counts"]["frontend_only"] == 4 assert fs["470", "upload"]["role"] == fs["475", "upload"]["role"] == "frontend" assert len(fs["501", "rgthree_comparer"]["value"]) == 2 assert fs["501", "rgthree_comparer"]["role"] == "frontend" assert SOURCE["links"] == [ [704, 470, 0, 459, 18, "IMAGE"], [728, 475, 0, 459, 19, "IMAGE"], [808, 470, 0, 501, 0, "IMAGE"], [809, 461, 0, 501, 1, "IMAGE"], [810, 502, 0, 459, 7, "INT"], [811, 502, 1, 459, 8, "INT"], [672, 459, 0, 461, 0, "IMAGE"], ] assert not doc(path="unknown.json").get("fixed_version") def test_old_nine_blocks_and_other_editorial_content_preserved(): import subprocess path = "calliope-backend/src/calliope/comfyui/source_reviews.json" old = json.loads(subprocess.check_output(["git", "show", "157a296:" + path], cwd=REPO)) now = json.loads((REPO / path).read_bytes()) # This revision authorizes only ten optional overview additions and one new block. background = next(p for p in now if p.endswith("Qwen_image2.1_图像编辑_背景移除.json")) now[background].pop("fixed_version_document") # Later grid additions are protected against their own real 27e6d56 baseline. # Gemma is separately checked against 9dac1b4 in test_gemma_fixed_document. additions = [ p for p in now if p.endswith( ( "图像合并成四宫格.json", "图像分割-多宫格分割.json", "gemma4_提示词反推(图像视频音频).json", "sdpose_视频人物姿势骨架提取.json", "openpose-video-姿态检测.json", "NLF_视频人物动作骨架获取.json", "/视频倒放.json", ) ) ] assert len(additions) == 7 for p in additions: now[p].pop("fixed_version_document") for entry in now.values(): if "fixed_version_document" in entry: assert entry["fixed_version_document"].pop("user_overview") now[PATH].pop("fixed_version_document") assert old == now @pytest.mark.parametrize("directory", ["qwen-document-evidence", "qwen-edit-document-evidence"]) def test_missing_packages_give_actionable_chinese_build_hint(tmp_path, directory): import runpy namespace = runpy.run_path(str(REPO / "docs/hel-892" / directory / "recompute.py")) check = namespace["require_packages"] check.__globals__["REPO"] = tmp_path with pytest.raises( SystemExit, match="缺少wheel/sdist包产物.*uv build --project calliope-backend --offline" ): check()