In this section
- Validate North Star test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_north_star.py lines 1–48
- Validate Projects Plugin V7 2 test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_projects_plugin_v7_2.py lines 1–296
- Validate V7 2 Spine test · globalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_v7_2_spine.py lines 1–143
- Canonical Projects V9 1 render · globalgrid2050 / uk_renewables_pipeline/202609061149/scripts/data/canonical-projects-v9-1.js lines 1–102
Validate North Star
A Python command-line tool in the tests folder of GlobalGrid2050 that uses SHA-256.
testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_north_star.py · lines 1–48 of 48 · version 2026-09-05 11:56 · Entry point · pattern parse_args (shared by 7 files)
- What it does
- It tests its inputs. Defines parse_args, main. Uses libraries __future__, argparse, hashlib, json, datetime. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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 north-star.v1.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Its name says it validates north star. Defines `parse_args`. It accepts `--phase` and `--report`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · uk_renewables_pipeline/202609051156/tests · Python CLI
- Uses
- North Star Checks (import), __future__, argparse, hashlib, json, datetime, pathlib
- Used by
- none found
- Produces
- parse_args, main
- Defines here
- parse_args, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/validate_north_star.py:1-48 · blob 4cf91f230b814ba9e4fd5737e08ddbfd33fa5597 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path
from north_star_checks import run_gate
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Validate the V7 North Star before or after one feature build.")
parser.add_argument("--phase", choices=("pre", "post"), required=True)
parser.add_argument("--report", type=Path, required=True)
return parser.parse_args()
def main() -> int:
args = parse_args()
root = Path(__file__).resolve().parents[3]
contract_path = root / "uk_renewables_pipeline/v7/contracts/north-star.v1.json"
contract_bytes = contract_path.read_bytes()
contract = json.loads(contract_bytes)
gate = run_gate(root, contract, args.phase)
report = {
"schema": "globalgrid2050.v7.north-star-report.v1",
"phase": args.phase,
"target_release": contract["target_release"],
"feature": contract["feature"],
"generated_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"contract_sha256": hashlib.sha256(contract_bytes).hexdigest(),
"result": "PASS" if gate.passed else "FAIL",
"metrics": gate.metrics,
"checks": gate.checks,
}
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
failures = [check for check in gate.checks if not check["passed"]]
print(f"North Star {args.phase}: {report['result']} ({len(gate.checks)} checks, {len(failures)} failures)")
for failure in failures:
print(f"FAIL: {failure['name']} actual={failure.get('actual')} expected={failure.get('expected')}")
return 0 if gate.passed else 1
if __name__ == "__main__":
raise SystemExit(main())Validate Projects Plugin V7 2
A Python command-line tool in the tests folder of GlobalGrid2050 that tests solar, battery storage (BESS), wind and the Renewable Energy Planning Database (REPD) register, using SHA-256.
testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_projects_plugin_v7_2.py · lines 1–296 of 296 · version 2026-09-05 11:56 · Entry point · pattern searchable (shared by 2 files)
- What it does
- It tests solar, battery storage (BESS), wind and the REPD register. Defines 10 functions or classes, including parse_args, load, sha256, is_finite_number, is_iso_date_or_none. Uses libraries __future__, argparse, hashlib, json, math. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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: solar, battery storage (BESS), wind, the REPD register.
- Inputs & outputs
- In: JSON file projects-plugin.v7.2.json; JSON file plugin_manifest.json; command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It searches records (`search_records`) and is built from the is finite number helper (`is_finite_number`) and the searchable step (`searchable`). Its name says it validates projects plugin. Defines `parse_args`, `load`, `sha256` and 6 more. It accepts `--phase`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · uk_renewables_pipeline/202609051156/tests · Python CLI
- Uses
- __future__, argparse, hashlib, json, math, re, datetime, pathlib
- Used by
- none found
- Produces
- parse_args, load, sha256, is_finite_number, is_iso_date_or_none, searchable, search_records, lifecycle_partition, main
- Defines here
- parse_args, load, sha256, is_finite_number, is_iso_date_or_none, searchable, search_records, lifecycle_partition, main, check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/validate_projects_plugin_v7_2.py:1-296 · blob f4c9877559266e319f67b6ded2c40e99600c6c14 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import hashlib
import json
import math
import re
from datetime import date
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[3]
V7 = ROOT / "uk_renewables_pipeline/v7"
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Validate the frozen V7.2 projects-plugin contract.")
parser.add_argument("--phase", choices=("spec", "integrated"), default="spec")
return parser.parse_args()
def load(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def is_finite_number(value: Any) -> bool:
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
def is_iso_date_or_none(value: Any) -> bool:
if value is None:
return True
if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
return False
try:
date.fromisoformat(value)
return True
except ValueError:
return False
def searchable(record: dict[str, Any], fields: list[str], query: str) -> bool:
needle = query.casefold()
values: list[str] = []
for field in fields:
value = record.get(field)
if isinstance(value, list):
values.extend(str(item) for item in value)
elif value is not None:
values.append(str(value))
return any(needle in value.casefold() for value in values)
def search_records(records: list[dict[str, Any]], fields: list[str], query: str) -> list[dict[str, Any]]:
needle = query.casefold()
direct = [
record for record in records
if str(record.get("repd_ref", "")).casefold() == needle
or str(record.get("gg_project_id", "")).casefold() == needle
]
return direct or [record for record in records if searchable(record, fields, query)]
def lifecycle_partition(record: dict[str, Any]) -> str:
lifecycle = record["lifecycle"]
status = record["status"]
if lifecycle in {"LIVE_PRE_CONSTRUCTION", "UNDER_CONSTRUCTION", "OPERATIONAL"}:
return "CURRENT"
if lifecycle == "INACTIVE":
return "HISTORICAL"
if lifecycle == "UNKNOWN" and status == "Appeal Lodged":
return "DISPUTED"
if lifecycle == "UNKNOWN" and status == "Revised":
return "REVIEW"
return "UNMAPPED"
def main() -> int:
args = parse_args()
contract_path = V7 / "contracts/projects-plugin.v7.2.json"
contract = load(contract_path)
spine_path = ROOT / contract["governance"]["project_spine_contract"]
spine = load(spine_path)
universe = contract["canonical_universe"]
projects_path = ROOT / universe["source_files"]["projects"]["path"]
geojson_path = ROOT / universe["source_files"]["geojson"]["path"]
manifest_path = ROOT / universe["source_files"]["manifest"]["path"]
payload = load(projects_path)
geojson = load(geojson_path)
_manifest = load(manifest_path)
projects = payload["projects"]
checks: list[tuple[str, bool, str]] = []
def check(name: str, condition: bool, detail: str = "") -> None:
checks.append((name, bool(condition), detail))
check("contract schema", contract.get("schema") == "globalgrid2050.v7.projects-plugin-contract.v1")
check("target release", contract.get("target_release") == "7.2")
check("specification status", contract.get("status") == "SPECIFICATION_ONLY_UI_NOT_LIVE")
check("project-spine hash", sha256(spine_path) == contract["governance"]["project_spine_contract_sha256"])
check("project-spine remains data only", spine.get("status") == "DATA_ONLY_NOT_LIVE")
for checkpoint_id in ("checkpoint_1", "checkpoint_2", "checkpoint_3"):
checkpoint = contract["implementation_checkpoints"][checkpoint_id]
checkpoint_label = checkpoint_id.replace("_", " ")
check(f"{checkpoint_label} isolated status", checkpoint.get("status") == "IMPLEMENTED_ISOLATED_NOT_LIVE")
for relative, expected_hash in checkpoint["files"].items():
path = ROOT / relative
check(f"{checkpoint_label} file exists: {relative}", path.is_file())
check(f"{checkpoint_label} file hash: {relative}", path.is_file() and sha256(path) == expected_hash)
check("checkpoint 4 pending", contract["implementation_checkpoints"]["checkpoint_4"].get("status") == "PENDING")
for key in ("projects", "geojson", "manifest"):
source = universe["source_files"][key]
path = ROOT / source["path"]
check(f"{key} source exists", path.is_file())
check(f"{key} source hash", sha256(path) == source["sha256"])
check("project count", len(projects) == universe["project_count"] == 766)
check("development count", len({row["gg_development_id"] for row in projects}) == universe["development_count"] == 718)
solar = [row for row in projects if row["technology"] == "solar"]
bess = [row for row in projects if row["technology"] == "bess"]
check("solar count", len(solar) == universe["solar_count"] == 384)
check("BESS count", len(bess) == universe["bess_count"] == 382)
check("no wind", len(projects) == len(solar) + len(bess) and universe["wind_count"] == 0)
check("exclusive solar threshold", all(row["capacity_mw"] > 49 for row in solar))
check("exclusive BESS threshold", all(row["capacity_mw"] > 99 for row in bess))
check("solar MWp", math.isclose(sum(row["capacity_mw"] for row in solar), universe["solar_mwp"], abs_tol=1e-8))
check("BESS MW", math.isclose(sum(row["capacity_mw"] for row in bess), universe["bess_mw"], abs_tol=1e-8))
check("largest solar", max(row["capacity_mw"] for row in solar) == universe["solar_largest_mwp"])
check("largest BESS", max(row["capacity_mw"] for row in bess) == universe["bess_largest_mw"])
check("combined capacity forbidden", contract["interface"]["combined_capacity_metric_forbidden"] is True)
check("technology units", contract["interface"]["technology_labels_and_units"] == {"solar": {"label": "Solar", "unit": "MWp"}, "bess": {"label": "Battery Storage", "unit": "MW"}})
expected_snapshot = universe["published_snapshot"]
for field in (
"projects_sha256",
"source_identity_sha256",
"source_coordinate_fixture_sha256",
"source_workbook_sha256",
):
check(f"published snapshot metadata: {field}", payload.get(field) == expected_snapshot.get(field))
check("published geometry policy", payload.get("geometry_policy") == expected_snapshot.get("geometry_policy"))
check("published source provenance", payload.get("source_provenance") == expected_snapshot.get("source_provenance"))
record_contract = contract["project_record"]
for field in record_contract["required_non_null_strings"]:
check(f"required string: {field}", all(isinstance(row.get(field), str) and bool(row[field]) for row in projects))
for field in record_contract["required_finite_numbers"]:
check(f"required finite number: {field}", all(is_finite_number(row.get(field)) for row in projects))
for field in record_contract["required_integers"]:
check(f"required integer: {field}", all(isinstance(row.get(field), int) and not isinstance(row[field], bool) for row in projects))
for field in record_contract["required_true_booleans"]:
check(f"required true boolean: {field}", all(row.get(field) is True for row in projects))
for field in record_contract["nullable_iso_dates"]:
check(f"nullable ISO date: {field}", all(is_iso_date_or_none(row.get(field)) for row in projects))
for field in record_contract["nullable_strings"]:
check(f"nullable string: {field}", all(row.get(field) is None or isinstance(row.get(field), str) for row in projects))
for field in record_contract["nullable_numbers"]:
check(f"nullable number: {field}", all(row.get(field) is None or is_finite_number(row.get(field)) for row in projects))
for field in record_contract["string_may_be_empty"]:
check(f"string may be empty: {field}", all(isinstance(row.get(field), str) for row in projects))
for field in record_contract["required_arrays"]:
check(f"required array: {field}", all(isinstance(row.get(field), list) for row in projects))
repd_refs = [row["repd_ref"] for row in projects]
project_ids = [row["gg_project_id"] for row in projects]
check("unique REPD refs", len(repd_refs) == len(set(repd_refs)))
check("unique project IDs", len(project_ids) == len(set(project_ids)))
check("canonical project ID", all(row["gg_project_id"] == f"GG2050-REPD-{row['repd_ref']}" for row in projects))
check("authoritative bound identity", all(row["identity_status"] == "REPD_BOUND" and row["identity_confidence"] == "authoritative" for row in projects))
check("development includes self", all(row["repd_ref"] in row["development_repd_refs"] for row in projects))
relationship_types = set(record_contract["relationship_object"]["type_enum"])
relationship_ok = all(
isinstance(rel, dict)
and set(record_contract["relationship_object"]["required_fields"]).issubset(rel)
and rel["type"] in relationship_types
for row in projects for rel in row["relationships"]
)
check("relationship schema", relationship_ok)
relationship_targets = {rel["repd_ref"] for row in projects for rel in row["relationships"]}
check("out-of-scope relationship targets preserved", bool(relationship_targets - set(repd_refs)))
partition_counts: dict[str, int] = {}
for row in projects:
key = lifecycle_partition(row)
partition_counts[key] = partition_counts.get(key, 0) + 1
expected_views = {view["id"]: view["count"] for view in contract["lifecycle_views"]}
check("lifecycle partition exhaustive", "UNMAPPED" not in partition_counts)
check("lifecycle partition disjoint totals", sum(partition_counts.values()) == len(projects))
for view in ("CURRENT", "DISPUTED", "HISTORICAL", "REVIEW"):
check(f"lifecycle view {view}", partition_counts.get(view) == expected_views[view])
check("ALL view", expected_views["ALL"] == len(projects))
valid_ids = {row["gg_project_id"] for row in projects if row["geometry_status"] == "valid"}
feature_ids = {feature["id"] for feature in geojson["features"]}
check("GeoJSON valid subset", feature_ids == valid_ids)
check("GeoJSON feature IDs unique", len(feature_ids) == len(geojson["features"]))
check("geometry edition count", len(feature_ids) == universe["geometry_count_this_edition"])
check("geometry does not govern project count", universe["project_count"] == len(projects))
search_fields = contract["interface"]["search_fields"]
by_ref = {row["repd_ref"]: row for row in projects}
for example in contract["acceptance_examples"]:
results = search_records(projects, search_fields, example["query"])
result_refs = sorted(row["repd_ref"] for row in results)
check(
f"search sentinel: {example['query']}",
len(results) == example["expected_records"] and result_refs == sorted(example["expected_repd_refs"]),
f"actual refs={result_refs}",
)
check("Beacon Fen components remain separate", by_ref["13599"]["gg_development_id"] == by_ref["13600"]["gg_development_id"] and by_ref["13599"]["gg_project_id"] != by_ref["13600"]["gg_project_id"])
table_fields = contract["interface"]["primary_table_fields"]
check("primary table has 11 fields", len(table_fields) == 11)
check(
"primary table labels preserve frozen order",
[field["label"] for field in table_fields] == contract["interface"]["primary_table_columns"],
)
check(
"official milestone fields are explicit",
contract["interface"]["official_milestone_fields"] == [
"planning_application_submitted",
"planning_application_withdrawn",
"planning_permission_granted",
"planning_permission_refused",
"planning_permission_expired",
"under_construction",
"operational",
],
)
export_contract = contract["interface"]["export"]
export_ids = [column["id"] for column in export_contract["columns"]]
check("export column IDs unique", len(export_ids) == len(set(export_ids)))
check("export is filtered only", export_contract["scope"] == "current filtered rows only")
check("zero-result export is header only", export_contract["zero_results"] == "header only")
check("CSV null semantics are explicit", export_contract["null_official_value"] == "empty CSV field")
check("export includes canonical project ID", "gg_project_id" in export_ids)
check("export includes canonical development ID", "gg_development_id" in export_ids)
check("export includes published provenance", {"projects_sha256", "source_dataset", "source_row"}.issubset(export_ids))
news_contract = contract["legacy_news_isolation"]
news_path = ROOT / news_contract["fixture_path"]
news = load(news_path)
items = news["items"]
check("V5 news fixture hash", sha256(news_path) == news_contract["fixture_sha256"])
check("V5 news item count", len(items) == news_contract["item_count"] == 125)
check("V5 solar news count", sum(item.get("technology") == "solar" for item in items) == news_contract["solar_count"])
check("V5 BESS news count", sum(item.get("technology") == "bess" for item in items) == news_contract["bess_count"])
check("V5 finance news count", sum(item.get("event") in {"FINANCIAL CLOSE", "ACQUISITION"} for item in items) == news_contract["finance_count"])
check("legacy news plugin hash", sha256(V7 / "scripts/plugins/newspaper.js") == news_contract["plugin_sha256"])
forbidden_news_fields = {"headline", "news_signal", "article_capacity_mw", "primary_match"}
check("canonical records contain no news facts", all(not forbidden_news_fields.intersection(row) for row in projects))
if args.phase == "spec":
for relative, expected_hash in contract["v7_1_runtime_guard"]["files"].items():
check(f"unchanged V7.1 runtime: {relative}", sha256(ROOT / relative) == expected_hash)
state_text = (V7 / "scripts/core/state.js").read_text(encoding="utf-8")
check("V7.1 legacy project source remains live", contract["release_state"]["current_project_source"] in state_text)
check("V7.2 project source not wired", contract["release_state"]["target_project_source"] not in state_text)
index_text = (V7 / "index.html").read_text(encoding="utf-8")
check("visible release remains V7.1", "V7.1" in index_text and "V7.2" not in index_text)
plugin_manifest = load(V7 / "data/plugin_manifest.json")
check("plugin manifest remains V7.1", plugin_manifest.get("version") == "7.1")
else:
state_text = (V7 / "scripts/core/state.js").read_text(encoding="utf-8")
index_text = (V7 / "index.html").read_text(encoding="utf-8")
plugin_manifest = load(V7 / "data/plugin_manifest.json")
check("contract promoted for integration", contract.get("status") in {"LIVE_CANDIDATE", "LIVE_VALIDATED"})
check("visible release is V7.2", "V7.2" in index_text)
check("plugin manifest is V7.2", plugin_manifest.get("version") == "7.2")
check("canonical project source wired", contract["release_state"]["target_project_source"] in state_text)
check("legacy project source removed", contract["release_state"]["current_project_source"] not in state_text)
check("wind controls absent", "Onshore Wind" not in index_text and "Offshore Wind" not in index_text)
failures = [(name, detail) for name, passed, detail in checks if not passed]
result = "PASS" if not failures else "FAIL"
print(f"V7.2 projects-plugin {args.phase}: {result} ({len(checks)} checks, {len(failures)} failures)")
for name, detail in failures:
print(f"FAIL: {name}{' — ' + detail if detail else ''}")
return 1 if failures else 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except (UnicodeError, json.JSONDecodeError, OSError, KeyError, TypeError, ValueError) as error:
print(f"V7.2 projects-plugin: FAIL (unreadable or malformed contract/data: {error})")
raise SystemExit(1) from NoneValidate V7 2 Spine
A Python command-line tool in the tests folder of GlobalGrid2050 that tests project spine, north star, solar and battery storage (BESS), using SHA-256.
testglobalgrid2050 / uk_renewables_pipeline/202609051156/tests/validate_v7_2_spine.py · lines 1–143 of 143 · version 2026-09-05 11:56 · Entry point · pattern canonical_sha (shared by 2 files)
- What it does
- It tests project spine, north star, solar and battery storage (BESS). Defines load, sha256, canonical_sha, main, check. Uses libraries __future__, hashlib, json, math, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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: solar, battery storage (BESS).
- Inputs & outputs
- In: JSON file project-spine.v7.2.json; JSON file north-star.v1.json. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the check step (`check`). Its name says it validates spine. Defines `load`, `sha256`, `canonical_sha` and 1 more.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- globalgrid2050 · uk_renewables_pipeline/202609051156/tests · Python CLI
- Uses
- __future__, hashlib, json, math, pathlib, typing
- Used by
- none found
- Produces
- load, sha256, canonical_sha, main
- Defines here
- load, sha256, canonical_sha, main, check
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609051156/tests/validate_v7_2_spine.py:1-143 · blob 04d62bd0ddd5489b37b014e141a8d040d99611d9 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
from __future__ import annotations
import hashlib
import json
import math
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[3]
V7 = ROOT / "uk_renewables_pipeline/v7"
def load(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def canonical_sha(value: Any) -> str:
raw = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def main() -> None:
contract_path = V7 / "contracts/project-spine.v7.2.json"
contract = load(contract_path)
expected = contract["expected"]
identity_path = ROOT / contract["identity_fixture"]
coordinate_path = ROOT / contract["coordinate_fixture"]
projects_path = ROOT / contract["outputs"]["projects"]
geojson_path = ROOT / contract["outputs"]["geojson"]
manifest_path = ROOT / contract["outputs"]["manifest"]
coordinates = load(coordinate_path)
payload = load(projects_path)
geojson = load(geojson_path)
manifest = load(manifest_path)
north_star = load(V7 / "contracts/north-star.v1.json")
checks: list[tuple[str, bool]] = []
def check(name: str, condition: bool) -> None:
checks.append((name, bool(condition)))
check("identity fixture hash", sha256(identity_path) == contract["identity_fixture_sha256"])
check("coordinate fixture hash", sha256(coordinate_path) == contract["coordinate_fixture_sha256"])
check("workbook hash provenance", coordinates["source_workbook_sha256"] == contract["source_workbook_sha256"])
coordinate_rows = coordinates["records"]
coordinate_refs = [row["repd_ref"] for row in coordinate_rows]
populated_coordinates = sum(
isinstance(row.get("easting"), (int, float)) and math.isfinite(row["easting"])
and isinstance(row.get("northing"), (int, float)) and math.isfinite(row["northing"])
for row in coordinate_rows
)
check("coordinate source rows", len(coordinate_rows) == coordinates["source_records"] == expected["source_records"])
check("coordinate unique REPD refs", len(coordinate_refs) == len(set(coordinate_refs)))
check("coordinate populated rows", populated_coordinates == coordinates["coordinate_records"] == expected["source_coordinate_records"])
projects = payload["projects"]
features = geojson["features"]
check("project count", len(projects) == payload["project_count"] == expected["projects"])
check("solar count", sum(row["technology"] == "solar" for row in projects) == expected["solar"])
check("BESS count", sum(row["technology"] == "bess" for row in projects) == expected["bess"])
check("no wind", all(row["technology"] in {"solar", "bess"} for row in projects))
check("development count", len({row["gg_development_id"] for row in projects}) == expected["developments"])
check("solar capacity", math.isclose(sum(row["capacity_mw"] for row in projects if row["technology"] == "solar"), expected["solar_mwp"], abs_tol=1e-8))
check("BESS capacity", math.isclose(sum(row["capacity_mw"] for row in projects if row["technology"] == "bess"), expected["bess_mw"], abs_tol=1e-8))
check("exclusive thresholds", all(row["capacity_mw"] > (49 if row["technology"] == "solar" else 99) for row in projects))
check("capacity known", all(row["capacity_known"] is True for row in projects))
check("unique REPD refs", len({row["repd_ref"] for row in projects}) == len(projects))
check("unique GG project IDs", len({row["gg_project_id"] for row in projects}) == len(projects))
check("canonical identity", all(row["gg_project_id"] == f"GG2050-REPD-{row['repd_ref']}" and row["identity_status"] == "REPD_BOUND" for row in projects))
valid_geometry_projects = [row for row in projects if row.get("geometry_status") == "valid"]
missing_geometry_projects = [row for row in projects if row.get("geometry_status") != "valid"]
check("geometry status vocabulary", all(row.get("geometry_status") in {"valid", "missing", "invalid"} for row in projects))
check("geometry count", len(features) == len(valid_geometry_projects) == payload["geometry_count"] == geojson["feature_count"] == expected["geometry_records"])
check("missing geometry count", len(missing_geometry_projects) == payload["missing_geometry_count"] == expected["missing_geometry"])
check("nullable missing geometry", all(row.get("longitude") is None and row.get("latitude") is None and row.get("coordinate_source") is None for row in missing_geometry_projects))
check("projects array hash", canonical_sha(projects) == payload["projects_sha256"] == expected["projects_array_sha256"])
check("GeoJSON feature hash", canonical_sha(features) == geojson["features_sha256"] == expected["geojson_features_sha256"])
by_id = {row["gg_project_id"]: row for row in projects}
geometry_ok = True
feature_ids = [feature["id"] for feature in features]
for feature in features:
row = by_id.get(feature["id"])
coords = feature.get("geometry", {}).get("coordinates", [])
if row is None or row.get("geometry_status") != "valid" or len(coords) != 2 or coords != [row["longitude"], row["latitude"]]:
geometry_ok = False
break
if not all(isinstance(value, (int, float)) and math.isfinite(value) for value in coords):
geometry_ok = False
break
if not (-9.5 <= coords[0] <= 3.5 and 49.0 <= coords[1] <= 61.5):
geometry_ok = False
break
check("canonical WGS84 geometry", geometry_ok)
check("unique GeoJSON feature IDs", len(feature_ids) == len(set(feature_ids)))
check("GeoJSON is valid-geometry subset", set(feature_ids) == {row["gg_project_id"] for row in valid_geometry_projects})
by_ref = {row["repd_ref"]: row for row in projects}
sentinel_ok = True
for sentinel in north_star["canonical_sentinels"]:
threshold = 49 if sentinel["technology"] == "Solar Photovoltaics" else 99
if sentinel["capacity_mw"] <= threshold:
continue
row = by_ref.get(sentinel["repd_ref"])
if row is None or row["gg_development_id"] != sentinel["gg_development_id"] or row["capacity_mw"] != sentinel["capacity_mw"] or row["status"] != sentinel["status"]:
sentinel_ok = False
break
check("North Star sentinels preserved", sentinel_ok)
forbidden = {"headline", "news_signal", "article_capacity_mw", "primary_match"}
check("no news-derived fields", all(not forbidden.intersection(row) for row in projects))
check("manifest contract hash", manifest["contract_sha256"] == sha256(contract_path))
expected_inputs = {contract["identity_fixture"], contract["coordinate_fixture"]}
expected_outputs = {contract["outputs"]["projects"], contract["outputs"]["geojson"]}
check("manifest input path set", set(manifest["inputs"]) == set(manifest["input_bytes"]) == expected_inputs)
check("manifest output path set", set(manifest["outputs"]) == set(manifest["output_bytes"]) == expected_outputs)
check("manifest identity input", manifest["inputs"][contract["identity_fixture"]] == sha256(identity_path) and manifest["input_bytes"][contract["identity_fixture"]] == identity_path.stat().st_size)
check("manifest coordinate input", manifest["inputs"][contract["coordinate_fixture"]] == sha256(coordinate_path) and manifest["input_bytes"][contract["coordinate_fixture"]] == coordinate_path.stat().st_size)
check("manifest project file", manifest["outputs"][contract["outputs"]["projects"]] == sha256(projects_path) and manifest["output_bytes"][contract["outputs"]["projects"]] == projects_path.stat().st_size)
check("manifest GeoJSON file", manifest["outputs"][contract["outputs"]["geojson"]] == sha256(geojson_path) and manifest["output_bytes"][contract["outputs"]["geojson"]] == geojson_path.stat().st_size)
metric_keys = ("project_count", "solar_count", "bess_count", "development_count", "solar_mwp", "bess_mw", "geometry_count", "missing_geometry_count")
check("manifest metrics", manifest["metrics"] == {key: payload[key] for key in metric_keys})
check("manifest projects canonical hash", manifest["projects_sha256"] == payload["projects_sha256"] == canonical_sha(projects) == expected["projects_array_sha256"])
check("manifest features canonical hash", manifest["features_sha256"] == geojson["features_sha256"] == canonical_sha(features) == expected["geojson_features_sha256"])
failures = [name for name, passed in checks if not passed]
print(f"V7.2 canonical spine: {'PASS' if not failures else 'FAIL'} ({len(checks)} checks, {len(failures)} failures)")
for name in failures:
print(f"FAIL: {name}")
if failures:
raise SystemExit(1)
if __name__ == "__main__":
try:
main()
except (UnicodeError, json.JSONDecodeError, OSError, KeyError, TypeError, ValueError) as error:
print(f"V7.2 canonical spine: FAIL (unreadable or malformed artefact: {error})")
raise SystemExit(1) from NoneCanonical Projects V9 1
A JavaScript module in the data folder of GlobalGrid2050 that fetches the Renewable Energy Planning Database (REPD) register, solar and battery storage (BESS), using SHA-256.
renderglobalgrid2050 / uk_renewables_pipeline/202609061149/scripts/data/canonical-projects-v9-1.js · lines 1–102 of 102 · version 2026-09-06 11:49 · Not reached from any entry point (candidate for review) · pattern loadCanonicalProjects (shared by 12 files)
- What it does
- It fetches the REPD register, solar and battery storage (BESS). Defines invariant, round2, fetchJson, loadCanonicalProjectsV9_1. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'renewables'): 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: the REPD register, solar, battery storage (BESS).
- Inputs & outputs
- In: JSON file release.v9.1.json; JSON file build_manifest.json.
- Downstream impact
- Used directly by 2 files: Projects V9 1 (globalgrid2050); JavaScript Canonical Projects V9 5 1 (pipelinenews).
- What it achieves
- It fetches JSON (`fetchJson`) and loads canonical projects v9 (`loadCanonicalProjectsV9_1`). Defines `invariant`, `round2`, `fetchJson` and 1 more. Its code works with 1 MW.
- Why it matters
- Imported by Projects V9 1 and JavaScript Canonical Projects V9 5 1, from PipelineNews.
- Application
- globalgrid2050 · uk_renewables_pipeline/202609061149/scripts/data · JavaScript module
- Uses
- none found
- Used by
- imported by Projects V9 1 (import), imported by JavaScript Canonical Projects V9 5 1 (import)
- Produces
- loadCanonicalProjectsV9_1
- Defines here
- invariant, round2, fetchJson, loadCanonicalProjectsV9_1
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 uk_renewables_pipeline/202609061149/scripts/data/canonical-projects-v9-1.js:1-102 · blob 349c9d932829cad84f304cdffd24a3e3755d3fbd · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
const CONTRACT_URL = "contracts/release.v9.1.json";
const MANIFEST_URL = "data/v9.1/build_manifest.json";
const ALLOWED_TECHNOLOGIES = new Set(["solar", "bess", "wind_onshore", "wind_offshore"]);
function invariant(condition, message) {
if (!condition) throw new Error(`V9.1 canonical projects: ${message}`);
}
function round2(value) {
return Math.round((value + Number.EPSILON) * 100) / 100;
}
/* WHY THIS IS NO LONGER cache: "no-store".
*
* Every file this module reads lives inside a published release directory,
* and a published release directory never changes - that is the whole point
* of the timestamp in the path. Asking the browser not to store them meant
* re-downloading the entire 1.15 MB spine on every visit and every deep link,
* ignoring the server's own max-age.
*
* Measured on the live 202609061004 build, same file, same session:
*
* cache: "no-store" 454 ms, 533 ms (every single time)
* cache: "default" 4 ms, 3 ms (after the first)
*
* Roughly 150x, across sixteen parts. No REPD record is dropped, filtered or
* summarised to get it: the bytes are identical, they are simply allowed to
* be reused. Integrity does not rest on re-fetching - it rests on the sha256
* and record-count invariants asserted below, which run on every load whether
* the bytes came from the network or the cache.
*/
async function fetchJson(path) {
const response = await fetch(path, { cache: "default" });
invariant(response.ok, `${path} returned HTTP ${response.status}`);
invariant(new URL(response.url).origin === window.location.origin, `${path} redirected cross-origin`);
return response.json();
}
export async function loadCanonicalProjectsV9_1({ onPartition } = {}) {
const [contract, payload] = await Promise.all([fetchJson(CONTRACT_URL), fetchJson(MANIFEST_URL)]);
invariant(contract.release === "9.1", "release contract mismatch");
invariant(payload.schema === "globalgrid2050.v9.project-spine-build.v9.1", "project manifest schema mismatch");
invariant(payload.release === "9.1", "project release mismatch");
invariant(Array.isArray(payload.project_partitions) && payload.project_partitions.length > 0, "project partitions missing");
invariant(payload.source_identity_sha256 === contract.source.identity_fixture_sha256, "identity hash mismatch");
invariant(payload.source_coordinate_fixture_sha256 === contract.source.coordinate_fixture_sha256, "coordinate hash mismatch");
invariant(payload.source_workbook_sha256 === contract.source.workbook_sha256, "workbook hash mismatch");
/* The sixteen partitions are still fetched together and still ALL have to
* arrive: onPartition is a progress signal, not a licence to render a
* partial pipeline. Every invariant below still runs over the complete set,
* and the total is still asserted against the manifest's own count, so a
* short read fails loudly instead of quietly publishing fewer projects. */
const partitions = await Promise.all(payload.project_partitions.map(async (partition, index) => {
const part = await fetchJson(partition.path);
invariant(part.schema === "globalgrid2050.v9.project-partition.v9.1", `${partition.path} schema mismatch`);
invariant(part.record_count === partition.record_count && part.projects.length === partition.record_count, `${partition.path} count mismatch`);
if (typeof onPartition === "function") {
onPartition({ index, of: payload.project_partitions.length, records: part.projects.length });
}
return part.projects;
}));
const sourceProjects = partitions.flat();
invariant(sourceProjects.length === payload.project_count, "partition total mismatch");
const refs = new Set();
const projectIds = new Set();
let capacity = 0;
let largest = 0;
const counts = { solar: 0, bess: 0, wind_onshore: 0, wind_offshore: 0 };
const projects = sourceProjects.map((project) => {
invariant(typeof project.repd_ref === "string" && project.repd_ref, "missing REPD Ref");
invariant(project.gg_project_id === `GG2050-REPD-${project.repd_ref}`, `invalid ID for ${project.repd_ref}`);
invariant(project.identity_status === "REPD_BOUND" && project.identity_confidence === "authoritative", `unbound identity for ${project.repd_ref}`);
invariant(ALLOWED_TECHNOLOGIES.has(project.technology), `out-of-scope technology for ${project.repd_ref}`);
invariant(Number.isFinite(project.capacity_mw) && project.capacity_mw >= 1, `capacity below 1 MW for ${project.repd_ref}`);
invariant(!refs.has(project.repd_ref), `duplicate REPD Ref ${project.repd_ref}`);
invariant(!projectIds.has(project.gg_project_id), `duplicate project ID ${project.gg_project_id}`);
refs.add(project.repd_ref);
projectIds.add(project.gg_project_id);
counts[project.technology] += 1;
capacity += project.capacity_mw;
largest = Math.max(largest, project.capacity_mw);
return Object.freeze({ ...project });
});
const actual = {
project_count: projects.length,
capacity_mw: round2(capacity),
largest_mw: largest,
solar_count: counts.solar,
bess_count: counts.bess,
wind_onshore_count: counts.wind_onshore,
wind_offshore_count: counts.wind_offshore,
};
Object.entries(contract.expected).forEach(([key, value]) => invariant(actual[key] === value, `${key} is ${actual[key]}, expected ${value}`));
return Object.freeze({
contract: Object.freeze(contract),
metadata: Object.freeze({ ...payload, projects: undefined }),
projects: Object.freeze(projects),
});
}