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

254 lines
9.3 KiB
Python

"""Interpolation comparison source identity, inactive lengths and fail-closed bindings."""
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/simple-vfi-document-evidence"
PATH = next(p for p in DEFINITIONS if p.endswith("/视频模型放大插帧(简单快速版).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]
return obj
def doc(source=SOURCE, review=REVIEW):
return build_document(PATH, source, None, None, [], review)
def refuse(s, r):
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest()
assert not doc(s, r)["fixed_version"]["matched"]
@pytest.mark.parametrize("f", BLOCK["fields"], ids=lambda f: f["node_id"] + "." + f["field"])
def test_position_type_scope_citations_and_no_fabricated_named_values(f):
assert canonical(pointer(SOURCE, f["pointer"])) == canonical(f["value"])
assert type(pointer(SOURCE, f["pointer"])).__name__ == f["json_type"]
assert f["scope"] == "root" and "named_value" not in f and "named_pointer" not in f
for key in [
"effect",
"label",
"schema_default",
"unit",
"limits",
"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", ["value", "text"])
def test_each_position_or_description_forgery_refused(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:
parent, _, key = f["pointer"].rpartition("/")
container = pointer(s, parent)
container[int(key) if isinstance(container, list) else key] = "forged"
refuse(s, r)
@pytest.mark.parametrize("i", range(10))
@pytest.mark.parametrize("variant", ["mode", "identity"])
def test_each_node_state_and_identity_is_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_all_physical_endpoints_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] = 99999
elif variant == "input":
ns[dst]["inputs"][inp]["link"] = 99999
else:
ns[src]["outputs"][slot]["links"] = []
refuse(s, r)
@pytest.mark.parametrize(
"variant",
[
"named",
"frontend",
"ue",
"empty_list",
"missing",
"empty",
"path",
"source_sha",
"citation",
"overview",
"unconnected",
"history",
"type",
],
)
def test_specific_boundaries_cannot_be_retrusted(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 == "named":
ns[146]["widgets_values_named"] = {"Number": 4}
elif variant == "frontend":
s["extra"]["frontendVersion"] = "new"
elif variant == "ue":
ns[104]["properties"]["ue_properties"]["version"] = "new"
elif variant == "empty_list":
ns[136]["widgets_values"] = None
elif variant in ["missing", "empty"]:
r["fixed_version_document"] = {} if variant == "empty" else None
assert not doc(s, r)["fixed_version"]["matched"]
return
elif variant == "path":
b["source_path"] = "wrong"
elif variant == "source_sha":
r["source_sha"] = "wrong"
elif variant == "citation":
b["sources"][0]["sha256"] = "wrong"
elif variant == "overview":
b["user_overview"] = "wrong"
elif variant == "unconnected":
ns[103]["outputs"][0]["links"] = [337]
elif variant == "history":
ns[124]["widgets_values"]["videopreview"]["params"]["fullpath"] = "new"
else:
ns[146]["widgets_values"][0] = "4"
refuse(s, r)
def test_independent_inventory_and_actual_unconnected_branch():
assert doc()["fixed_version"]["matched"]
assert len(SOURCE["nodes"]) == len(SOURCE["links"]) == 10 and "definitions" not in SOURCE
expected = [
f"/nodes/{i}/widgets_values/{j}"
for i, n in enumerate(SOURCE["nodes"])
for j in (
list(n["widgets_values"])
if isinstance(n["widgets_values"], dict)
else range(len(n["widgets_values"]))
)
]
assert expected == [f["pointer"] for f in BLOCK["fields"]] and len(expected) == 37
ns = {n["id"]: n for n in SOURCE["nodes"]}
for eid, src, slot, dst, inp, _ in SOURCE["links"]:
assert ns[dst]["inputs"][inp]["link"] == eid
assert eid in ns[src]["outputs"][slot]["links"]
assert ns[103]["outputs"][0]["links"] == []
assert [(e[1], e[3]) for e in SOURCE["links"]] == [
(123, 136),
(136, 103),
(137, 104),
(104, 124),
(123, 124),
(146, 104),
(149, 123),
(156, 103),
(155, 124),
(136, 137),
]
assert [n["node_id"] for n in BLOCK["zero_saved_nodes"]] == ["136", "137"]
assert not BLOCK["comments"]
assert sum(isinstance(f["value"], dict) for f in BLOCK["fields"]) == 2
assert all(n["mode"] == 0 for n in SOURCE["nodes"])
def test_static_implementation_conditions_without_upstream_execution():
ref = OUT.parent / "simple-vfi-reference"
literal = (ref / "literals__nodes.py").read_text()
tree = ast.parse(literal)
for name, method, cast in [
("IntLiteral", "to_int", "int"),
("FloatLiteral", "to_float", "float"),
]:
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name)
fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == method)
calls = [
n for n in ast.walk(fn) if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)
]
assert any(c.func.id == cast for c in calls)
assert any(isinstance(n, ast.Raise) for n in ast.walk(fn))
rife = (ref / "rife__vfi_models__rife____init__.py").read_text()
assert '"rife49.pth": "4.7"' in rife and '"default":True' in rife
arch = (ref / "rife__vfi_models__rife__rife_arch.py").read_text()
assert 'if not fastmode and self.arch_ver in ["4.0", "4.2", "4.3"]:' in arch
loop = (ref / "rife__vfi_utils.py").read_text()
assert "range(len(frames) - 1)" in loop and "range(1, multiplier)" in loop
cr = (ref / "cr__nodes__functions_upscale.py").read_text()
assert "if mode == 'rescale':" in cr and "if supersample == 'true':" in cr
assert "int(original_width * factor)" in cr and "new_width * 8" in cr
fields = {(f["node_id"], f["field"]): f for f in BLOCK["fields"]}
assert (
fields["146", "Number"]["json_type"] == "int"
and fields["146", "Number"]["type"] == "STRING"
)
for nid in ["149", "155", "156"]:
assert fields[nid, "Number"]["json_type"] == "str"
assert fields["103", "rescale_factor"]["value"] == 2.0000000000000004
assert fields["103", "supersample"]["value"] == "true"
assert "未接" in BLOCK["user_overview"] or "没有接入" in BLOCK["user_overview"]
assert all(
fields[n, k]["role"] == "linked_cache"
for n, k in [
("104", "multiplier"),
("123", "force_rate"),
("103", "rescale_factor"),
("124", "frame_rate"),
]
)
def test_old_34_blocks_and_all_other_reviews_frozen():
p = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old = json.loads(subprocess.check_output(["git", "show", "8afc7af:" + p], cwd=REPO))
now = json.loads((REPO / p).read_bytes())
now[PATH].pop("fixed_version_document")
assert now == old and len(DEFINITIONS) == 35
blocks = [r["fixed_version_document"] for r in old.values() if "fixed_version_document" in r]
assert (
len(blocks) == 34
and sum(len(b["fields"]) for b in blocks) == 1069
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
)
== 25
)