Files
aigc-home/docs/hel-892/animate-mask-document-evidence/verify_sources.py
T

344 lines
14 KiB
Python

"""Independent graph/value/date/identity/proxy audit; AST/text only, never upstream imports."""
import ast
import collections
import hashlib
import json
import re
import zlib
from datetime import datetime
from build_definition import OUT, PATHS, REF, REPO, build, canonical
from inventory import inventory
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def write(name, value):
(OUT / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
def moment(value):
if value is None or value.startswith(("未知", "unknown")):
return None
result = datetime.fromisoformat(value.replace("Z", "+00:00"))
assert result.utcoffset() is not None, value
return result
def main():
raw = (REPO / PATHS[0]).read_bytes()
assert sha(raw) == "394c3c31ad05255d3eb130f309d8445764f4d3772b40fa07fbf19708bfcc1002"
g = json.loads(raw)
b, inv = build(), inventory()
assert len(g["nodes"]) == 114 and len(g["links"]) == 101
assert collections.Counter(n["mode"] for n in g["nodes"]) == {0: 113, 4: 1}
assert next(n for n in g["nodes"] if n["mode"] == 4)["id"] == 430
assert [len(s["nodes"]) for s in g["definitions"]["subgraphs"]] == [6, 7, 7]
assert [len(s["links"]) for s in g["definitions"]["subgraphs"]] == [33, 32, 32]
assert len(inv["fields"]) == len(b["fields"]) == 236
assert collections.Counter(f["json_type"] for f in inv["fields"]) == {
"str": 141,
"int": 74,
"bool": 16,
"dict": 4,
"NoneType": 1,
}
assert all(s["named_nodes"] == 0 for s in inv["scopes"])
assert collections.Counter(n["state"] for n in inv["empty"]) == {
"empty_list": 12,
"empty_dict": 1,
}
for old, current in zip(inv["fields"], b["fields"], strict=True):
assert old["pointer"] == current["pointer"]
assert canonical(old["value"]) == canonical(current["value"])
assert old["json_type"] == current["json_type"] == type(current["value"]).__name__
assert current["named_state"] == "missing"
assert "named_pointer" not in current and "named_value" not in current
expected_notes = {
161: (245, 2, False),
103: (201, 3, True),
226: (455, 7, True),
44: (2110, 41, False),
238: (101, 0, False),
126: (208, 10, False),
227: (183, 7, False),
}
notes = []
for n in inv["notes"]:
text = n["text"]
assert (len(text), text.count("\n"), text.endswith("\n")) == expected_notes[n["node"]]
assert "\r" not in text
assert text == next(x["text"] for x in b["comments"] if x["node_id"] == str(n["node"]))
notes.append(
dict(
node=str(n["node"]),
characters=len(text),
LF=text.count("\n"),
CR=0,
tail_LF=text.endswith("\n"),
sha256=sha(text.encode()),
)
)
rows = json.loads((REF / "sources.json").read_bytes())["sources"]
times, identities = [], []
trees = {}
for i, e in enumerate(rows):
data = (REF / e["local_file"]).read_bytes()
assert sha(data) == e["sha256"]
acquired, verified = moment(e.get("acquisition_time")), moment(e.get("reverified_at"))
assert verified is not None
if acquired is not None:
assert acquired <= verified, (i, e["file"])
times.append(
dict(
index=i,
first=e.get("acquisition_time", "未知:原记录缺首次取得时间"),
reverified=e["reverified_at"],
comparable=acquired is not None,
)
)
blob = e.get("git_blob_sha1", "")
if re.fullmatch("[0-9a-f]{40}", blob):
assert (
hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest() == blob
)
root = (REF / e["identity_root"]).resolve()
key = e.get("identity_key", e["id"])
tree = json.loads((root / (key + "-tree.json")).read_bytes())
assert tree["sha"] == e["tree"]
assert next(x["sha"] for x in tree["tree"] if x["path"] == e["file"]) == blob
cb = (root / (key + "-commit.txt")).read_bytes()
assert (
hashlib.sha1(b"commit " + str(len(cb)).encode() + b"\0" + cb).hexdigest()
== e["commit"]
)
assert cb.splitlines()[0] == ("tree " + e["tree"]).encode()
if "member_crc32" in e:
assert zlib.crc32(data) & 0xFFFFFFFF == e["member_crc32"]
members = json.loads((REF / (e["id"] + "-members.json")).read_bytes())
member = next(x for x in members if x["name"] == e["file"])
assert member["crc"] == e["member_crc32"] and member["size"] == len(data)
assert e["package_sha256"] == "unknown-not-downloaded-whole-archive"
if not e["license_file"].startswith("未知"):
assert (REF / e["license_file"]).is_file()
if e["file"].endswith(".py"):
trees[i] = ast.parse(data)
identities.append(
dict(
index=i,
file=e["file"],
sha256=e["sha256"],
git_blob=blob,
commit=e["commit"],
tree=e["tree"],
member_crc=e.get("member_crc32"),
)
)
accurate = [n for n in b["node_bindings"] if n["implementation_verified"]]
gaps = [n for n in b["node_bindings"] if n["source_id"].startswith("unresolved-")]
unknown = [n for n in b["node_bindings"] if n["source_id"] == "unknown-no-version"]
assert (len(accurate), len(gaps), len(unknown), len(b["boundaries"])) == (55, 3, 66, 3)
assert {n["node_id"] for n in gaps} == {"232:62", "375:362", "409:428"}
registrations = []
for n in accurate:
candidate = n["candidates"][0]
tree = trees[candidate["source"]]
cls = next(
x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == candidate["symbol"]
)
assert [cls.lineno, cls.end_lineno] == candidate["lines"]
registrations.append(
dict(
node=n["node_id"],
type=n["class_type"],
source=candidate["source"],
symbol=cls.name,
lines=candidate["lines"],
)
)
frontend = [e for e in rows if e["id"] == "frontend"]
assert g["extra"]["frontendVersion"] == "1.32.1"
package = next(e for e in frontend if e["file"] == "package.json")
pkg = json.loads((REF / package["local_file"]).read_bytes())
assert pkg["version"] == "1.32.1"
assert "@comfyorg/litegraph" not in pkg.get("dependencies", {})
assert any(e["file"] == "pnpm-lock.yaml" for e in frontend)
assert any(e["file"] == "src/lib/litegraph/LICENSE" for e in frontend)
assert len({e["commit"] for e in frontend}) == len({e["tree"] for e in frontend}) == 1
frontend_proof = dict(
declared="1.32.1",
exact_same_tree_lock=True,
litegraph="bundled exact frontend Git tree; no external0.15.15 claim",
members=[dict(file=e["file"], sha256=e["sha256"]) for e in frontend],
target_restore_verified=False,
)
assert [len(h["proxy_mappings"]) for h in b["boundaries"]] == [9, 10, 11]
for s, host in zip(g["definitions"]["subgraphs"], b["boundaries"], strict=True):
assert host["widgets"] == s["widgets"] == [] and host["host"]["widgets_values"] == []
assert [m["raw_pair"] for m in host["proxy_mappings"]] == host["host"]["properties"][
"proxyWidgets"
]
for m in host["proxy_mappings"]:
f = next(f for f in b["fields"] if f["pointer"] == m["internal_saved_pointer"])
assert m["definition_node_id"] == f["definition_node_id"] and m["field"] == f["field"]
assert canonical(m["internal_saved_value"]) == canonical(f["value"])
assert not m["host_value_generated"]
scopes = [("root", g)] + [
("宿主" + h["host_node_id"] + "内部定义", s)
for h, s in zip(b["boundaries"], g["definitions"]["subgraphs"], strict=True)
]
scoped = [dict(scope=scope, edge=e) for scope, graph in scopes for e in graph["links"]]
assert len(scoped) == 198
duplicate_declarations = []
boundary_inconsistencies = []
inconsistencies = []
for scope, graph in scopes:
edges = {e[0] if isinstance(e, list) else e["id"]: e for e in graph["links"]}
for direction in ["inputs", "outputs"]:
for slot, port in enumerate(graph.get(direction, [])):
counts = collections.Counter(port.get("linkIds", []))
boundary_id = graph["inputNode" if direction == "inputs" else "outputNode"]["id"]
endpoint = "origin" if direction == "inputs" else "target"
actual_ids = [
e["id"]
for e in graph["links"]
if e[endpoint + "_id"] == boundary_id and e[endpoint + "_slot"] == slot
]
if counts != collections.Counter(actual_ids):
boundary_inconsistencies.append(
dict(
scope=scope,
direction=direction,
slot=slot,
declared_linkIds=port.get("linkIds", []),
graph_records=actual_ids,
)
)
for eid, count in counts.items():
if count > 1:
duplicate_declarations.append(
dict(scope=scope, direction=direction, slot=slot, id=eid, count=count)
)
for n in graph["nodes"]:
for direction in ["inputs", "outputs"]:
for slot, port in enumerate(n.get(direction, [])):
declared = (
[port["link"]]
if direction == "inputs" and port.get("link") is not None
else port.get("links", []) or []
)
for eid in declared:
edge = edges.get(eid)
if isinstance(edge, dict):
actual = (
(edge["target_id"], edge["target_slot"])
if direction == "inputs"
else (edge["origin_id"], edge["origin_slot"])
)
elif edge:
actual = (
(edge[3], edge[4]) if direction == "inputs" else (edge[1], edge[2])
)
else:
actual = None
if actual != (n["id"], slot):
inconsistencies.append(
dict(
scope=scope,
node=n["id"],
direction=direction,
slot=slot,
id=eid,
edge=edge,
)
)
assert any(d["id"] == 187 for d in duplicate_declarations)
nodes = {n["id"]: n for n in g["nodes"]}
assert nodes[229]["outputs"][0]["links"] == [438]
assert all(p["links"] is None for p in nodes[229]["outputs"][1:])
assert nodes[107]["inputs"][3]["link"] is None
assert nodes[229]["widgets_values"][-2:] == ["", None]
assert nodes[229]["widgets_values"][6:9] == [480, 832, False]
assert nodes[417]["widgets_values"] == {}
histories = []
for nid in [287, 288, 289, 291]:
v = nodes[nid]["widgets_values"]["videopreview"]
ordered = json.dumps(v, ensure_ascii=False, separators=(",", ":"))
histories.append(
dict(
node=str(nid),
original_order_json=ordered,
original_order_sha256=sha(ordered.encode()),
sorted_canonical_sha256=sha(canonical(v)),
)
)
texts = [
dict(
node=f["node_id"],
field=f["field"],
pointer=f["pointer"],
characters=len(f["value"]),
LF=f["value"].count("\n"),
CR=f["value"].count("\r"),
tail_LF=f["value"].endswith("\n"),
sha256=sha(f["value"].encode()),
)
for f in b["fields"]
if isinstance(f["value"], str) and len(f["value"]) > 100
]
write("independent-inventory.json", inv)
write(
"source-check.json",
dict(
original_sha256=sha(raw),
saved_fields=236,
notes=notes,
texts=texts,
accurate_instances=55,
unresolved_instances=3,
unknown_instances=66,
),
)
write(
"exact-source-check.json",
dict(
accurate=accurate,
unresolved=gaps,
unknown=unknown,
identities=identities,
sources=len(rows),
upstream_executed=False,
),
)
write("registration-check.json", registrations)
write("source-time-check.json", times)
write("frontend-lock-check.json", frontend_proof)
write("identity-gaps.json", dict(unresolved=gaps, unknown=unknown, boundary_hosts=3))
write(
"proxy-check.json", dict(proxy_widgets=30, hosts=b["boundaries"], frontend=frontend_proof)
)
write("expected-edges.json", {scope: graph["links"] for scope, graph in scopes})
write(
"scoped-edge-check.json",
dict(
records=198,
endpoints=scoped,
duplicate_boundary_declarations=duplicate_declarations,
boundary_port_inconsistencies=boundary_inconsistencies,
node_port_inconsistencies=inconsistencies,
repaired=False,
),
)
write("history-order-evidence.json", histories)
print(
"PASS236 typed saved/7 Notes/134 nodes/198 scoped records/30proxy;"
"55 exact/3 specific gaps/66 unknown;real source dates"
)
if __name__ == "__main__":
main()