GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / data-gridatlas / atman

Verify V8 Transplant and 1 more file

A Python command-line tool in the atman folder of Data GridAtlas that reads transplant plan, runtime dependencies, repository boundary and dependency ledger, using SHA-256.

700 lines of Python from data-gridatlas, in 2 files. Topic: Maps, GIS and field navigation. Section 478 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Verify Bootstrap storage · data-gridatlas / atman/202608290904-verify-bootstrap.py lines 1–304
  2. Verify V8 Transplant storage · data-gridatlas / atman/202608291015-verify-v8-transplant.py lines 1–396

Verify Bootstrap

A Python command-line tool in the atman folder of Data GridAtlas that reads GridAtlas bootstrap, GridAtlas consumer, dependency ledger and quarantine, using SHA-256.

storagedata-gridatlas / atman/202608290904-verify-bootstrap.py · lines 1–304 of 304 · version 2026-08-29 09:04 · Entry point · pattern safe_relative (shared by 2 files)

What it does
It loads GridAtlas bootstrap, GridAtlas consumer, dependency ledger and quarantine. Defines 11 functions or classes, including reject_duplicate_keys, load, digest, require, safe_relative. Uses libraries argparse, hashlib, json, re, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file 202608290904-data-gridatlas-bootstrap.json; JSON file 202608290904-gridatlas-consumer.json; JSON file 202608290904-v8-dependency-ledger.json; JSON file 202608290904-v8-file-ledger.json; JSON file 202608290904-v8-quarantine.json; Parquet file files.parquet; Parquet file layers.parquet; Parquet file quarantine.parquet.
Downstream impact
Used directly by 1 file: Bootstrap Verify Data GridAtlas Workflow (data-gridatlas).
What it achieves
It verifies repository (`verify_repository`), parses oracle tree (`parse_oracle_tree`) and verifies oracle (`verify_oracle`). Independent verifier for the inventory-only data-GridAtlas bootstrap. It accepts `--repository`, `--oracle-tree` and `--catalog`.
Why it matters
Run by Bootstrap Verify Data GridAtlas Workflow.
Application
data-gridatlas · atman · Python CLI
Uses
argparse, hashlib, json, re, subprocess, collections, pathlib, duckdb
Used by
run by Bootstrap Verify Data GridAtlas Workflow (workflow run)
Produces
reject_duplicate_keys, load, digest, require, safe_relative, inventory, verify_repository, parse_oracle_tree, verify_oracle, verify_catalog, main
Defines here
reject_duplicate_keys, load, digest, require, safe_relative, inventory, verify_repository, parse_oracle_tree, verify_oracle, verify_catalog, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e atman/202608290904-verify-bootstrap.py:1-304 · blob a87cd4f05650686bcffa2d961ac533cd8258660a · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Independent verifier for the inventory-only data-gridatlas bootstrap."""

import argparse
import hashlib
import json
import re
import subprocess
from collections import Counter
from pathlib import Path, PurePosixPath


GENERATION = "202608290904"
CONTRACT_PATHS = {
    "bootstrap": "contracts/202608290904-data-gridatlas-bootstrap.json",
    "consumer": "contracts/202608290904-gridatlas-consumer.json",
    "layers": "contracts/202608290904-v8-dependency-ledger.json",
    "files": "contracts/202608290904-v8-file-ledger.json",
    "quarantine": "contracts/202608290904-v8-quarantine.json",
}
HEX40 = re.compile(r"^[0-9a-f]{40}$")
HEX64 = re.compile(r"^[0-9a-f]{64}$")


def reject_duplicate_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key}")
        result[key] = value
    return result


def load(path: Path):
    return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicate_keys)


def digest(path: Path):
    value = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            value.update(chunk)
    return value.hexdigest()


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def safe_relative(value):
    path = PurePosixPath(value)
    return not path.is_absolute() and ".." not in path.parts and value not in {"", "."}


def inventory(repository: Path):
    contracts = {name: load(repository / path) for name, path in CONTRACT_PATHS.items()}
    bootstrap = contracts["bootstrap"]
    files = contracts["files"]
    layers = contracts["layers"]
    quarantine = contracts["quarantine"]
    consumer = contracts["consumer"]

    require(bootstrap["schema"] == "data-gridatlas.bootstrap-contract.v1", "bootstrap schema mismatch")
    require(bootstrap["generation"] == GENERATION, "bootstrap generation mismatch")
    require(bootstrap["classification"] == "INVENTORY_ONLY", "bootstrap is not inventory-only")
    require(bootstrap["v8_oracle"]["v8_untouched"] is True, "V8 immutability gate missing")
    require(bootstrap["promotion"] == {
        "release_allowed": False,
        "current_pointer_allowed": False,
        "pages_publication_allowed": False,
        "raw_dumps_allowed": False,
        "next_gate": "verified bootstrap artifact and exact consumer contract",
    }, "bootstrap promotion boundary mismatch")

    file_rows = files["rows"]
    require(files["schema"] == "data-gridatlas.v8-file-ledger.v1", "file ledger schema mismatch")
    require(len(file_rows) == 104, f"expected 104 V8 files, found {len(file_rows)}")
    require(sum(row["bytes"] for row in file_rows) == 39541206, "V8 subtree byte closure mismatch")
    require(len({row["path"] for row in file_rows}) == len(file_rows), "duplicate V8 file path")
    require(all(safe_relative(row["path"]) for row in file_rows), "unsafe V8 file path")
    require(all(HEX40.fullmatch(row["git_blob_sha1"]) for row in file_rows), "invalid V8 blob OID")
    class_summary = {
        key: {
            "files": sum(row["class"] == key for row in file_rows),
            "bytes": sum(row["bytes"] for row in file_rows if row["class"] == key),
        }
        for key in (".github", "data", "root", "scripts")
    }
    require(class_summary == bootstrap["v8_oracle"]["class_summary"], f"class closure mismatch: {class_summary}")
    for row in file_rows:
        expected_class = row["path"].split("/", 1)[0] if "/" in row["path"] else "root"
        require(row["class"] == expected_class, f"bad class for {row['path']}")

    layer_rows = layers["rows"]
    require(layers["schema"] == "data-gridatlas.v8-dependency-ledger.v1", "layer ledger schema mismatch")
    require(len(layer_rows) == 60, f"expected 60 layer entries, found {len(layer_rows)}")
    require(len({row["layer_id"] for row in layer_rows}) == 60, "duplicate layer id")
    require(len({row["group"] for row in layer_rows}) == 11, "group closure mismatch")
    require(len({row["configured_url"] for row in layer_rows}) == 40, "URL closure mismatch")
    require(sum(row["preload"] for row in layer_rows) == 12, "preload layer closure mismatch")
    require(len({row["resolved_path"] for row in layer_rows if row["preload"]}) == 11, "preload source closure mismatch")
    require(all(safe_relative(row["resolved_path"]) for row in layer_rows), "unsafe resolved path")
    require(all(HEX40.fullmatch(row["git_blob_sha1"]) for row in layer_rows), "invalid layer blob OID")
    require(all(HEX64.fullmatch(row["sha256"]) for row in layer_rows), "invalid layer SHA-256")
    require(all(row["publishable"] is False for row in layer_rows), "bootstrap layer marked publishable")
    require(all(row["source_authority_state"] == "UNVERIFIED" for row in layer_rows), "unverified authority state lost")
    require(all(row["licence_state"] == "UNVERIFIED" for row in layer_rows), "unverified licence state lost")

    by_url = {}
    for row in layer_rows:
        identity = tuple(row[key] for key in ("resolved_path", "git_blob_sha1", "bytes", "sha256"))
        if row["configured_url"] in by_url:
            require(by_url[row["configured_url"]] == identity, f"inconsistent source identity for {row['configured_url']}")
        by_url[row["configured_url"]] = identity

    local_paths = {f"repd_grid_atlasv8/{row['path']}": row for row in file_rows}
    wired_local = {row["resolved_path"] for row in layer_rows if row["configured_url"].startswith("data/")}
    require(len(wired_local) == 33, "wired local source closure mismatch")
    for row in layer_rows:
        if row["resolved_path"].startswith("repd_grid_atlasv8/"):
            source = local_paths.get(row["resolved_path"])
            require(source is not None, f"configured local path missing from file ledger: {row['resolved_path']}")
            require(source["git_blob_sha1"] == row["git_blob_sha1"], f"blob mismatch: {row['resolved_path']}")
            require(source["bytes"] == row["bytes"], f"byte mismatch: {row['resolved_path']}")

    unwired = quarantine["unwired_atlas_data"]
    require(len(unwired) == 16 and len(set(unwired)) == 16, "unwired quarantine closure mismatch")
    for name in unwired:
        path = f"repd_grid_atlasv8/data/{name}"
        require(path in local_paths, f"unwired file missing from oracle ledger: {name}")
        require(path not in wired_local, f"unwired file is actually configured: {name}")
    root_urls = quarantine["root_absolute_dependencies"]
    require(len(root_urls) == 7 and set(root_urls) == {row["configured_url"] for row in layer_rows if row["configured_url"].startswith("/")}, "root dependency closure mismatch")
    metro = next(item for item in quarantine["known_defects"] if item["id"] == "metro_tram_geometry_mismatch")
    require(metro["disposition"] == "DO_NOT_SILENTLY_SWAP", "metro/tram defect not quarantined")
    for layer_id in metro["layer_ids"]:
        row = next(row for row in layer_rows if row["layer_id"] == layer_id)
        require(row["disposition"] == "QUARANTINE_GEOMETRY_MISMATCH", f"{layer_id} is not quarantined")

    require(consumer["accepted_release"]["immutable"] is True, "consumer permits mutable releases")
    require(consumer["accepted_release"]["floating_raw_urls"] is False, "consumer permits floating raw URLs")
    require(consumer["truth"]["proximity_establishes_identity"] is False, "consumer truth contract drift")

    return contracts


def verify_repository(repository: Path, bootstrap):
    command = ["git", "-C", str(repository), "ls-files", "--cached", "--others", "--exclude-standard", "-z"]
    files = sorted(filter(None, subprocess.check_output(command).decode().split("\0")))
    expected = sorted(bootstrap["source_boundary"]["expected_tracked_files"])
    require(files == expected, f"source allowlist mismatch: expected={expected}, observed={files}")
    total = 0
    forbidden_suffixes = tuple(bootstrap["source_boundary"]["forbidden_suffixes"])
    forbidden_roots = set(bootstrap["source_boundary"]["forbidden_roots"])
    for value in files:
        path = repository / value
        require(path.is_file() and not path.is_symlink(), f"non-regular source file: {value}")
        size = path.stat().st_size
        total += size
        require(size <= bootstrap["source_boundary"]["maximum_file_bytes"], f"oversize source file: {value}")
        require(not value.lower().endswith(forbidden_suffixes), f"raw/generated suffix in source: {value}")
        require(PurePosixPath(value).parts[0] not in forbidden_roots, f"forbidden source root: {value}")
    require(total <= bootstrap["source_boundary"]["maximum_repository_bytes"], f"source repository too large: {total}")

    workflow_path = repository / ".github/workflows/202608290904-bootstrap-verify-data-gridatlas.yml"
    workflow = workflow_path.read_text(encoding="utf-8")
    require("contents: read" in workflow, "workflow is not read-only")
    for forbidden in ("contents: write", "pages: write", "id-token: write", "pull_request_target", "git push"):
        require(forbidden not in workflow, f"forbidden workflow capability: {forbidden}")
    for line in workflow.splitlines():
        if line.strip().startswith("uses:"):
            action = line.split("@", 1)
            require(len(action) == 2 and HEX40.fullmatch(action[1].strip()), f"unpinned Action: {line.strip()}")
    require((repository / "requirements.lock").read_text(encoding="utf-8") == "duckdb==1.3.2\n", "dependency lock drift")
    return {"tracked_files": len(files), "tracked_bytes": total}


def parse_oracle_tree(path: Path):
    rows = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        head, value = line.split("\t", 1)
        mode, kind, oid = head.split()
        if kind == "blob":
            rows[value] = {"mode": mode, "oid": oid}
    return rows


def verify_oracle(tree_path: Path, contracts):
    remote = parse_oracle_tree(tree_path)
    file_rows = contracts["files"]["rows"]
    expected_subtree = {f"repd_grid_atlasv8/{row['path']}": row["git_blob_sha1"] for row in file_rows}
    observed_subtree = {path: item["oid"] for path, item in remote.items() if path.startswith("repd_grid_atlasv8/")}
    require(observed_subtree == expected_subtree, "pinned V8 subtree path/blob closure mismatch")
    for row in contracts["layers"]["rows"]:
        item = remote.get(row["resolved_path"])
        require(item is not None, f"resolved dependency absent from pinned oracle: {row['resolved_path']}")
        require(item["oid"] == row["git_blob_sha1"], f"resolved dependency OID drift: {row['resolved_path']}")
    return {"verified_subtree_blobs": len(observed_subtree), "verified_layer_paths": len({row['resolved_path'] for row in contracts['layers']['rows']})}


def verify_catalog(repository: Path, catalog: Path, contracts):
    import duckdb

    expected_names = {"files.parquet", "layers.parquet", "quarantine.parquet", "manifest.json"}
    observed_names = {path.name for path in catalog.iterdir() if path.is_file()}
    require(observed_names == expected_names, f"catalog allowlist mismatch: {observed_names}")
    manifest = load(catalog / "manifest.json")
    require(manifest["schema"] == "data-gridatlas.bootstrap-manifest.v1", "manifest schema mismatch")
    require(manifest["generation"] == GENERATION, "manifest generation mismatch")
    require(manifest["classification"] == "BOOTSTRAP_CANDIDATE", "candidate classification mismatch")
    require(manifest["release"] is False and manifest["current_pointer"] is False, "bootstrap attempts promotion")
    require(manifest["raw_payloads_copied"] == 0 and manifest["v8_untouched"] is True, "bootstrap data boundary drift")
    require(manifest["runtime"]["duckdb"] == "1.3.2", "DuckDB runtime drift")

    manifest_contracts = {item["path"]: item for item in manifest["contracts"]}
    for relative in CONTRACT_PATHS.values():
        path = repository / relative
        item = manifest_contracts.get(relative)
        require(item is not None, f"contract absent from manifest: {relative}")
        require(item["bytes"] == path.stat().st_size and item["sha256"] == digest(path), f"contract identity mismatch: {relative}")

    artifacts = {item["path"]: item for item in manifest["artifacts"]}
    require(set(artifacts) == expected_names - {"manifest.json"}, "manifest artifact allowlist mismatch")
    expected_rows = {"files.parquet": 104, "layers.parquet": 60, "quarantine.parquet": 34}
    connection = duckdb.connect()
    connection.execute("PRAGMA threads=1")
    for name, rows in expected_rows.items():
        path = catalog / name
        item = artifacts[name]
        require(item["bytes"] == path.stat().st_size and item["sha256"] == digest(path), f"artifact identity mismatch: {name}")
        escaped = str(path).replace("'", "''")
        count = connection.execute(f"SELECT count(*) FROM read_parquet('{escaped}')").fetchone()[0]
        require(count == rows == item["rows"], f"typed row closure mismatch: {name}")
        compressions = {row[0] for row in connection.execute(f"SELECT DISTINCT compression FROM parquet_metadata('{escaped}')").fetchall()}
        require(compressions == {"ZSTD"}, f"Parquet compression mismatch for {name}: {compressions}")

    files_path = str(catalog / "files.parquet").replace("'", "''")
    layers_path = str(catalog / "layers.parquet").replace("'", "''")
    quarantine_path = str(catalog / "quarantine.parquet").replace("'", "''")
    file_closure = connection.execute(
        f"SELECT count(*), count(DISTINCT path), sum(bytes) FROM read_parquet('{files_path}')"
    ).fetchone()
    require(tuple(file_closure) == (104, 104, 39541206), f"file Parquet closure mismatch: {file_closure}")
    layer_closure = connection.execute(
        f"SELECT count(*), count(DISTINCT layer_id), count(DISTINCT configured_url), "
        f"count(DISTINCT group_name), count(*) FILTER (WHERE preload), "
        f"count(*) FILTER (WHERE publishable OR source_authority_state <> 'UNVERIFIED' OR licence_state <> 'UNVERIFIED') "
        f"FROM read_parquet('{layers_path}')"
    ).fetchone()
    require(tuple(layer_closure) == (60, 60, 40, 11, 12, 0), f"layer Parquet closure mismatch: {layer_closure}")
    q_closure = connection.execute(
        f"SELECT count(*), count(*) FILTER (WHERE kind='unwired_atlas_data'), "
        f"count(*) FILTER (WHERE kind='root_absolute_dependency') FROM read_parquet('{quarantine_path}')"
    ).fetchone()
    require(tuple(q_closure) == (34, 16, 7), f"quarantine Parquet closure mismatch: {q_closure}")
    connection.close()

    total = sum(path.stat().st_size for path in catalog.iterdir() if path.is_file())
    require(total < 2_000_000, f"bootstrap artifact exceeds 2 MB: {total}")
    return {"artifact_files": 4, "artifact_bytes": total, "typed_rows": sum(expected_rows.values())}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--repository", default=".")
    parser.add_argument("--oracle-tree")
    parser.add_argument("--catalog")
    parser.add_argument("--output", required=True)
    args = parser.parse_args()

    repository = Path(args.repository).resolve()
    contracts = inventory(repository)
    checks = {"inventory": {
        "v8_files": len(contracts["files"]["rows"]),
        "layers": len(contracts["layers"]["rows"]),
        "configured_urls": len({row["configured_url"] for row in contracts["layers"]["rows"]}),
        "quarantined_unwired_files": len(contracts["quarantine"]["unwired_atlas_data"]),
    }}
    checks["repository"] = verify_repository(repository, contracts["bootstrap"])
    classification = "VERIFIED_SOURCE_BOUNDARY"
    if args.oracle_tree:
        checks["oracle"] = verify_oracle(Path(args.oracle_tree), contracts)
        classification = "VERIFIED_ORACLE"
    if args.catalog:
        checks["catalog"] = verify_catalog(repository, Path(args.catalog).resolve(), contracts)
        classification = "VERIFIED_BOOTSTRAP_CANDIDATE"

    proof = {
        "schema": "data-gridatlas.bootstrap-verification.v1",
        "generation": GENERATION,
        "classification": classification,
        "checks": checks,
        "failed": 0,
        "v8_untouched": True,
    }
    output = Path(args.output)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(proof, sort_keys=True, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(proof, sort_keys=True))


if __name__ == "__main__":
    main()

Verify V8 Transplant

A Python command-line tool in the atman folder of Data GridAtlas that reads transplant plan, runtime dependencies, repository boundary and dependency ledger, using SHA-256.

storagedata-gridatlas / atman/202608291015-verify-v8-transplant.py · lines 1–396 of 1134 · version 2026-08-29 10:15 · Entry point · pattern validate_candidate (shared by 2 files)

What it does
It loads transplant plan, runtime dependencies, repository boundary and dependency ledger. Defines 30 functions or classes, including canonical, reject_duplicate_keys, load, digest, digest_bytes. Uses libraries argparse, copy, hashlib, json, math. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (repository name word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: 11kV.
Inputs & outputs
In: JSON file 202608291015-v8-transplant-plan.json; JSON file 202608291015-v8-layer-config.json; JSON file 202608291015-v8-runtime-dependencies.json; JSON file 202608291015-repository-boundary.json; JSON file 202608291015-v8-transplant-parquet.json; JSON file 202608290904-v8-dependency-ledger.json; JSON file 202608290904-v8-file-ledger.json; JSON file 202608290904-v8-quarantine.json. Coordinate systems named: WGS84 / EPSG:4326. Voltage levels named: 11kV.
Downstream impact
Used directly by 2 files: Build V8 Transplant (data-gridatlas); Build V8 Transplant Candidate Workflow (data-gridatlas).
What it achieves
It reads oracle source (`read_oracle_source`), collects coordinates (`collect_coordinates`) and snaps feature independently (`snap_feature_independently`). Independent verifier for the full V8 parity transplant candidate. Its code works with 11 kV. It accepts `--repository`, `--phase-output` and `--source-root`.
Why it matters
Run by Build V8 Transplant and Build V8 Transplant Candidate Workflow.
Application
data-gridatlas · atman · Python CLI
Uses
Build V8 Transplant (script call), argparse, copy, hashlib, json, math, os, platform, re
Used by
run by Build V8 Transplant (script call), run by Build V8 Transplant Candidate Workflow (workflow run)
Produces
canonical, reject_duplicate_keys, load, digest, digest_bytes, git_blob_oid, expected_compute_identity, require, safe_relative, sql_string, loads_strict, read_oracle_source
Defines here
canonical, reject_duplicate_keys, load, digest, digest_bytes, git_blob_oid, expected_compute_identity, require, safe_relative, sql_string, loads_strict, read_oracle_source, collect_coordinates, evaluate_filter, snap_feature_independently, snap, verify_rows_against_features, validate_contracts, validate_repository
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gridatlas@203f9dc3764c05153c2b95f8ace88eb543f26c1e atman/202608291015-verify-v8-transplant.py:1-396 · blob be2a0b88524914d84b0e90f56ed3efe35667b586 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Independent verifier for the full V8 parity transplant candidate."""

