Files
aigc-home/docs/hel-892/h3-document-evidence/recompute.py
T
2026-10-30 08:17:25 +08:00

300 lines
12 KiB
Python

"""Reproduce H3 document adoption, real old-DB refresh and untouched boundaries offline."""
from __future__ import annotations
import hashlib
import io
import json
import os
import sqlite3
import subprocess
import sys
import tarfile
import tempfile
import zipfile
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
BASE = "b47e13d169be9a786f69625f2fda58895204802a"
sys.path.insert(0, str(REPO / "calliope-backend"))
from calliope.comfyui.fixed_document import (
DEFINITION_SHA256,
SOURCE_PATH,
canonical,
)
from scripts.audit_library_documents import audit
def write(name, data):
(OUT / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
def main():
local = REPO / ".local-evidence/h3-document"
local.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=local) as directory:
work = Path(directory)
baseline = work / "baseline"
baseline.mkdir()
raw = subprocess.check_output(
["git", "archive", BASE, "calliope-backend/src"], cwd=REPO
)
with tarfile.open(fileobj=io.BytesIO(raw)) as archive:
archive.extractall(baseline, filter="data")
db = work / "library.db"
def run(name, old=False):
output = work / name
env = {
**os.environ,
"PYTHONPATH": str((baseline if old else REPO) / "calliope-backend/src"),
}
command = [
sys.executable,
"-m",
"calliope.comfyui.library_cli",
"import",
"--root",
str(REPO / "example_ComfyUI_workflows"),
"--db",
str(db),
"--source-commit",
BASE,
"--companions",
str(REPO / "docs/hel-892/supplied-api/manifest.json"),
"--output-dir",
str(output),
]
subprocess.run(
command, env=env, cwd=REPO, check=True, stdout=subprocess.DEVNULL
)
return json.loads((output / "import_report.json").read_bytes()), output
def rows():
with sqlite3.connect(db) as conn:
conn.row_factory = sqlite3.Row
return {
r["source_repo_path"]: dict(r)
for r in conn.execute("SELECT * FROM workflows")
}
first, _ = run("first", old=True)
before = rows()
assert first["counts"] == {"imported": 155, "user_excluded": 1}
assert "fixed_version" not in json.loads(before[SOURCE_PATH]["doc_json"])
original_db = db
db = work / "old-user.db"
with sqlite3.connect(original_db) as src, sqlite3.connect(db) as dst:
src.backup(dst)
dst.execute(
"UPDATE workflows SET description=? WHERE source_repo_path=?",
("旧库用户版", SOURCE_PATH),
)
old_user_before = rows()
old_user, _ = run("old-user-protection")
assert old_user["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1}
assert rows() == old_user_before
db = original_db
refreshed, exported = run("refresh")
after = rows()
assert refreshed["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
for path, row in after.items():
if path != SOURCE_PATH:
assert row == before[path]
else:
for column in row.keys() - {
"doc_json",
"batch_id",
"imported_at",
"library_fingerprint",
}:
assert row[column] == before[path][column]
doc = json.loads(after[SOURCE_PATH]["doc_json"])
assert doc["fixed_version"]["matched"]
block = {k: v for k, v in doc["fixed_version"].items() if k != "matched"}
assert hashlib.sha256(canonical(block)).hexdigest() == DEFINITION_SHA256
write("actual-document.json", doc)
report = audit(REPO, exported)
assert (
report["named_values_preserved"] == 1217
and report["unnamed_widget_nodes"] == 3660
)
assert report["full_documents_completed"] == report["real_executions"] == 0
write(
"document-audit-summary.json",
{k: v for k, v in report.items() if k != "files"},
)
companion = 0
for row in after.values():
d = json.loads(row["doc_json"])
companion += sum(
p.get("value_origin") == "supplied_api_companion" for p in d["params"]
)
assert (
not row["is_enabled"]
and row["doc_completed_at"] is None
and row["exec_verified_at"] is None
)
assert d["dependencies"]["check_state"] == "unchecked"
assert companion == 294
repeat, _ = run("repeat")
assert repeat["counts"] == {"skipped": 155, "user_excluded": 1}
# Restore the actual historical row, then repeat adoption. No mocks here.
from calliope.comfyui.library import rollback_batch
with sqlite3.connect(db) as conn:
conn.row_factory = sqlite3.Row
rollback = rollback_batch(conn, refreshed["batch_id"])
assert rollback["files"] == [
{"workflow_id": after[SOURCE_PATH]["id"], "result": "restored"}
]
assert rows() == before
restored, _ = run("after-rollback")
assert restored["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
with sqlite3.connect(db) as conn:
conn.execute(
"UPDATE workflows SET description=? WHERE source_repo_path=?",
("用户整行保护", SOURCE_PATH),
)
protected = rows()
user, _ = run("user")
assert user["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1}
assert rows() == protected and len(protected[SOURCE_PATH]) == 29
# A second genuinely fresh current import, distinct from the historical upgrade.
db = work / "current-fresh.db"
current, _ = run("current-first")
again, _ = run("current-repeat")
assert current["counts"] == {"imported": 155, "user_excluded": 1}
assert current["states"] == {"pending_check": 16, "needs_conversion": 139}
assert again["counts"] == {"skipped": 155, "user_excluded": 1}
write(
"import-protection.json",
{
"historical_code": BASE,
"historical_first": first["counts"],
"actual_historical_doc_lacked_fixed_block": True,
"refresh": refreshed["counts"],
"only_updated_path": SOURCE_PATH,
"other_154_rows_byte_equal": True,
"repeat": repeat["counts"],
"rollback_restored_actual_old_row": True,
"after_rollback": restored["counts"],
"user_modified": user["counts"],
"old_user_before_refresh": old_user["counts"],
"old_user_all_columns_preserved": True,
"protected_columns": 29,
"whole_row_equal": True,
"current_fresh": current["counts"],
"current_repeat": again["counts"],
"states": current["states"],
"source_named": 1217,
"source_positional": 3660,
"companion_values": companion,
"new_definitions": doc["fixed_version"]["counts"],
"all_disabled": True,
"environment_unchecked": True,
"completed": 0,
"executed": 0,
},
)
originals = json.loads(
(REPO / "docs/hel-892/media-evidence/original-bytes.json").read_bytes()
)["files"]
production = json.loads(
(REPO / "docs/hel-892/setget-evidence/production-protection.json").read_bytes()
)["files"]
preserved = []
protected_production = [
p for p in production if not p["path"].endswith("/library.py")
]
for item in originals + protected_production:
path = item["path"]
raw = (REPO / path).read_bytes()
assert raw == subprocess.check_output(
["git", "show", f"{BASE}:{path}"], cwd=REPO
)
preserved.append({"path": path, "sha256": hashlib.sha256(raw).hexdigest()})
assert len(originals) == 163 and len(production) == 9
# Freeze the complete 28-profile baseline artifacts and every executable conversion module.
boundaries = [
"docs/hel-892/h3-chain-evidence/library.json",
"docs/hel-892/media-evidence/protected-six-cases.json",
"calliope-backend/src/calliope/comfyui/structure_reference.py",
"calliope-backend/src/calliope/comfyui/serialization_reference.py",
"calliope-backend/src/calliope/comfyui/ui2api.py",
"calliope-backend/src/calliope/comfyui/h3_core_reference.py",
"calliope-backend/src/calliope/comfyui/h3_chain_reference.py",
]
for path in boundaries:
assert (REPO / path).read_bytes() == subprocess.check_output(
["git", "show", f"{BASE}:{path}"], cwd=REPO
)
frozen = json.loads((REPO / boundaries[0]).read_bytes())
assert len(frozen["profiles"]) == 28
write(
"unchanged-boundaries.json",
{
"base": BASE,
"original_files": 163,
"unchanged_production_files": 8,
"authorized_document_integration": "library.py",
"files": preserved,
"frozen_conversion_and_audits": boundaries,
"old_28_attempts_and_gaps_9_candidate_hashes_six_diffs": "unchanged artifacts and implementation; no conversion rerun claimed",
},
)
review_path = "calliope-backend/src/calliope/comfyui/source_reviews.json"
old_reviews = json.loads(
subprocess.check_output(["git", "show", f"{BASE}:{review_path}"], cwd=REPO)
)
current_reviews = json.loads((REPO / review_path).read_bytes())
del current_reviews[SOURCE_PATH]["fixed_version_document"]
assert current_reviews == old_reviews
ui_path = "calliope-web/src/lib/components/WorkflowDocumentDrawer.svelte"
old_ui = subprocess.check_output(
["git", "show", f"{BASE}:{ui_path}"], cwd=REPO
).decode()
assert (REPO / ui_path).read_text().split("<style>")[1] == old_ui.split("<style>")[
1
]
write(
"editorial-boundaries.json",
{
"source_reviews_only_one_new_named_block": True,
"old_all_source_reviews_identical": True,
"drawer_css_unchanged": True,
},
)
packages = []
with (
zipfile.ZipFile(next((REPO / "calliope-backend/dist").glob("*.whl"))) as wheel,
tarfile.open(next((REPO / "calliope-backend/dist").glob("*.tar.gz"))) as sdist,
):
for name in ("library.py", "source_reviews.json", "fixed_document.py"):
path = f"calliope-backend/src/calliope/comfyui/{name}"
raw = (REPO / path).read_bytes()
assert wheel.read(f"calliope/comfyui/{name}") == raw
member = next(
n
for n in sdist.getnames()
if n.endswith(f"/src/calliope/comfyui/{name}")
)
assert sdist.extractfile(member).read() == raw
packages.append(
{
"path": path,
"sha256": hashlib.sha256(raw).hexdigest(),
"wheel": True,
"sdist": True,
}
)
write("package-check.json", packages)
print(
"PASS: real historical DB refresh1/skipped154; fresh155/repeat155; 18 definitions; 1217/3660/294; protections and packages"
)
if __name__ == "__main__":
main()