"""Recompute this batch's evidence from pinned bytes; never connect to a target.""" from __future__ import annotations import argparse import hashlib import json import sqlite3 import subprocess import sys import tarfile import zipfile from collections import Counter from pathlib import Path BASE = "846d6fcbfef8921f38708a98a02738713abff1e6" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", type=Path, required=True) parser.add_argument("--db", type=Path, required=True) args = parser.parse_args() repo = args.repo.resolve() sys.path.insert(0, str(repo / "calliope-backend")) from scripts import audit_reference_conversion as audit from scripts.verify_frontend_sources import verify out = repo / "docs/hel-892/vhs-evidence" def write(name, value): (out / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") old = json.loads( (repo / "docs/hel-892/crop-split-evidence/library.json").read_bytes() ) baseline_profiles = tuple( p for p in audit.REFERENCE_PROFILES if p not in audit.VHS_PROFILES ) baseline = audit.audit_library(repo, baseline_profiles) now = audit.audit_library(repo, baseline_profiles=baseline_profiles) write("library.json", now) for historical, previous, current in zip( old["cases"], baseline["cases"], now["cases"] ): assert ( historical["source_path"] == previous["source_path"] == current["source_path"] ) assert ( historical["attempts"] == previous["attempts"] == current["attempts"][:-2] ) assert historical.get("comparisons") == previous.get("comparisons") assert old["gap_groups"] == baseline["gap_groups"] six = audit.audit(repo, "case04-batch-reference") assert six == json.loads( (repo / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() ) write( "previous-protection.json", { "old_profile_count": len(baseline_profiles), "actual_same_source_rerun": True, "all_old_attempts_exactly_equal": True, "old_gap_groups_exactly_equal": True, "six_supplied_differential_reports_equal": True, }, ) def groups(report): return { tuple( g[k] for k in ("type", "provider", "version", "profile", "code", "rule_gap") ): Counter( (o["source_path"], o["node_pointer"], o["node_id"]) for o in g["occurrences"] ) for g in report["gap_groups"] } def stat(report): gs = groups(report) return { "groups": len(gs), "raw_occurrences": sum(sum(v.values()) for v in gs.values()), "deduplicated_occurrences_per_group": sum(len(v) for v in gs.values()), "entered_rejected_paths": len({p[0] for v in gs.values() for p in v}), "blocked_total": sum(r["status"] == "blocked" for r in report["cases"]), } def gaprows(diff): return [ { "key": list(k), "occurrences": [ { "source_path": o[0], "node_pointer": o[1], "node_id": o[2], "count": c, } for o, c in sorted(v.items(), key=str) ], } for k, v in sorted(diff.items(), key=str) if v ] before, after = groups(baseline), groups(now) added = {k: v - before.get(k, Counter()) for k, v in after.items()} removed = {k: v - after.get(k, Counter()) for k, v in before.items()} def unavailable(report): return sorted( r["source_path"] for r in report["cases"] if all(a["status"] == "not_applicable" for a in r["attempts"]) ) assert unavailable(baseline) == unavailable(now) write( "coverage-delta.json", { "baseline": stat(baseline), "current": stat(now), "key_fields": [ "type", "provider", "version", "profile", "code", "rule_gap", ], "new_groups": len(after.keys() - before.keys()), "fully_removed_groups": len(before.keys() - after.keys()), "added_occurrences": sum(sum(v.values()) for v in added.values()), "removed_occurrences": sum(sum(v.values()) for v in removed.values()), "removed_groups": gaprows(removed), "added_groups": gaprows(added), "new_complete_paths": now["coverage_delta"]["new_complete_paths"], "unavailable_frontend_paths_unchanged": unavailable(now), "closed_paths": sorted( r["source_path"] for r in now["cases"] if r["status"] == "blocked" ), "attempt_counts": dict( Counter(a["status"] for r in now["cases"] for a in r["attempts"]) ), "conflict_count": sum( r["status"] == "candidate_conflict" for r in now["cases"] ), }, ) from calliope.comfyui.serialization_reference import ( VHS_COMBINE_COMMIT, VHS_LOAD_COMMIT, serialize_vhs_node, ) occurrences = {} for group in old["gap_groups"]: if group["type"] not in ("VHS_VideoCombine", "VHS_LoadVideo"): continue for occurrence in group["occurrences"]: occurrences[(occurrence["source_path"], occurrence["node_pointer"])] = ( occurrence ) targets = [] for (path, pointer), occurrence in sorted(occurrences.items()): source = json.loads((repo / path).read_bytes()) node = source for part in pointer.split("/")[1:]: node = node[int(part)] if isinstance(node, list) else node[part] if (node.get("properties") or {}).get("ver") not in ( VHS_COMBINE_COMMIT, VHS_LOAD_COMMIT, ): continue row = next(r for r in now["cases"] if r["source_path"] == path) assert row["status"] == "blocked" frontend = (source.get("extra") or {}).get("frontendVersion") or "1.37.11" profile = next(p for p, v in audit.VHS_PROFILES.items() if v == frontend) attempt = next(a for a in row["attempts"] if a["profile"] == profile) try: values = serialize_vhs_node(node) node_error = None except ValueError as exc: values, node_error = None, str(exc) fields = [] if values is not None: for name, value in values.items(): expected = node["widgets_values"][name] assert type(value) is type(expected) and value == expected fields.append( { "field": name, "value": value, "json_type": type(value).__name__, "source_pointer": pointer + "/widgets_values/" + name, "input_is_linked": any( s["name"] == name and s.get("link") is not None for s in node["inputs"] ), } ) edge_evidence = [] for slot, socket in enumerate(node.get("inputs", [])): if socket.get("link") is None: continue li, edge = next( (i, e) for i, e in enumerate(source["links"]) if e[0] == socket["link"] ) assert str(edge[3]) == str(node["id"]) and edge[4] == slot upstream = next(n for n in source["nodes"] if str(n["id"]) == str(edge[1])) assert edge[0] in (upstream["outputs"][edge[2]].get("links") or []) assert edge[5] == socket["type"] == upstream["outputs"][edge[2]]["type"] edge_evidence.append( { "field": socket["name"], "source_pointer": f"/links/{li}", "raw_link": edge, "upstream_node": str(edge[1]), "original_output_slot": edge[2], "target_input_slot": slot, "bidirectional_records_match": True, } ) for slot, socket in enumerate(node.get("outputs", [])): for lid in socket.get("links") or []: li, edge = next( (i, e) for i, e in enumerate(source["links"]) if e[0] == lid ) downstream = next( n for n in source["nodes"] if str(n["id"]) == str(edge[3]) ) assert str(edge[1]) == str(node["id"]) and edge[2] == slot assert downstream["inputs"][edge[4]].get("link") == lid assert ( edge[5] == socket["type"] == downstream["inputs"][edge[4]]["type"] ) edge_evidence.append( { "direction": "outgoing", "source_pointer": f"/links/{li}", "raw_link": edge, "original_output_slot": slot, "bidirectional_records_match": True, } ) targets.append( { "source_path": path, "source_sha256": row["source_sha256"], "node_pointer": pointer, "node_id": str(node["id"]), "type": node["type"], "source_mode": node.get("mode", 0), "source_properties": node.get("properties"), "source_widgets": node["widgets_values"], "saved_field_inventory": [ { "field": k, "value": v, "json_type": type(v).__name__, "source_pointer": pointer + "/widgets_values/" + k, "status": "saved_source_value_not_execution_proof", } for k, v in node["widgets_values"].items() if k not in ("videopreview", "choose video to upload") ], "source_inputs": node["inputs"], "edge_evidence": edge_evidence, "source_outputs": node["outputs"], "profile": profile, "node_contract_accepted": values is not None, "node_error": node_error, "fields": fields, "whole_graph_prompt": None, "whole_graph_issues": attempt["issues"], "comparison_status": row["comparison_status"], "execution_verified": False, } ) assert len(targets) == 10 assert Counter(t["type"] for t in targets) == { "VHS_VideoCombine": 5, "VHS_LoadVideo": 5, } assert sum(t["node_contract_accepted"] for t in targets) == 7 write("actual-node-evidence.json", targets) write( "node-summary.json", { "dedup_key": ["source_path", "node_pointer"], "target_nodes": len(targets), "target_graphs": len({t["source_path"] for t in targets}), "accepted_node_contracts": 7, "accepted_node_graphs": len( {t["source_path"] for t in targets if t["node_contract_accepted"]} ), "mode_rejections": 3, "new_complete_graphs": 0, "field_count": sum(len(t["fields"]) for t in targets), "saved_field_inventory_count": sum( len(t["saved_field_inventory"]) for t in targets ), "historical_gaps_are_unchanged": True, "meaning": "7 node widget contracts are now proven under explicit new profiles; other unknown nodes/links and bypass still close every target graph; historical profile attempts remain byte-equivalent", }, ) manifests = [ "serialization-evidence", "structure-reference", "controlnet-reference", "promoted-reference", "case04-reference", "media-reference", "separation-reference", "crop-split-reference", "vhs-reference", ] new_count = len( json.loads((repo / "docs/hel-892/vhs-reference/sources.json").read_bytes())[ "sources" ] ) entries = [] per_manifest_unique_ids = [] for directory in manifests: d = repo / "docs/hel-892" / directory check = verify(d) for entry in json.loads((d / "sources.json").read_bytes())["sources"]: # Rule ranges are separately checked, in addition to the existing verifier. raw = (d / entry["local_file"]).read_bytes() rules = entry.get("rule_locations", {}) for start, end in rules.values() if isinstance(rules, dict) else rules: assert 1 <= start <= end <= len(raw.decode().splitlines()), entry["id"] per_manifest_unique_ids.append( len({r["id"] for r in check["sources_verified"]}) ) entries.extend(check["sources_verified"]) write( "cached-sources-check.json", { "manifest_entries": len(entries), "unique_ids_summed_per_manifest": sum(per_manifest_unique_ids), "global_distinct_id_strings": len({e["id"] for e in entries}), "old_entries": len(entries) - new_count, "old_unique_ids_summed_per_manifest": sum(per_manifest_unique_ids[:-1]), "old_global_distinct_id_strings": len( {e["id"] for e in entries[:-new_count]} ), "counting_note": ( "historical 186 entries/185 within-manifest unique IDs uses sum of within-manifest distinct IDs; " "cross-manifest distinct ID strings are a separate count, and IDs can span commits" ), "new_entries": new_count, "new_unique_ids": len({e["id"] for e in entries[-new_count:]}), "sources_verified": entries, }, ) # Use the immutable historical receipt inventory to include all seven API exports. originals = json.loads( (repo / "docs/hel-892/media-evidence/original-bytes.json").read_bytes() )["files"] files = [] for row in originals: path = row["path"] raw = (repo / path).read_bytes() oldraw = subprocess.check_output(["git", "show", f"{BASE}:{path}"], cwd=repo) assert raw == oldraw files.append({"path": path, "sha256": hashlib.sha256(raw).hexdigest()}) assert len(files) == 163 write( "original-bytes.json", {"base": BASE, "all_unchanged": True, "count": len(files), "files": files}, ) registry = "calliope-backend/src/calliope/comfyui/registry.py" assert (repo / registry).read_bytes() == subprocess.check_output( ["git", "show", f"{BASE}:{registry}"], cwd=repo ) db = sqlite3.connect(args.db) db.row_factory = sqlite3.Row rows = db.execute( "SELECT * FROM workflows WHERE source_repo_path IS NOT NULL" ).fetchall() assert len(rows) == 155 assert not any( r["is_enabled"] or r["doc_completed_at"] or r["exec_verified_at"] for r in rows ) issue_counts = Counter( i["code"] for r in rows for i in json.loads(r["import_issues"]) ) write( "isolation.json", { "states": dict(Counter(r["import_state"] for r in rows)), "target_count": len(rows), "enabled_or_completed_or_executed": 0, "environment_unchecked_count": issue_counts["environment_unchecked"], "companion_unverified_count": issue_counts["companion_unverified"], "production_registry_unchanged": True, "companion_named_values": sum( param.get("value_origin") == "supplied_api_companion" for row in rows for param in json.loads(row["doc_json"])["params"] ), "reference_candidates_written_to_db": False, "user_whole_row_protection": "covered by executed affected tests", }, ) db.close() wheel = next((repo / "calliope-backend/dist").glob("*.whl")) sdist = next((repo / "calliope-backend/dist").glob("*.tar.gz")) package_rows = [] with zipfile.ZipFile(wheel) as wh, tarfile.open(sdist) as sd: for name in [ "serialization_reference.py", "ui2api.py", "protocol_references.json", "source_reviews.json", "delivery_scope.py", "delivery_scope.json", ]: path = f"calliope-backend/src/calliope/comfyui/{name}" raw = (repo / path).read_bytes() assert wh.read(f"calliope/comfyui/{name}") == raw member = next( n for n in sd.getnames() if n.endswith(f"/src/calliope/comfyui/{name}") ) assert sd.extractfile(member).read() == raw package_rows.append( { "path": path, "sha256": hashlib.sha256(raw).hexdigest(), "wheel_matches": True, "sdist_matches": True, } ) write("package-check.json", package_rows) print( json.dumps( { "old_profiles": len(baseline_profiles), "new_candidates": len(now["coverage_delta"]["new_complete_paths"]), "current_gap_counts": stat(now), "cached_source_entries": len(entries), "original_bytes_unchanged": len(files), }, ensure_ascii=False, ) ) if __name__ == "__main__": main()