import argparse
import copy
import hashlib
import json
import math
import os
import platform
import re
import subprocess
from collections import Counter
from pathlib import Path, PurePosixPath

import duckdb


GENERATION = "202608291015"
PLAN = "contracts/202608291015-v8-transplant-plan.json"
LAYERS = "contracts/202608291015-v8-layer-config.json"
RUNTIME = "contracts/202608291015-v8-runtime-dependencies.json"
BOUNDARY = "contracts/202608291015-repository-boundary.json"
SCHEMA = "schemas/202608291015-v8-transplant-parquet.json"
LEDGER = "contracts/202608290904-v8-dependency-ledger.json"
COMPUTE_INPUTS = [
    PLAN, LAYERS, RUNTIME, BOUNDARY, SCHEMA, LEDGER,
    "contracts/202608290904-v8-file-ledger.json",
    "contracts/202608290904-v8-quarantine.json",
    "compiler/202608291015-build-v8-transplant.py",
    "atman/202608291015-verify-v8-transplant.py",
    ".github/workflows/202608291015-build-v8-transplant-candidate.yml",
    "requirements.lock",
]
HEX40 = re.compile(r"^[0-9a-f]{40}$")
HEX64 = re.compile(r"^[0-9a-f]{64}$")
SNAP_EXPECTED = {
    "grid_400kv": (4528, 2679), "grid_275kv": (3806, 2212),
    "grid_220kv": (150, 93), "grid_132kv": (7218, 4342), "grid_66kv": (1353, 828),
}
EXPECTED_CLOSURE = {
    "sources": 56, "wired_sources": 40, "unwired_sources": 16, "layers": 60,
    "features": 541282, "wired_features": 530263, "unwired_features": 11019,
    "input_bytes": 262709675,
    "geometry_counts": {"LineString": 437288, "MultiLineString": 23, "Point": 103971},
    "coordinate_tuples": 3812791, "raw_property_pairs": 5088905,
    "retained_property_pairs": 1064163, "dropped_property_pairs": 4024742,
    "layer_membership_rows": 526388,
}
FEATURE_COLUMNS = [
    ("source_id", "VARCHAR"), ("feature_index", "INTEGER"), ("feature_id", "VARCHAR"),
    ("geometry_type", "VARCHAR"), ("geometry_json", "VARCHAR"), ("properties_json", "VARCHAR"),
    ("original_feature_sha256", "VARCHAR"), ("projected_feature_sha256", "VARCHAR"),
    ("min_x", "DOUBLE"), ("min_y", "DOUBLE"), ("max_x", "DOUBLE"), ("max_y", "DOUBLE"),
]
MEMBERSHIP_COLUMNS = [("layer_id", "VARCHAR"), ("source_id", "VARCHAR"), ("feature_index", "INTEGER")]
EXPECTED_RETAINED_KEYS = [
    "name", "SiteName", "Site Name", "type", "street", "city", "postcode", "area_m2", "area_ha",
    "colour", "brand", "operator", "club", "capacity", "sport", "emission_tco2e", "datatype",
    "sector", "country", "tech", "raw_tech", "voltage", "power_kw", "connectors", "status",
    "mounting", "source",
]
EXPECTED_FORBIDDEN_KEYS = ["phone", "operator:phone", "payment:phone", "owner", "owner:wikidata", "ownership"]


