Files
aigc-home/docs/hel-892/batch177-controlnet-provenance/audit.py
T

580 lines
22 KiB
Python

"""Static provenance/schema evidence only. Never import or evaluate upstream code."""
import ast
import csv
import datetime as dt
import hashlib
import json
import subprocess
from pathlib import Path
from urllib.parse import urlparse
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
BASE = "e9ffdbb62961aa19148bccc4fc8ed5e58d8b3477"
AUX_REPO = "https://github.com/Fannovel16/comfyui_controlnet_aux"
CORE_REPO = "https://github.com/Comfy-Org/ComfyUI"
def now():
return dt.datetime.now(dt.timezone.utc).isoformat()
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def read(name):
return json.loads((HERE / name).read_text())
def write(name, value):
with (HERE / name).open("x", encoding="utf-8") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2)
stream.write("\n")
def literal(node):
if isinstance(node, ast.Name) and node.id == "MAX_RESOLUTION":
return 16384
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
return literal(node.left) + literal(node.right)
return ast.literal_eval(node)
def typed(value):
if isinstance(value, (dict, list)):
return [
type(value).__name__,
{k: typed(v) for k, v in value.items()}
if isinstance(value, dict)
else [typed(v) for v in value],
]
return [type(value).__name__, value]
def reference_identity(entry):
"""Require exact canonical URL/repo/commit/path before inheriting any history."""
url = urlparse(entry["url"])
bits = url.path.strip("/").split("/")
if url.netloc == "github.com":
if len(bits) < 5 or bits[2] != "blob":
return None
owner, repo, _, commit, *path = bits
elif url.netloc == "raw.githubusercontent.com":
if len(bits) < 4:
return None
owner, repo, commit, *path = bits
else:
return None
repository = f"https://github.com/{owner}/{repo}"
if entry.get("repository", repository) != repository:
return None
if commit != entry["commit"] or "/".join(path) != entry["file"]:
return None
if repository not in (AUX_REPO, CORE_REPO, "https://github.com/Comfy-Org/ComfyUI_frontend"):
return None
return repository, commit, entry["file"], entry["sha256"]
def declaration_matches(properties, proof):
if not properties.get("ver") or not properties.get("cnr_id"):
return False
if properties["ver"] != proof["version"]:
return False
repo = (
AUX_REPO
if properties["cnr_id"] == "comfyui_controlnet_aux"
else (CORE_REPO if properties["cnr_id"] == "comfy-core" else None)
)
return repo is not None and proof["repository"] == repo
def class_node(text, name):
return next(
node
for node in ast.parse(text).body
if isinstance(node, ast.ClassDef) and node.name == name
)
def excerpt(text, node):
selected = "\n".join(text.splitlines()[node.lineno - 1 : node.end_lineno])
return dict(
lines=[node.lineno, node.end_lineno], text=selected, utf8_sha256=sha(selected.encode())
)
def aux_schema(text, name, utils):
cls = class_node(text, name)
schema = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "INPUT_TYPES")
returned = next(n.value for n in schema.body if isinstance(n, ast.Return))
assert isinstance(returned, ast.Call) and isinstance(returned.func, ast.Name)
assert returned.func.id == "define_preprocessor_inputs"
fields = {"image": dict(type="IMAGE", required=True, default_known=False)}
for keyword in returned.keywords:
call = keyword.value
assert isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
assert isinstance(call.func.value, ast.Name) and call.func.value.id == "INPUT"
method = call.func.attr
cfg = {k.arg: literal(k.value) for k in call.keywords}
if method == "COMBO":
options = None if isinstance(call.args[0], ast.Name) else literal(call.args[0])
default = cfg.get("default", options[0] if options else None)
fields[keyword.arg] = dict(
type="COMBO",
options=options,
default=default,
default_known=True,
dynamic_options=options is None,
declaration=ast.get_source_segment(text, call),
)
else:
helper = next(
n
for n in class_node(utils, "INPUT").body
if isinstance(n, ast.FunctionDef) and n.name == method
)
defaults = dict(
zip(
[a.arg for a in helper.args.args][-len(helper.args.defaults) :],
[literal(n) for n in helper.args.defaults],
)
)
defaults.update(cfg)
fields[keyword.arg] = dict(
type="INT" if method == "RESOLUTION" else method,
**defaults,
default_known="default" in defaults,
declaration=ast.get_source_segment(text, call),
)
return fields
def core_schema(text, name):
if name == "LoadImage":
return {
"image": dict(
type="COMBO",
options=None,
dynamic_options=True,
default_known=False,
image_upload=True,
)
}
if name == "PreviewImage":
return {"images": dict(type="IMAGE", required=True, default_known=False)}
cls = class_node(text, name)
fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "define_schema")
call = next(n.value for n in fn.body if isinstance(n, ast.Return))
inputs = next(k.value.elts for k in call.keywords if k.arg == "inputs")
fields = {}
for item in inputs:
name = literal(item.args[0])
typ = item.func.value.attr
cfg = {k.arg: literal(k.value) for k in item.keywords}
fields[name] = dict(
type=typ.upper(),
**cfg,
default_known="default" in cfg,
declaration=ast.get_source_segment(text, item),
)
return fields
def schemas():
release = {p["name"]: p for p in read("release-member-proofs.json")}
bindings = read("core-bindings.json")
result = {}
utils = (HERE / release["utils.py"]["file"]).read_text()
files = [
"__init__.py",
"node_wrappers/depth_anything.py",
"node_wrappers/canny.py",
"node_wrappers/anyline.py",
"node_wrappers/lineart.py",
"node_wrappers/lineart_anime.py",
"node_wrappers/lineart_standard.py",
"node_wrappers/dwpose.py",
]
wanted = {
"AIO_Preprocessor",
"DepthAnythingPreprocessor",
"CannyEdgePreprocessor",
"AnyLineArtPreprocessor_aux",
"LineArtPreprocessor",
"AnimeLineArtPreprocessor",
"LineartStandardPreprocessor",
"DWPreprocessor",
"AnimalPosePreprocessor",
}
for file in files:
proof = release[file]
text = (HERE / proof["file"]).read_text()
assert sha(text.encode()) == proof["sha256"]
tree = ast.parse(text)
mappings = next(
n.value
for n in tree.body
if isinstance(n, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == "NODE_CLASS_MAPPINGS" for t in n.targets)
)
for key, value in zip(mappings.keys, mappings.values):
if not isinstance(key, ast.Constant) or key.value not in wanted:
continue
assert isinstance(value, ast.Name)
name = value.id
cls = class_node(text, name)
members = {n.name: excerpt(text, n) for n in cls.body if isinstance(n, ast.FunctionDef)}
function_defaults = {}
for fn in cls.body:
if isinstance(fn, ast.FunctionDef) and fn.args.defaults:
function_defaults[fn.name] = dict(
zip(
[a.arg for a in fn.args.args][-len(fn.args.defaults) :],
[literal(d) for d in fn.args.defaults],
)
)
attrs = {
n.targets[0].id: literal(n.value)
for n in cls.body
if isinstance(n, ast.Assign)
and isinstance(n.targets[0], ast.Name)
and n.targets[0].id in ("FUNCTION", "RETURN_TYPES", "RETURN_NAMES")
}
result[key.value] = dict(
class_name=name,
repository=AUX_REPO,
version="1.1.5",
file=file,
source_proof=proof,
schema=aux_schema(text, name, utils),
registration=excerpt(text, mappings),
class_excerpt=excerpt(text, cls),
members=members,
attributes=attrs,
bases=[ast.unparse(b) for b in cls.bases],
function_defaults=function_defaults,
acquisition="exact registry release member, Git commit unknown",
)
assert set(result) == wanted
for ct, path in (
("PreviewImage", "nodes.py"),
("LoadImage", "nodes.py"),
("Canny", "comfy_extras/nodes_canny.py"),
("ImageStitch", "comfy_extras/nodes_images.py"),
):
proof = next(p for p in bindings if p["path"] == path)
text = (ROOT / proof["retained_path"]).read_text()
cls = class_node(text, ct)
members = {n.name: excerpt(text, n) for n in cls.body if isinstance(n, ast.FunctionDef)}
result[ct] = dict(
class_name=ct,
repository=CORE_REPO,
version=proof["version"],
file=path,
source_proof=proof,
schema=core_schema(text, ct),
class_excerpt=excerpt(text, cls),
members=members,
bases=[ast.unparse(b) for b in cls.bases],
acquisition="retained bytes bound to exact tag/commit/tree/blob",
)
if ct == "PreviewImage":
result[ct]["base_excerpt"] = excerpt(text, class_node(text, "SaveImage"))
if ct in ("Canny", "ImageStitch"):
entry = next(
n
for n in ast.parse(text).body
if isinstance(n, ast.AsyncFunctionDef) and n.name == "comfy_entrypoint"
)
result[ct]["registration"] = excerpt(text, entry)
else:
mapping = next(
n.value
for n in ast.parse(text).body
if isinstance(n, ast.Assign)
and any(
isinstance(t, ast.Name) and t.id == "NODE_CLASS_MAPPINGS" for t in n.targets
)
)
assert any(
isinstance(k, ast.Constant)
and k.value == ct
and isinstance(v, ast.Name)
and v.id == ct
for k, v in zip(mapping.keys, mapping.values)
)
result[ct]["registration"] = dict(file=path, mapping="NODE_CLASS_MAPPINGS", key=ct)
return result
def historical_sources(previous):
candidates = []
for folder in (
"controlnet-reference",
"controlnet-document-evidence",
"serialization-evidence",
):
manifest = ROOT / "docs/hel-892" / folder / "sources.json"
for i, row in enumerate(json.loads(manifest.read_text())["sources"]):
local = (manifest.parent / row["local_file"]).resolve()
identity = reference_identity(row)
valid = (
identity is not None
and local.is_file()
and sha(local.read_bytes()) == row["sha256"]
)
candidates.append(
dict(
manifest=str(manifest.relative_to(ROOT)),
index=i,
record=row,
identity=identity,
accepted=valid,
reason="exact repo/commit/path/SHA" if valid else "identity or byte mismatch",
)
)
results = []
for old in previous["source_evidence"]:
ref = old["reference"]
identity = reference_identity(ref)
local = ROOT / old["retained_path"]
assert identity and sha(local.read_bytes()) == ref["sha256"]
matches = [c for c in candidates if c["accepted"] and c["identity"] == identity]
times = [
c["record"].get("retrieved_at") for c in matches if c["record"].get("retrieved_at")
]
first = min(times, key=dt.datetime.fromisoformat) if times else None
history = subprocess.check_output(
[
"git",
"log",
"--reverse",
"--diff-filter=A",
"--format=%H %aI",
BASE,
"--",
old["retained_path"],
],
cwd=ROOT,
text=True,
).splitlines()
results.append(
dict(
entry_index=old["entry_index"],
identity=list(identity),
retained_path=old["retained_path"],
reference=ref,
earliest_known_recorded_retrieval=first,
time_basis="matching member's own valid record only; missing stays null",
first_git_add_record=history[0] if history else None,
git_add_is_not_acquisition_time=True,
matching_history=[
dict(
manifest=c["manifest"],
index=c["index"],
own_recorded_time=c["record"].get("retrieved_at"),
)
for c in matches
],
rechecked_at=now(),
bytes_verified=True,
)
)
return results, candidates
def main():
previous = json.loads(
(ROOT / "docs/hel-892/batch176-offline-mapping/controlnet-matrix.json").read_text()
)
original_path = previous["source_path"]
raw = (ROOT / original_path).read_bytes()
assert sha(raw) == previous["source_sha256"]
original = json.loads(raw)
api_path = "docs/hel-892/supplied-api/01.api.json"
api_raw = (ROOT / api_path).read_bytes()
assert sha(api_raw) == previous["binding"]["export_sha256"]
api = json.loads(api_raw)
classes = schemas()
root_text = (HERE / "release-members/__init__.py").read_text()
excluded = []
for statement in ast.parse(root_text).body:
if isinstance(statement, ast.Assign) and any(
isinstance(t, ast.Name) and t.id == "AIO_NOT_SUPPORTED" for t in statement.targets
):
excluded.extend(literal(statement.value))
elif (
isinstance(statement, ast.AugAssign)
and isinstance(statement.target, ast.Name)
and statement.target.id == "AIO_NOT_SUPPORTED"
):
excluded.extend(literal(statement.value))
nodes, fields, dispatch = [], [], []
for i, node in enumerate(original["nodes"]):
nid, ct = str(node["id"]), node["type"]
props = node.get("properties", {})
definition = classes.get(ct)
category = (
"no_identity"
if not props.get("ver") or not props.get("cnr_id")
else (
"exact_declared_source"
if definition and declaration_matches(props, definition)
else "declared_not_obtained"
)
)
nodes.append(
dict(
node_id=nid,
class_type=ct,
original_pointer=f"/nodes/{i}",
original_properties=props,
category=category,
declaration_version=props.get("ver"),
class_definition=ct if definition else None,
target_installation="unknown",
frontend_restoration="unknown",
definition_scope=(
"registration/schema/class text only; dependency execution not certified"
),
rechecked_at=now(),
)
)
if ct == "AIO_Preprocessor":
selected = api[nid]["inputs"]["preprocessor"]
assert selected not in excluded
assert selected in classes and classes[selected]["repository"] == AUX_REPO
selected_schema = classes[selected]["schema"]
effective = {
k: v.get("default")
for k, v in selected_schema.items()
if k not in ("image", "resolution") and v.get("default_known")
}
dispatch.append(
dict(
node_id=nid,
selected=selected,
class_name=classes[selected]["class_name"],
selected_schema=selected_schema,
forwarded_image=api[nid]["inputs"]["image"],
forwarded_resolution=api[nid]["inputs"]["resolution"],
static_schema_defaults_for_other_inputs=effective,
source="__init__.py:AIO_Preprocessor.execute + utils.py:INPUT",
conditional_on="wrapper imports succeeding; options not evaluated",
source_return=classes[selected].get("attributes"),
actual_execution=False,
)
)
for old in previous["saved_values"]:
nid, name = old["node_id"], old["field"]
node = next(n for n in nodes if n["node_id"] == nid)
definition = classes[node["class_type"]]
spec = definition["schema"].get(name)
frontend = old["api_pointer"] is None
assert spec is not None or frontend
default_known = bool(spec and spec.get("default_known"))
differences = []
if default_known and typed(spec["default"]) != typed(old["value"]):
differences.append("saved_value_differs_from_schema_default")
if spec and spec.get("dynamic_options"):
differences.append("runtime_combo_membership_unknown")
if spec:
value = old["value"]
if spec.get("type") == "INT":
assert type(value) is int
if spec.get("type") == "FLOAT":
assert type(value) in (int, float)
if spec.get("type") == "BOOLEAN":
assert type(value) is bool
if "min" in spec:
assert value >= spec["min"]
if "max" in spec:
assert value <= spec["max"]
if spec.get("options") is not None:
assert value in spec["options"]
fields.append(
dict(
original_document=original_path,
original_pointer=old["original_pointer"],
node_id=nid,
class_type=node["class_type"],
field=name,
saved_value=old["value"],
recursive_type=typed(old["value"]),
api_pointer=old["api_pointer"],
schema=spec,
scope="frontend_cache_not_node_input" if frontend else "exact_source_schema_text",
default_is_not_saved_value=True,
differences=differences,
unit=None,
unit_basis="no explicit unit declaration inferred",
target_installation="unknown",
)
)
history, candidates = historical_sources(previous)
for definition in classes.values():
proof = definition["source_proof"]
matches = [
r
for r in history
if r["identity"][0] == definition["repository"]
and r["identity"][2] == definition["file"]
and r["identity"][3] == proof["sha256"]
]
times = [
r["earliest_known_recorded_retrieval"]
for r in matches
if r["earliest_known_recorded_retrieval"]
]
definition["earliest_known_prior_member_retrieval"] = (
min(times, key=dt.datetime.fromisoformat) if times else None
)
definition["prior_member_time_basis"] = (
"own exact historical member only; unknown stays null"
)
definition["new_binding_time"] = proof.get("retrieved_at", proof.get("rechecked_at"))
write("historical-citation-audit.json", dict(sources=history, bounded_candidates=candidates))
write("class-schema-matrix.json", classes)
write("node-matrix.json", nodes)
write("field-matrix.json", fields)
write("aio-dispatch.json", dispatch)
all_rows = [dict(kind="node", **r) for r in nodes] + [dict(kind="field", **r) for r in fields]
columns = sorted({k for row in all_rows for k in row})
with (HERE / "node-field-matrix.csv").open("x", encoding="utf-8", newline="") as stream:
writer = csv.DictWriter(stream, columns, lineterminator="\n")
writer.writeheader()
for row in all_rows:
writer.writerow({k: json.dumps(v, ensure_ascii=False) for k, v in row.items()})
counts = {
category: sum(n["category"] == category for n in nodes)
for category in ("exact_declared_source", "declared_not_obtained", "no_identity")
}
write(
"summary.json",
dict(
nodes=len(nodes),
fields=len(fields),
classes=len(classes),
aio_dispatches=len(dispatch),
categories=counts,
historical_citations=len(history),
historical_unknown_times=sum(
r["earliest_known_recorded_retrieval"] is None for r in history
),
original_sha256=sha(raw),
case01_sha256=sha(api_raw),
target_installations_verified=0,
source_export_equivalence=False,
semantic_execution_certification=False,
dependencies_not_imported=True,
baseline=BASE,
),
)
print(json.dumps(read("summary.json"), ensure_ascii=False))
if __name__ == "__main__":
main()