"""Recompute Scail loader 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 = "821e33dd87e28d8ede95dc08e62c87ba64a07815" 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 ( SCAIL_LOAD_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/scail-load-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/videoinfo-evidence/library.json").read_bytes() ) profiles = tuple(old["profiles"]) assert len(profiles) == 22 assert profiles == tuple( p for p in audit.REFERENCE_PROFILES if p not in SCAIL_LOAD_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"][:22] 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"]), }, ) from calliope.comfyui.serialization_reference import serialize_scail_load_node from calliope.comfyui.ui2api import convert_reference inventory, chains = [], [] profile = ( "comfy-frontend-1.37.11-scail-load-8e4d7947-info-537f3a02-kj-ab72eda7-reference" ) 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_LoadVideo": inventory.append({"source_path": row["source_path"], **n}) for old_chain in json.loads( (repo / "docs/hel-892/videoinfo-evidence/scail-endpoints.json").read_bytes() ): source = json.loads((repo / old_chain["source_path"]).read_bytes()) nid = old_chain["upstream"]["node_id"] ni, node = next((i, n) for i, n in enumerate(source["nodes"]) if n["id"] == nid) try: serialize_scail_load_node(node) except ValueError as exc: rejection = str(exc) else: raise AssertionError("Real UE-bound loader must remain rejected") result = convert_reference(source, profile) assert result.prompt is None and "UE" in rejection edges = [] nodes = {n["id"]: (i, n) for i, n in enumerate(source["nodes"])} for li, edge in enumerate(source["links"]): if nid not in (edge[1], edge[3]): continue 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(edge[0]) == 1 assert b["inputs"][edge[4]]["link"] == edge[0] edges.append( { "pointer": f"/links/{li}", "edge": edge, "origin_pointer": f"/nodes/{ai}/outputs/{edge[2]}", "target_pointer": f"/nodes/{bi}/inputs/{edge[4]}", } ) aliases = [ {"pointer": f"/nodes/{i}", "node": n} for i, n in enumerate(source["nodes"]) if n["type"] in ("SetNode", "GetNode") and n["id"] in [int(h["node_id"]) for h in old_chain["downstream_alias_hops"]] ] chains.append( { "source_path": old_chain["source_path"], "source_sha256": old_chain["source_sha256"], "loader_pointer": f"/nodes/{ni}", "loader": node, "checked_physical_edges": edges, "loader_schema": "fixed registration/schema/no-VAE output slots proven; UE-bound construction not proven", "loader_rejection": rejection, "info_endpoint": old_chain["node_pointer"], "info_schema": "537f3a02 exact five slots proven; loaded_fps value unknown", "aliases": aliases, "alias_history": "KJ historical emission proven; user provenance unproven, old rejection retained", "saved_combine_fps": old_chain["saved_frame_rate"], "saved_force_rate": node["widgets_values"]["force_rate"], "fps_value": "unknown; saved30 and force_rate0/16 do not evaluate media info", "prompt": None, "comparison_status": "comparison_unavailable", "whole_graph_issues": result.issues, } ) write("scail-loaders.json", chains) write("inventory.json", inventory) dirs = [ "serialization-evidence", "structure-reference", "controlnet-reference", "promoted-reference", "case04-reference", "media-reference", "separation-reference", "crop-split-reference", "vhs-reference", "setget-reference", "videoinfo-reference", "scail-load-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()