def canonical(value):
    return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)


def reject_duplicate_keys(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"duplicate JSON key: {key}")
        result[key] = value
    return result


def load(path):
    return json.loads(
        Path(path).read_text(encoding="utf-8"),
        object_pairs_hook=reject_duplicate_keys,
        parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)),
    )


def digest(path):
    value = hashlib.sha256()
    with Path(path).open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            value.update(chunk)
    return value.hexdigest()


def digest_bytes(payload):
    return hashlib.sha256(payload).hexdigest()


def git_blob_oid(payload):
    return hashlib.sha1(f"blob {len(payload)}\0".encode() + payload).hexdigest()


def expected_compute_identity(repository):
    inputs = [
        {"path": path, "bytes": (repository / path).stat().st_size, "sha256": digest(repository / path)}
        for path in COMPUTE_INPUTS
    ]
    identity = {
        "repository": "Ventusltd/data-gridatlas",
        "v8_repository": "Ventusltd/globalgrid2050",
        "v8_commit": "f2f343a92ee972cc74ed23b4b99d8a22896791ad",
        "runtime": {
            "python": platform.python_version(), "duckdb": duckdb.__version__, "threads": 1,
            "runner_image_os": os.environ.get("ImageOS"), "runner_image_version": os.environ.get("ImageVersion"),
        },
        "inputs": inputs,
    }
    identity["key_sha256"] = digest_bytes(canonical(identity).encode())
    return identity


