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

177 lines
7.4 KiB
Python

"""Editorial trust, original conflict retention and separate subgraph saved states."""
import copy
import hashlib
import json
import runpy
import subprocess
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/flux2-lineart-document-evidence"
PATH = "example_ComfyUI_workflows/3-图像生成/Flux/6_flux2-klein+Qwen3.5_转线稿洗图.json"
RAW = (REPO / PATH).read_bytes()
SOURCE = json.loads(RAW)
REVIEW = review_for(PATH, hashlib.sha1(RAW).hexdigest())
BLOCK = REVIEW["fixed_version_document"]
def pointer(obj, p):
for part in p.strip("/").split("/"):
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
return obj
def doc(s=SOURCE, r=REVIEW):
return build_document(PATH, s, None, None, [], r)
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_each_saved_type_pointer_input_and_exact_evidence(f):
assert canonical(pointer(SOURCE, f["pointer"])) == canonical(f["value"])
assert type(pointer(SOURCE, f["pointer"])).__name__ == f["json_type"]
assert "named_value" not in f and "无widgets_values_named" in f["named_pointer"]
if f["input_pointer"].startswith("/"):
assert pointer(SOURCE, f["input_pointer"])["name"] == f["input_name"]
for i in f["evidence"]:
e = BLOCK["sources"][i]
data = (OUT / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
assert 1 <= e["lines"][0] <= e["lines"][1] <= len(data.decode().splitlines())
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
@pytest.mark.parametrize("variant", ["position", "editorial"])
def test_caller_rehash_cannot_expand_saved_or_editorial_trust(f, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "editorial":
r["fixed_version_document"]["fields"][BLOCK["fields"].index(f)]["effect"] = "forged"
else:
p, _, k = f["pointer"].rpartition("/")
pointer(s, p)[int(k)] = "forged"
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
NODES = [f"/nodes/{i}" for i in range(45)] + [
f"/definitions/subgraphs/0/nodes/{i}" for i in range(4)
]
@pytest.mark.parametrize("path", NODES)
@pytest.mark.parametrize("variant", ["mode", "identity", "named"])
def test_every_root_and_internal_node_is_bound(path, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
n = pointer(s, path)
if variant == "mode":
n["mode"] = 4 if n["mode"] == 0 else 0
elif variant == "identity":
n.setdefault("properties", {})["ver"] = "forged"
else:
n["widgets_values_named"] = {"forged": 0}
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
EDGES = [f"/links/{i}" for i in range(60)] + [
f"/definitions/subgraphs/0/links/{i}" for i in range(13)
]
@pytest.mark.parametrize("path", EDGES)
def test_every_root_or_boundary_edge_is_bound(path):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
e = pointer(s, path)
if isinstance(e, list):
e[4] = 0 if e[4] != 0 else 1
else:
e["target_slot"] = 999
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
@pytest.mark.parametrize(
"path", [f"/nodes/{i}" for i, n in enumerate(SOURCE["nodes"]) if not n.get("widgets_values")]
)
@pytest.mark.parametrize("value", [None, [], [0], "missing"])
def test_missing_empty_null_host_and_reroutes_stay_distinct(path, value):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
n = pointer(s, path)
old = copy.deepcopy(n)
if value == "missing":
n.pop("widgets_values", None)
else:
n["widgets_values"] = value
if old == n:
return
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
def test_independent_inventory_preserves_conflicting_endpoints_and_boundaries():
inv = runpy.run_path(str(OUT / "inventory.py"))["inventory"]()
assert len(inv["fields"]) == 96 and len(inv["nodes"]) == 49 and len(inv["edges"]) == 73
conflicts = [
e for e in inv["edges"] if e["target_backref"] is False or e["source_backref"] is False
]
assert [
(e["edge"][0], e["target_slot"], e["target_actual_link_inputs"]) for e in conflicts
] == [(328, 16, [(7, "width")]), (329, 17, [(8, "height")])]
host = next(n for n in SOURCE["nodes"] if n["id"] == 181)
g = SOURCE["definitions"]["subgraphs"][0]
assert host["widgets_values"] == [] and len(host["properties"]["proxyWidgets"]) == 10
assert len(g["inputs"]) == 9 and len(g["outputs"]) == 1 and g["widgets"] == []
assert not any(n["named_present"] for n in inv["nodes"])
def test_separate_stages_long_text_history_versions_and_unchanged_status():
fs = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]}
assert fs["143", "steps"]["value"] == 5 and fs["57", "steps"]["value"] == 4
assert (
fs["143", "seed"]["value"] == 519817890873890
and fs["53", "noise_seed"]["value"] == 1034590073422611
)
assert fs["173", "prompt"]["value"] == "将这张图片转换为canny线稿图"
assert type(fs["173", "batch_size"]["value"]) is int
for nid, field in [("169", "system_prompt"), ("171", "history_text"), ("183", "text")]:
assert len(fs[nid, field]["value"]) > 100
assert len(fs["195", "history_images"]["value"]) == 2 and "temp_yiyuk" in str(
fs["195", "history_images"]["value"]
)
assert fs["180", "presence_penalty"]["json_type"] == "int"
assert fs["169", "control_after_generate"]["input_name"] is None
assert SOURCE["extra"]["frontendVersion"] == "1.23.0"
for key, commit in [
("painter", "66eb4c6edc6dd52cd0a5f5d786caedf252ea2a87"),
("llama", "a69be4883f98c4025915f0390a3e87aae9ea3477"),
]:
assert {s["commit"] for s in BLOCK["sources"] if s["id"] == key} == {commit}
text = " ".join(BLOCK["flow"])
assert "target_slot16/17" in text and "195.B来自152" in text
d = doc()
assert d["fixed_version"]["matched"]
assert not d["status"]["doc_done"] and not d["status"]["exec_verified"]
assert len(BLOCK["fields"]) == 96 and not BLOCK["comments"] and len(DEFINITIONS) == 52
assert hashlib.sha256(canonical(BLOCK)).hexdigest() == DEFINITIONS[PATH]
def test_previous_fifty_one_definitions_and_reviews_frozen():
resource = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(
subprocess.check_output(
["git", "show", "f090d64175e3076f82d37777e9f4f7e03e1ef559:" + resource], cwd=REPO
)
)
new = json.loads((REPO / resource).read_bytes())
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert len(blocks) == 51 and sum(len(b["fields"]) for b in blocks) == 1921
assert sum(len(b.get("comments", [])) for b in blocks) == 56
assert [p for p in old if old[p] != new[p]] == [PATH]
new[PATH].pop("fixed_version_document")
assert old == new