227 lines
10 KiB
Python
227 lines
10 KiB
Python
"""Offline identity/evidence contracts, never a reimplementation of engine behavior."""
|
|
|
|
import ast
|
|
import base64
|
|
import copy
|
|
import csv
|
|
import hashlib
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import textwrap
|
|
|
|
from acquire import API, COMMIT, DOC, PATHS, REPO, ROOT, save, sha
|
|
from build import nodes
|
|
|
|
SNAPSHOT = ROOT / "docs/hel-892/batch179-target-snapshots/incoming/ssh-snapshot.stdout.json"
|
|
|
|
|
|
def gate(row, raw, snapshot, loaded_claim=False):
|
|
"""Accept exact historical working bytes only; caller cannot elevate to loaded state."""
|
|
if loaded_claim or row.get("current_process_loaded") != "unknown":
|
|
raise ValueError("current process state not observed")
|
|
if row["repo"] != REPO or row["commit"] != COMMIT or row["tree"] != snapshot["tree"]:
|
|
raise ValueError("canonical identity mismatch")
|
|
if row["path"] not in PATHS or not row.get("sampling_time_only"):
|
|
raise ValueError("path/scope mismatch")
|
|
expected = next(x for x in snapshot["files"] if x["relative_path"] == row["path"])
|
|
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
|
|
if len(raw) > 262144:
|
|
raise ValueError("decoded cap")
|
|
actual = dict(bytes=len(raw), sha256=sha(raw), git_blob_sha1=blob)
|
|
for field, value in actual.items():
|
|
if value != row[field] or value != expected[field]:
|
|
raise ValueError("working bytes mismatch: " + field)
|
|
if row["snapshot"] != expected or not expected["matches_head_blob"]:
|
|
raise ValueError("snapshot binding mismatch")
|
|
if row["snapshot_sha256"] != sha(SNAPSHOT.read_bytes()):
|
|
raise ValueError("snapshot original mismatch")
|
|
return True
|
|
|
|
|
|
def main():
|
|
baseline = json.loads((DOC / "baseline.json").read_text())
|
|
for entry in baseline["files"]:
|
|
raw = (ROOT / entry["path"]).read_bytes()
|
|
assert len(raw) == entry["bytes"] and sha(raw) == entry["sha256"], entry["path"]
|
|
local = json.loads((DOC / "old-local-artifacts.json").read_text())
|
|
for entry in local["files"]:
|
|
path = ROOT / entry["path"]
|
|
assert sha(path.read_bytes()) == entry["sha256"]
|
|
assert path.stat().st_mtime_ns == entry["observed_mtime_ns"]
|
|
core = json.loads(SNAPSHOT.read_bytes())["installations"][0]["core"]
|
|
assert core["path"] == "/media/ComfyUI" and core["head"] == COMMIT
|
|
network_keys = ["commit", "root-tree", "execution-tree", *["text-" + str(i) for i in range(5)]]
|
|
bodies = {}
|
|
for key in network_keys:
|
|
receipt = json.loads((DOC / "network" / (key + ".json")).read_text())
|
|
raw = (DOC / "network" / (key + ".body")).read_bytes()
|
|
assert receipt["status"] == 200 and receipt["bytes"] == len(raw)
|
|
assert receipt["sha256"] == sha(raw) and len(raw) <= receipt["response_cap"]
|
|
assert receipt["started_at_utc"] <= receipt["completed_at_utc"]
|
|
assert receipt["url"].startswith(API + "/") and not receipt.get("error")
|
|
bodies[key] = json.loads(raw)
|
|
assert bodies["commit"]["sha"] == COMMIT
|
|
assert bodies["commit"]["tree"]["sha"] == core["tree"] == bodies["root-tree"]["sha"]
|
|
root = {x["path"]: x for x in bodies["root-tree"]["tree"]}
|
|
children = {x["path"]: x for x in bodies["execution-tree"]["tree"]}
|
|
assert root["comfy_execution"]["sha"] == bodies["execution-tree"]["sha"]
|
|
assert not bodies["root-tree"]["truncated"] and not bodies["execution-tree"]["truncated"]
|
|
rows = json.loads((DOC / "identities.json").read_text())
|
|
for i, row in enumerate(rows):
|
|
raw = (DOC / row["file"]).read_bytes()
|
|
item = bodies[row["request_key"]]
|
|
entry = children[row["path"].split("/")[1]] if "/" in row["path"] else root[row["path"]]
|
|
receipt = json.loads((DOC / "network" / (row["request_key"] + ".json")).read_text())
|
|
assert receipt["url"] == API + "/contents/" + row["path"] + "?ref=" + COMMIT
|
|
assert row["retrieved_at_utc"] == receipt["completed_at_utc"]
|
|
assert item["path"] == row["path"] and item["sha"] == entry["sha"] == row["git_blob_sha1"]
|
|
assert (
|
|
raw == base64.b64decode(item["content"]) and len(raw) == entry["size"] == item["size"]
|
|
)
|
|
assert sha(raw) == row["sha256"]
|
|
assert json.loads((DOC / ("identity-" + str(i) + ".json")).read_text()) == row
|
|
if i < 4:
|
|
assert gate(row, raw, core)
|
|
ast.parse(raw)
|
|
else:
|
|
assert row["path"] == "LICENSE" and row["license_only_not_working_file"]
|
|
tests = []
|
|
|
|
def reject(name, row=None, raw=None, loaded=False):
|
|
candidate = copy.deepcopy(rows[0] if row is None else row)
|
|
try:
|
|
gate(
|
|
candidate,
|
|
(DOC / rows[0]["file"]).read_bytes() if raw is None else raw,
|
|
core,
|
|
loaded,
|
|
)
|
|
except ValueError as error:
|
|
tests.append(dict(name=name, passed=True, expected="rejected", reason=str(error)))
|
|
else:
|
|
raise AssertionError("negative accepted: " + name)
|
|
|
|
for name, field, value in (
|
|
("near-version", "commit", "26515acd23fa291a8f5ab53c5997258598de0701"),
|
|
("wrong-repository", "repo", "https://github.com/other/ComfyUI"),
|
|
("wrong-tree", "tree", "0" * 40),
|
|
("wrong-path", "path", "nodes.py"),
|
|
("correct-commit-wrong-path", "path", "comfy_execution/graph.py"),
|
|
("size-drift", "bytes", rows[0]["bytes"] + 1),
|
|
("sha-drift", "sha256", "0" * 64),
|
|
("blob-drift", "git_blob_sha1", "0" * 40),
|
|
("false-loaded-field", "current_process_loaded", True),
|
|
("false-scope", "sampling_time_only", False),
|
|
):
|
|
row = copy.deepcopy(rows[0])
|
|
row[field] = value
|
|
reject(name, row)
|
|
altered = (DOC / rows[0]["file"]).read_bytes() + b"\n"
|
|
row = copy.deepcopy(rows[0])
|
|
row.update(
|
|
bytes=len(altered),
|
|
sha256=sha(altered),
|
|
git_blob_sha1=hashlib.sha1(
|
|
b"blob " + str(len(altered)).encode() + b"\0" + altered
|
|
).hexdigest(),
|
|
)
|
|
reject("correct-commit-self-consistent-wrong-working-bytes", row, altered)
|
|
reject("decoded-size-over-cap", raw=b"x" * 262145)
|
|
reject("falsely-certify-current-loaded", loaded=True)
|
|
evidence = json.loads((DOC / "branch-evidence.json").read_text())
|
|
for key, item in evidence.items():
|
|
source = item["source"]
|
|
text = (DOC / source["file"]).read_text()
|
|
start, end = item["lines"]
|
|
excerpt = "\n".join(text.splitlines()[start - 1 : end]) + "\n"
|
|
assert excerpt == item["text"] and sha(excerpt.encode()) == item["sha256"], key
|
|
node = nodes(text)[item["function"]]
|
|
assert sha(ast.dump(node, include_attributes=False).encode()) == item["ast_sha256"], key
|
|
matrix = json.loads((DOC / "protocol-matrix.json").read_text())
|
|
|
|
def span_valid(item):
|
|
row = next(x for x in rows if x["path"] == item["path"])
|
|
a, b = item["lines"]
|
|
text = "".join((DOC / row["file"]).read_text().splitlines(True)[a - 1 : b])
|
|
return (
|
|
text == item["excerpt"]
|
|
and sha(text.encode()) == item["excerpt_sha256"]
|
|
and row["sha256"] == item["source_sha256"]
|
|
and item["evidence"] in evidence
|
|
and item["evidence"].startswith(item["path"] + ":")
|
|
and a <= evidence[item["evidence"]]["lines"][1]
|
|
and b >= evidence[item["evidence"]]["lines"][0]
|
|
)
|
|
|
|
assert all(span_valid(item) for item in matrix)
|
|
for name, field, value in (
|
|
("branch-line-drift", "lines", [1, 2]),
|
|
("branch-wrong-valid-function", "evidence", "execution.py:merge_result_data"),
|
|
("branch-excerpt-drift", "excerpt", "changed"),
|
|
("branch-source-drift", "source_sha256", "0" * 64),
|
|
("branch-wrong-function-reference", "evidence", "nonexistent:function"),
|
|
):
|
|
item = copy.deepcopy(matrix[0])
|
|
item[field] = value
|
|
assert not span_valid(item)
|
|
tests.append(dict(name=name, passed=True, expected="evidence rejected"))
|
|
old = json.loads((ROOT / "docs/hel-892/batch178-aio-protocol/branch-evidence.json").read_text())
|
|
comparisons = json.loads((DOC / "function-comparison.json").read_text())
|
|
for item in comparisons:
|
|
before = old[item["version"] + ":" + item["function"]]
|
|
new = evidence[item["new_evidence"]]
|
|
old_ast = ast.dump(
|
|
ast.parse(textwrap.dedent(before["text"])).body[0], include_attributes=False
|
|
)
|
|
assert item["ast_equal"] == (sha(old_ast.encode()) == new["ast_sha256"])
|
|
assert item["old_source"] == before["source"]
|
|
for name, expected in (
|
|
("identities", rows[:4]),
|
|
("protocol-matrix", matrix),
|
|
("function-comparison", comparisons),
|
|
):
|
|
with (DOC / (name + ".csv")).open(newline="") as stream:
|
|
restored = [
|
|
{k: json.loads(v) for k, v in row.items()} for row in csv.DictReader(stream)
|
|
]
|
|
assert restored == expected, name
|
|
aux = json.loads((DOC / "reused-aux-evidence.json").read_text())
|
|
for key, item in aux.items():
|
|
assert item == old[key]
|
|
original = ROOT / "docs/hel-892/batch177-controlnet-provenance" / item["source"]["file"]
|
|
assert sha(original.read_bytes()) == item["source"]["sha256"]
|
|
links = json.loads((DOC / "case-links.json").read_text())
|
|
assert sha((ROOT / links["file"]).read_bytes()) == links["sha256"] and not links["executed"]
|
|
assert len(links["uses"]) == 2 and all(x["index"] == 0 for x in links["uses"])
|
|
for path in DOC.glob("*.py"):
|
|
ast.parse(path.read_text())
|
|
changed = subprocess.check_output(
|
|
["git", "diff", "--name-only", baseline["base"]], cwd=ROOT, text=True
|
|
)
|
|
assert not changed.strip(), "No old tracked file may change before staging new directory"
|
|
save(
|
|
sys.argv[1] if len(sys.argv) > 1 else "verification.json",
|
|
dict(
|
|
frozen_files=len(baseline["files"]),
|
|
old_changes=0,
|
|
frozen_old_local_artifacts=len(local["files"]),
|
|
identities=4,
|
|
licenses=1,
|
|
function_comparisons=len(comparisons),
|
|
branch_rows=len(matrix),
|
|
reversible_csv=3,
|
|
negatives=tests,
|
|
real_engine_tests=0,
|
|
simulated_engine_tests=0,
|
|
scope="offline provenance and static evidence only",
|
|
),
|
|
)
|
|
print(
|
|
"PASS", len(baseline["files"]), "frozen;", len(tests), "negative contracts; engine tests 0"
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|