def require(condition, message):
    if not condition:
        raise RuntimeError(message)


def safe_relative(value):
    path = PurePosixPath(value)
    return value not in {"", "."} and not path.is_absolute() and ".." not in path.parts


def sql_string(value):
    return str(value).replace("'", "''")


def loads_strict(value):
    return json.loads(
        value,
        object_pairs_hook=reject_duplicate_keys,
        parse_constant=lambda item: (_ for _ in ()).throw(ValueError(item)),
    )


def read_oracle_source(source, source_root):
    path = source_root / source["resolved_path"]
    require(path.is_file() and not path.is_symlink(), f"pinned source not materialised: {source['source_id']}")
    payload = path.read_bytes()
    require(len(payload) == source["bytes"], f"source byte drift: {source['source_id']}")
    require(digest_bytes(payload) == source["sha256"], f"source SHA-256 drift: {source['source_id']}")
    require(git_blob_oid(payload) == source["git_blob_sha1"], f"source Git blob drift: {source['source_id']}")
    obj = loads_strict(payload)
    require(obj.get("type") == "FeatureCollection" and isinstance(obj.get("features"), list), f"not FeatureCollection: {source['source_id']}")
    return obj


def collect_coordinates(node, output):
    if isinstance(node, list) and len(node) >= 2 and all(
        isinstance(value, (int, float)) and not isinstance(value, bool) for value in node[:2]
    ):
        require(len(node) == 2, "non-2D coordinate")
        x, y = float(node[0]), float(node[1])
        require(math.isfinite(x) and math.isfinite(y), "non-finite coordinate")
        require(-180 <= x <= 180 and -90 <= y <= 90, f"coordinate outside WGS84 range: {(x, y)}")
        output.append((x, y))
    elif isinstance(node, list):
        for child in node:
            collect_coordinates(child, output)


