Files
aigc-home/docs/hel-892/scail-document-evidence/verify_sources.py
T
2026-11-01 18:11:45 +08:00

430 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Independently verify scoped original, exact class registration and real proxies."""
import ast
import collections
import hashlib
import json
import re
import zlib
from build_definition import (
BINDINGS,
HOSTS,
OUT,
PATHS,
REF,
REPO,
build,
canonical,
node_schema,
scoped_graphs,
)
from inventory import inventory
def write(name, value):
(OUT / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
def pointer(obj, path):
for key in path.strip("/").split("/"):
obj = obj[int(key)] if isinstance(obj, list) else obj[key]
return obj
def registered(tree, symbol):
for n in ast.walk(tree):
if isinstance(n, ast.Assign) and any(
isinstance(t, ast.Name) and t.id in ["NODE_CLASS_MAPPINGS", "NODE_CONFIG"]
for t in n.targets
):
if any(isinstance(x, ast.Name) and x.id == symbol for x in ast.walk(n.value)):
return True
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "get_node_list":
if any(isinstance(x, ast.Name) and x.id == symbol for x in ast.walk(n)):
return True
return False
def output_count(cl):
method = next(
m for m in cl.body if isinstance(m, ast.FunctionDef) and m.name == "define_schema"
)
schema = next(
c
for c in ast.walk(method)
if isinstance(c, ast.Call) and isinstance(c.func, ast.Attribute) and c.func.attr == "Schema"
)
out = next((k.value for k in schema.keywords if k.arg == "outputs"), None)
return len(out.elts) if isinstance(out, ast.List) else 0
def main():
inv = inventory()
g = json.loads((REPO / PATHS[0]).read_bytes())
b = build()
assert inv["sha256"] == "60d7a6c9b1b567d726ffd0981de3d8afb3675f88b320733d8442081d849b0ba8"
assert [(s["nodes"], s["edges"]) for s in inv["scopes"]] == [
(53, 53),
(42, 89),
(46, 96),
(8, 16),
]
assert all(set(s["modes"]) == {0} and s["named_nodes"] == 0 for s in inv["scopes"])
assert len(inv["fields"]) == 195 and len(inv["notes"]) == 10
assert collections.Counter(f["json_type"] for f in inv["fields"]) == dict(
str=90, int=75, bool=18, NoneType=6, float=6
)
assert collections.Counter(x["state"] for x in inv["empty"]) == dict(empty_list=17, missing=15)
assert collections.Counter(f["scope"] for f in inv["fields"]) == {
"root": 39,
"/definitions/subgraphs/0": 72,
"/definitions/subgraphs/1": 79,
"/definitions/subgraphs/2": 5,
}
scoped = scoped_graphs(g)
all_nodes, edge_checks = {}, []
expected = {}
for pre, prefix, graph in scoped:
ns = {n["id"]: n for n in graph["nodes"]}
all_nodes.update({pre + str(n["id"]): n for n in graph["nodes"]})
expected[pre or "root"] = graph["links"]
for raw in graph["links"]:
eid, src, si, dst, di, typ = (
raw
if isinstance(raw, list)
else [
raw[k]
for k in ["id", "origin_id", "origin_slot", "target_id", "target_slot", "type"]
]
)
if src in ns:
assert eid in ns[src]["outputs"][si]["links"]
else:
assert pre and src == graph["inputNode"]["id"]
assert eid in graph["inputs"][si]["linkIds"]
if dst in ns:
assert ns[dst]["inputs"][di]["link"] == eid
else:
assert pre and dst == graph["outputNode"]["id"]
assert eid in graph["outputs"][di]["linkIds"]
edge_checks.append(
dict(
scope=pre or "root",
id=eid,
origin=src,
origin_slot=si,
target=dst,
target_slot=di,
type=typ,
)
)
assert len(edge_checks) == 254
write("expected-edges.json", expected)
for f, x in zip(b["fields"], inv["fields"], strict=True):
assert f["pointer"] == x["pointer"] and f["json_type"] == x["json_type"]
assert (
canonical(f["value"]) == canonical(x["value"])
and type(f["value"]).__name__ == f["json_type"]
)
assert f["named_state"] == "missing" and "named_value" not in f and "named_pointer" not in f
if f["input_pointer"].startswith("/"):
assert pointer(g, f["input_pointer"])["name"] == f["input_name"]
for note, x in zip(b["comments"], inv["notes"], strict=True):
assert note["pointer"] == x["pointer"] and note["text"] == x["text"]
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
assert len({(e["id"], e["file"]) for e in manifest}) == len(manifest)
trees, checks = {}, []
for e in manifest:
raw = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\x00" + raw).hexdigest()
if re.fullmatch("[0-9a-f]{40}", e.get("git_blob_sha1", "")):
assert blob == e["git_blob_sha1"]
if not e["license_file"].startswith("未知"):
assert (REF / e["license_file"]).is_file()
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(raw)
checks.append(
dict(
id=e["id"],
file=e["file"],
sha256=e["sha256"],
git_blob_sha1=e.get("git_blob_sha1", "未知"),
first_acquisition=e.get("acquisition_time", "未知:原记录未载"),
reverified_at=e.get("reverified_at", "未知"),
license_file=e["license_file"],
)
)
exact, gaps, unknown, hosts, classes = [], [], [], [], {}
for binding in b["node_bindings"]:
nid = binding["node_id"]
key, file, symbol = BINDINGS[nid]
if key == "boundary":
assert all_nodes[nid]["type"] in HOSTS and binding["source_id"] == "subgraph-definition"
hosts.append(nid)
continue
if key == "unknown":
assert not all_nodes[nid].get("properties", {}).get("ver")
assert not binding["implementation_verified"] and not binding["candidates"]
unknown.append(
dict(
node=nid,
class_type=all_nodes[nid]["type"],
scope="没有准确版本;名称/aux不认证schema/默认/副作用/穿透/恢复",
)
)
continue
e = next(e for e in manifest if e["id"] == key and e["file"] == file)
cl = next(
(
c
for c in trees[e["local_file"]].body
if isinstance(c, ast.ClassDef) and c.name == symbol
),
None,
)
if cl is None:
assert nid in ["213:197", "262:245"]
assert not binding["implementation_verified"] and not binding["candidates"]
gaps.append(
dict(
node=nid,
class_type=symbol,
commit=e["commit"],
scope="准确nodes_wan.py/nodes_sam3.py/所选post-processing入口未匹配;准确tree无nodes_scail.py,不作全仓不存在证明,不借后版",
)
)
continue
assert binding["implementation_verified"] and any(
registered(trees[x["local_file"]], symbol)
for x in manifest
if x["id"] == key and x["file"].endswith(".py")
), (nid, symbol)
classes[nid] = cl
exact.append(
dict(
node=nid,
class_type=binding["class_type"],
symbol=symbol,
source=e["local_file"],
commit=e["commit"],
lines=[cl.lineno, cl.end_lineno],
registered=True,
)
)
assert (len(exact), len(gaps), len(unknown), len(hosts)) == (111, 2, 23, 3)
for nid in ["213:114", "262:259"]:
schema = node_schema(classes[nid])
assert output_count(classes[nid]) == 3
assert (
not set(
[
"video_frame_offset",
"previous_frame_count",
"replacement_mode",
"pose_video_mask",
"reference_image_mask",
"previous_frames",
]
)
& schema.keys()
)
assert len(all_nodes[nid]["outputs"]) == 4
for nid in ["201", "270"]:
assert all_nodes[nid]["widgets_values"] == [30, 8]
assert "fps" in node_schema(classes[nid]) and "crf" not in node_schema(classes[nid])
for nid in ["202", "271"]:
assert len(all_nodes[nid]["widgets_values"]) == 3 and output_count(classes[nid]) == 0
assert all_nodes[nid]["outputs"][0]["links"] is None
for nid in ["213:19", "262:227"]:
assert output_count(classes[nid]) == 2
assert all_nodes[nid]["outputs"][0]["links"] == []
assert all_nodes[nid]["outputs"][1]["links"] == [124]
assert (
all_nodes["263"]["outputs"][0]["links"] is None
and all_nodes["263"]["outputs"][1]["links"] is None
)
assert (
all_nodes["264"]["outputs"][0]["links"] == []
and all_nodes["264"]["outputs"][2]["links"] is None
)
assert all_nodes["30"]["outputs"][1]["links"] is None
assert all_nodes["262"]["outputs"][1]["links"] == []
assert all_nodes["262:253"]["widgets_values"] == [-1, 1]
assert all_nodes["262:251"]["widgets_values"] == [5, 4096]
assert all_nodes["262:235"]["widgets_values"] == [0, 81]
assert all_nodes["264"]["widgets_values"] == ["ceil(a / (81 - 5))"]
proxies = []
for boundary in b["boundaries"]:
host = all_nodes[boundary["host_node_id"]]
s = next(s for s in g["definitions"]["subgraphs"] if s["id"] == host["type"])
assert host["widgets_values"] == [] and s["widgets"] == []
assert (
boundary["host"] == host
and boundary["inputs"] == s["inputs"]
and boundary["outputs"] == s["outputs"]
)
assert boundary["proxyWidgets"] == host["properties"]["proxyWidgets"]
for i, mapping in enumerate(boundary["proxy_mappings"]):
assert mapping["raw"] == host["properties"]["proxyWidgets"][i]
if mapping["preview_only"]:
assert (
mapping["widget"] == "$$canvas-image-preview"
and "saved_value" not in mapping
and "saved_pointer" not in mapping
)
else:
assert canonical(pointer(g, mapping["saved_pointer"])) == canonical(
mapping["saved_value"]
)
inner = all_nodes[mapping["node_id"]]
inp = next(
(p for p in inner.get("inputs", []) if p["name"] == mapping["widget"]), None
)
edge = next((e for e in s["links"] if inp and e["id"] == inp.get("link")), None)
assert edge == mapping["internal_origin_edge"]
if edge and edge["origin_id"] == s["inputNode"]["id"]:
slot = edge["origin_slot"]
assert mapping["host_input"] == host["inputs"][slot]
assert mapping["definition_input"] == s["inputs"][slot]
proxies.append(dict(host=boundary["host_node_id"], **mapping))
assert len(proxies) == 48 and sum(p["preview_only"] for p in proxies) == 4
assert [len(all_nodes[n]["inputs"]) for n in ["213", "262", "368"]] == [24, 26, 4]
assert g["extra"]["frontendVersion"] == "1.45.15"
front = next(e for e in manifest if e["id"] == "frontend" and e["file"] == "pnpm-lock.yaml")
assert front["commit"] == "deb4045f18d6457167598f61df63854372536db0"
lock = (REF / front["local_file"]).read_text()
assert "@comfyorg/litegraph" not in lock
assert any(
e["id"] == "litegraph" and e["file"] == "src/lib/litegraph/LICENSE" for e in manifest
)
range_record = json.loads((REF / "mathpkg-range-requests.json").read_bytes())
assert not range_record["full_archive_acquired"] and all(
r["status"] == 206 for r in range_record["requests"]
)
members = json.loads((REF / "mathpkg-members.json").read_bytes())["members"]
for e in manifest:
if e["id"] == "mathpkg":
raw = (REF / e["local_file"]).read_bytes()
m = next(m for m in members if m["name"] == e["file"])
assert len(raw) == m["size"] and zlib.crc32(raw) == m["crc"]
sensitive = []
def scan(v, p=""):
if isinstance(v, dict):
for k, x in v.items():
if k.lower() in [
"api_key",
"apikey",
"secret",
"password",
"token",
"access_token",
"authorization",
] and x not in [None, "", [], {}]:
sensitive.append(p + "/" + k)
scan(x, p + "/" + k)
elif isinstance(v, list):
for i, x in enumerate(v):
scan(x, p + "/" + str(i))
scan(g)
assert not sensitive
notes = [
dict(
node=str(n["node"]),
characters=len(n["text"]),
LF=n["text"].count("\n"),
CR=n["text"].count("\r"),
literal_backslash_n=n["text"].count("\\n"),
tail_LF=n["text"].endswith("\n"),
sha256=hashlib.sha256(n["text"].encode()).hexdigest(),
)
for n in inv["notes"]
]
assert [(n["node"], n["characters"], n["LF"], n["tail_LF"]) for n in notes] == [
("363", 7, 0, False),
("364", 6, 0, False),
("365", 8, 0, False),
("359", 10, 0, False),
("274", 3025, 90, True),
("320", 2448, 59, True),
("360", 10, 0, False),
("382", 10, 0, False),
("361", 8, 0, False),
("362", 19, 0, False),
]
texts = [
dict(
node=f["node_id"],
field=f["field"],
characters=len(f["value"]),
LF=f["value"].count("\n"),
CR=f["value"].count("\r"),
tail_LF=f["value"].endswith("\n"),
sha256=hashlib.sha256(f["value"].encode()).hexdigest(),
)
for f in b["fields"]
if isinstance(f["value"], str) and len(f["value"]) > 100
]
write(
"source-check.json",
dict(
original_sha256=inv["sha256"],
scopes=inv["scopes"],
saved_fields=195,
notes=notes,
texts=texts,
accurate_instances=111,
unresolved_instances=gaps,
unknown_instances=unknown,
source_hosts=hosts,
sensitive_positions=sensitive,
all_scoped_edge_endpoints_checked=True,
),
)
write(
"exact-source-check.json",
dict(
sources=checks,
exact_instances=exact,
unresolved_instances=gaps,
unknown_instances=unknown,
source_hosts=hosts,
upstream_executed=False,
),
)
write(
"identity-gaps.json",
dict(
unresolved=gaps,
unknown=unknown,
hosts=hosts,
protocol="Wan0.24额外三保存/三mask和续帧口/第四返回口;Create8额外;Save无VIDEO后端输出,原口不改",
publication="Math1.2.5仅五成员Range,Git/整包未知;Easy目标前端恢复未知",
),
)
write(
"proxy-check.json",
dict(
proxy_widgets=48,
saved_references=44,
preview_only=4,
mappings=proxies,
structural_mapping_is_not_backend_or_restoration_guarantee=True,
),
)
write(
"scoped-edge-check.json",
dict(records=254, scopes=expected, checked=edge_checks, not_flattened_or_executed=True),
)
print(
"PASS195 saved/10 full Notes/4 scopes/254 edge records;"
"111 exact/2 bounded gaps/23 no-version/3 source hosts;48 real proxies"
)
if __name__ == "__main__":
main()