In this section
- Renewable Energy Planning Database (REPD) Hashguard storage · globalgrid2050 / automation/repd/hashguard.py lines 413–430
- Renewable Energy Planning Database (REPD) Monthly storage · globalgrid2050 / automation/repd/monthly.py lines 1–303
- Automation — Renewable Energy Planning Database (REPD) energy-data · globalgrid2050 / automation/repd/run.py lines 1–379
Renewable Energy Planning Database (REPD) Hashguard
A Python command-line tool in the automation folder of GlobalGrid2050 that reads manifest (`read_manifest`), writes manifest (`write_manifest`) and lists worktree files (`list_worktree_files`), using SHA-256.
storageglobalgrid2050 / automation/repd/hashguard.py · lines 413–430 of 430 (continued from section 824) · Entry point · pattern read_manifest (shared by 2 files)
- What it does
- It loads data. Defines 22 functions or classes, including GuardError, _unquote, read_manifest, write_manifest, id_kind. Uses libraries argparse, datetime, fnmatch, hashlib, json. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): 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: command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 1 file: Test Hashguard (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It guards error (`GuardError`) and is built from the id kind helper (`id_kind`) and the is git worktree helper (`is_git_worktree`). "no truncation of previous work" guard. It accepts `--git`, `--rev` and `--root`.
- Why it matters
- Checked by Test Hashguard.
- Application
- globalgrid2050 · automation/repd · Python CLI
- Uses
- argparse, datetime, fnmatch, hashlib, json, os, subprocess, sys
- Used by
- imported by Test Hashguard (sys.path import)
- Produces
- GuardError, read_manifest, write_manifest, id_kind, is_git_worktree, raw_blob_id, sha256_id, git_hash_paths, snapshot_git, snapshot_sha256, list_worktree_files, Snap
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/hashguard.py:413-430 · blob 08cab909d0ff987eab2e5e5035339051ebd383a3 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
f'{rep["violations_total"]} violations {rep["violations_by_change"]}, '
f'{rep["allowed_changes_total"]} allowed changes, {rep["additions_total"]} additions '
f'({rep["additions_bytes"]} bytes)')
for v in rep['violations'][:50]:
print(f' VIOLATION {v["change"]:11} {v["path"]}')
for v in rep['additions'][:50]:
print(f' added {v["path"]}')
if rep['additions_total'] > 50:
print(f' ... {rep["additions_total"] - 50} more additions')
if a.json:
with open(a.json, 'w', encoding='utf-8') as f:
json.dump(rep, f, indent=1, ensure_ascii=False)
f.write('\n')
return rep['exit_code']
if __name__ == '__main__':
sys.exit(main())Renewable Energy Planning Database (REPD) Monthly
A Python command-line tool in the automation folder of GlobalGrid2050 that reads the REPD register, project identity, major projects and solar, using SHA-256.
storageglobalgrid2050 / automation/repd/monthly.py · lines 1–303 of 303 · Entry point · pattern first_existing (shared by 2 files)
- What it does
- It loads the REPD register, project identity, major projects and solar. Defines 13 functions or classes, including NeedsPerson, quarter_from_date, release_name, find_published, download. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): 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.
- Inputs & outputs
- In: CSV file repd.csv; JSON file project_identity_v6.json; JSON file major_projects_v6.json; command-line arguments. Out: JSON file result.json.
- Downstream impact
- Used directly by 2 files: Test Monthly (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It finds published (`find_published`), writes descriptors (`write_descriptors`) and adds allowlist (`add_allowlist`). Monthly REPD check: has GOV.UK published new REPD bytes? It accepts `--out`, `--repo-root` and `--automation-dir`.
- Why it matters
- Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow. Checked by Test Monthly.
- Application
- globalgrid2050 · automation/repd · Python CLI
- Uses
- Automation — Renewable Energy Planning Database (REPD) (import), Renewable Energy Planning Database (REPD) Detect (import), Renewable Energy Planning Database (REPD) Fetch (import), __future__, argparse, datetime, hashlib, json, os, sys, collections
- Used by
- imported by Test Monthly (import), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (workflow run)
- Produces
- NeedsPerson, quarter_from_date, release_name, find_published, download, counts, first_existing, write_descriptors, allowlist_lines, add_allowlist, run, summary
- Defines here
- NeedsPerson, quarter_from_date, release_name, find_published, download, counts, first_existing, write_descriptors, allowlist_lines, add_allowlist, run, summary, 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 automation/repd/monthly.py:1-303 · blob 3d46a5340e654cadd31db66e5f43b816865d1cc0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Monthly REPD check: has GOV.UK published new REPD bytes? If so, prepare the release.
Used by .github/workflows/repd-monthly.yml (3rd of each month). One decision, by hash:
* download the CSV and XLSX the publication currently links to (GOV.UK redirects a
replaced attachment's old URL to the new file, so URLs prove nothing: hashes do);
* if BOTH sha256 values are already pinned by a descriptor in automation/repd/releases/,
status = "unchanged" (the usual month: REPD is published about quarterly), exit 0;
* otherwise status = "new": derive the release id (2027q1 from the file name or
attachment title; failing that, from the publication date: the last quarter that had
ended by then), write releases/<id>.json and releases_v6/v6_<id>.json with the hashes
and counts of the downloaded files, add the three over-5-MB outputs of the release to
.github/large-files-allowlist.txt, exit 0;
* if the bytes are new but the derived id already has a descriptor (a same-quarter
correction) or is older than the newest one, status = "needs_person", exit 1:
a person decides, nothing is written.
The downloaded files are kept in <out>/raw/ so the workflow feeds the same bytes to
run.py (--offline --csv --xlsx). <out>/result.json and <out>/summary.md record the
decision; with GITHUB_OUTPUT set, status/release_id/release_folder/csv/xlsx are exported.
Offline (tests, dry runs): --api-file <saved content API JSON> --files-dir <dir holding
files named as the attachment URLs>.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import os
import sys
from collections import Counter
from pathlib import Path
if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from automation.repd import config, detect # noqa: E402
from automation.repd.fetch import file_name, local_fetcher, urllib_fetcher, utc_now # noqa: E402
HERE = Path(__file__).resolve().parent
QUARTER_MONTH = {1: "April", 2: "July", 3: "October", 4: "January"}
class NeedsPerson(RuntimeError):
pass
def quarter_from_date(day: str) -> tuple[int, int]:
"""Last calendar quarter that had ended on `day` (YYYY-MM-DD): 2026-11-13 -> (2026, 3)."""
d = dt.date.fromisoformat(day[:10])
q = (d.month - 1) // 3 # quarters fully ended this year
return (d.year - 1, 4) if q == 0 else (d.year, q)
def release_name(yq: tuple[int, int]) -> str:
year, q = yq
return f"{QUARTER_MONTH[q]} {year + 1 if q == 4 else year}"
def find_published(fetcher, api_file: str | None = None) -> dict:
"""Newest REPD CSV + XLSX attachment pair on the publication, with release id."""
errors = []
sources = [("content_api", None)] if api_file else [("content_api", config.CONTENT_API),
("publication_html", config.SOURCE_PAGE)]
for kind, url in sources:
try:
if api_file:
body = Path(api_file).read_text(encoding="utf-8")
else:
resp = fetcher(url)
if resp.status_chain[-1][0] != 200:
raise RuntimeError(f"status {resp.status_chain}")
body = resp.body.decode("utf-8")
parsed = (detect.parse_content_api(body) if kind == "content_api"
else detect.parse_publication_html(body))
if parsed["attachments"]:
break
errors.append(f"{kind}: no REPD attachments")
except Exception as exc: # noqa: BLE001 - try the next source
errors.append(f"{kind}: {exc}")
else:
raise RuntimeError("cannot read the publication: " + "; ".join(errors))
when = parsed.get("page_last_updated") or utc_now()[:10]
try:
desc = detect.build_descriptor(parsed)
return {"release_id": desc.release_id, "label": desc.label, "csv_url": desc.csv_url,
"xlsx_url": desc.xlsx_url, "title": desc.dataset_title, "page_last_updated": when,
"govuk_public_updated_at": parsed.get("govuk_public_updated_at"),
"id_from": "file name / attachment title", "source": parsed["source"]}
except detect.DetectError as exc:
# Quarter not readable from names: one CSV + one XLSX, labelled by publication date.
pick = {}
for role in ("csv", "xlsx"):
cands = [a for a in parsed["attachments"] if a["role"] == role]
if len(cands) != 1:
raise NeedsPerson(f"{exc}; and {len(cands)} .{role} attachments, so no date fallback") from exc
pick[role] = cands[0]
yq = quarter_from_date(when)
return {"release_id": config.release_id_for(*yq), "label": release_name(yq),
"csv_url": pick["csv"]["url"], "xlsx_url": pick["xlsx"]["url"],
"title": pick["csv"]["title"] or None, "page_last_updated": when,
"govuk_public_updated_at": parsed.get("govuk_public_updated_at"),
"id_from": f"publication date {when} ({exc})", "source": parsed["source"]}
def download(fetcher, url: str, role: str, raw_dir: Path) -> dict:
resp = fetcher(url)
if not resp.status_chain or resp.status_chain[-1][0] != 200:
raise RuntimeError(f"{url}: final status {resp.status_chain}")
body = resp.body
if body[:512].lstrip().lower().startswith((b"<!doctype", b"<html")):
raise RuntimeError(f"{url}: got an HTML page, not a data file")
if role == "xlsx" and not body.startswith(b"PK\x03\x04"):
raise RuntimeError(f"{url}: XLSX is not a zip container")
raw_dir.mkdir(parents=True, exist_ok=True)
path = raw_dir / file_name(url) # saved under the descriptor URL's name (run.py offline)
path.write_bytes(body)
return {"url": url, "final_url": resp.final_url, "redirected": resp.redirected, "path": str(path),
"bytes": len(body), "sha256": hashlib.sha256(body).hexdigest()}
def counts(csv_path: Path, xlsx_path: Path, repo_root: Path) -> dict:
"""Rows, refs and threshold counts exactly as scripts/repd_sources_v6.py computes them."""
sys.path.insert(0, str(repo_root / "scripts"))
try:
import repd_sources_v6 as v6 # noqa: PLC0415 - July defaults; no descriptor env needed
finally:
sys.path.pop(0)
frame = v6.read_csv(csv_path.read_bytes())
refs = [v6.clean_ref(x) for x in frame["Ref ID"].tolist()]
dups = sorted(r for r, k in Counter(refs).items() if k > 1)
xlsx, _ = v6.read_xlsx(xlsx_path.read_bytes())
xlsx, _ = v6.drop_identical_duplicates(xlsx, "XLSX")
solar, bess = v6.threshold_counts(xlsx)
return {"csv_rows": len(frame), "unique_refs": len(set(refs)), "duplicate_refs": dups,
"solar_gt_1mw": solar, "bess_gt_100mw": bess}
def first_existing(repo_root: Path, *rels: str) -> str | None:
return next((r for r in rels if r and (repo_root / r).is_file()), None)
def write_descriptors(pub: dict, files: dict, n: dict, prev: str | None, auto_dir: Path,
repo_root: Path) -> list[str]:
rid = pub["release_id"]
year, q = int(rid[:4]), int(rid[-1])
title = f"Renewable Energy Planning Database (REPD): {pub['label']} (Q{q} {year})" # as releases_v6/v6_2026q3.json
desc = config.ReleaseDescriptor(
release_id=rid, label=pub["label"], quarter=config.quarter_text(year, q),
csv_url=pub["csv_url"], xlsx_url=pub["xlsx_url"], page_last_updated=pub["page_last_updated"],
govuk_public_updated_at=pub["govuk_public_updated_at"], dataset_title=title,
previous_release_id=prev,
baseline_path=first_existing(repo_root, f"repd-{prev}.csv" if prev else "", "repd.csv"),
expected=config.Expected(csv_sha256=files["csv"]["sha256"], xlsx_sha256=files["xlsx"]["sha256"],
csv_bytes=files["csv"]["bytes"], xlsx_bytes=files["xlsx"]["bytes"], **n),
provenance=[f"written by automation/repd/monthly.py at {utc_now()} from {pub['source']}; "
f"release id from {pub['id_from']}; hashes and counts are of the downloaded files"],
)
path = auto_dir / "releases" / f"{rid}.json"
config.dump(desc, path)
prev_v6 = auto_dir / "releases_v6" / f"v6_{prev}.json"
v6 = json.loads(prev_v6.read_text(encoding="utf-8")) if prev and prev_v6.is_file() else {}
v6.update({
"schema": "globalgrid2050.repd-release-descriptor.v6", "release_id": rid, "quarter_label": f"Q{q}",
"output_suffix": rid, "csv_url": pub["csv_url"], "xlsx_url": pub["xlsx_url"],
"publication_date": pub["page_last_updated"],
"dataset_title": title,
"expected_rows": n["csv_rows"], "expected_unique_refs": n["unique_refs"],
"expected_solar_gt1": n["solar_gt_1mw"], "expected_bess_gt100": n["bess_gt_100mw"],
"expected_csv_sha256": files["csv"]["sha256"], "expected_xlsx_sha256": files["xlsx"]["sha256"],
"baseline_identity": first_existing(repo_root, f"dist/project_identity_{prev}.json",
"dist/project_identity_v6.json") or "dist/project_identity_v6.json",
"baseline_projects": first_existing(repo_root, f"dist/major_projects_{prev}.json",
"dist/major_projects_v6.json") or "dist/major_projects_v6.json",
"notes": f"Written by automation/repd/monthly.py at {utc_now()}; counts computed from the downloaded files.",
})
v6.setdefault("duplicate_row_policy", "drop_identical")
v6.setdefault("date_rule", "xlsx_typed_wins")
v6_path = auto_dir / "releases_v6" / f"v6_{rid}.json"
v6_path.parent.mkdir(parents=True, exist_ok=True)
v6_path.write_text(json.dumps(v6, indent=2) + "\n", encoding="utf-8")
written = [str(path), str(v6_path)]
# Reviewed acceptance waivers (cells the CSV cannot carry, e.g. a character outside cp1252)
# are carried forward from the previous release; acceptance.py lists every waived cell.
prev_known = auto_dir / "baselines" / f"{prev}_known_anomalies.json"
waive = (json.loads(prev_known.read_text(encoding="utf-8")).get("acceptance_waive_cells") or []
if prev and prev_known.is_file() else [])
new_known = auto_dir / "baselines" / f"{rid}_known_anomalies.json"
if waive and not new_known.exists():
new_known.write_text(json.dumps({
"schema": "globalgrid2050.repd-validate-known-anomalies.v1", "release_id": rid,
"note": f"Written by automation/repd/monthly.py: acceptance waivers carried forward from {prev}; "
"no validation anomalies are pre-approved.",
"known": {}, "acceptance_waive_cells": waive}, indent=2) + "\n", encoding="utf-8")
written.append(str(new_known))
return written
def allowlist_lines(rid: str, folder: str) -> list[str]:
return [f"dist/project_identity_{rid}.json", f"dist/repd_master_{rid}.json",
f"uk_renewables_pipeline/{folder}/fixtures/{rid}/project_identity_{rid}.json"]
def add_allowlist(repo_root: Path, rid: str, folder: str) -> list[str]:
path = repo_root / ".github" / "large-files-allowlist.txt"
text = path.read_text(encoding="utf-8") if path.is_file() else ""
have = {ln.split("#", 1)[0].strip() for ln in text.splitlines()}
new = [ln for ln in allowlist_lines(rid, folder) if ln not in have]
if new:
sep = "" if not text or text.endswith("\n") else "\n"
path.write_text(text + sep + f"# REPD {rid} (automation/repd/monthly.py): identity registry and master GeoJSON.\n"
+ "".join(f"{ln}\n" for ln in new), encoding="utf-8")
return new
def run(args, res: dict) -> dict:
out = Path(args.out)
out.mkdir(parents=True, exist_ok=True)
repo_root = Path(args.repo_root).resolve()
auto_dir = Path(args.automation_dir).resolve() if args.automation_dir else repo_root / "automation" / "repd"
fetcher = local_fetcher(args.files_dir) if args.files_dir else urllib_fetcher()
known = config.load_all(auto_dir / "releases")
newest = max(known) if known else None
res.update(newest_known=newest, known_releases=sorted(known))
pub = find_published(fetcher, args.api_file)
res["published"] = pub
files = {role: download(fetcher, pub[f"{role}_url"], role, out / "raw") for role in ("csv", "xlsx")}
res["files"] = files
registry = config.known_hashes(known)
owners = {role: registry.get(files[role]["sha256"]) for role in files}
if owners["csv"] and owners["xlsx"]:
res.update(status="unchanged", release_id=owners["csv"][0],
reason=f"published CSV and XLSX sha256 equal the pinned hashes of {owners['csv'][0]}")
return res
rid = pub["release_id"]
if rid in known or (newest and rid < newest):
raise NeedsPerson(f"new bytes on GOV.UK but they name {rid}, and the newest known release is {newest}: "
"a same-quarter correction or an older file. Review by hand, then update or add "
f"automation/repd/releases/{rid}.json (CSV pinned by {owners['csv']}, XLSX by {owners['xlsx']}).")
folder = args.release_folder or dt.datetime.now(dt.timezone.utc).strftime("%Y%m%d%H%M")
n = counts(Path(files["csv"]["path"]), Path(files["xlsx"]["path"]), repo_root)
written = write_descriptors(pub, files, n, newest, auto_dir, repo_root)
allow = add_allowlist(repo_root, rid, folder) if not args.no_allowlist else []
res.update(status="new", release_id=rid, release_folder=folder, counts=n, descriptors=written,
allowlist_added=allow,
reason=f"published sha256 not pinned by any known release; derived {rid} from {pub['id_from']}")
return res
def summary(res: dict) -> str:
st = res.get("status")
head = {"unchanged": "No new REPD release", "new": f"New REPD release {res.get('release_id')}",
"needs_person": "REPD changed: needs a person", "error": "REPD monthly check failed"}.get(st, st)
lines = [f"## {head}", "", f"- Checked at {res.get('checked_at')}; newest known release: "
f"`{res.get('newest_known')}`", f"- Reason: {res.get('reason')}"]
for role, f in (res.get("files") or {}).items():
lines.append(f"- {role.upper()}: {f['url']} ({f['bytes']} bytes, sha256 `{f['sha256']}`"
+ (f", redirected to {f['final_url']}" if f.get("redirected") else "") + ")")
if st == "new":
lines.append(f"- Counts: {json.dumps(res.get('counts'))}")
lines.append(f"- Release folder: `uk_renewables_pipeline/{res.get('release_folder')}/`")
return "\n".join(lines) + "\n"
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--out", required=True, help="work directory (outside the repo)")
ap.add_argument("--repo-root", default=str(HERE.parents[1]))
ap.add_argument("--automation-dir", help="where releases/ and releases_v6/ live (default <repo>/automation/repd)")
ap.add_argument("--api-file", help="offline: saved GOV.UK content API JSON")
ap.add_argument("--files-dir", help="offline: directory with the attachment files by name")
ap.add_argument("--release-folder", help="12-digit stamp for uk_renewables_pipeline/<stamp>/ (default now)")
ap.add_argument("--no-allowlist", action="store_true", help="do not edit .github/large-files-allowlist.txt")
a = ap.parse_args(argv)
res = {"schema": "globalgrid2050.repd-monthly-check.v1", "checked_at": utc_now()}
try:
run(a, res)
code = 0
except NeedsPerson as exc:
res.update(status="needs_person", reason=str(exc))
code = 1
except Exception as exc: # noqa: BLE001 - any failure is reported, never green
res.update(status="error", reason=f"{type(exc).__name__}: {exc}")
code = 2
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
(out / "result.json").write_text(json.dumps(res, indent=2, default=str) + "\n", encoding="utf-8")
(out / "summary.md").write_text(summary(res), encoding="utf-8")
if os.environ.get("GITHUB_OUTPUT"):
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as fh:
for key in ("status", "release_id", "release_folder"):
fh.write(f"{key}={res.get(key) or ''}\n")
for role in ("csv", "xlsx"):
fh.write(f"{role}={(res.get('files') or {}).get(role, {}).get('path', '')}\n")
print(summary(res))
return code
if __name__ == "__main__":
raise SystemExit(main())Automation — Renewable Energy Planning Database (REPD)
A Python command-line tool in GlobalGrid2050 that fetches REPD publication q3, REPD grid batteries, REPD solar operational over 4MW and REPD master, using SHA-256.
energy-dataglobalgrid2050 / automation/repd/run.py · lines 1–379 of 1377 · Entry point · pattern compare_manifests (shared by 2 files)
- What it does
- It fetches REPD publication q3, REPD grid batteries, REPD solar operational over 4MW and REPD master. Defines 68 functions or classes, including utc_now, sha256_file, sha256_bytes, write_json, StageError. Uses libraries __future__, argparse, dataclasses, datetime, fnmatch. Side effects: reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'repd'): 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: CSV file REPD_Publication_Q3_2026.csv; Excel file REPD_Publication_Q3_2026.xlsx; CSV file repd.csv; CSV file repd-grid-batteries.csv; CSV file repd-solar-operational.csv; CSV file repd-solar-operational-over-4mw.csv; JSON file repd_master.json; JSON file manifest_v4.json. Out: CSV file.
- Downstream impact
- Used directly by 4 files: Test Hardening Nl013 (globalgrid2050); Test Run (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
- What it achieves
- It writes JSON (`write_json`), runs context (`RunContext`) and loads module (`load_module`). REPD release-candidate orchestrator. It writes `detect_report.json`. It accepts `--label`, `--release-folder` and `--descriptor`.
- Why it matters
- Run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow and GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow. Checked by 2 tests, including Test Hardening Nl013.
- Application
- globalgrid2050 · automation/repd · Python CLI
- Uses
- __future__, argparse, dataclasses, datetime, fnmatch, hashlib, importlib, inspect
- Used by
- imported by Test Hardening Nl013 (import), imported by Test Run (import), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (workflow run), run by GlobalGrid2050 Renewable Energy Planning Database (REPD) Release Candidate Workflow (workflow run)
- Produces
- utc_now, sha256_file, sha256_bytes, write_json, StageError, RunContext, load_module, find_component, call_component, normalise_result, first_path, common_pool
- Defines here
- utc_now, sha256_file, sha256_bytes, write_json, StageError, RunContext, label, folder, stage_dir, pr_dir, load_module, find_component, call_component, normalise_result, first_path, common_pool, iter_protected, hash_manifest, compare_manifests, check_known_pins, allowed_new_path_patterns, is_allowed_new_path, load_large_file_allowlist, large_file_allowed, paths_existing_in_repo, git_tracked
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/run.py:1-379 · blob 447c8d05339e438dfa138881ede3f645efad8853 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""REPD release-candidate orchestrator.
One command runs the whole quarterly pipeline and writes everything under --out:
detect -> fetch -> clean -> validate -> diff -> build (root, v6, news)
-> acceptance (optional) -> assemble PR tree -> hash guard -> run report
Nothing inside the repository is written. The repository is read (component code,
previous-release baseline, existing paths) and its protected files are hashed before
and after the run; any difference fails the run ("no truncation of previous work").
Each stage is a plain function ``stage_<name>(ctx) -> dict`` and calls the component
module ``automation.repd.<module>`` when it exists (see STAGES and NOTES.md for the
interface). When a component is absent, the stage either runs a small, clearly
labelled fallback (detect/fetch/clean/validate/diff) or is reported as MISSING
(build stages). A run with a MISSING stage exits 3 unless --allow-partial is given.
Examples
python -m automation.repd.run --label 2026q3 --offline \
--csv REPD_Publication_Q3_2026.csv --xlsx REPD_Publication_Q3_2026.xlsx \
--out /tmp/repd-out
python -m automation.repd.run --label 2026q3 --out "$RUNNER_TEMP/repd-out"
python -m automation.repd.run --detect-only --out /tmp/repd-detect
"""
from __future__ import annotations
import argparse
import dataclasses
import datetime as dt
import fnmatch
import hashlib
import importlib
import inspect
import json
import os
import re
import shutil
import subprocess
import sys
import time
import traceback
from pathlib import Path
from typing import Any, Callable
if __package__ in (None, ""):
# Allow ``python automation/repd/run.py`` as well as ``python -m automation.repd.run``.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
PACKAGE = "automation.repd"
RUN_SCHEMA = "globalgrid2050.repd-run-report.v1"
SOURCE_PAGE = "https://www.gov.uk/government/publications/renewable-energy-planning-database-quarterly-extract"
CONTENT_API = "https://www.gov.uk/api/content/government/publications/renewable-energy-planning-database-quarterly-extract"
MAX_PR_FILE_BYTES = 5 * 1024 * 1024 # pr-file-size-guard.yml MAX_MB: '5'
LARGE_FILE_ALLOWLIST = ".github/large-files-allowlist.txt"
LABEL_RE = re.compile(r"^20[0-9]{2}q[1-4]$")
FOLDER_RE = re.compile(r"^20[0-9]{10}$")
SHA_RE = re.compile(r"^[0-9a-f]{64}$")
CODE_ROOT = Path(__file__).resolve().parents[2] # the checkout that holds automation/ and scripts/
# Built-in descriptors, used only when automation.repd.config is absent.
KNOWN_RELEASES: dict[str, dict[str, Any]] = {
"2026q3": {
"label": "2026q3",
"quarter": "Q3 2026",
"title": "Renewable Energy Planning Database (REPD): October 2026 (Q3 2026)",
"published": "2026-11-13",
"release_folder": "202611132345",
"csv_url": "https://assets.publishing.service.gov.uk/media/6af42ff0a4004bdbe54e54a5/REPD_Publication_Q3_2026.csv",
"xlsx_url": "https://assets.publishing.service.gov.uk/media/6af42ffdb83b3cae0d0a21c9/REPD_Publication_Q3_2026.xlsx",
"expected_csv_sha256": "48e76c49f33a1090e78108d1ea9bfe689b35963ea3be1bb4f6516d038a5ff862",
"expected_xlsx_sha256": "87811e249395a05b223db6855952334f425e66cc9a2106caea0e38fd9e5037ea",
"expected_rows": 14968,
"expected_unique_refs": 14967,
# Last independently validated unique-ref count (July 2026, Q2): row floor.
"row_floor": 14657,
# January-era root file; the July official bytes are not in the repo.
"previous_baseline_path": "repd.csv",
},
}
# Files that later releases and gates pin by hash (crawl notes 03, 04, 13, 16).
# Globs are relative to the repo root. Missing paths are recorded, not an error.
PROTECTED_GLOBS = [
"repd.csv",
"repd-grid-batteries.csv",
"repd-solar-operational.csv",
"repd-solar-operational-over-4mw.csv",
"dist/*.json",
"dist/*.txt",
"uk_renewables_pipeline/*.html",
"uk_renewables_pipeline/2026*/**",
"uk_renewables_pipeline/v*/**",
"pipelinenews_intelligence/**",
"homepage_versions/**",
"homepage_v127.html",
"homepage-before-four-nests-20260925.html",
"index.html",
".github/large-files-allowlist.txt",
".github/workflows/*.yml",
]
QUICK_PROTECTED_GLOBS = [g for g in PROTECTED_GLOBS if "**" not in g]
# sha256 prefixes recorded by the crawl (03 section 6). A mismatch means the checkout
# is not the frozen baseline the candidate was designed against: fail closed.
KNOWN_PINS = {
"dist/repd_master.json": "ca5da437ddb832f7",
"dist/manifest_v4.json": "9c83f953f36c42326",
"dist/project_identity_v6.json": "d614084c05c03808",
"dist/major_projects_v6.json": "ad04f772189868b2",
"dist/major_project_news_v6.json": "40cd71f34bf0bf46",
"dist/manifest_v6.json": "c75af73e3cb717fe",
"dist/repd_source_reconciliation_v6.json": "28715150d3f03659",
"dist/major_project_news_v9_5_1.json": "cea104c3e9cfc079",
"uk_renewables_pipeline/dashboard.html": "341da90d9c4de1ad",
}
# --------------------------------------------------------------------------- utils
def utc_now() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as fh:
for block in iter(lambda: fh.read(1 << 20), b""):
h.update(block)
return h.hexdigest()
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def write_json(path: Path, payload: Any) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=False, default=str) + "\n", encoding="utf-8")
return path
class StageError(RuntimeError):
"""A stage failed closed. The message is shown verbatim in the report."""
@dataclasses.dataclass
class RunContext:
repo_root: Path
out_dir: Path
descriptor: dict[str, Any]
offline: bool = False
local_csv: Path | None = None
local_xlsx: Path | None = None
previous_csv: Path | None = None
fetcher: Callable[[str], bytes] | None = None
allow_partial: bool = False
protected_globs: list[str] = dataclasses.field(default_factory=lambda: list(PROTECTED_GLOBS))
check_pins: bool = True
news_accept_expected: bool = True
code_root: Path = CODE_ROOT
artifacts: dict[str, Any] = dataclasses.field(default_factory=dict)
stages: list[dict[str, Any]] = dataclasses.field(default_factory=list)
@property
def label(self) -> str:
return self.descriptor["label"]
@property
def folder(self) -> str:
return self.descriptor["release_folder"]
def stage_dir(self, name: str) -> Path:
path = self.out_dir / "staging" / name
path.mkdir(parents=True, exist_ok=True)
return path
@property
def pr_dir(self) -> Path:
return self.out_dir / "pr"
# ------------------------------------------------------------- component plumbing
# stage -> (module, candidate function names in preference order)
STAGES: dict[str, tuple[str, list[str]]] = {
"config": ("config", ["load_release", "load_descriptor", "get_release", "release_descriptor"]),
"detect": ("detect", ["detect_latest", "detect_release", "discover_latest", "detect"]),
"fetch": ("fetch", ["fetch_release", "fetch_sources", "fetch"]),
"clean": ("clean", ["clean_release", "clean_files", "clean"]),
"validate": ("validate", ["validate_release", "run_gates", "validate"]),
"diff": ("diff", ["diff_releases", "diff_release", "build_diff", "diff"]),
"build_root": ("build_root", ["build_root", "build_root_datasets", "build"]),
"build_v6": ("build_v6", ["build_v6", "build_v6_candidates", "build"]),
"build_news": ("build_news", ["build_news", "build_news_release", "build_release_folder", "build"]),
}
def load_module(module_name: str):
"""Import automation.repd.<module_name>; None if that module is absent.
A component that exists but has a broken import of its own raises (fail loudly)."""
full = f"{PACKAGE}.{module_name}"
try:
return importlib.import_module(full)
except ModuleNotFoundError as exc:
if exc.name in (full, PACKAGE, "automation"):
return None
raise
def find_component(stage: str) -> tuple[Callable | None, str]:
"""Generic probe: return (callable, "module.func") or (None, reason)."""
module_name, candidates = STAGES[stage]
full = f"{PACKAGE}.{module_name}"
module = load_module(module_name)
if module is None:
return None, f"module {full} not present"
for name in candidates:
fn = getattr(module, name, None)
if callable(fn):
return fn, f"{full}.{name}"
return None, f"module {full} has none of {candidates}"
def call_component(fn: Callable, pool: dict[str, Any]) -> Any:
"""Call fn with the subset of ``pool`` its signature accepts.
Aliases let components choose natural parameter names. A required parameter that
cannot be satisfied is an interface mismatch and fails the stage with its name.
"""
sig = inspect.signature(fn)
kwargs: dict[str, Any] = {}
takes_var_kw = any(p.kind is p.VAR_KEYWORD for p in sig.parameters.values())
for name, param in sig.parameters.items():
if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
continue
if name in pool and pool[name] is not None:
kwargs[name] = pool[name]
elif param.default is inspect.Parameter.empty:
raise StageError(
f"interface mismatch: {getattr(fn, '__module__', '?')}.{fn.__name__} needs '{name}', "
f"orchestrator offers {sorted(k for k, v in pool.items() if v is not None)}"
)
if takes_var_kw:
for key, value in pool.items():
kwargs.setdefault(key, value)
return fn(**kwargs)
def normalise_result(result: Any) -> dict[str, Any]:
if result is None:
return {}
if isinstance(result, dict):
return result
if dataclasses.is_dataclass(result):
return dataclasses.asdict(result)
if isinstance(result, (str, os.PathLike)):
return {"path": str(result)}
if isinstance(result, tuple):
return {"result": [str(x) if isinstance(x, os.PathLike) else x for x in result]}
if hasattr(result, "__dict__"):
return dict(vars(result))
return {"result": repr(result)}
def first_path(result: dict[str, Any], *keys: str) -> Path | None:
for key in keys:
value = result.get(key)
if value:
return Path(value)
return None
def common_pool(ctx: RunContext, out_dir: Path) -> dict[str, Any]:
d = ctx.descriptor
return {
"ctx": ctx, "context": ctx,
"descriptor": d, "release": d, "config": d, "release_descriptor": d,
"label": ctx.label, "release_label": ctx.label, "release_id": ctx.label,
"release_folder": ctx.folder, "folder_id": ctx.folder,
"repo_root": ctx.repo_root, "repo": ctx.repo_root, "root": ctx.repo_root,
"out_dir": out_dir, "out": out_dir, "output_dir": out_dir, "staging_dir": out_dir,
"offline": ctx.offline, "fetcher": ctx.fetcher,
}
# ------------------------------------------------------------------- hash guard
def iter_protected(repo_root: Path, globs: list[str]) -> list[str]:
seen: set[str] = set()
for pattern in globs:
for path in repo_root.glob(pattern):
if path.is_file() and not path.is_symlink():
seen.add(path.relative_to(repo_root).as_posix())
return sorted(seen)
def hash_manifest(repo_root: Path, globs: list[str]) -> dict[str, Any]:
files = {rel: sha256_file(repo_root / rel) for rel in iter_protected(repo_root, globs)}
return {"generated_utc": utc_now(), "repo_root": str(repo_root), "globs": globs,
"file_count": len(files), "files": files}
def compare_manifests(before: dict[str, Any], after: dict[str, Any]) -> dict[str, list[str]]:
b, a = before["files"], after["files"]
return {
"changed": sorted(k for k in b.keys() & a.keys() if b[k] != a[k]),
"removed": sorted(b.keys() - a.keys()),
"added_in_protected_area": sorted(a.keys() - b.keys()),
}
def check_known_pins(repo_root: Path) -> list[str]:
problems = []
for rel, prefix in KNOWN_PINS.items():
path = repo_root / rel
if not path.is_file():
continue # sparse checkout or older tree: recorded as absent, not checked
digest = sha256_file(path)
if not digest.startswith(prefix):
problems.append(f"{rel}: sha256 {digest[:16]} does not start with pinned {prefix}")
return problems
# --------------------------------------------------------------- PR path policy
def allowed_new_path_patterns(label: str, folder: str) -> list[str]:
"""Only these NEW repo paths may appear in the candidate PR (fnmatch, '*' crosses '/')."""
if not LABEL_RE.match(label) or not FOLDER_RE.match(folder):
raise StageError(f"refusing unsafe release label/folder {label!r}/{folder!r}")
return [
f"repd-{label}.csv",
f"repd-grid-batteries-{label}.csv",
f"repd-solar-operational-{label}.csv",
f"repd-solar-operational-over-4mw-{label}.csv",
f"dist/*_{label}.json",
f"dist/*_{label}_*.json",
f"dist/*_{label}.md",
f"data/repd/{label}/*",
f"docs/repd/releases/{label}/*",
f"uk_renewables_pipeline/{folder}/*",
]
def is_allowed_new_path(rel: str, label: str, folder: str) -> bool:
if rel.startswith("/") or ".." in Path(rel).parts or rel.startswith(".github/"):
return False
return any(fnmatch.fnmatchcase(rel, pat) for pat in allowed_new_path_patterns(label, folder))
def load_large_file_allowlist(repo_root: Path) -> list[str]:
path = repo_root / LARGE_FILE_ALLOWLIST
if not path.is_file():
return []
patterns = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.split("#", 1)[0].strip()
if line:
patterns.append(line)
return patterns
def large_file_allowed(rel: str, patterns: list[str]) -> bool:
# bash [[ $p == $pat ]] semantics: '*' also matches '/', same as fnmatchcase.
return any(fnmatch.fnmatchcase(rel, pat) for pat in patterns)
def paths_existing_in_repo(repo_root: Path, rels: list[str]) -> set[str]:
"""Paths that already exist on disk or in git HEAD (works with sparse checkouts)."""
existing = {r for r in rels if (repo_root / r).exists()}
for tracked in git_tracked(repo_root, _top_prefixes(rels)):
if tracked in rels:
existing.add(tracked)
return existing
def git_tracked(repo_root: Path, prefixes: list[str]) -> set[str]:
if not prefixes:
return set()
try:
proc = subprocess.run(
["git", "-C", str(repo_root), "ls-tree", "-r", "--name-only", "HEAD", "--", *prefixes],