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

377 lines
14 KiB
Python

"""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 = "b30ea8917d12ce80a6d3d8d3bb10dfa8e7dab39f"
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/crop-split-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/separation-evidence/library.json").read_bytes()
)
baseline_profiles = tuple(
p for p in audit.REFERENCE_PROFILES if p not in audit.CROP_SPLIT_PROFILES
)
baseline = audit.audit_library(repo, baseline_profiles)
now = audit.audit_library(repo)
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"]
),
},
)
targets = []
for suffix, profile in zip(
("/音频人声分离.json", "/图像分割-多宫格分割.json"), audit.CROP_SPLIT_PROFILES
):
selected = next(r for r in now["cases"] if r["source_path"].endswith(suffix))
attempt = next(a for a in selected["attempts"] if a["profile"] == profile)
source = json.loads((repo / selected["source_path"]).read_bytes())
assert selected["comparison_status"] == "comparison_unavailable"
if attempt["status"] == "complete_reference_candidate":
prompt = attempt["candidate_prompt"]
assert audit.canonical_sha(prompt) == attempt["candidate_sha256"]
assert set(prompt) == {str(n["id"]) for n in source["nodes"]}
for n in source["nodes"]:
assert prompt[str(n["id"])]["class_type"] == n["type"]
assert prompt[str(n["id"])]["_meta"] == {
"title": n.get("title") or n["type"]
}
for field in attempt["field_evidence"]:
pointer = field["source_pointer"]
if pointer is None:
assert field["field"] == "audioUI" and field["value"] == ""
continue
expected = source
for part in pointer.split("/")[1:]:
expected = (
expected[int(part)]
if isinstance(expected, list)
else expected[part]
)
if pointer.startswith("/links/"):
expected = [str(expected[1]), expected[2]]
assert expected == field["value"] and type(expected) is type(
field["value"]
)
else:
assert attempt["status"] == "rejected" and "candidate_prompt" not in attempt
assert any(
i["node_id"] == "3" and "输出槽" in i["message"]
for i in attempt["issues"]
)
targets.append(
{
"source_path": selected["source_path"],
"source_sha256": selected["source_sha256"],
"comparison_status": selected["comparison_status"],
"execution_verified": False,
"production_prompt_available": False,
**attempt,
}
)
# Explain GuHai's confirmed individual widgets without exposing a partial prompt.
split = json.loads((repo / targets[1]["source_path"]).read_bytes())
n = next(n for n in split["nodes"] if n["id"] == 2)
from calliope.comfyui.serialization_reference import serialize_reference_widgets
values = serialize_reference_widgets(n, audit.CROP_SPLIT_PROFILES[1])
write(
"guhai-node-only.json",
{
"authority": "individual_node_contract_only_not_partial_prompt",
"whole_graph_closed": True,
"fields": [
{
"field": k,
"value": v,
"json_type": type(v).__name__,
"source_pointer": f"/nodes/1/widgets_values/{i}",
}
for i, (k, v) in enumerate(values.items())
],
"graph_blocker": targets[1]["issues"],
"source_preview_outputs": split["nodes"][0]["outputs"],
},
)
write("candidates.json", targets)
manifests = [
"serialization-evidence",
"structure-reference",
"controlnet-reference",
"promoted-reference",
"case04-reference",
"media-reference",
"separation-reference",
"crop-split-reference",
]
new_count = len(
json.loads(
(repo / "docs/hel-892/crop-split-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 173 entries/172 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()