def evaluate_filter(expression, properties):
    if not isinstance(expression, list):
        return expression
    operation = expression[0]
    if operation == "get":
        return properties.get(expression[1])
    if operation == "==":
        return evaluate_filter(expression[1], properties) == evaluate_filter(expression[2], properties)
    if operation == "!=":
        return evaluate_filter(expression[1], properties) != evaluate_filter(expression[2], properties)
    if operation == "all":
        return all(bool(evaluate_filter(item, properties)) for item in expression[1:])
    if operation == "any":
        return any(bool(evaluate_filter(item, properties)) for item in expression[1:])
    if operation == "!":
        return not bool(evaluate_filter(expression[1], properties))
    if operation == "in":
        needle = evaluate_filter(expression[1], properties)
        haystack = evaluate_filter(expression[2], properties)
        try:
            return needle in haystack
        except TypeError:
            return False
    raise RuntimeError(f"unsupported filter operation: {operation}")


def snap_feature_independently(feature, substations):
    tolerance = 0.001 * 0.001
    radians = math.pi / 180

    def snap(coordinate):
        best = coordinate
        minimum = math.inf
        latitude_cosine = math.cos(coordinate[1] * radians)
        for candidate in substations:
            dx = (coordinate[0] - candidate[0]) * latitude_cosine
            dy = coordinate[1] - candidate[1]
            distance = dx * dx + dy * dy
            if distance < minimum and distance <= tolerance:
                minimum = distance
                best = candidate
        return list(best)

    transformed = copy.deepcopy(feature)
    geometry = transformed.get("geometry") or {}
    coordinates = geometry.get("coordinates")
    if geometry.get("type") == "LineString" and coordinates:
        coordinates[0] = snap(coordinates[0])
        coordinates[-1] = snap(coordinates[-1])
    elif geometry.get("type") == "MultiLineString":
        for line in coordinates or []:
            if line:
                line[0] = snap(line[0])
                line[-1] = snap(line[-1])
    return transformed


