In this section
- Automation — Renewable Energy Planning Database (REPD) energy-data · globalgrid2050 / automation/repd/run.py lines 380–1079
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 380–1079 of 1377 (continued from section 825) · 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
- release_folder_exists, _top_prefixes, default_fetcher, fallback_detect, read_csv_frame, _ref_column, NotApplicable, _has, _json_load, descriptor_from_config, adapt_detect, adapt_fetch, adapt_clean, adapt_validate, adapt_diff, adapt_build_v6, adapt_build_news, try_adapter, stage_detect, stage_fetch, _reuse_ingest_reconcile, stage_clean, _previous_csv, stage_validate, stage_diff, map_root_name, map_v6_name, _collect_files, _build_stage, stage_build_root
- 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:380-1079 · 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
capture_output=True, text=True, check=True, timeout=300,
)
return set(proc.stdout.splitlines())
except (OSError, subprocess.SubprocessError):
return set() # not a git checkout: filesystem checks only
def release_folder_exists(repo_root: Path, folder: str) -> bool:
rel = f"uk_renewables_pipeline/{folder}"
return (repo_root / rel).exists() or bool(git_tracked(repo_root, [rel]))
def _top_prefixes(rels: list[str]) -> list[str]:
return sorted({r.split("/", 1)[0] if "/" in r else r for r in rels}) or ["."]
# ------------------------------------------------------------- fallback helpers
def default_fetcher(url: str) -> bytes: # pragma: no cover - network
from urllib.request import Request, urlopen
req = Request(url, headers={"User-Agent": "globalgrid2050-repd-release-candidate/1"})
with urlopen(req, timeout=120) as resp:
return resp.read()
def fallback_detect(fetcher: Callable[[str], bytes]) -> dict[str, Any]:
"""Read the gov.uk content API and return the newest REPD CSV/XLSX attachment pair."""
payload = json.loads(fetcher(CONTENT_API).decode("utf-8"))
details = payload.get("details", {})
attachments = details.get("attachments") or details.get("documents") or []
found: dict[str, dict[str, str]] = {}
for att in attachments:
if not isinstance(att, dict):
continue
url = att.get("url") or att.get("file_url") or ""
name = url.rsplit("/", 1)[-1]
match = re.match(r"REPD_Publication_(Q[1-4])_(20\d\d)\.(csv|xlsx)$", name, re.I)
if not match:
continue
quarter, year, ext = match.group(1).upper(), match.group(2), match.group(3).lower()
found.setdefault(f"{year}{quarter.lower()}", {})[ext] = url if url.startswith("http") else "https://www.gov.uk" + url
complete = {k: v for k, v in found.items() if "csv" in v and "xlsx" in v}
if not complete:
raise StageError("detect: no REPD_Publication_Q?_YYYY csv+xlsx pair on the publication page")
latest = max(complete)
return {"label": latest, "csv_url": complete[latest]["csv"], "xlsx_url": complete[latest]["xlsx"],
"public_updated_at": payload.get("public_updated_at"), "all_pairs": complete}
def read_csv_frame(path: Path):
import pandas as pd
raw = path.read_bytes()
for enc in ("utf-8-sig", "cp1252"):
try:
text = raw.decode(enc)
break
except UnicodeDecodeError:
continue
else:
raise StageError(f"{path.name}: neither UTF-8 nor cp1252")
import io
return pd.read_csv(io.StringIO(text), dtype=str, keep_default_na=False)
def _ref_column(frame) -> str:
for col in frame.columns:
if col.strip().lower() in ("ref id", "ref_id", "repd_ref"):
return col
raise StageError("no 'Ref ID' column")
# ------------------------------------------------------- component adapters
# Explicit wiring to the real component entry points (as written by the component
# agents on 2026-11-13). Each adapter takes (module, ctx, out) and returns a result
# dict, or raises NotApplicable to fall through to the generic probe / fallback.
class NotApplicable(Exception):
pass
def _has(mod, *names: str) -> bool:
return all(hasattr(mod, n) for n in names)
def _json_load(path: Path) -> Any:
return json.loads(Path(path).read_text(encoding="utf-8"))
def descriptor_from_config(obj: Any) -> dict[str, Any]:
"""automation.repd.config.ReleaseDescriptor -> the orchestrator's flat dict."""
td = obj.to_dict()
e = td.get("expected") or {}
d = json.loads(json.dumps(KNOWN_RELEASES.get(td["release_id"], {})))
d.update({k: v for k, v in {
"label": td["release_id"], "release_name": td.get("label"), "quarter": td.get("quarter"),
"title": td.get("dataset_title"), "csv_url": td.get("csv_url"), "xlsx_url": td.get("xlsx_url"),
"published": td.get("page_last_updated"), "previous_release_id": td.get("previous_release_id"),
"previous_baseline_path": td.get("baseline_path"),
"expected_csv_sha256": e.get("csv_sha256"), "expected_xlsx_sha256": e.get("xlsx_sha256"),
"expected_csv_bytes": e.get("csv_bytes"), "expected_xlsx_bytes": e.get("xlsx_bytes"),
"expected_rows": e.get("csv_rows"), "expected_unique_refs": e.get("unique_refs"),
"duplicate_refs": e.get("duplicate_refs") or None,
}.items() if v not in (None, "")})
return d
def adapt_detect(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
fetchmod = load_module("fetch")
if not (_has(mod, "detect", "parse_content_api") and fetchmod is not None):
raise NotApplicable
fetcher = ctx.artifacts.get("component_fetcher") or fetchmod.urllib_fetcher()
rep = mod.detect(fetcher, "api", ctx.artifacts.get("config_descriptor"))
write_json(out / "detect_report.json", rep)
det = rep["descriptor"]
res = {"status": rep["status"], "detected_release_id": det["release_id"],
"csv_url": det["csv_url"], "xlsx_url": det["xlsx_url"]}
if det["release_id"] != ctx.label:
res["warning"] = f"newest release on gov.uk is {det['release_id']}, run requested {ctx.label}"
elif rep["status"] == "REPLACED_SAME_QUARTER":
raise StageError("gov.uk now serves different files for this quarter than the pinned descriptor; "
"review the correction and update automation/repd/releases/<id>.json first")
elif rep["status"] == "NO_BASELINE":
cfg = load_module("config")
ctx.artifacts["config_descriptor"] = cfg.ReleaseDescriptor.from_dict(det)
for key in ("csv_url", "xlsx_url"):
ctx.descriptor.setdefault(key, det[key])
return res
def adapt_fetch(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
desc = ctx.artifacts.get("config_descriptor")
if desc is None or not _has(mod, "fetch_release", "local_fetcher", "urllib_fetcher", "file_name"):
raise NotApplicable
if ctx.offline:
if not (ctx.local_csv and ctx.local_xlsx):
raise StageError("--offline needs --csv and --xlsx")
src = out.parent / "offline_src"
src.mkdir(parents=True, exist_ok=True)
for url, local in ((desc.csv_url, ctx.local_csv), (desc.xlsx_url, ctx.local_xlsx)):
shutil.copyfile(local, src / mod.file_name(url))
fetcher = mod.local_fetcher(src)
else:
fetcher = ctx.artifacts.get("component_fetcher") or mod.urllib_fetcher()
receipt = mod.fetch_release(desc, out, fetcher)
paths = {f["role"]: out / f["path"] for f in receipt["files"]}
return {"receipt_status": receipt["status"], "csv_path": str(paths["csv"]), "xlsx_path": str(paths["xlsx"]),
"receipt": str(out / "fetch_receipt.json"), "offline_local_fetcher": ctx.offline}
def adapt_clean(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
if not _has(mod, "main", "clean", "CleaningRejected"):
raise NotApplicable
name = f"REPD_canonical_{ctx.label}.csv"
argv = ["--csv", str(ctx.artifacts["raw_csv"]), "--xlsx", str(ctx.artifacts["raw_xlsx"]),
"--out", str(out), "--output-name", name, "--overwrite"]
for kind in ("csv", "xlsx"):
if ctx.descriptor.get(f"expected_{kind}_sha256"):
argv += [f"--expected-{kind}-sha256", ctx.descriptor[f"expected_{kind}_sha256"]]
code = mod.main(argv)
log_path = out / "cleaning_log.json"
log = _json_load(log_path) if log_path.is_file() else {}
if code != 0:
raise StageError(f"clean.py exit {code}: " + "; ".join(map(str, log.get("reasons", [log.get("status")])))[:2000])
return {"canonical_csv": str(out / name), "cleaning_log": str(log_path),
"cleaning_log_text": str(out / "CLEANING-LOG.txt"),
"rows": (log.get("output") or {}).get("rows"), "output_sha256": (log.get("output") or {}).get("sha256"),
"counts": log.get("counts")}
def adapt_validate(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
if not _has(mod, "run_check", "load_baseline", "baseline_from_csv", "load_known"):
raise NotApplicable
d = ctx.descriptor
bdir = Path(mod.__file__).resolve().parent / "baselines"
bfile = bdir / f"{d.get('previous_release_id')}.json" if d.get("previous_release_id") else None
if bfile and bfile.is_file():
baseline = mod.load_baseline(str(bfile))
elif _previous_csv(ctx):
baseline = mod.baseline_from_csv(str(_previous_csv(ctx)), "previous")
else:
raise StageError("validate: no baseline (automation/repd/baselines/<previous_release_id>.json or a previous CSV)")
kfile = bdir / f"{ctx.label}_known_anomalies.json"
known = mod.load_known(str(kfile)) if kfile.is_file() else {}
kcoord = mod.load_known_coordinates(str(kfile)) if kfile.is_file() and hasattr(mod, "load_known_coordinates") else None
kw = {"known_coordinates": kcoord} if kcoord is not None else {}
exp_raw = {k: v for k, v in {
"rows": d.get("expected_rows"), "unique_refs": d.get("expected_unique_refs"),
"csv_sha256": d.get("expected_csv_sha256"), "xlsx_sha256": d.get("expected_xlsx_sha256"),
"csv_bytes": d.get("expected_csv_bytes"), "xlsx_bytes": d.get("expected_xlsx_bytes"),
"duplicate_refs": d.get("duplicate_refs")}.items() if v is not None}
raw_rep, _ = mod.run_check(str(ctx.artifacts["raw_csv"]), str(ctx.artifacts["raw_xlsx"]), baseline, known,
None, False, False, exp_raw or None, **kw)
n = d.get("expected_unique_refs")
cand_rep, _ = mod.run_check(str(ctx.artifacts["canonical_csv"]), None, baseline, known, None, True, False,
{"rows": n, "unique_refs": n} if n else None, **kw)
raw_path = write_json(out / f"validation_raw_{ctx.label}.json", raw_rep)
cand_path = write_json(out / f"validation_{ctx.label}.json", cand_rep)
failures = [f"raw:{g}" for g in raw_rep["failed_gates"]] + [f"candidate:{g}" for g in cand_rep["failed_gates"]]
return {"ok": not failures, "failures": failures, "baseline": str(bfile) if bfile and bfile.is_file() else "previous CSV",
"known_anomalies": len(known), "raw": {"result": raw_rep["result"], "summary": raw_rep["summary"]},
"candidate": {"result": cand_rep["result"], "summary": cand_rep["summary"]},
"reports": [str(raw_path), str(cand_path)]}
def adapt_diff(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
if not _has(mod, "run", "build_diff", "render_md"):
raise NotApplicable
d = ctx.descriptor
prev = d.get("diff_previous_path")
pid = d.get("previous_release_id")
by_id = ctx.repo_root / "dist" / f"project_identity_{pid}.json" if pid else None
# Previous release's identity registry when it is on main (2026q3 onward), else frozen V6.
prev = (ctx.repo_root / prev if prev else by_id if by_id and by_id.is_file()
else ctx.repo_root / "dist" / "project_identity_v6.json")
if not prev.is_file():
prev = _previous_csv(ctx)
if not prev:
raise StageError("diff: no previous release file")
prev_label = f"{d.get('previous_release_id') or 'previous'} ({prev.name})"
res = mod.run(str(prev), str(ctx.artifacts["canonical_csv"]), str(out), prev_label,
f"{ctx.label} ({d.get('release_name') or d.get('quarter') or ''})".strip())
return {"summary": res.get("summary"), "baseline": str(prev), "markdown": str(out / "changelog.md"),
"json": str(out / "diff.json")}
def adapt_build_v6(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
if not _has(mod, "main", "stability_report"):
raise NotApplicable
desc = ctx.descriptor.get("v6_descriptor")
if desc:
desc = Path(desc)
else:
# releases/ is owned by config.load_all() (one ReleaseDescriptor per file), so the V6
# descriptor belongs in releases_v6/; releases/v6_<id>.json is accepted for now.
here = Path(mod.__file__).resolve().parent
cands = [here / "releases_v6" / f"v6_{ctx.label}.json", here / "releases" / f"v6_{ctx.label}.json"]
desc = next((c for c in cands if c.is_file()), cands[0])
if not desc.is_file():
raise StageError(f"build_v6: no V6 descriptor {desc}")
code = mod.main(["--descriptor", str(desc), "--out", str(out), "--input-root", str(ctx.repo_root),
"--csv", str(ctx.artifacts["raw_csv"]), "--xlsx", str(ctx.artifacts["raw_xlsx"])])
run_json = out / f"build_v6_run_{ctx.label}.json"
if code != 0:
tail = ""
if run_json.is_file():
tail = json.dumps([s for s in _json_load(run_json)["stages"] if s["returncode"]])[:1500]
raise StageError(f"build_v6.py exit {code} {tail}")
files = {f"dist/{p.name}": str(p) for p in sorted((out / "dist").glob("*")) if p.is_file()}
files[f"docs/repd/releases/{ctx.label}/build_v6_run_{ctx.label}.json"] = str(run_json)
canon = out / "data" / f"latest_repd_{ctx.label}_canonical.csv"
if canon.is_file():
ctx.artifacts["v6_canonical"] = canon
ctx.artifacts["v6_manifest"] = out / "dist" / f"manifest_{ctx.label}.json"
return {"files": files, "v6_descriptor": str(desc)}
def adapt_build_news(mod, ctx: RunContext, out: Path) -> dict[str, Any]:
if not _has(mod, "main", "build_identity", "SPINE_LINE_OLD"):
raise NotApplicable
d = ctx.descriptor
manifest = ctx.artifacts.get("v6_manifest")
if not manifest or not Path(manifest).is_file():
raise StageError("build_news needs the V6 source manifest (dist/manifest_<id>.json from build_v6)")
canonical = ctx.artifacts.get("v6_canonical") or ctx.artifacts["canonical_csv"]
parent = d.get("news_parent", "202609082224")
work = out / "repo_copy"
if work.exists():
shutil.rmtree(work)
scripts_src = ctx.code_root / "scripts" if (ctx.code_root / "scripts").is_dir() else ctx.repo_root / "scripts"
shutil.copytree(scripts_src, work / "scripts", ignore=shutil.ignore_patterns("__pycache__"))
shutil.copytree(ctx.repo_root / "uk_renewables_pipeline" / parent, work / "uk_renewables_pipeline" / parent,
symlinks=True)
(work / "dist").mkdir()
cmd = [sys.executable, "-m", f"{PACKAGE}.build_news", "--repo", str(work), "--parent", parent,
"--release", ctx.folder, "--quarter", ctx.label,
"--dataset", d.get("news_dataset") or f"DESNZ Renewable Energy Planning Database {d.get('quarter', ctx.label)}",
"--canonical-csv", str(canonical), "--xlsx", str(ctx.artifacts["raw_xlsx"]),
"--source-manifest", str(manifest), "--scratch", str(out / "scratch"),
"--hash-report", str(out / f"news_hash_report_{ctx.label}.json")]
if d.get("expected_unique_refs"):
cmd += ["--expected-rows", str(d["expected_unique_refs"])]
if ctx.news_accept_expected:
cmd.append("--accept-expected")
edits = ctx.code_root / "automation" / "repd" / "news_inputs" / f"release_text_edits_{ctx.label}.json"
if edits.is_file():
cmd += ["--release-text-edits", str(edits)]
env = dict(os.environ, PYTHONPATH=str(ctx.code_root) + os.pathsep + os.environ.get("PYTHONPATH", ""))
proc = subprocess.run(cmd, cwd=str(ctx.code_root), capture_output=True, text=True, env=env, timeout=3600)
(out / "build_news.log").write_text(proc.stdout + "\n--- stderr ---\n" + proc.stderr, encoding="utf-8")
if proc.returncode != 0:
raise StageError("build_news failed: " + (proc.stderr.strip() or proc.stdout.strip())[-1500:])
release = work / "uk_renewables_pipeline" / ctx.folder
files = {p.relative_to(work).as_posix(): str(p) for p in sorted(release.rglob("*")) if p.is_file()}
files[f"docs/repd/releases/{ctx.label}/news_hash_report_{ctx.label}.json"] = str(out / f"news_hash_report_{ctx.label}.json")
return {"files": files, "parent": parent, "text_edits": str(edits) if edits.is_file() else None,
"accept_expected": ctx.news_accept_expected, "stdout_tail": proc.stdout.strip().splitlines()[-4:]}
ADAPTERS: dict[str, Callable[..., dict[str, Any]]] = {
"detect": adapt_detect, "fetch": adapt_fetch, "clean": adapt_clean, "validate": adapt_validate,
"diff": adapt_diff, "build_v6": adapt_build_v6, "build_news": adapt_build_news,
}
def try_adapter(stage: str, ctx: RunContext, out: Path) -> dict[str, Any] | None:
module = load_module(STAGES[stage][0])
adapter = ADAPTERS.get(stage)
if module is None or adapter is None:
return None
try:
res = adapter(module, ctx, out)
except NotApplicable:
return None
res["impl"] = f"{module.__name__} (adapter {adapter.__name__})"
return res
# ------------------------------------------------------------------- the stages
def stage_detect(ctx: RunContext) -> dict[str, Any]:
d = ctx.descriptor
if ctx.offline:
return {"impl": "offline: release descriptor (no network)", "status_override": "skipped", "label": ctx.label,
"csv_url": d.get("csv_url"), "xlsx_url": d.get("xlsx_url")}
out = ctx.stage_dir("detect")
res = try_adapter("detect", ctx, out)
fn, where = (None, "") if res else find_component("detect")
if res:
pass
elif fn:
res = normalise_result(call_component(fn, common_pool(ctx, out)))
res["impl"] = where
else:
res = fallback_detect(ctx.fetcher or default_fetcher)
res["impl"] = f"run.py fallback_detect ({where})"
for key in ("csv_url", "xlsx_url"):
if res.get(key) and not d.get(key):
d[key] = res[key]
if res.get("label") and res["label"] != ctx.label:
res["warning"] = f"newest release on the page is {res['label']}, run requested {ctx.label}"
write_json(out / "detect.json", res)
return res
def stage_fetch(ctx: RunContext) -> dict[str, Any]:
d = ctx.descriptor
out = ctx.stage_dir("raw")
res = try_adapter("fetch", ctx, out)
fn, where = (None, "") if res else find_component("fetch")
if res:
csv_path, xlsx_path = Path(res["csv_path"]), Path(res["xlsx_path"])
elif fn and not ctx.offline:
res = normalise_result(call_component(fn, common_pool(ctx, out)))
res["impl"] = where
csv_path = first_path(res, "csv_path", "csv", "raw_csv")
xlsx_path = first_path(res, "xlsx_path", "xlsx", "raw_xlsx")
else:
files = {}
for kind, local in (("csv", ctx.local_csv), ("xlsx", ctx.local_xlsx)):
if ctx.offline:
if not local:
raise StageError(f"--offline needs --{kind}")
data = Path(local).read_bytes()
origin = str(local)
else:
url = d.get(f"{kind}_url")
if not url:
raise StageError(f"no {kind}_url in descriptor and detect did not supply one")
data = (ctx.fetcher or default_fetcher)(url)
origin = url
name = f"REPD_{ctx.label}.{kind}" if not local else Path(local).name
target = out / name
target.write_bytes(data)
files[kind] = {"path": str(target), "origin": origin, "bytes": len(data), "sha256": sha256_bytes(data)}
res = {"impl": "run.py offline copy" if ctx.offline else f"run.py urllib fallback ({where})", "files": files}
csv_path, xlsx_path = Path(files["csv"]["path"]), Path(files["xlsx"]["path"])
if not csv_path or not csv_path.is_file() or not xlsx_path or not xlsx_path.is_file():
raise StageError("fetch did not produce both a CSV and an XLSX file")
checks = {}
for kind, path in (("csv", csv_path), ("xlsx", xlsx_path)):
digest = sha256_file(path)
expected = (d.get(f"expected_{kind}_sha256") or "").lower()
checks[kind] = {"path": str(path), "sha256": digest, "expected": expected or None,
"match": (digest == expected) if expected else None}
if expected and digest != expected:
raise StageError(f"{kind} sha256 {digest} != expected {expected}")
ctx.artifacts.update(raw_csv=csv_path, raw_xlsx=xlsx_path)
res["sha256_checks"] = checks
write_json(out / "fetch.json", res)
return res
def _reuse_ingest_reconcile(ctx: RunContext, out: Path) -> dict[str, Any]:
"""Fallback clean: reuse scripts/repd_q3_2026_ingest.reconcile from the repo (October-specific)."""
scripts = ctx.repo_root / "scripts"
if not (scripts / "repd_q3_2026_ingest.py").is_file():
raise StageError("no clean component and scripts/repd_q3_2026_ingest.py not in repo")
if ctx.label != "2026q3":
raise StageError("fallback clean reuses the October-specific ingest script; it refuses other releases")
sys.path.insert(0, str(scripts))
try:
ingest = importlib.import_module("repd_q3_2026_ingest")
finally:
sys.path.remove(str(scripts))
baseline = ctx.previous_csv or (ctx.repo_root / ctx.descriptor.get("previous_baseline_path", "repd.csv"))
canonical, report = ingest.reconcile(
ctx.artifacts["raw_csv"].read_bytes(), ctx.artifacts["raw_xlsx"].read_bytes(),
Path(baseline).read_bytes(), f"previous baseline {Path(baseline).name}", False,
)
log = write_json(out / f"cleaning_log_{ctx.label}.json", report)
if report.get("failures"):
raise StageError("clean (reused ingest) failures: " + "; ".join(report["failures"]))
target = out / f"REPD_canonical_{ctx.label}.csv"
canonical.to_csv(target, index=False, encoding="utf-8-sig")
return {"canonical_csv": str(target), "cleaning_log": str(log), "rows": int(len(canonical)),
"stage_label": report.get("stage")}
def stage_clean(ctx: RunContext) -> dict[str, Any]:
out = ctx.stage_dir("clean")
res = try_adapter("clean", ctx, out)
fn, where = (None, "") if res else find_component("clean")
if res:
pass
elif fn:
pool = common_pool(ctx, out) | {
"csv_path": ctx.artifacts["raw_csv"], "xlsx_path": ctx.artifacts["raw_xlsx"],
"csv": ctx.artifacts["raw_csv"], "xlsx": ctx.artifacts["raw_xlsx"],
"raw_csv": ctx.artifacts["raw_csv"], "raw_xlsx": ctx.artifacts["raw_xlsx"],
}
res = normalise_result(call_component(fn, pool))
res["impl"] = where
else:
res = _reuse_ingest_reconcile(ctx, out)
res["impl"] = f"fallback: scripts/repd_q3_2026_ingest.reconcile ({where})"
canonical = first_path(res, "canonical_csv", "canonical", "csv_path", "path")
if not canonical or not canonical.is_file():
raise StageError("clean did not report an existing canonical_csv")
ctx.artifacts["canonical_csv"] = canonical
log = first_path(res, "cleaning_log", "log_json", "log")
if log:
ctx.artifacts["cleaning_log"] = log
return res
def _previous_csv(ctx: RunContext) -> Path | None:
if ctx.previous_csv:
return Path(ctx.previous_csv)
rel = ctx.descriptor.get("previous_baseline_path")
return (ctx.repo_root / rel) if rel and (ctx.repo_root / rel).is_file() else None
def stage_validate(ctx: RunContext) -> dict[str, Any]:
out = ctx.stage_dir("validate")
canonical = ctx.artifacts["canonical_csv"]
res = try_adapter("validate", ctx, out)
fn, where = (None, "") if res else find_component("validate")
if res:
if not res["ok"]:
raise StageError("validation gates failed: " + "; ".join(res["failures"]))
ctx.artifacts["validation_reports"] = res["reports"]
return res
if fn:
pool = common_pool(ctx, out) | {
"canonical_csv": canonical, "csv_path": canonical, "input_csv": canonical,
"previous_csv": _previous_csv(ctx), "baseline_csv": _previous_csv(ctx),
"raw_xlsx": ctx.artifacts.get("raw_xlsx"), "xlsx_path": ctx.artifacts.get("raw_xlsx"),
}
res = normalise_result(call_component(fn, pool))
res["impl"] = where
ok = res.get("ok", res.get("passed", res.get("pass")))
failures = res.get("failures") or res.get("errors") or []
if ok is False or failures:
write_json(out / "validation.json", res)
raise StageError("validation gates failed: " + "; ".join(map(str, failures))[:2000])
else:
frame = read_csv_frame(canonical)
ref = _ref_column(frame)
refs = frame[ref].str.strip()
failures = []
if len(frame.columns) != 53:
failures.append(f"expected 53 columns, found {len(frame.columns)}")
if (refs == "").any():
failures.append(f"{int((refs == '').sum())} blank Ref IDs")
if refs.duplicated().any():
failures.append(f"{int(refs.duplicated().sum())} duplicate Ref IDs after cleaning")
floor = int(ctx.descriptor.get("row_floor") or 0)
if len(frame) < floor:
failures.append(f"{len(frame)} rows below floor {floor}")
exp = ctx.descriptor.get("expected_unique_refs")
if exp and refs.nunique() != int(exp):
failures.append(f"{refs.nunique()} unique refs != expected {exp}")
res = {"impl": f"run.py minimal gates ({where})", "rows": int(len(frame)),
"columns": int(len(frame.columns)), "unique_refs": int(refs.nunique()),
"row_floor": floor, "failures": failures, "ok": not failures}
write_json(out / "validation.json", res)
if failures:
raise StageError("validation gates failed: " + "; ".join(failures))
write_json(out / "validation.json", res)
ctx.artifacts["validation_json"] = out / "validation.json"
return res
def stage_diff(ctx: RunContext) -> dict[str, Any]:
out = ctx.stage_dir("diff")
prev = _previous_csv(ctx)
if not prev:
return {"impl": "skipped", "note": "no previous baseline available", "status_override": "skipped"}
canonical = ctx.artifacts["canonical_csv"]
res = try_adapter("diff", ctx, out)
fn, where = (None, "") if res else find_component("diff")
if res:
pass
elif fn:
pool = common_pool(ctx, out) | {
"previous_csv": prev, "old_csv": prev, "baseline_csv": prev, "old": prev, "previous": prev,
"current_csv": canonical, "new_csv": canonical, "canonical_csv": canonical, "new": canonical, "current": canonical,
}
res = normalise_result(call_component(fn, pool))
res["impl"] = where
else:
old, new = read_csv_frame(prev), read_csv_frame(canonical)
o = set(old[_ref_column(old)].str.strip())
n = set(new[_ref_column(new)].str.strip())
res = {"impl": f"run.py ref-set diff ({where})", "baseline": str(prev),
"baseline_unique_refs": len(o), "current_unique_refs": len(n),
"added": len(n - o), "removed": len(o - n), "common": len(n & o),
"added_examples": sorted(n - o, key=lambda x: (len(x), x))[:20],
"removed_examples": sorted(o - n, key=lambda x: (len(x), x))[:20]}
md = out / f"diff_{ctx.label}.md"
md.write_text(
f"# REPD {ctx.label} vs {prev.name}\n\nBaseline unique refs: {len(o)}\n\n"
f"Current unique refs: {len(n)}\n\nAdded: {len(n - o)}; removed: {len(o - n)}; common: {len(n & o)}\n",
encoding="utf-8")
res["markdown"] = str(md)
write_json(out / f"diff_{ctx.label}.json", res)
res["json"] = str(out / f"diff_{ctx.label}.json")
ctx.artifacts["diff"] = res
return res
ROOT_NAME_MAP = {
"repd.csv": "repd-{label}.csv",
"repd-grid-batteries.csv": "repd-grid-batteries-{label}.csv",
"repd-solar-operational.csv": "repd-solar-operational-{label}.csv",
"repd-solar-operational-over-4mw.csv": "repd-solar-operational-over-4mw-{label}.csv",
"dist/repd_master.json": "dist/repd_master_{label}.json",
"dist/manifest_v4.json": "dist/manifest_v4_{label}.json",
}
def map_root_name(rel: str, label: str) -> str:
rel = rel.replace("\\", "/")
if rel in ROOT_NAME_MAP:
return ROOT_NAME_MAP[rel].format(label=label)
base = Path(rel).name
if base in ROOT_NAME_MAP:
return ROOT_NAME_MAP[base].format(label=label)
if f"dist/{base}" in ROOT_NAME_MAP:
return ROOT_NAME_MAP[f"dist/{base}"].format(label=label)
return rel
def map_v6_name(rel: str, label: str) -> str:
"""dist/project_identity_v6.json -> dist/project_identity_2026q3.json; labelled names kept."""
rel = rel.replace("\\", "/")
p = Path(rel)
if label in p.name:
return rel if rel.startswith("dist/") else f"dist/{p.name}"
stem = re.sub(r"_v6$", "", p.stem)
return f"dist/{stem}_{label}{p.suffix}"
def _collect_files(res: dict[str, Any], out: Path) -> dict[str, Path]:
"""Return {relative repo path: file} from a build result or, failing that, from out/."""
files = res.get("files") or res.get("outputs") or res.get("written")
mapping: dict[str, Path] = {}
if isinstance(files, dict):
for rel, path in files.items():
mapping[str(rel)] = Path(path)
elif isinstance(files, list):
for item in files:
path = Path(item["path"] if isinstance(item, dict) else item)
if not path.is_absolute():
path = out / path
try:
rel = path.relative_to(out).as_posix()
except ValueError:
rel = path.name
mapping[rel] = path
else:
for path in sorted(out.rglob("*")):
if path.is_file():
mapping[path.relative_to(out).as_posix()] = path
return mapping
def _build_stage(ctx: RunContext, stage: str, mapper: Callable[[str], str]) -> dict[str, Any]:
out = ctx.stage_dir(stage)
res = try_adapter(stage, ctx, out)
if res is None:
fn, where = find_component(stage)
if not fn:
return {"impl": where, "status_override": "missing",
"note": f"component automation/repd/{STAGES[stage][0]}.py not present; nothing built"}
canonical = ctx.artifacts["canonical_csv"]
pool = common_pool(ctx, out) | {
"canonical_csv": canonical, "csv_path": canonical, "input_csv": canonical, "source_csv": canonical,
"previous_csv": _previous_csv(ctx), "diff": ctx.artifacts.get("diff"),
"label_suffix": ctx.label, "suffix": ctx.label, "raw_csv": ctx.artifacts.get("raw_csv"),
"raw_xlsx": ctx.artifacts.get("raw_xlsx"), "xlsx_path": ctx.artifacts.get("raw_xlsx"),
}
res = normalise_result(call_component(fn, pool))
res["impl"] = where
files = _collect_files(res, out)
else:
files = {rel: Path(p) for rel, p in res.pop("files").items()} # adapters give final repo paths
mapper = lambda rel: rel # noqa: E731
staged = {}
for rel, path in files.items():
if not path.is_file():
raise StageError(f"{stage}: reported file {path} does not exist")
staged[mapper(rel)] = str(path)
ctx.artifacts.setdefault("pr_files", {}).update(staged)
res["pr_paths"] = sorted(staged)
return res
def stage_build_root(ctx: RunContext) -> dict[str, Any]:
return _build_stage(ctx, "build_root", lambda rel: map_root_name(rel, ctx.label))
def stage_build_v6(ctx: RunContext) -> dict[str, Any]:
return _build_stage(ctx, "build_v6", lambda rel: map_v6_name(rel, ctx.label))
def stage_build_news(ctx: RunContext) -> dict[str, Any]:
prefix = f"uk_renewables_pipeline/{ctx.folder}/"
def mapper(rel: str) -> str:
rel = rel.replace("\\", "/")
if rel.startswith(prefix):
return rel
rel = re.sub(r"^uk_renewables_pipeline/[^/]+/", "", rel)
if rel.startswith(ctx.folder + "/"):
rel = rel[len(ctx.folder) + 1:]
return prefix + rel
return _build_stage(ctx, "build_news", mapper)
def acceptance_waivers(label: str, base: Path | None = None) -> list[str]:
"""REF:COLUMN cells listed under "acceptance_waive_cells" in baselines/<label>_known_anomalies.json."""
path = (base or Path(__file__).resolve().parent / "baselines") / f"{label}_known_anomalies.json"
if not path.is_file():
return []
cells = json.loads(path.read_text(encoding="utf-8")).get("acceptance_waive_cells") or []
bad = [c for c in cells if not isinstance(c, str) or ":" not in c or not c.split(":", 1)[0].strip()]
if bad:
raise StageError(f"acceptance_waive_cells in {path.name} must be 'REF:COLUMN' strings: {bad}")
return list(cells)
def stage_acceptance(ctx: RunContext) -> dict[str, Any]:
"""Optional end-to-end gate (automation/repd/tests/acceptance.py) on the root-format datasets."""
out = ctx.stage_dir("acceptance")
mod = load_module("tests.acceptance")
if mod is None or not _has(mod, "main"):
return {"impl": "module automation.repd.tests.acceptance not present", "status_override": "skipped"}
pr_files = ctx.artifacts.get("pr_files", {})
names = {key: ROOT_NAME_MAP[src].format(label=ctx.label) for key, src in (
("--full", "repd.csv"), ("--batteries", "repd-grid-batteries.csv"),
("--solar-op", "repd-solar-operational.csv"), ("--over4", "repd-solar-operational-over-4mw.csv"),
("--master", "dist/repd_master.json"))}
if not all(n in pr_files for n in names.values()):
return {"impl": f"{mod.__name__}.main", "status_override": "skipped",
"note": "root-format datasets were not built (build_root missing); nothing to accept"}
root = out / "root"
for rel in names.values():
(root / rel).parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(pr_files[rel], root / rel)
argv = ["--official-csv", str(ctx.artifacts["raw_csv"]), "--official-xlsx", str(ctx.artifacts["raw_xlsx"]),
"--cleaned", str(ctx.artifacts["canonical_csv"]), "--root-dir", str(root),
"--json", str(out / f"acceptance_{ctx.label}.json")]
for flag, rel in names.items():
argv += [flag, rel]
if (ctx.repo_root / "dist" / "repd_master.json").is_file():
argv += ["--baseline-master", str(ctx.repo_root / "dist" / "repd_master.json")]
# Source cells the official CSV cannot carry exactly (e.g. a character outside cp1252 that the
# CSV shows as '?') differ from the workbook by construction. They are listed, reviewed, under
# "acceptance_waive_cells" in baselines/<label>_known_anomalies.json and passed as --waive-cell,
# which acceptance.py reports as waived (never silently). Nothing else is waived.
waivers = acceptance_waivers(ctx.label)
for cell in waivers:
argv += ["--waive-cell", cell]
code = mod.main(argv)
if code != 0:
raise StageError(f"acceptance.py exit {code}; see {out / f'acceptance_{ctx.label}.json'}")
ctx.artifacts.setdefault("validation_reports", []).append(str(out / f"acceptance_{ctx.label}.json"))
return {"impl": f"{mod.__name__}.main", "report": str(out / f"acceptance_{ctx.label}.json"),
"waived_cells": waivers}
def stage_assemble(ctx: RunContext) -> dict[str, Any]: