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

262 lines
9.7 KiB
Python

"""VOSR2 exact saved states, editorial integrity and source identity boundaries."""
import ast
import copy
import hashlib
import json
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/vosr2-document-evidence"
PATH = next(p for p in DEFINITIONS if p.endswith("/VOSR2_图像超分放大.json"))
SOURCE = json.loads((REPO / PATH).read_bytes())
REVIEW = review_for(PATH, hashlib.sha1((REPO / PATH).read_bytes()).hexdigest())
BLOCK = REVIEW["fixed_version_document"]
def pointer(obj, path):
for part in path.strip("/").split("/"):
obj = (
obj[int(part)]
if isinstance(obj, list)
else obj[part.replace("~1", "/").replace("~0", "~")]
)
return obj
def doc(source=SOURCE, review=REVIEW):
return build_document(PATH, source, None, None, [], review)
def refuse(source, review):
b = review["fixed_version_document"]
b["canonical_sha256"] = hashlib.sha256(canonical(source)).hexdigest()
review["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
assert not doc(source, review)["fixed_version"]["matched"]
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_saved_position_dual_storage_scope_and_evidence(f):
value = pointer(SOURCE, f["pointer"])
assert canonical(value) == canonical(f["value"])
assert type(value).__name__ == f["json_type"]
assert pointer(SOURCE, f["named_pointer"]) == f["named_value"]
assert f["scope"] == "root" and f["named_pointer"] in f["execution_note"]
if f["field"] == "rgthree_comparer":
assert [
{k: v for k, v in x.items() if k != "img"} for x in f["named_value"]["images"]
] == value
else:
assert canonical(value) == canonical(f["named_value"])
for key in [
"label",
"schema_default",
"unit",
"limits",
"effect",
"execution_note",
"role",
"type",
]:
assert f[key]
for i in f["evidence"]:
e = BLOCK["sources"][i]
raw = (OUT / e["local_file"]).read_bytes()
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines())
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
@pytest.mark.parametrize("variant", ["physical", "named", "text"])
def test_each_position_forgery_refused_with_recomputed_caller_digest(f, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "text":
r["fixed_version_document"]["fields"][BLOCK["fields"].index(f)]["effect"] = "forged"
else:
p = f["pointer"] if variant == "physical" else f["named_pointer"]
parent, _, key = p.rpartition("/")
value = pointer(s, parent)
value[int(key) if isinstance(value, list) else key] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(13))
@pytest.mark.parametrize("variant", ["mode", "identity"])
def test_all_node_modes_and_identities_bound(i, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
if variant == "mode":
s["nodes"][i]["mode"] = 2
else:
s["nodes"][i]["properties"]["ver"] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(10))
@pytest.mark.parametrize("variant", ["record", "input", "output"])
def test_each_edge_endpoint_bound(i, variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
eid, src, slot, dst, inp, _ = s["links"][i]
ns = {n["id"]: n for n in s["nodes"]}
if variant == "record":
s["links"][i][3] = 999999
elif variant == "input":
ns[dst]["inputs"][inp]["link"] = 999999
else:
ns[src]["outputs"][slot]["links"] = [999999]
refuse(s, r)
@pytest.mark.parametrize(
"variant",
[
"note",
"history_url",
"history_img",
"upload_null",
"group_active",
"disable",
"sdppp",
"ue",
"graph_version",
"frontend",
"null",
"source_sha",
"path",
"citation",
"overview",
"missing",
"empty",
],
)
def test_special_saved_shapes_and_metadata_fail_closed(variant):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
ns = {n["id"]: n for n in s["nodes"]}
b = r["fixed_version_document"]
if variant == "note":
ns[140]["widgets_values"][0] = "forged"
elif variant == "history_url":
ns[139]["widgets_values"][0][0]["url"] = "https://example.invalid/never"
elif variant == "history_img":
ns[139]["widgets_values_named"]["rgthree_comparer"]["images"][0]["img"] = {"changed": True}
elif variant == "upload_null":
del ns[148]["widgets_values_named"]["choose video to upload"]
elif variant == "group_active":
ns[149]["properties"]["guhai_ig_active_set"] = []
elif variant == "disable":
ns[149]["properties"]["guhai_ig_disable"] = True
elif variant == "sdppp":
ns[29]["properties"]["#sdppp_simple_content"] = "changed"
elif variant == "ue":
s["extra"].pop("links_added_by_ue")
elif variant == "graph_version":
s["extra"]["node_versions"]["ComfyUI-VOSR2"] = "forged"
elif variant == "frontend":
s["extra"]["frontendVersion"] = "forged"
elif variant == "null":
ns[28]["widgets_values"] = []
elif variant == "source_sha":
r["source_sha"] = "forged"
elif variant == "path":
b["source_path"] = "forged"
elif variant == "citation":
b["sources"][0]["sha256"] = "forged"
elif variant == "overview":
b["user_overview"] = "forged"
elif variant == "missing":
r.pop("fixed_version_document")
assert not doc(s, r)["fixed_version"]["matched"]
return
elif variant == "empty":
r["fixed_version_document"] = {}
assert not doc(s, r)["fixed_version"]["matched"]
return
refuse(s, r)
def test_independent_source_inventory_and_topology():
assert doc()["fixed_version"]["matched"]
assert len(SOURCE["nodes"]) == 13 and len(SOURCE["links"]) == 10 and "definitions" not in SOURCE
expected = []
for i, n in enumerate(SOURCE["nodes"]):
w = n.get("widgets_values")
if w is None or n["type"] == "Note":
continue
expected.extend(
f"/nodes/{i}/widgets_values/{k}" for k in (range(len(w)) if isinstance(w, list) else w)
)
assert expected == [f["pointer"] for f in BLOCK["fields"]] and len(expected) == 46
assert sum(f["json_type"] in ["dict", "list"] for f in BLOCK["fields"]) == 3
assert [n["id"] for n in SOURCE["nodes"] if n["mode"] == 4] == [143, 146, 150, 142, 151, 148]
ns = {n["id"]: n for n in SOURCE["nodes"]}
for eid, src, slot, dst, inp, typ in SOURCE["links"]:
assert ns[dst]["inputs"][inp]["link"] == eid
assert eid in ns[src]["outputs"][slot]["links"]
assert ns[dst]["inputs"][inp]["type"] == typ
assert [e for e in SOURCE["links"] if e[3] == 139] == [
[262, 29, 0, 139, 0, "IMAGE"],
[263, 28, 0, 139, 1, "IMAGE"],
]
assert ns[29]["outputs"][1]["links"] is None
for n in BLOCK["comments"]:
assert pointer(SOURCE, n["pointer"]) == pointer(SOURCE, n["named_pointer"]) == n["text"]
assert len(BLOCK["comments"]) == 1
def test_exact_static_contracts_without_importing_upstream():
ref = OUT.parent / "vosr2-reference"
text = (ref / "vosr__nodes_vosr.py").read_text()
ast.parse(text)
assert "tile_overlap >= tile_size" in text and "vae_tile_overlap >= vae_tile_size" in text
assert "default=42" in text and "control_after_generate=io.ControlAfterGenerate.fixed" in text
core = (ref / "core__nodes.py").read_text()
tree = ast.parse(core)
save = next(x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == "SaveImage")
preview = next(x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == "PreviewImage")
assert ast.literal_eval(
next(
x.value
for x in save.body
if isinstance(x, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "RETURN_TYPES" for t in x.targets)
)
) == ("IMAGE",)
assert preview.bases[0].id == "SaveImage"
assert '"result" : (images,)' in ast.get_source_segment(core, save)
loader = (ref / "vosr__loader.py").read_text()
assert (
"if model_name != KNOWN_MODEL:" in loader
and "if not (dit_missing or vae_missing or vision_missing):" in loader
)
assert "revision=" not in loader
comparer = (ref / "rgthree__py__image_comparer.py").read_text()
assert "return result" in comparer and "'result'" not in comparer and '"result"' not in comparer
def test_old_32_blocks_and_all_other_reviews_frozen():
path = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(subprocess.check_output(["git", "show", "282c0e8:" + path], cwd=REPO))
now = json.loads((REPO / path).read_bytes())
now[PATH].pop("fixed_version_document")
assert old == now and len(DEFINITIONS) == 33
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert (
len(blocks) == 32
and sum(len(b["fields"]) for b in blocks) == 988
and sum(
len(
build_document(p, json.loads((REPO / p).read_bytes()), None, None, [], r)[
"source_notes"
]
)
for p, r in old.items()
if "fixed_version_document" in r
)
== 24
)