def verify_rows_against_features(connection, path, source, features, retained_keys, original_features=None):
    require(len(features) == source["expected_features"], f"raw feature closure mismatch: {source['source_id']}")
    escaped = sql_string(path)
    rows = connection.execute(
        f"SELECT source_id, feature_index, feature_id, geometry_type, geometry_json, properties_json, "
        f"original_feature_sha256, projected_feature_sha256, min_x, min_y, max_x, max_y "
        f"FROM read_parquet('{escaped}') ORDER BY feature_index"
    ).fetchall()
    require(len(rows) == len(features), f"projected row closure mismatch: {source['source_id']}")
    geometry_counts = Counter()
    property_keys = set()
    coordinate_count = raw_pairs = retained_pairs = 0
    all_coordinates = []
    for index, (row, feature) in enumerate(zip(rows, features, strict=True)):
        require(feature.get("type") == "Feature", f"non-Feature: {source['source_id']}:{index}")
        geometry = feature.get("geometry")
        require(isinstance(geometry, dict) and geometry.get("type") in {"Point", "LineString", "MultiLineString"}, f"bad geometry: {source['source_id']}:{index}")
        coordinates = []
        collect_coordinates(geometry.get("coordinates"), coordinates)
        require(coordinates, f"empty geometry: {source['source_id']}:{index}")
        properties = feature.get("properties") or {}
        require(isinstance(properties, dict), f"bad properties: {source['source_id']}:{index}")
        projected_properties = {key: properties[key] for key in retained_keys if key in properties}
        projected = {"type": "Feature", "geometry": geometry, "properties": projected_properties}
        if feature.get("id") is not None:
            projected["id"] = feature["id"]
        original = feature if original_features is None else original_features[index]
        xs = [item[0] for item in coordinates]
        ys = [item[1] for item in coordinates]
        expected = (
            source["source_id"], index, None if feature.get("id") is None else str(feature["id"]),
            geometry["type"], canonical(geometry), canonical(projected_properties),
            digest_bytes(canonical(original).encode()), digest_bytes(canonical(projected).encode()),
            min(xs), min(ys), max(xs), max(ys),
        )
        require(tuple(row) == expected, f"projected feature mismatch: {source['source_id']}:{index}")
        geometry_counts[geometry["type"]] += 1
        property_keys.update(properties)
        coordinate_count += len(coordinates)
        raw_pairs += len((original.get("properties") or {}))
        retained_pairs += len(projected_properties)
        all_coordinates.extend(coordinates)
    bbox = None
    if all_coordinates:
        bbox = [
            min(item[0] for item in all_coordinates), min(item[1] for item in all_coordinates),
            max(item[0] for item in all_coordinates), max(item[1] for item in all_coordinates),
        ]
    return {
        "geometry_counts": dict(sorted(geometry_counts.items())),
        "coordinate_tuples": coordinate_count,
        "bbox": bbox,
        "property_key_count": len(property_keys),
        "property_schema_sha256": digest_bytes(canonical(sorted(property_keys)).encode()),
        "raw_property_pairs": raw_pairs,
        "retained_property_pairs": retained_pairs,
        "dropped_property_pairs": raw_pairs - retained_pairs,
    }


