Files
aigc-home/calliope-backend/tests/test_qwen_fixed_document.py
T

242 lines
9.2 KiB
Python

"""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-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(64))
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"]
assert canonical(pointer(SOURCE, f["named_pointer"])) == 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(64))
@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(17))
def test_host_bindings_are_scoped_named_and_have_physical_provenance(index):
b = BLOCK["bindings"][index]
assert b["value_pointer"] == f"/nodes/1/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(
"kind",
[
"source_path",
"sha1",
"sha256",
"canonical",
"subgraph_digest",
"definition_id",
"scope",
"widgetId",
"boundary",
"seed1",
"seed2",
"prompt",
"note1",
"note2",
"model",
"edge",
"source",
"citation",
"version",
"frontend",
"host_name",
"host_binding",
"switch",
"text_template",
"companion",
],
)
def test_forged_identity_graph_and_caller_digest_are_refused(kind):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
b = r["fixed_version_document"]
g = s["definitions"]["subgraphs"][0]
if kind == "source_path":
b["source_path"] = "other.json"
elif kind == "sha1":
r["source_sha"] = "0" * 40
elif kind == "sha256":
b["source_sha256"] = "0" * 64
elif kind == "canonical":
b["canonical_sha256"] = "0" * 64
elif kind == "subgraph_digest":
b["subgraph_sha256"] = "0" * 64
elif kind == "definition_id":
g["id"] = "forged"
elif kind == "scope":
b["fields"][-1]["scope"] = "root"
elif kind == "widgetId":
b["bindings"][0]["widget_id_rule"] = "widgetId(other,459,prompt)"
elif kind == "boundary":
g["inputs"][0]["linkIds"].reverse()
elif kind in ["seed1", "seed2"]:
g["nodes"][6 if kind == "seed1" else 7]["widgets_values"][0 if kind == "seed1" else 8] = 777
elif kind == "prompt":
s["nodes"][5]["widgets_values"][0] = "forged"
elif kind in ["note1", "note2"]:
s["nodes"][3 if kind == "note1" else 4]["widgets_values"][0] = "forged"
elif kind == "model":
g["nodes"][0]["widgets_values"][0] = "other.safetensors"
elif kind == "edge":
g["links"][0]["origin_slot"] = 1
elif kind == "source":
b["sources"][0]["commit"] = "0" * 40
elif kind == "citation":
b["sources"][0]["lines"] = [1, 2]
elif kind == "version":
g["nodes"][0]["properties"]["ver"] = "0.33.0"
elif kind == "frontend":
s["extra"]["frontendVersion"] = "1.53.10"
elif kind == "host_name":
s["nodes"][1]["inputs"][8]["name"] = "sampler"
elif kind == "host_binding":
g["links"][19]["target_slot"] = 7
elif kind == "switch":
g["nodes"][10]["widgets_values"][0] = True
elif kind == "text_template":
g["nodes"][7]["widgets_values"][11] = True
else:
b["companion_difference"]["export_sha256"] = "0" * 64
if kind != "canonical":
b["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
if kind != "subgraph_digest":
b["subgraph_sha256"] = hashlib.sha256(canonical(g)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
assert doc(s, r)["fixed_version"]["matched"] is False
def test_exact_coverage_override_chains_and_api_difference():
b = doc()["fixed_version"]
assert b["matched"]
saved = set()
for scope, g in [("root", SOURCE), ("def", SOURCE["definitions"]["subgraphs"][0])]:
for i, n in enumerate(g["nodes"]):
if n["type"] == "MarkdownNote":
continue
for j, _ in enumerate(n.get("widgets_values", [])):
saved.add(
("/nodes/" if scope == "root" else "/definitions/subgraphs/0/nodes/")
+ f"{i}/widgets_values/{j}"
)
assert saved == {f["pointer"] for f in b["fields"]} and len(saved) == 64
assert sum(f["scope"] == "root" for f in b["fields"]) == 25
assert len(b["comments"]) == 2 and all(
pointer(SOURCE, c["pointer"]) == c["text"] for c in b["comments"]
)
fields = {(f["node_id"], f["field"]): f for f in b["fields"]}
for nid, name in [("459:458", "seed"), ("459:471", "sampling_mode.seed")]:
f = fields[nid, name]
assert f["value"] == 0 and f["binding"]["value_pointer"] == "/nodes/1/widgets_values/10"
assert fields["459", "seed"]["value"] == 447606998181263
assert fields["459", "scheduler"]["binding"]["targets"][0]["field"] == "sampler_name"
assert fields["459", "scheduler_1"]["binding"]["targets"][0]["field"] == "scheduler"
assert "713" in fields["459", "prompt"]["execution_note"]
assert all("覆盖" in fields["459", name]["execution_note"] for name in ["width", "height"])
assert fields["459:471", "use_default_template"]["value"] is False
assert "不采用" in fields["459:475", "value"]["execution_note"]
assert (
fields["459:474", "switch"]["value"] is False and fields["459", "switch"]["value"] is True
)
diff = b["companion_difference"]["differences"]
assert len(diff) == 16 and sum(d["field"] == "_meta" for d in diff) == 14
assert {(d["node_id"], d["field"]) for d in diff if d["field"] != "_meta"} == {
("459:451", "unet_name"),
("459:473", "clip_name"),
}
assert (
b["counts"]["final_entities"] == 16
and b["counts"]["final_scalars"] == 42
and b["counts"]["final_endpoints"] == 18
)