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

298 lines
12 KiB
Python

"""Actual a4f3616 upgrade, one-row rollback, user protection and package byte checks."""
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 = "a4f36165162c4c793aa93934bb5bd2607df54cc0"
sys.path.insert(0, str(REPO / "calliope-backend"))
def write(name, data):
(OUT / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
def main():
from calliope.comfyui.fixed_document import DEFINITIONS as ALL_DEFINITIONS
from calliope.comfyui.fixed_document import canonical
definitions = {
p: d for p, d in ALL_DEFINITIONS.items() if p.endswith("ControlNet_aux_常用样例.json")
}
old_paths = ALL_DEFINITIONS.keys() - definitions.keys()
from calliope.comfyui.library import rollback_batch
from scripts.audit_library_documents import audit
with tempfile.TemporaryDirectory() as directory:
work = Path(directory)
old = work / "old"
old.mkdir()
raw = subprocess.check_output(["git", "archive", BASE, "calliope-backend/src"], cwd=REPO)
with tarfile.open(fileobj=io.BytesIO(raw)) as archive:
archive.extractall(old, filter="data")
db = work / "old.db"
def run(name, historical=False):
output = work / name
env = {
**os.environ,
"PYTHONPATH": str((old if historical else REPO) / "calliope-backend/src"),
}
subprocess.run(
[
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),
],
cwd=REPO,
env=env,
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("old-first", True)
before = rows()
assert first["counts"] == {"imported": 155, "user_excluded": 1}
for p in old_paths:
assert json.loads(before[p]["doc_json"])["fixed_version"]["matched"]
for p in definitions:
assert "fixed_version" not in json.loads(before[p]["doc_json"])
original = db
old_protection = []
def protect_old(name):
nonlocal db
save_db = db
db = work / (name + ".db")
with sqlite3.connect(save_db) as src, sqlite3.connect(db) as dst:
src.backup(dst)
for p in old_paths:
dst.execute(
"UPDATE workflows SET description=? WHERE source_repo_path=?", (name, p)
)
snapshot = rows()
protected, _ = run(name)
assert (
protected["counts"] == {"conflict": 7, "skipped": 148, "user_excluded": 1}
if name == "old-user-after"
else protected["counts"]
== {"conflict": 7, "updated": 1, "skipped": 147, "user_excluded": 1}
)
# New document updates before upgrade are expected, every old edited row must be exact.
result = rows()
assert all(result[p] == snapshot[p] and len(result[p]) == 29 for p in old_paths)
old_protection.append(
{"phase": name, "counts": protected["counts"], "whole_old_rows_protected": 7}
)
db = save_db
protect_old("old-user-before")
db = work / "user-before.db"
with sqlite3.connect(original) as src, sqlite3.connect(db) as dst:
src.backup(dst)
for p in definitions:
dst.execute(
"UPDATE workflows SET description=? WHERE source_repo_path=?",
("用户升级前编辑", p),
)
user_before = rows()
protected_before, _ = run("user-before")
assert protected_before["counts"] == {
"conflict": 1,
"skipped": 154,
"user_excluded": 1,
}
assert rows() == user_before
db = original
upgrade, _exported = run("upgrade")
after = rows()
assert upgrade["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
for path, row in after.items():
if path not in definitions:
assert row == before[path]
else:
for k in row.keys() - {
"doc_json",
"batch_id",
"imported_at",
"library_fingerprint",
}:
assert row[k] == before[path][k]
d = json.loads(row["doc_json"])
assert d["fixed_version"]["matched"]
b = {k: v for k, v in d["fixed_version"].items() if k != "matched"}
assert hashlib.sha256(canonical(b)).hexdigest() == definitions[path]
write("actual-" + Path(path).stem + ".json", d)
protect_old("old-user-after")
repeat, _ = run("repeat")
assert repeat["counts"] == {"skipped": 155, "user_excluded": 1}
with sqlite3.connect(db) as conn:
conn.row_factory = sqlite3.Row
rollback = rollback_batch(conn, upgrade["batch_id"])
assert len(rollback["files"]) == 1 and all(
f["result"] == "restored" for f in rollback["files"]
)
assert rows() == before
redo, _ = run("redo")
assert redo["counts"] == upgrade["counts"]
for p in definitions:
with sqlite3.connect(db) as conn:
conn.execute(
"UPDATE workflows SET description=? WHERE source_repo_path=?",
("用户升级后编辑", p),
)
user_after = rows()
protected_after, _ = run("user-after")
assert protected_after["counts"] == protected_before["counts"]
assert rows() == user_after and all(len(user_after[p]) == 29 for p in definitions)
db = work / "fresh.db"
fresh, fresh_export = run("fresh")
fresh_repeat, _ = run("fresh-repeat")
assert fresh["counts"] == first["counts"]
assert fresh["states"] == {"pending_check": 16, "needs_conversion": 139}
assert fresh_repeat["counts"] == repeat["counts"]
companion = 0
for row in rows().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 not d["status"]["doc_done"] and not d["status"]["exec_verified"]
assert d["dependencies"]["check_state"] == "unchecked"
assert companion == 294
report = audit(REPO, fresh_export)
assert report["named_values_preserved"] == 1217 and report["unnamed_widget_nodes"] == 3660
assert report["full_documents_completed"] == report["real_executions"] == 0
write("audit-summary.json", {k: v for k, v in report.items() if k != "files"})
write(
"import-protection.json",
dict(
historical_code=BASE,
old_seven_protection=old_protection,
first=first["counts"],
upgrade=upgrade["counts"],
repeat=repeat["counts"],
restored_rows=1,
untouched_whole_rows=154,
eligibility_columns_unchanged=True,
redo=redo["counts"],
user_before=protected_before["counts"],
user_after=protected_after["counts"],
user_whole_row_columns=29,
fresh=fresh["counts"],
fresh_repeat=fresh_repeat["counts"],
states=fresh["states"],
source_named_fields=1217,
positional_widgets=3660,
companion_values=companion,
new_saved_definitions=36,
old_saved_definitions=102,
all_disabled=True,
dependencies_unchecked=True,
doc_done=0,
executed=0,
),
)
reviews_path = "calliope-backend/src/calliope/comfyui/source_reviews.json"
previous = json.loads(
subprocess.check_output(["git", "show", f"{BASE}:{reviews_path}"], cwd=REPO)
)
current = json.loads((REPO / reviews_path).read_bytes())
for p in definitions:
assert "fixed_version_document" not in previous[p]
current[p].pop("fixed_version_document")
assert previous == current
boundaries = json.loads(
(REPO / "docs/hel-892/h3-document-evidence/unchanged-boundaries.json").read_bytes()
)
paths = [f["path"] for f in boundaries["files"]] + boundaries["frozen_conversion_and_audits"]
paths += ["calliope-backend/src/calliope/comfyui/library.py"]
kept = []
for p in paths:
raw = (REPO / p).read_bytes()
assert raw == subprocess.check_output(["git", "show", f"{BASE}:{p}"], cwd=REPO)
kept.append(dict(path=p, sha256=hashlib.sha256(raw).hexdigest()))
ui = "calliope-web/src/lib/components/WorkflowDocumentDrawer.svelte"
assert (REPO / ui).read_text().split("<style>")[1] == subprocess.check_output(
["git", "show", f"{BASE}:{ui}"], cwd=REPO
).decode().split("<style>")[1]
write(
"boundaries.json",
dict(
base=BASE,
files=kept,
originals=163,
source_reviews_only_one_new_block=True,
drawer_css_unchanged=True,
conversion_rerun=False,
old_28_profiles_9_candidates_6_diffs="unchanged artifacts and implementation",
),
)
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 ["fixed_document.py", "source_reviews.json", "library.py"]:
raw = (REPO / "calliope-backend/src/calliope/comfyui" / name).read_bytes()
assert wheel.read("calliope/comfyui/" + name) == raw
member = next(
n for n in sdist.getnames() if n.endswith("/src/calliope/comfyui/" + name)
)
assert sdist.extractfile(member).read() == raw
packages.append(
dict(
file=name,
sha256=hashlib.sha256(raw).hexdigest(),
wheel=True,
sdist=True,
)
)
write("package-check.json", packages)
print(
(
"PASS: actual old-code upgrade1/skip154, ro"
"llback1, user conflicts1 before/after, old"
"7 protected, fresh155, 36+102 definitions, "
"1217/3660/294, boundaries and packages"
)
)
if __name__ == "__main__":
main()