Files
aigc-home/docs/hel-892/grid-evidence/recompute.py
T

387 lines
14 KiB
Python

"""Recompute grid reference 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 = "0609341afaab955755b2f17d64e449727f65784c"
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 (
GRID_PROFILE,
)
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/grid-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/scail-load-evidence/library.json").read_bytes()
)
profiles = tuple(old["profiles"])
assert len(profiles) == 24
assert profiles == tuple(p for p in audit.REFERENCE_PROFILES if p != GRID_PROFILE)
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"][:24]
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"])
)
removed_unavailable = sorted(set(unavailable(before)) - set(unavailable(now)))
added_unavailable = sorted(set(unavailable(now)) - set(unavailable(before)))
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_before": unavailable(before),
"unavailable_frontend_after": unavailable(now),
"removed_unavailable_frontend_paths": removed_unavailable,
"added_unavailable_frontend_paths": added_unavailable,
"unavailable_frontend_change_reason": "new explicit 1.41.20 profile; applicability is not conversion success",
"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 copy import deepcopy
from calliope.comfyui.ui2api import convert_reference
target = next((repo / "example_ComfyUI_workflows").rglob("图像合并成四宫格.json"))
source = json.loads(target.read_bytes())
actual = convert_reference(source, GRID_PROFILE)
assert actual.prompt is None
row = next(
r
for r in now["cases"]
if r["source_path"] == target.relative_to(repo).as_posix()
)
assert row["comparison_status"] == "comparison_unavailable"
write(
"actual-grid.json",
{
"source_path": row["source_path"],
"source_sha256": row["source_sha256"],
"profile": GRID_PROFILE,
"prompt": actual.prompt,
"issues": actual.issues,
"comparison_status": row["comparison_status"],
"ue_record": "all nine entities have ue_properties.version=7.7, both maps empty; implementation and hook ordering unknown",
"source_nodes": source["nodes"],
"source_edges": source["links"],
"original_bytes_modified": False,
},
)
# Deliberately counterfactual. This NEVER enters the library candidate report.
synthetic = deepcopy(source)
for n in synthetic["nodes"]:
n["properties"].pop("ue_properties", None)
result = convert_reference(synthetic, GRID_PROFILE)
assert result.prompt is not None, result.issues
fields = audit.grid_field_evidence(synthetic, result.prompt)
assert len(fields) == 30
write(
"synthetic-no-ue-grid.json",
{
"authority": "synthetic_no_ue_counterfactual_not_original_conversion_or_API_export",
"premise": "ue_properties removed only in a deep copy; actual source always refused",
"candidate_sha256": audit.canonical_sha(result.prompt),
"candidate_prompt": result.prompt,
"field_evidence": fields,
"metadata": [
{
"node_id": str(n["id"]),
"source_pointer": f"/nodes/{i}",
"value": result.prompt[str(n["id"])]["_meta"],
}
for i, n in enumerate(source["nodes"])
if str(n["id"]) in result.prompt
],
"excluded_virtual_note": {
"pointer": "/nodes/8",
"node_id": "24",
"reason": "pinned MarkdownNote.isVirtualNode=true; no edges",
},
"comparison_status": "comparison_unavailable",
"execution_verified": False,
},
)
inventory = row["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",
"grid-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": 1,
"gap_stats": stats(now),
},
ensure_ascii=False,
)
)
if __name__ == "__main__":
main()