def validate_contracts(repository):
    plan = load(repository / PLAN)
    layers = load(repository / LAYERS)
    runtime = load(repository / RUNTIME)
    boundary = load(repository / BOUNDARY)
    schema = load(repository / SCHEMA)
    ledger = load(repository / LEDGER)
    require(plan["schema"] == "data-gridatlas.v8-transplant-plan.v1" and plan["generation"] == GENERATION, "plan identity mismatch")
    require(plan["classification"] == "FULL_V8_PARITY_CANDIDATE_ONLY", "plan classification mismatch")
    require(plan["compute"]["python"] == "3.12.13" and plan["compute"]["runner_image"] == "ubuntu-24.04", "compute runtime contract drift")
    for key, value in EXPECTED_CLOSURE.items():
        require(plan["closure"][key] == value, f"plan closure drift: {key}")
    require(len(plan["sources"]) == 56 and len({row["source_id"] for row in plan["sources"]}) == 56, "source ID closure mismatch")
    require(len({row["resolved_path"] for row in plan["sources"]}) == 56, "source path closure mismatch")
    require(sum(row["publishable"] for row in plan["sources"]) == 0, "candidate source marked publishable")
    require(all(HEX40.fullmatch(row["git_blob_sha1"]) and HEX64.fullmatch(row["sha256"]) for row in plan["sources"]), "invalid source identity")
    require(all(safe_relative(row["resolved_path"]) and safe_relative(row["output_partition"]) for row in plan["sources"]), "unsafe source/partition path")
    require(sum(row["wiring"] == "wired" for row in plan["sources"]) == 40, "wired source count mismatch")
    require(sum(row["phase"] == "quarantine" for row in plan["sources"]) == 19, "quarantine source count mismatch")
    by_id = {row["source_id"]: row for row in plan["sources"]}
    require(by_id["grid_11kv_ukpn"]["disposition"] == "QUARANTINED_SYNTHETIC_UKPN_11KV_IDENTITY", "11kV identity not quarantined")
    require(by_id["industrial_offtakers"]["disposition"] == "QUARANTINED_OUTPUT_NOT_REPRODUCIBLE_FROM_ADJACENT_FETCHER", "industry mismatch not quarantined")
    require(by_id["uk_metros_trams_root"]["disposition"] == "QUARANTINED_GEOMETRY_MISMATCH", "metro geometry not quarantined")
    require(by_id["repd_master_v8_oracle"]["disposition"] == "ORACLE_ONLY_REPLACED_BY_OFFICIAL_REPD_V9", "old REPD not oracle-only")
    require(set(plan["property_policy"]["retained_keys"]).isdisjoint(plan["property_policy"]["forbidden_keys"]), "privacy allowlist overlap")
    require(plan["property_policy"]["retained_keys"] == EXPECTED_RETAINED_KEYS, "retained property allowlist drift")
    require(plan["property_policy"]["forbidden_keys"] == EXPECTED_FORBIDDEN_KEYS, "forbidden property policy drift")

    require(layers["schema"] == "data-gridatlas.declarative-layer-config.v1", "layer config schema mismatch")
    flat_layers = [layer for group in layers["groups"] for layer in group["layers"]]
    require(len(layers["groups"]) == 11 and len(flat_layers) == 60, "declarative layer closure mismatch")
    require(len({layer["id"] for layer in flat_layers}) == 60 and len({layer["url"] for layer in flat_layers}) == 40, "layer ID/URL closure mismatch")
    require(sum(bool(layer.get("preload")) for layer in flat_layers) == 12, "preload closure mismatch")
    require(all(layer["v9_data"]["source_id"] in by_id for layer in flat_layers), "layer source mapping gap")
    require(all(layer.get("color") and layer.get("type") in {"point", "line"} for layer in flat_layers), "style contract incomplete")
    require(layers["closure"]["layer_membership_rows"] == 526388, "membership contract drift")
    require(sum(row["selected_features"] for row in ledger["rows"]) == 526388, "legacy membership baseline drift")

    require(runtime["schema"] == "data-gridatlas.v8-runtime-dependencies.v1" and len(runtime["dependencies"]) == 7, "runtime dependency closure mismatch")
    require(runtime["data_repository_payload"] is False and runtime["rules"]["copy_tiles_or_external_payloads"] is False, "runtime copied into data plane")
    require(schema["partition"]["compression"] == "ZSTD" and schema["forbidden_outputs"], "Parquet schema contract mismatch")
    require(
        schema["derived"]["parent_column"] == "original_feature_sha256"
        and schema["derived"]["derived_column"] == "projected_feature_sha256",
        "derived lineage schema mismatch",
    )
    return {"plan": plan, "layers": layers, "runtime": runtime, "boundary": boundary, "schema": schema, "ledger": ledger}


