"""Recompute VideoInfoLoaded evidence and protections without services or upstream execution.""" 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 = "cd39533320aa1c8926a01ca0764a8f7b734f7109" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", type=Path, required=True) parser.add_argument("--db", type=Path, required=True) parser.add_argument("--documents", type=Path, required=True) args = parser.parse_args() repo = args.repo.resolve() sys.path.insert(0, str(repo / "calliope-backend")) from calliope.comfyui.structure_reference import ( VIDEOINFO_PROFILES, ) from scripts import audit_reference_conversion as audit from scripts.audit_library_documents import audit as audit_docs from scripts.verify_frontend_sources import verify out = repo / "docs/hel-892/videoinfo-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/setget-evidence/library.json").read_bytes()) profiles = tuple(old["profiles"]) assert len(profiles) == 20 assert profiles == tuple( p for p in audit.REFERENCE_PROFILES if p not in VIDEOINFO_PROFILES ) before = audit.audit_library(repo, profiles) now = audit.audit_library(repo, baseline_profiles=profiles) write("library.json", now) for a, b, c in zip(old["cases"], before["cases"], now["cases"]): assert a["source_path"] == b["source_path"] == c["source_path"] assert a["attempts"] == b["attempts"] == c["attempts"][:20] assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") assert a["candidate_hashes"] == c["candidate_hashes"] assert old["gap_groups"] == before["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", { "baseline_profiles": profiles, "old_attempts_identical": True, "old_gaps_identical": True, "six_companion_differences_identical": True, "old_candidate_hashes_identical": 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 stats(report): gs = groups(report) return { "groups": len(gs), "raw_occurrences": sum(sum(c.values()) for c in gs.values()), "unique_occurrences_per_group": sum(len(c) for c in gs.values()), "unique_nodes": len({o for c in gs.values() for o in c}), "unique_paths": len({o[0] for c in gs.values() for o in c}), } def diffrows(a, b): return [ { "key": list(k), "occurrences": [ { "source_path": o[0], "node_pointer": o[1], "node_id": o[2], "count": n, } for o, n in sorted((v - b.get(k, Counter())).items(), key=str) ], } for k, v in sorted(a.items(), key=str) if v - b.get(k, Counter()) ] 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(before) == unavailable(now) ga, gb = groups(before), groups(now) added, removed = diffrows(gb, ga), diffrows(ga, gb) write( "coverage-delta.json", { "baseline_profiles": profiles, "baseline": stats(before), "current": stats(now), "key_fields": [ "type", "provider", "version", "profile", "code", "rule_gap", ], "occurrence_key": ["source_path", "node_pointer", "node_id"], "added_groups": added, "removed_groups": removed, "added_occurrences": sum( o["count"] for g in added for o in g["occurrences"] ), "removed_occurrences": sum( o["count"] for g in removed for o in g["occurrences"] ), "new_complete_paths": now["coverage_delta"]["new_complete_paths"], "complete_paths": now["coverage_delta"]["current_complete_paths"], "closed_paths": [ r["source_path"] for r in now["cases"] if r["status"] == "blocked" ], "unavailable_frontend_paths_unchanged": unavailable(now), "attempt_counts": dict( Counter(a["status"] for r in now["cases"] for a in r["attempts"]) ), "conflicts": sum(r["status"] == "candidate_conflict" for r in now["cases"]), }, ) # Read every manifest path, including non-.json suffixes and unused subgraphs. inventory = [] for row in now["cases"]: source = json.loads((repo / row["source_path"]).read_bytes()) for n in audit.node_inventory(source, include_aux=True): if n["type"] != "VHS_VideoInfoLoaded": continue node = source for k in n["pointer"].split("/")[1:]: node = node[int(k)] if isinstance(node, list) else node[k] inventory.append( { "source_path": row["source_path"], "source_sha256": row["source_sha256"], "node_pointer": n["pointer"], "node_id": n["node_id"], "type": n["type"], "mode": node.get("mode", 0), "scope": "root" if n["pointer"].startswith("/nodes/") else "definition", "properties": node.get("properties"), "widgets_values": node.get("widgets_values"), "frontend": row["frontend_version"], } ) write("inventory.json", inventory) old_gaps = [g for g in old["gap_groups"] if g["type"] == "VHS_VideoInfoLoaded"] occurrences = Counter( (o["source_path"], o["node_pointer"], o["node_id"]) for g in old_gaps for o in g["occurrences"] ) write( "inventory-summary.json", { "target_scope": "145 UI after case06 exclusion; includes unused definitions", "nodes": len(inventory), "paths": len({n["source_path"] for n in inventory}), "types": dict(Counter(n["type"] for n in inventory)), "scopes": dict(Counter(n["scope"] for n in inventory)), "declarations": dict( Counter( json.dumps( { k: (n["properties"] or {}).get(k) for k in ("cnr_id", "aux_id", "ver") }, sort_keys=True, ) for n in inventory ) ), "modes": dict(Counter(str(n["mode"]) for n in inventory)), "old_gap_groups": len(old_gaps), "old_gap_raw": sum(occurrences.values()), "old_gap_unique_nodes": len(occurrences), "old_gap_paths": len({o[0] for o in occurrences}), "old_gap_occurrences": [ {"source_path": k[0], "node_pointer": k[1], "node_id": k[2], "count": v} for k, v in sorted(occurrences.items()) ], }, ) # Re-read all endpoints, five slots and their links, then extend the old # literal Scail trace upstream. No clipped graph is ever converted. from calliope.comfyui.serialization_reference import serialize_videoinfo_node from calliope.comfyui.ui2api import convert_reference chains = [] previous_chains = json.loads( (repo / "docs/hel-892/setget-evidence/scail-frame-rate.json").read_bytes() ) for old_chain in previous_chains: source = json.loads((repo / old_chain["source_path"]).read_bytes()) nodes = {n["id"]: (i, n) for i, n in enumerate(source["nodes"])} links = {e[0]: (i, e) for i, e in enumerate(source["links"])} nid = int(old_chain["endpoint"][0]) ni, node = nodes[nid] assert serialize_videoinfo_node(node) == {} checked_edges = [] for direction in ("inputs", "outputs"): for slot, socket in enumerate(node[direction]): ids = ( [socket["link"]] if direction == "inputs" else socket.get("links") or [] ) for lid in ids: li, edge = links[lid] ai, a = nodes[edge[1]] bi, b = nodes[edge[3]] assert ( a["outputs"][edge[2]]["type"] == edge[5] == b["inputs"][edge[4]]["type"] ) assert a["outputs"][edge[2]]["links"].count(lid) == 1 assert b["inputs"][edge[4]]["link"] == lid assert ( (edge[1], edge[2]) == (nid, slot) if direction == "outputs" else (edge[3], edge[4]) == (nid, slot) ) checked_edges.append( { "link_pointer": f"/links/{li}", "link": edge, "origin_pointer": f"/nodes/{ai}/outputs/{edge[2]}", "target_pointer": f"/nodes/{bi}/inputs/{edge[4]}", } ) li, incoming = links[node["inputs"][0]["link"]] ui, upstream = nodes[incoming[1]] result = convert_reference(source, next(iter(VIDEOINFO_PROFILES))) assert result.prompt is None chains.append( { "source_path": old_chain["source_path"], "source_sha256": old_chain["source_sha256"], "node_id": nid, "node_pointer": f"/nodes/{ni}", "node": node, "layer_states": { "node": "exact_provider_and_full_commit_declared; normal_mode; empty_widgets", "schema": "verified_pinned_input_and_all_five_original_output_slots", "topology": "all_entity_physical_edges_bidirectionally_verified; alias_chain_literal_only", "provenance": "entity_pinned_reference_only; four_aliases_literal_aux_unproven; no_scope_upgrade", }, "checked_edges": checked_edges, "upstream": { "node_id": upstream["id"], "node_pointer": f"/nodes/{ui}", "output_slot": incoming[2], "link_pointer": f"/links/{li}", "type": upstream["type"], "properties": upstream.get("properties"), "status": "uncovered_loader_commit_8e4d7947_and_UE_dimension_bindings", "input_origins": [ { "pointer": f"/nodes/{ui}/inputs/{j}", "socket": sock, "edge": links[sock["link"]][1] if sock.get("link") is not None else None, } for j, sock in enumerate(upstream.get("inputs", [])) ], }, "saved_frame_rate": old_chain["saved_frame_rate"], "saved_value_pointer": old_chain["saved_value_pointer"], "frame_rate_input_pointer": old_chain["target_pointer"], "downstream_alias_hops": old_chain["hops"], "alias_authority": old_chain["authority"], "final_scalar": "unknown; loaded_fps is a dictionary key, never evaluated; saved 30 is not final fps", "comparison_status": old_chain["comparison_status"], "whole_graph_issues": result.issues, "prompt": None, } ) write("scail-endpoints.json", chains) dirs = [ "serialization-evidence", "structure-reference", "controlnet-reference", "promoted-reference", "case04-reference", "media-reference", "separation-reference", "crop-split-reference", "vhs-reference", "setget-reference", "videoinfo-reference", ] entries = [] counts = [] for name in dirs: directory = repo / "docs/hel-892" / name verify(directory) rows = json.loads((directory / "sources.json").read_bytes())["sources"] for entry in rows: lines = (directory / entry["local_file"]).read_text().splitlines() locations = entry.get("rule_locations", {}) for lo, hi in ( locations.values() if isinstance(locations, dict) else locations ): assert 1 <= lo <= hi <= len(lines) counts.append( { "manifest": name, "entries": len(rows), "unique_ids": len({r["id"] for r in rows}), } ) entries.extend(rows) write( "cached-sources-check.json", { "manifests": counts, "entries": len(entries), "unique_ids_summed_per_manifest": sum(c["unique_ids"] for c in counts), "global_distinct_id_strings": len({r["id"] for r in entries}), "unique_url_and_hash": len({(r["raw_url"], r["sha256"]) for r in entries}), "note": "ID counts are strings; URL+SHA256 is separately deduplicated; repeated frontend originals retained", }, ) originals = json.loads( (repo / "docs/hel-892/media-evidence/original-bytes.json").read_bytes() )["files"] for row in originals: raw = (repo / row["path"]).read_bytes() assert raw == subprocess.check_output( ["git", "show", f"{BASE}:{row['path']}"], cwd=repo ) assert len(originals) == 163 write( "original-bytes.json", {"base": BASE, "count": 163, "all_unchanged": True, "files": originals}, ) production = json.loads( (repo / "docs/hel-892/setget-evidence/production-protection.json").read_bytes() )["files"] for row in production: raw = (repo / row["path"]).read_bytes() assert raw == subprocess.check_output( ["git", "show", f"{BASE}:{row['path']}"], cwd=repo ) assert hashlib.sha256(raw).hexdigest() == row["sha256"] write("production-protection.json", {"base": BASE, "files": production}) 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 ) issues = Counter(i["code"] for r in rows for i in json.loads(r["import_issues"])) companion_values = sum( p.get("value_origin") == "supplied_api_companion" for r in rows for p in json.loads(r["doc_json"])["params"] ) assert ( companion_values == 294 and issues["companion_unverified"] == 6 and issues["environment_unchecked"] == 16 ) write( "isolation.json", { "states": dict(Counter(r["import_state"] for r in rows)), "count": 155, "enabled_or_completed_or_executed": 0, "issue_counts": dict(issues), "companion_named_values": companion_values, "reference_candidates_written_to_db": False, "user_whole_row_protection": "executed affected tests", }, ) db.close() report = audit_docs(repo, args.documents.resolve()) summary = {k: v for k, v in report.items() if k != "files"} assert ( summary["named_values_preserved"] == 1217 and summary["unnamed_widget_nodes"] == 3660 ) assert summary["full_documents_completed"] == 0 and summary["real_executions"] == 0 write("document-audit-summary.json", summary) packages = [] with ( zipfile.ZipFile(next((repo / "calliope-backend/dist").glob("*.whl"))) as wh, tarfile.open(next((repo / "calliope-backend/dist").glob("*.tar.gz"))) as sd, ): for name in [ "structure_reference.py", "serialization_reference.py", "ui2api.py", "protocol_references.json", "source_reviews.json", "delivery_scope.py", "delivery_scope.json", ]: p = f"calliope-backend/src/calliope/comfyui/{name}" raw = (repo / p).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 packages.append( { "path": p, "sha256": hashlib.sha256(raw).hexdigest(), "wheel_matches": True, "sdist_matches": True, } ) write("package-check.json", packages) print( json.dumps( { "ui": now["ui_total"], "attempts": Counter( a["status"] for r in now["cases"] for a in r["attempts"] ), "complete": len(now["coverage_delta"]["current_complete_paths"]), "new_complete": now["coverage_delta"]["new_complete_paths"], "inventory_nodes": len(inventory), "inventory_paths": len({n["source_path"] for n in inventory}), "gap_stats": stats(now), }, ensure_ascii=False, ) ) if __name__ == "__main__": main()