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

313 lines
12 KiB
Python

"""Independent original, exact Git/release identities and protocol audit; AST/text only."""
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 source_time(value):
"""Preserve explicit unknowns; never replace them with a default timestamp."""
if value is None or (isinstance(value, str) and value.startswith(("未知", "unknown"))):
return None
parsed = datetime.fromisoformat(value[:-1] + "+00:00" if value.endswith("Z") else value)
if parsed.utcoffset() is None:
raise ValueError("source timestamp requires an explicit timezone: " + value)
return parsed
def validate_source_times(rows):
records, errors = [], []
for i, row in enumerate(rows):
first = source_time(row.get("acquisition_time"))
verified = source_time(row.get("reverified_at"))
record = dict(
index=i,
acquisition_time=row.get("acquisition_time"),
reverified_at=row.get("reverified_at"),
comparable=first is not None and verified is not None,
)
records.append(record)
if first is not None and verified is not None and verified < first:
errors.append(record)
if errors:
raise ValueError("reverified_at precedes acquisition_time: " + json.dumps(errors))
return records
def main():
raw = (REPO / PATHS[0]).read_bytes()
assert sha(raw) == "3ea95e56f193c046937ad246087292865a809d2cc26571357c22fff415295f41"
g = json.loads(raw)
b = build()
inv = inventory()
nodes = {n["id"]: n for n in g["nodes"]}
assert len(g["nodes"]) == 90 and len(g["links"]) == 87 and "definitions" not in g
assert collections.Counter(n["mode"] for n in g["nodes"]) == {0: 76, 4: 14}
assert len(inv["fields"]) == len(b["fields"]) == 270
assert collections.Counter(f["json_type"] for f in inv["fields"]) == {
"str": 122,
"int": 78,
"bool": 51,
"dict": 6,
"float": 11,
"NoneType": 2,
}
assert not any("widgets_values_named" in n for n in g["nodes"])
assert len(inv["empty"]) == len(b["zero_saved_nodes"]) == 7
assert collections.Counter(n["state"] for n in inv["empty"]) == {"missing": 3, "empty_list": 4}
for s, f in zip(inv["fields"], b["fields"], strict=True):
assert s["pointer"] == f["pointer"] and canonical(s["value"]) == canonical(f["value"])
assert s["json_type"] == f["json_type"] and f["named_state"] == "missing"
assert "named_value" not in f and "named_pointer" not in f
note = inv["notes"][0]
text = note["text"]
assert len(inv["notes"]) == len(b["comments"]) == 1
assert (
note["node"] == 722
and len(text) == 38
and text.count("\n") == 2
and text.endswith("\n")
and "\r" not in text
)
assert text == b["comments"][0]["text"]
notes = [dict(node="722", characters=38, LF=2, CR=0, tail_LF=True, sha256=sha(text.encode()))]
assert g["extra"]["frontendVersion"] == "1.23.0" and all(
"proxyWidgets" not in n.get("properties", {}) for n in g["nodes"]
)
rows = json.loads((REF / "sources.json").read_bytes())["sources"]
write("source-time-check.json", validate_source_times(rows))
trees = {}
identities = []
for e in rows:
data = (REF / e["local_file"]).read_bytes()
assert sha(data) == e["sha256"]
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.get("identity_root", ".")).resolve()
key = e.get("identity_key", e["id"])
tree = json.loads((root / (key + "-tree.json")).read_bytes())
assert next(x["sha"] for x in tree["tree"] if x["path"] == e["file"]) == blob
commit = (root / (key + "-commit.txt")).read_bytes()
assert (
hashlib.sha1(b"commit " + str(len(commit)).encode() + b"\0" + commit).hexdigest()
== e["commit"]
)
assert commit.splitlines()[0] == ("tree " + tree["sha"]).encode()
if "member_crc32" in e:
assert (zlib.crc32(data) & 0xFFFFFFFF) == e["member_crc32"]
members = json.loads((REF / (e["id"] + "-members.json")).read_bytes())
m = next(x for x in members if x["name"] == e["file"])
assert m["crc"] == e["member_crc32"] and m["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[(e["id"], e["file"])] = ast.parse(data)
identities.append(
dict(
id=e["id"],
file=e["file"],
sha256=e["sha256"],
git_blob=blob,
member_crc=e.get("member_crc32"),
first=e.get("acquisition_time", "未知"),
reverified=e["reverified_at"],
)
)
lock = json.loads((REF / "frontend__package-lock.json").read_bytes())
lg = lock["packages"]["node_modules/@comfyorg/litegraph"]
assert lg["version"] == "0.15.15"
assert (
json.loads((REF / "litegraph__package__package.json").read_bytes())["version"] == "0.15.15"
)
lgrows = [e for e in rows if e["id"] == "litegraph"]
assert all("sha512-" + e["artifact_sha512_base64"] == lg["integrity"] for e in lgrows)
frontend = dict(
declared="1.23.0",
same_tree_lock=True,
litegraph_version=lg["version"],
lock_integrity=lg["integrity"],
member_shas=[dict(file=e["file"], sha256=e["sha256"]) for e in lgrows],
whole_package_rehashed_this_batch=False,
git_binding="unknown for npm members",
target_restore_verified=False,
)
assert len({e["commit"] for e in rows if e["id"] == "frontend"}) == 1
accurate = [x for x in b["node_bindings"] if x["implementation_verified"]]
gaps = [x for x in b["node_bindings"] if x["source_id"].startswith("unresolved-")]
unknown = [x for x in b["node_bindings"] if x["source_id"] == "unknown-no-version"]
assert len(accurate) == 38 and len(gaps) == 3 and len(unknown) == 48
assert {n["node_id"] for n in gaps} == {"638", "649", "611"}
for n in accurate:
c = n["candidates"][0]
e = rows[c["source"]]
cls = next(
x
for x in trees[(e["id"], e["file"])].body
if isinstance(x, ast.ClassDef) and x.name == c["symbol"]
)
assert [cls.lineno, cls.end_lineno] == c["lines"]
for stem in ["761b", "2bdd"]:
request = json.loads(
(
REF
/ (
stem
+ "-current-response"
+ (".json.request.json" if stem == "761b" else "-request.json")
)
).read_bytes()
)
assert request["status"] == 422
edge = {e[0]: e for e in g["links"]}
for eid, a, z in [
(937, 592, 591),
(977, 591, 628),
(1283, 752, 574),
(1284, 574, 754),
(1282, 754, 628),
(979, 628, 629),
(1109, 634, 629),
(1016, 630, 651),
(1234, 725, 726),
(1233, 726, 724),
(1235, 724, 646),
(1011, 646, 645),
(1257, 732, 642),
(1267, 740, 735),
(1260, 735, 737),
]:
assert edge[eid][1] == a and edge[eid][3] == z
valid = set(nodes)
assert all(e[1] in valid and e[3] in valid for e in g["links"])
assert "links" not in nodes[630]["outputs"][1] and "link" not in next(
x for x in nodes[630]["inputs"] if x["name"] == "samples"
)
assert (
next(x for x in nodes[649]["inputs"] if x["name"] == "positive_prompt")["link"] == 1273
and nodes[649]["widgets_values"][2] == ""
)
assert (
nodes[594]["widgets_values"][-1] == "True" and type(nodes[710]["widgets_values"][0]) is int
)
assert nodes[735]["widgets_values"][-1] is None and nodes[740]["widgets_values"][-1] is None
assert nodes[752]["widgets_values"][3] == 0.6500000000000001
def field(n, name):
return next(f for f in b["fields"] if f["node_id"] == str(n) and f["field"] == name)
assert (
field(630, "batched_cfg")["value"] == "" and "BOOLEAN" in field(630, "batched_cfg")["type"]
)
assert all(
field(592, k)["role"] == "extra_saved"
for k in ["force_parameter_static_shapes", "allow_unmerged_lora_compile"]
)
assert all(field(626, k)["role"] == "extra_saved" for k in ["use_cpu_cache", "verbose"])
assert field(593, "face_padding")["role"] == "extra_saved"
for nid in [735, 740]:
assert field(nid, "position_3")["role"] == "extra_saved"
histories = []
for nid in [640, 641, 642, 653, 737, 670]:
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)),
)
)
sensitive = []
def scan(v, p=""):
if isinstance(v, dict):
for k, x in v.items():
if (
re.fullmatch(
r"api[_-]?key|authorization|password|secret|access[_-]?token", k, re.I
)
and x
):
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
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=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("expected-edges.json", {"root": g["links"]})
write(
"scoped-edge-check.json",
dict(records=87, endpoints=[dict(scope="root", edge=e) for e in g["links"]]),
)
write("proxy-check.json", dict(proxy_widgets=0, hosts=[], frontend_version="1.23.0"))
write("frontend-lock-check.json", frontend)
write("identity-gaps.json", dict(unresolved=gaps, unknown=unknown, frontend=frontend))
write(
"exact-source-check.json",
dict(
accurate=accurate,
unresolved=gaps,
unknown=unknown,
sources=len(rows),
identities=identities,
upstream_executed=False,
),
)
write(
"source-check.json",
dict(
original_sha256=sha(raw),
saved_fields=270,
notes=notes,
texts=texts,
accurate_instances=38,
unresolved_instances=3,
unknown_instances=48,
sensitive_positions=sensitive,
),
)
write("history-order-evidence.json", histories)
print(
"PASS270 saved/1 Note/90 nodes/87 edges;38 exact/3 commit gaps/48 unknown;frontend1.23 lock"
)
if __name__ == "__main__":
main()