499 lines
19 KiB
Python
499 lines
19 KiB
Python
"""Bounded, inert JSON comparison. No workflow imports, eval, network or DB writes."""
|
|
|
|
import csv
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
ROOT = HERE.parents[2]
|
|
OUT = HERE
|
|
|
|
|
|
def sha(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def write(name, value):
|
|
path = OUT / name
|
|
with path.open("x", encoding="utf-8") as stream:
|
|
json.dump(value, stream, ensure_ascii=False, indent=2)
|
|
stream.write("\n")
|
|
|
|
|
|
def read(name):
|
|
return json.loads((HERE / name).read_text())
|
|
|
|
|
|
def escape(key):
|
|
return str(key).replace("~", "~0").replace("/", "~1")
|
|
|
|
|
|
def at(value, pointer):
|
|
for key in pointer.split("/")[1:]:
|
|
key = key.replace("~1", "/").replace("~0", "~")
|
|
value = value[int(key)] if isinstance(value, list) else value[key]
|
|
return value
|
|
|
|
|
|
def typed(value):
|
|
"""JSON equality with bool/int/float and every nested container distinguished."""
|
|
if isinstance(value, dict):
|
|
return ["object", {key: typed(val) for key, val in sorted(value.items())}]
|
|
if isinstance(value, list):
|
|
return ["array", [typed(val) for val in value]]
|
|
return [type(value).__name__, value]
|
|
|
|
|
|
def same(left, right):
|
|
return typed(left) == typed(right)
|
|
|
|
|
|
def reference(value, graph):
|
|
return (
|
|
isinstance(value, list)
|
|
and len(value) == 2
|
|
and isinstance(value[0], str)
|
|
and value[0] in graph
|
|
and type(value[1]) is int
|
|
and value[1] >= 0
|
|
)
|
|
|
|
|
|
def api_compare(expected, actual):
|
|
"""Whole API shape, names, nested types, class and metadata; no omitted-key pass."""
|
|
differences = []
|
|
|
|
def walk(left, right, pointer):
|
|
if type(left) is not type(right):
|
|
differences.append(dict(pointer=pointer, kind="type", expected=left, actual=right))
|
|
elif isinstance(left, dict):
|
|
for key in sorted(left.keys() | right.keys()):
|
|
ptr = pointer + "/" + escape(key)
|
|
if key not in right or key not in left:
|
|
differences.append(dict(pointer=ptr, kind="missing_or_extra"))
|
|
else:
|
|
walk(left[key], right[key], ptr)
|
|
elif isinstance(left, list):
|
|
if len(left) != len(right):
|
|
differences.append(dict(pointer=pointer, kind="length"))
|
|
for i, (lv, rv) in enumerate(zip(left, right)):
|
|
walk(lv, rv, f"{pointer}/{i}")
|
|
elif left != right:
|
|
differences.append(dict(pointer=pointer, kind="value", expected=left, actual=right))
|
|
|
|
walk(expected, actual, "")
|
|
return differences
|
|
|
|
|
|
def qualify(identities, qualification):
|
|
"""Fail closed: byte/port matches never release identity or execution gates."""
|
|
if not identities or any(i.get("target_identity_verified") is not True for i in identities):
|
|
return False
|
|
return (
|
|
qualification.get("is_enabled") == 1
|
|
and qualification.get("doc_completed_at") is not None
|
|
and qualification.get("exec_verified_at") is not None
|
|
)
|
|
|
|
|
|
def resolve(source):
|
|
"""Independent physical edge traversal through only this graph's Reroutes."""
|
|
nodes = {str(n["id"]): (i, n) for i, n in enumerate(source["nodes"])}
|
|
edges = {edge[0]: (i, edge) for i, edge in enumerate(source["links"])}
|
|
assert len(nodes) == len(source["nodes"]) and len(edges) == len(source["links"])
|
|
results = []
|
|
for nid, (ni, node) in nodes.items():
|
|
if node["type"] == "Reroute":
|
|
continue
|
|
for slot, socket in enumerate(node.get("inputs", [])):
|
|
if socket.get("link") is None:
|
|
continue
|
|
edge_id, seen, chain = socket["link"], set(), []
|
|
target, target_slot = nid, slot
|
|
while True:
|
|
assert edge_id not in seen, "cycle"
|
|
seen.add(edge_id)
|
|
ei, edge = edges[edge_id]
|
|
assert str(edge[3]) == target and edge[4] == target_slot
|
|
assert type(edge[2]) is int and edge[2] >= 0
|
|
chain.append(dict(pointer=f"/links/{ei}", edge=edge))
|
|
upstream = str(edge[1])
|
|
_, origin = nodes[upstream]
|
|
assert edge[2] < len(origin.get("outputs", []))
|
|
if origin["type"] != "Reroute":
|
|
break
|
|
assert edge[2] == 0 and len(origin["inputs"]) == 1
|
|
target, target_slot = upstream, 0
|
|
edge_id = origin["inputs"][0]["link"]
|
|
results.append(
|
|
dict(
|
|
node_id=nid,
|
|
field=socket["name"],
|
|
input_slot=slot,
|
|
pointer=f"/nodes/{ni}/inputs/{slot}",
|
|
endpoint=[upstream, edge[2]],
|
|
source_chain=chain,
|
|
)
|
|
)
|
|
return results
|
|
|
|
|
|
def parameters(graph, doc):
|
|
rows = []
|
|
consumed = set()
|
|
for nid, node in graph.items():
|
|
for key, value in node["inputs"].items():
|
|
ptr = f"/{escape(nid)}/inputs/{escape(key)}"
|
|
is_ref = reference(value, graph)
|
|
matches = [
|
|
(i, p)
|
|
for i, p in enumerate(doc["params"])
|
|
if str(p.get("api_node_id", p["node_id"])) == nid and p["field"] == key
|
|
]
|
|
if not is_ref:
|
|
assert len(matches) == 1, (ptr, "parameter ambiguous or absent")
|
|
pi, param = matches[0]
|
|
assert same(value, param["default"]), (ptr, "parameter recursive type/value drift")
|
|
consumed.add(pi)
|
|
else:
|
|
assert not matches, (ptr, "reference incorrectly editable")
|
|
rows.append(
|
|
dict(
|
|
kind="api_reference" if is_ref else "api_saved_value",
|
|
original_pointer=ptr,
|
|
node_id=nid,
|
|
field=key,
|
|
value=value,
|
|
recursive_type=typed(value),
|
|
doc_param_pointer=None if is_ref else f"/params/{matches[0][0]}/default",
|
|
endpoint=value if is_ref else None,
|
|
implementation="unknown",
|
|
evidence="retained import snapshot, not a new import",
|
|
status="structure_equal",
|
|
)
|
|
)
|
|
assert consumed == set(range(len(doc["params"]))), "extra unconsumed doc parameters"
|
|
return rows
|
|
|
|
|
|
def source_proofs(block):
|
|
results = []
|
|
for i, entry in enumerate(block["sources"]):
|
|
# Resolve only a retained local file; never fetch the URL or import source text.
|
|
path = (ROOT / "docs/hel-892/controlnet-document-evidence" / entry["local_file"]).resolve()
|
|
path.relative_to(ROOT)
|
|
raw = path.read_bytes()
|
|
assert sha(raw) == entry["sha256"]
|
|
lines = raw.decode("utf-8").splitlines()
|
|
start, end = entry["lines"]
|
|
assert 1 <= start <= end <= len(lines)
|
|
selected = "\n".join(lines[start - 1 : end])
|
|
results.append(
|
|
dict(
|
|
entry_index=i,
|
|
reference=entry,
|
|
retained_path=str(path.relative_to(ROOT)),
|
|
retained_sha256=sha(raw),
|
|
bytes_equal=True,
|
|
line_excerpt=selected,
|
|
excerpt_utf8_sha256=sha(selected.encode()),
|
|
proves="retained reference commit/file bytes and cited static text only",
|
|
target_identity_verified=False,
|
|
package_release_to_commit_verified=False,
|
|
frontend_restoration_verified=False,
|
|
)
|
|
)
|
|
return results
|
|
|
|
|
|
def matrix(key, original, imported, doc, block, qualification, import_fields, binding=None):
|
|
ui = "nodes" in original
|
|
graph = imported if ui else original
|
|
assert not api_compare(graph, imported), "imported API differs"
|
|
rows = parameters(graph, doc)
|
|
identities = []
|
|
source_nodes = original["nodes"] if ui else list(original.values())
|
|
ids = [str(n["id"]) for n in source_nodes] if ui else list(original)
|
|
assert len(doc["source_nodes"]) == len(source_nodes)
|
|
for i, (nid, node) in enumerate(zip(ids, source_nodes)):
|
|
inventory = doc["source_nodes"][i]
|
|
values = node.get("widgets_values", []) if ui else node["inputs"]
|
|
assert same(inventory["source_values"], values)
|
|
assert inventory["node_id"] == nid
|
|
ct = node["type"] if ui else node["class_type"]
|
|
assert inventory["class_type"] == ct
|
|
assert same(inventory["inputs"], node.get("inputs", []) if ui else values)
|
|
assert inventory["mode"] == node.get("mode", 0)
|
|
assert inventory["title"] == (node.get("title") or node.get("_meta", {}).get("title"))
|
|
ptr = f"/nodes/{i}" if ui else "/" + escape(nid)
|
|
identities.append(
|
|
dict(
|
|
node_id=nid,
|
|
original_pointer=ptr,
|
|
class_type=ct,
|
|
raw_properties=node.get("properties"),
|
|
fixed_binding=next(
|
|
(b for b in block.get("node_bindings", []) if b["node_id"] == nid), None
|
|
),
|
|
binding_collection_present="node_bindings" in block,
|
|
target_identity_verified=False,
|
|
implementation="unknown target; declared reference version only"
|
|
if ui
|
|
else "unknown",
|
|
imported_node=nid if nid in imported else None,
|
|
doc_inventory_pointer=f"/source_nodes/{i}",
|
|
missing_reason="frontend Reroute omitted in API" if nid not in imported else None,
|
|
)
|
|
)
|
|
field_rows = []
|
|
for i, field in enumerate(block["fields"]):
|
|
value = at(original, field["pointer"])
|
|
assert same(value, field["value"])
|
|
nid, name = field["node_id"], field["field"]
|
|
frontend = field.get("role") == "frontend"
|
|
api_pointer = None if frontend else f"/{escape(nid)}/inputs/{escape(name)}"
|
|
if api_pointer:
|
|
assert same(value, at(graph, api_pointer))
|
|
field_rows.append(
|
|
dict(
|
|
kind="frontend_cache" if frontend else "original_saved_value",
|
|
original_pointer=field["pointer"],
|
|
node_id=nid,
|
|
field=name,
|
|
value=value,
|
|
recursive_type=typed(value),
|
|
api_pointer=api_pointer,
|
|
fixed_pointer=f"/fixed_version/fields/{i}",
|
|
doc_inventory_pointer=next(
|
|
item["doc_inventory_pointer"] for item in identities if item["node_id"] == nid
|
|
)
|
|
+ "/source_values",
|
|
status="frontend_only_unconsumed_by_api" if frontend else "structure_equal",
|
|
implementation="unknown target",
|
|
evidence=field.get("evidence", []),
|
|
)
|
|
)
|
|
assert len({r["original_pointer"] for r in field_rows}) == len(field_rows)
|
|
if ui:
|
|
expected_fields = {
|
|
f"/nodes/{ni}/widgets_values/{wi}"
|
|
for ni, node in enumerate(source_nodes)
|
|
for wi, _ in enumerate(node.get("widgets_values", []))
|
|
}
|
|
else:
|
|
expected_fields = {r["original_pointer"] for r in rows if r["kind"] == "api_saved_value"}
|
|
assert {r["original_pointer"] for r in field_rows} == expected_fields
|
|
assert same(doc["fixed_version"]["fields"], block["fields"])
|
|
if ui:
|
|
endpoints = resolve(original)
|
|
for endpoint in endpoints:
|
|
assert same(
|
|
at(graph, f"/{endpoint['node_id']}/inputs/{endpoint['field']}"),
|
|
endpoint["endpoint"],
|
|
)
|
|
assert len(endpoints) == sum(r["kind"] == "api_reference" for r in rows)
|
|
for i, edge in enumerate(original["links"]):
|
|
assert same(doc["source_links"][i]["link"], edge)
|
|
assert len(doc["source_links"]) == len(original["links"])
|
|
assert same(
|
|
endpoints,
|
|
[
|
|
dict(
|
|
e,
|
|
**{
|
|
"input_slot": next(
|
|
x["input_slot"]
|
|
for x in endpoints
|
|
if x["node_id"] == e["node_id"] and x["field"] == e["field"]
|
|
),
|
|
"pointer": next(
|
|
x["pointer"]
|
|
for x in endpoints
|
|
if x["node_id"] == e["node_id"] and x["field"] == e["field"]
|
|
),
|
|
},
|
|
)
|
|
for e in block["resolved_endpoints"]
|
|
],
|
|
)
|
|
physical = [
|
|
dict(kind="physical_edge", original_pointer=f"/links/{i}", edge=e)
|
|
for i, e in enumerate(original["links"])
|
|
]
|
|
else:
|
|
endpoints = []
|
|
physical = []
|
|
for r in rows:
|
|
if r["kind"] == "api_reference":
|
|
matches = [
|
|
x
|
|
for x in doc["source_links"]
|
|
if x["node_id"] == r["node_id"] and x["field"] == r["field"]
|
|
]
|
|
assert len(matches) == 1
|
|
assert same(
|
|
[matches[0]["upstream_node_id"], matches[0]["output_slot"]], r["endpoint"]
|
|
)
|
|
assert len(doc["source_links"]) == sum(r["kind"] == "api_reference" for r in rows)
|
|
assert same(block["api_references"], doc["fixed_version"]["api_references"])
|
|
assert {r["pointer"] for r in block["api_references"]} == {
|
|
r["original_pointer"] for r in rows if r["kind"] == "api_reference"
|
|
}
|
|
for r in block["api_references"]:
|
|
assert same(at(original, r["pointer"]), r["original"])
|
|
assert same(r["original"], [r["source_node_id"], r["output_index"]])
|
|
assert not qualify(identities, qualification)
|
|
interface = []
|
|
for collection in ("input_schema", "output_schema", "output_map"):
|
|
for index, entry in enumerate(import_fields[collection]):
|
|
nid = entry["nodeId"]
|
|
assert nid in graph
|
|
interface.append(
|
|
dict(
|
|
kind="import_interface",
|
|
collection=collection,
|
|
entry=entry,
|
|
imported_pointer=f"/{collection}/{index}",
|
|
api_node_pointer="/" + escape(nid),
|
|
evidence="retained importer role/registry guess, not target schema or history",
|
|
target_verified=False,
|
|
)
|
|
)
|
|
title_differences = []
|
|
if ui:
|
|
for nid, node in zip(ids, source_nodes):
|
|
if nid in graph:
|
|
assert node["type"] == graph[nid]["class_type"]
|
|
before = node.get("title") or node["type"]
|
|
after = graph[nid].get("_meta", {}).get("title")
|
|
if before != after:
|
|
title_differences.append(
|
|
dict(node_id=nid, source_title=before, api_title=after)
|
|
)
|
|
result = dict(
|
|
case=key,
|
|
source_path=block["source_path"],
|
|
source_sha256=sha((ROOT / block["source_path"]).read_bytes()),
|
|
fixed_pin=sha(
|
|
json.dumps(block, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
|
|
),
|
|
source_canonical_sha256=block["canonical_sha256"],
|
|
original_node_count=len(source_nodes),
|
|
imported_node_count=len(graph),
|
|
original_saved_count=len(field_rows),
|
|
api_named_saved_count=sum(r["kind"] == "api_saved_value" for r in rows),
|
|
api_reference_count=sum(r["kind"] == "api_reference" for r in rows),
|
|
nonzero_output_references=[r for r in rows if r["endpoint"] and r["endpoint"][1] != 0],
|
|
identity_records=identities,
|
|
saved_values=field_rows,
|
|
api_inputs=rows,
|
|
physical_edges=physical,
|
|
resolved_endpoints=endpoints,
|
|
unconsumed_original_values=[r for r in field_rows if r["api_pointer"] is None],
|
|
unmappable=[],
|
|
ambiguous=[],
|
|
unexpected_imported_nodes=sorted(set(graph) - set(ids)),
|
|
qualification=qualification,
|
|
execution_release=False,
|
|
source_export_full_equivalence_verified=False if ui else None,
|
|
frontend_restoration_verified=False,
|
|
binding=binding,
|
|
import_fields=import_fields,
|
|
interface_mappings=interface,
|
|
title_differences=title_differences,
|
|
source_evidence=source_proofs(block) if ui else [],
|
|
)
|
|
for row in field_rows + physical + identities + endpoints:
|
|
row["original_document"] = block["source_path"]
|
|
for row in rows:
|
|
row["original_document"] = (
|
|
"docs/hel-892/supplied-api/01.api.json" if ui else block["source_path"]
|
|
)
|
|
write(f"{key}-matrix.json", result)
|
|
csv_rows = (
|
|
field_rows
|
|
+ rows
|
|
+ physical
|
|
+ [dict(kind="node", **r) for r in identities]
|
|
+ [dict(kind="resolved_endpoint", **r) for r in endpoints]
|
|
+ interface
|
|
)
|
|
columns = sorted({k for r in csv_rows for k in r})
|
|
with (OUT / f"{key}-matrix.csv").open("x", encoding="utf-8", newline="") as stream:
|
|
writer = csv.DictWriter(stream, columns, lineterminator="\n")
|
|
writer.writeheader()
|
|
for row in csv_rows:
|
|
writer.writerow({k: json.dumps(v, ensure_ascii=False) for k, v in row.items()})
|
|
return result
|
|
|
|
|
|
def main():
|
|
global OUT
|
|
if len(sys.argv) > 1:
|
|
assert len(sys.argv) == 3 and sys.argv[1] == "--output-dir"
|
|
OUT = Path(sys.argv[2]).resolve()
|
|
OUT.mkdir(exist_ok=False)
|
|
inputs = read("inputs.json")
|
|
for entry in inputs["file_evidence"]:
|
|
assert sha((ROOT / entry["path"]).read_bytes()) == entry["sha256"]
|
|
results = []
|
|
for key in ("krea", "controlnet"):
|
|
item = inputs[key]
|
|
source = json.loads((ROOT / item["source_path"]).read_text())
|
|
assert sha((ROOT / item["source_path"]).read_bytes()) == item["block"]["source_sha256"]
|
|
assert (
|
|
sha(
|
|
json.dumps(
|
|
source, ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
|
).encode()
|
|
)
|
|
== item["block"]["canonical_sha256"]
|
|
)
|
|
assert (
|
|
sha(
|
|
json.dumps(
|
|
item["block"], ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
|
).encode()
|
|
)
|
|
== item["definition_pin"]
|
|
)
|
|
assert same(item["doc"]["fixed_version"], dict(item["block"], matched=True))
|
|
results.append(
|
|
matrix(
|
|
key,
|
|
source,
|
|
item["imported_api"],
|
|
item["doc"],
|
|
item["block"],
|
|
item["qualification"],
|
|
item["import_fields"],
|
|
item.get("binding"),
|
|
)
|
|
)
|
|
assert [
|
|
(r["original_node_count"], r["original_saved_count"], r["api_reference_count"])
|
|
for r in results
|
|
] == [(24, 42, 34), (26, 36, 23)]
|
|
write(
|
|
"summary.json",
|
|
[
|
|
dict(
|
|
case=r["case"],
|
|
nodes=r["original_node_count"],
|
|
saved=r["original_saved_count"],
|
|
named=r["api_named_saved_count"],
|
|
refs=r["api_reference_count"],
|
|
nonzero=len(r["nonzero_output_references"]),
|
|
release=r["execution_release"],
|
|
)
|
|
for r in results
|
|
],
|
|
)
|
|
print((OUT / "summary.json").read_text())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|