def validate_repository(repository, contracts):
    command = ["git", "-C", str(repository), "ls-files", "--cached", "--others", "--exclude-standard", "-z"]
    observed = sorted(filter(None, subprocess.check_output(command).decode().split("\0")))
    boundary = contracts["boundary"]
    required = set(boundary["expected_tracked_files"])
    successors = set(boundary["allowed_successor_files"])
    release_roots = set(boundary["allowed_live_release_roots"])
    pointers = set(boundary["allowed_pointer_files"])
    observed_set = set(observed)
    require(required <= observed_set, f"required repository source missing: {sorted(required - observed_set)}")
    source_files = {
        relative for relative in observed
        if PurePosixPath(relative).parts[0] not in release_roots and relative not in pointers
    }
    require(source_files <= required | successors, f"repository source allowlist mismatch: {sorted(source_files - required - successors)}")
    total = 0
    forbidden_suffixes = tuple(boundary["forbidden_suffixes"])
    forbidden_roots = set(boundary["forbidden_roots"])
    for relative in sorted(source_files):
        path = repository / relative
        require(path.is_file() and not path.is_symlink(), f"non-regular source: {relative}")
        size = path.stat().st_size
        total += size
        require(size <= boundary["maximum_file_bytes"], f"oversize source: {relative}")
        require(not relative.lower().endswith(forbidden_suffixes), f"generated/raw source: {relative}")
        require(PurePosixPath(relative).parts[0] not in forbidden_roots, f"forbidden source root: {relative}")
    require(total <= boundary["maximum_repository_bytes"], f"repository source too large: {total}")

    release_files = [
        relative for relative in observed
        if PurePosixPath(relative).parts[0] in release_roots
    ]
    release_bytes = 0
    if release_files:
        require(len(release_roots) == 1, "ambiguous live release root")
        release_root = next(iter(release_roots))
        ledger_path = repository / release_root / "sha256sums.txt"
        require(ledger_path.is_file(), "live release SHA ledger missing")
        ledger = {}
        for line in ledger_path.read_text(encoding="utf-8").splitlines():
            digest, relative = line.split(maxsplit=1)
            relative = relative.lstrip("*")
            require(HEX64.fullmatch(digest) and relative not in ledger, "invalid live release SHA ledger")
            ledger[relative] = digest
        expected_release = {f"{release_root}/{relative}" for relative in ledger} | {f"{release_root}/sha256sums.txt"}
        require(set(release_files) == expected_release, "live release file allowlist mismatch")
        for relative in release_files:
            path = repository / relative
            require(path.is_file() and not path.is_symlink(), f"non-regular live release file: {relative}")
            size = path.stat().st_size
            release_bytes += size
            require(size <= boundary["maximum_live_release_file_bytes"], f"oversize live release file: {relative}")
            if path.name != "sha256sums.txt":
                logical = PurePosixPath(relative).relative_to(release_root).as_posix()
                require(hashlib.sha256(path.read_bytes()).hexdigest() == ledger[logical], f"live release SHA mismatch: {relative}")
        require(release_bytes <= boundary["maximum_live_release_bytes"], "live release repository budget exceeded")

    for relative in sorted(observed_set & pointers):
        pointer = load_json(repository / relative)
        require(pointer.get("generation") == "202608291237", f"pointer generation mismatch: {relative}")
        require(pointer.get("release_path") == "202608291237-data-gridatlas/", f"pointer release mismatch: {relative}")