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

132 lines
5.1 KiB
Python

"""Verify exact bytes, bounded citations, identities and physical backreferences."""
import hashlib
import json
from build_definition import OUT, PATHS, REF, REPO, build, canonical
from inventory import inventory
def main():
b = build()
rows = json.loads((REF / "sources.json").read_bytes())["sources"]
checked = []
for e in rows:
raw = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
assert blob == e["git_blob_sha1"]
root, key = REF / e["identity_root"], e["identity_key"]
tree = json.loads((root / (key + "-tree.json")).read_bytes())
assert not tree["truncated"]
assert next(t["sha"] for t in tree["tree"] if t["path"] == e["file"]) == blob
commit_path = root / (key + "-commit.txt")
if commit_path.is_file():
commit = commit_path.read_bytes()
assert (
hashlib.sha1(b"commit " + str(len(commit)).encode() + b"\0" + commit).hexdigest()
== e["commit"]
)
assert commit.decode().splitlines()[0] == "tree " + e["tree"]
proof = "raw Git commit object hash + selected blob + tree index"
else:
c = json.loads((root / (key + "-commit.json")).read_bytes())
assert c["sha"] == e["commit"]
assert c.get("commit", c)["tree"]["sha"] == e["tree"]
proof = (
"pinned GitHub commit/tree metadata + selected blob; not full tree-object rehash"
)
# Some historic API indexes use the commit as the requested ref in `sha`.
# Compare its immutable ref with the independently bound commit/tree, and
# never mislabel that request ref as the Git tree object identity.
assert tree["sha"] in [e["commit"], e["tree"]]
license_path = REF / e["license_file"]
if license_path.is_file():
license_row = next(v for v in rows if v["id"] == e["id"] and v["file"] == "LICENSE")
assert hashlib.sha256(license_path.read_bytes()).hexdigest() == license_row["sha256"]
else:
assert e["id"] in ["tt", "llama", "cr"]
assert not any(
t["path"].lower().split("/")[-1].startswith(("license", "licence", "copying"))
for t in tree["tree"]
)
checked.append(
dict(
id=e["id"],
file=e["file"],
commit=e["commit"],
tree=e["tree"],
blob=blob,
sha256=e["sha256"],
proof=proof,
license=e["license_file"],
)
)
inv = inventory()
assert (len(inv["fields"]), inv["nodes"], inv["edges"], inv["notes"], inv["named_nodes"]) == (
48,
23,
24,
1,
0,
)
assert inv["modes"].count(0) == 18 and inv["modes"].count(4) == 5
assert {e["node"]: e["state"] for e in inv["empty"]} == {
83: "empty_list",
82: "empty_list",
95: "empty_list",
102: "missing",
103: "missing",
}
for a, f in zip(inv["fields"], b["fields"], strict=True):
assert (a["pointer"], a["json_type"], canonical(a["value"])) == (
f["pointer"],
f["json_type"],
canonical(f["value"]),
)
assert f["evidence"]
for e in b["sources"]:
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())
g = json.loads((REPO / PATHS[0]).read_bytes())
ns = {n["id"]: n for n in g["nodes"]}
edges = []
for edge in g["links"]:
eid, a, ao, z, zi, kind = edge
source, target = ns[a]["outputs"][ao], ns[z]["inputs"][zi]
assert eid in (source.get("links") or []) and target.get("link") == eid
assert source["type"] in [kind, "*"] and target["type"] in [kind, "*"]
edges.append(
dict(
edge=edge,
source_backref=True,
target_backref=True,
source_type=source["type"],
target_type=target["type"],
)
)
assert ns[82]["outputs"][1]["links"] == [] and ns[9]["outputs"] == []
assert ns[97]["outputs"][0]["links"] is None
assert ns[97]["outputs"][1]["shape"] == 6
assert not {n["type"] for n in g["nodes"]} & {"LoadImage", "ReferenceLatent", "PreviewImage"}
result = dict(
all_pass=True,
source_files=len(rows),
citations=len(b["sources"]),
identities=checked,
counts=b["counts"],
physical_endpoint_checks=edges,
upstream_executed=False,
list_processed=False,
prompt_constructed=False,
source_protocol_conflicts_retained=[],
saveimage_empty_outputs_matches_return=True,
)
(OUT / "source-check.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
print("PASS", len(rows), "texts;", len(b["sources"]), "citations; 48 positions/24 edges")
if __name__ == "__main__":
main()