In this section
- Fetch Sources storage · data-grid-gb / pipelines/fetch_sources.py lines 1–131
- Run Lanes other · data-grid-gb / pipelines/run_lanes.py lines 1–146
- Data Grid GB — Renewable Energy Planning Database (REPD) Columnar other · data-grid-gb / repd_columnar/__init__.py lines 1–1
- Data Grid GB — Renewable Energy Planning Database (REPD) Columnar other · data-grid-gb / repd_columnar/__main__.py lines 1–3
- Export storage · data-grid-gb / repd_columnar/export.py lines 1–305
Fetch Sources
A Python command-line tool in the pipelines folder of Data Grid GB that fetches grid substations, using SHA-256 from National Energy System Operator (NESO) data portal and the GridAtlas repository.
storagedata-grid-gb / pipelines/fetch_sources.py · lines 1–131 of 131 · Entry point
- What it does
- It fetches grid substations. Defines get, write, main. Uses libraries hashlib, io, json, os, sys. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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: data source: gridatlas data; data source: NESO data portal; GeoJSON file grid_substations.geojson; JSON file sources-manifest.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Refresh Network Products Workflow (data-grid-gb).
- What it achieves
- It is built from the get step (`get`) and the write step (`write`). Fetch the public sources this repository derives from, and pin them. Its code works with 100 MVA.
- Why it matters
- Run by Refresh Network Products Workflow.
- Application
- data-grid-gb · pipelines · Python CLI
- Uses
- hashlib, io, json, os, sys, urllib.request
- Used by
- run by Refresh Network Products Workflow (workflow run)
- Produces
- get, write, main
- Defines here
- get, write, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 pipelines/fetch_sources.py:1-131 · blob d3f065b0a2b324c6533a383d61e48750f6b4af9e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""Fetch the public sources this repository derives from, and pin them.
WHY THIS REPOSITORY EXISTS
--------------------------
The estate already owns prices (Ventusltd/data-gb-electricity). It did not
own the NETWORK, and the consequence showed up on the map: the Atlas drew
projects against OpenStreetMap substations, which know a name and a
location and nothing else. They do not know a circuit's impedance, a
node's fault level, a substation's seasonal rating, or which circuits the
system operator has already published a plan to change. Every one of those
is public, and NESO publishes them.
So this repository owns GB network data: it fetches the published sources,
pins them by SHA-256, derives clean products, and verifies them. Consumers
- the Atlas, Pipeline News - read the products and never the sources, the
same rule that keeps the price repository honest.
WHAT IT FETCHES
---------------
NESO's Electricity Ten Year Statement appendices, published annually:
Appendix B system technical data - the node/branch model itself:
substation code indexes for all four transmission owners,
circuits with R, X, B on a 100 MVA base and seasonal
ratings, transformers, reactive compensation, and the
CHANGES the operator plans out to 2033/34
Appendix D fault levels, peak and minimum, by node and demand year
Appendix A system schematics (reference only, not parsed)
Appendix C power flow diagrams (reference only, not parsed)
and the substation geometry published by the Atlas release, which is the
only place the estate holds coordinates for named substations. ETYS names
sites; it does not locate them. Joining the two is what makes the model
drawable, and the join is reported honestly rather than assumed.
python pipelines/fetch_sources.py
"""
import hashlib
import io
import json
import os
import sys
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.dirname(HERE)
SOURCES = os.path.join(REPO, "sources")
# NESO document ids, read from the ETYS documents and appendices index.
# Pinned deliberately: an id is stable, a "latest" link is not, and a
# product whose inputs can silently change is not a product.
ETYS_EDITION = "2025"
ETYS_DOCUMENTS = {
"appendix-b-system-technical-data": (383936, "xlsx"),
"appendix-d-fault-levels-peak": (383951, "xlsx"),
"appendix-d-fault-levels-minimum": (383961, "xlsx"),
}
# Kept for reference and provenance; large, and not parsed by any build.
ETYS_REFERENCE = {
"appendix-a-system-schematics": (383931, "pdf"),
"appendix-c-power-flow-diagrams": (383946, "pdf"),
}
SUBSTATION_GEOMETRY = (
"https://ventusltd.github.io/gridatlas/atlas/releases/"
"202608300453-atlas-v9/data/grid_substations.geojson"
)
UA = {"User-Agent": "Ventus data-grid-gb (public data fetch)"}
def get(url):
request = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(request, timeout=180) as response:
return response.read()
def write(path, payload):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as handle:
handle.write(payload)
return {
"bytes": len(payload),
"sha256": hashlib.sha256(payload).hexdigest(),
}
def main(include_reference=False):
manifest = {
"schema": "data-grid-gb.sources.v1",
"etys_edition": ETYS_EDITION,
"why_pinned": (
"document ids are stable and 'latest' links are not; a product "
"whose inputs can change without notice is not a product"),
"sources": {},
}
wanted = dict(ETYS_DOCUMENTS)
if include_reference:
wanted.update(ETYS_REFERENCE)
for name, (document_id, extension) in sorted(wanted.items()):
url = f"https://www.neso.energy/document/{document_id}/download"
payload = get(url)
record = write(os.path.join(SOURCES, f"etys-{ETYS_EDITION}-{name}.{extension}"), payload)
record.update({"url": url, "document_id": document_id,
"publisher": "NESO", "extension": extension})
manifest["sources"][name] = record
print(f" {name:<38} {record['bytes']:>9,} bytes {record['sha256'][:16]}")
payload = get(SUBSTATION_GEOMETRY)
record = write(os.path.join(SOURCES, "grid_substations.geojson"), payload)
record.update({
"url": SUBSTATION_GEOMETRY,
"publisher": "OpenStreetMap contributors, via the GridAtlas release",
"note": ("ETYS names substations and does not locate them; this is "
"the only geometry the estate holds for named substations"),
})
manifest["sources"]["substation-geometry"] = record
print(f" {'substation-geometry':<38} {record['bytes']:>9,} bytes {record['sha256'][:16]}")
out = os.path.join(SOURCES, "sources-manifest.json")
io.open(out, "w", encoding="utf-8", newline="\n").write(
json.dumps(manifest, ensure_ascii=False, indent=2) + "\n")
print(f"\nwrote sources/sources-manifest.json ({len(manifest['sources'])} sources)")
return 0
if __name__ == "__main__":
raise SystemExit(main("--with-reference" in sys.argv))Run Lanes
A Python command-line tool in the pipelines folder of Data Grid GB that works with cmd fetch (`cmd_fetch`) and cmd inputs (`cmd_inputs`), using SHA-256.
otherdata-grid-gb / pipelines/run_lanes.py · lines 1–146 of 146 · Entry point · pattern cmd_build (shared by 3 files)
- What it does
- Defines 7 functions or classes, including selected, cmd_fetch, cmd_inputs, cmd_build, cmd_selftest. Uses libraries __future__, argparse, json, sys, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): 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.
- Downstream impact
- Used directly by 4 files: Fetch Assets Workflow (data-grid-gb); Test Assets Workflow (data-grid-gb); Test Lanes (data-grid-gb); Reproduce (data-grid-gb). Reached from 1 other entry point, including Test Assets (data-grid-gb).
- What it achieves
- It is built from the selected step (`selected`), the cmd build helper (`cmd_build`) and the cmd selftest helper (`cmd_selftest`). Run the vendored #73 lane scripts and pin what they produce. It accepts `--lane` and `--include-unverified`.
- Why it matters
- Run by Fetch Assets Workflow and Reproduce. Checked by 2 tests, including Test Assets Workflow.
- Application
- data-grid-gb · pipelines · Python CLI
- Uses
- Data Grid GB — Assetpipe (import), Lanes (import), __future__, argparse, json, sys, pathlib
- Used by
- run by Fetch Assets Workflow (workflow run), run by Test Assets Workflow (workflow run), run by Test Lanes (script call), run by Reproduce (script call)
- Produces
- selected, cmd_fetch, cmd_inputs, cmd_build, cmd_selftest, summary_lines, main
- Defines here
- selected, cmd_fetch, cmd_inputs, cmd_build, cmd_selftest, summary_lines, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 pipelines/run_lanes.py:1-146 · blob 0dad84822f76eda23893e34a442f039557beb89a · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
#!/usr/bin/env python3
"""Run the vendored #73 lane scripts and pin what they produce.
python pipelines/run_lanes.py fetch [all|datacentres|conventional] [--lane ID ...] [--include-unverified]
python pipelines/run_lanes.py inputs [domain] [--lane ID ...] # pinned downloads (url + sha256)
python pipelines/run_lanes.py build [domain] [--lane ID ...] # offline
python pipelines/run_lanes.py selftest [domain] [--lane ID ...] # offline, synthetic fixtures
python pipelines/run_lanes.py manifest [domain] # re-pin every committed lane file
python pipelines/run_lanes.py summary [domain] # markdown summary for a PR body
``fetch`` runs each permitted lane's network commands. A lane is permitted when
``open`` is "yes", or when it is "unverified" and ``--include-unverified`` is given.
A command that fails is recorded in MANIFEST.json (``last_fetch.codes``), and the
run carries on with the next lane. The previous snapshot stays in place, and a
failure never empties an output. ``build`` then rebuilds every lane offline, in
lanes.json order, so the merge lane (DC-A7) runs last. ``manifest`` re-pins the
files.
The exit status is 0 when every build command succeeds. A failed fetch does not
change the exit status: it is reported in the summary, where an unreachable source
shows as unknown, not zero. Any other failure exits 1.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from assetpipe import DOMAINS # noqa: E402
from assetpipe.lanes import (LaneError, allowed, fetch_inputs, lanes_dir, load_lanes, # noqa: E402
read_manifest, retrieved_for, run_commands, today_utc, write_manifest)
def selected(doc: dict, only):
return [lane for lane in doc["lanes"] if not only or lane["id"] in only]
def cmd_fetch(domain, only, include_unverified) -> int:
doc = load_lanes(domain)
fetches = {}
today = today_utc()
for lane in selected(doc, only):
ok, why = allowed(lane, include_unverified)
if not lane.get("fetch"):
continue
if not ok:
print(f" skip {lane['id']}: {why}")
continue
codes = run_commands(lanes_dir(domain) / lane["id"], lane, lane["fetch"], today=today,
retrieved=today)
fetches[lane["id"]] = {"date": today, "codes": codes, "ok": all(c == 0 for c in codes),
"licence_gate": why}
write_manifest(domain, fetches=fetches)
return 0
def cmd_inputs(domain, only) -> int:
for lane in selected(load_lanes(domain), only):
fetch_inputs(lanes_dir(domain) / lane["id"], lane)
return 0
def cmd_build(domain, only, include_unverified) -> int:
doc = load_lanes(domain)
manifest = read_manifest(domain)
failed = False
for lane in selected(doc, only):
ok, why = allowed(lane, include_unverified)
if not lane.get("build"):
continue
if not ok:
print(f" skip {lane['id']}: {why}")
continue
ldir = lanes_dir(domain) / lane["id"]
fetch_inputs(ldir, lane)
codes = run_commands(ldir, lane, lane["build"], today=today_utc(),
retrieved=retrieved_for(manifest, lane["id"]))
failed |= any(codes)
write_manifest(domain)
return 1 if failed else 0
def cmd_selftest(domain, only) -> int:
failed = False
for lane in selected(load_lanes(domain), only):
if lane.get("selftest"):
failed |= any(run_commands(lanes_dir(domain) / lane["id"], lane, lane["selftest"],
today=today_utc(), retrieved="selftest"))
return 1 if failed else 0
def summary_lines(domain) -> list:
doc = load_lanes(domain)
manifest = read_manifest(domain)
lines = [f"### {domain}", "", "| lane | open | last fetch | exit codes | outputs |", "|---|---|---|---|---|"]
for lane in doc["lanes"]:
entry = manifest.get("lanes", {}).get(lane["id"], {})
last = entry.get("last_fetch") or {}
outs = []
for rel in lane.get("outputs", []):
pin = entry.get("files", {}).get(rel)
outs.append(f"`{rel}` {pin['sha256'][:12]}" if pin else f"`{rel}` (none)")
fetched = last.get("date", "never") + ("" if last.get("ok", True) else " **FAILED: unknown, not zero**")
lines.append(f"| {lane['id']} ({lane['lane']}) | {lane['open']} | {fetched} | "
f"{last.get('codes', '-')} | {'<br>'.join(outs)} |")
return lines + [""]
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("command", choices=("fetch", "inputs", "build", "selftest", "manifest", "summary"))
parser.add_argument("domain", nargs="?", default="all", choices=(*DOMAINS, "all"))
parser.add_argument("--lane", action="append", help="limit to this lane id (repeatable)")
parser.add_argument("--include-unverified", action="store_true")
args = parser.parse_args(argv)
domains = DOMAINS if args.domain == "all" else (args.domain,)
status = 0
try:
for domain in domains:
if args.command == "summary":
print("\n".join(summary_lines(domain)))
continue
print(f"{args.command} {domain}")
if args.command == "fetch":
status |= cmd_fetch(domain, args.lane, args.include_unverified)
elif args.command == "inputs":
status |= cmd_inputs(domain, args.lane)
elif args.command == "build":
status |= cmd_build(domain, args.lane, args.include_unverified)
elif args.command == "selftest":
status |= cmd_selftest(domain, args.lane)
else:
write_manifest(domain)
print(json.dumps({k: len(v["files"]) for k, v in read_manifest(domain)["lanes"].items()}))
except LaneError as error:
print(f"::error::{error}")
return 1
return status
if __name__ == "__main__":
raise SystemExit(main())Data Grid GB — Renewable Energy Planning Database (REPD) Columnar
A Python module covering the REPD register.
otherdata-grid-gb / repd_columnar/__init__.py · lines 1–1 of 1 · Not reached from any entry point (candidate for review)
- 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.
- What it achieves
- Offline pinned REPD analytical export; no live importer or source refresh.
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · repd_columnar · Python module
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- 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
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 repd_columnar/__init__.py:1-1 · blob 6742946fd7d191552e2ff5590c64af7f4ffeee87 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""Offline pinned REPD analytical export; no live importer or source refresh."""Data Grid GB — Renewable Energy Planning Database (REPD) Columnar
A Python module.
otherdata-grid-gb / repd_columnar/__main__.py · lines 1–3 of 3 · Not reached from any entry point (candidate for review)
- 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.
- What it achieves
- Entry point only: it runs `main()` from `.export`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · repd_columnar · Python module
- Uses
- Export (relative import)
- Used by
- none found
- Produces
- none declared
- 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
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 repd_columnar/__main__.py:1-3 · blob c79fa26cea6816b83a95a6ff7025294feaeb4554 · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
from .export import main
main()Export
A Python module in the REPD columnar folder of Data Grid GB that reads Renewable Energy Planning Database (REPD), load, benchmark baseline and filtered, using SHA-256.
storagedata-grid-gb / repd_columnar/export.py · lines 1–305 of 305 · pattern load_source (shared by 2 files)
- What it does
- It loads REPD, load, benchmark baseline and filtered. Defines 12 functions or classes, including encoded, sha, git_blob, load_source, _q. Uses libraries argparse, datetime, gzip, hashlib, json. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (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: JSON file build_manifest.json; Parquet file repd.parquet; JSON file source-load.json; JSON file benchmark-baseline.json; JSON file filtered.json; JSON file solar1000-manifest.json; JSON file measurements.json; JSON file v939-source.json. Out: JSON file filtered.json; JSON file solar1000-manifest.json; JSON file measurements.json.
- Downstream impact
- Used directly by 2 files: Data Grid GB — Renewable Energy Planning Database (REPD) Columnar (data-grid-gb); Test Export (data-grid-gb). Reached from 1 other entry point, including Renewable Energy Planning Database (REPD) Columnar Workflow (data-grid-gb).
- What it achieves
- It loads source (`load_source`) and exports product (`export_product`). DuckDB/Parquet prototype preserving the exact frozen canonical records. It accepts `--source-root`, `--pin` and `--out`.
- Why it matters
- Imported by Data Grid GB — Renewable Energy Planning Database (REPD) Columnar. Checked by Test Export.
- Application
- data-grid-gb · repd_columnar · Python module
- Uses
- argparse, datetime, gzip, hashlib, json, math, pathlib, re
- Used by
- imported by Data Grid GB — Renewable Energy Planning Database (REPD) Columnar (relative import), imported by Test Export (import)
- Produces
- encoded, sha, git_blob, load_source, schema_for, filters, projection, measure, export_product, main
- Defines here
- encoded, sha, git_blob, load_source, _q, schema_for, filters, projection, _matches, measure, export_product, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 repd_columnar/export.py:1-305 · blob a021d6374cc53fe610844972b44c6d911d9b1284 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
"""DuckDB/Parquet prototype preserving the exact frozen canonical records.
Source blobs are read from a caller-provided local Git repository at a pinned
commit. Only a new caller-owned output directory is written. No network, source
refresh, scheduled writes, browser engine or live-pointer modification occurs.
"""
import argparse
import datetime as dt
import gzip
import hashlib
import json
import math
from pathlib import Path, PurePosixPath
import re
import subprocess
import time
DATES = {"planning_application_submitted", "repd_record_updated", "operational", "planning_application_withdrawn",
"planning_permission_granted", "planning_permission_refused", "planning_permission_expired", "under_construction"}
TECH = {"solar", "bess", "wind_onshore", "wind_offshore"}
HERE = Path(__file__).resolve().parent
def encoded(value):
return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode()
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def git_blob(root, commit, path):
if not re.fullmatch(r"[0-9a-f]{40}", commit):
raise ValueError("source commit must be an immutable 40-character SHA")
p = PurePosixPath(path)
if p.is_absolute() or ".." in p.parts or "\\" in path or not path or ":" in path:
raise ValueError("unsafe source path")
return subprocess.check_output(["git", "-C", str(root), "show", commit + ":" + path], stderr=subprocess.PIPE)
def load_source(source_root, pin):
if pin.get("schema") != "data-grid-gb.repd-columnar-input.v1":
raise ValueError("invalid input pin schema")
files = pin.get("files")
if not isinstance(files, list) or not files or len({f["path"] for f in files}) != len(files):
raise ValueError("missing or duplicate source pins")
blobs = {}
for f in files:
raw = git_blob(source_root, pin["source_commit"], f["path"])
if len(raw) != f["bytes"] or sha(raw) != f["sha256"]:
raise ValueError("source byte/hash pin mismatch: " + f["path"])
blobs[f["path"]] = raw
base = pin["edition_path"].rstrip("/") + "/"
manifest = json.loads(blobs[base + "data/v9.1/build_manifest.json"])
raw_expected = json.loads(blobs[pin["raw_descriptor_path"]])["expected"]
if any(raw_expected[k] != v for k, v in pin["raw_dataset_hashes"].items()):
raise ValueError("raw dataset hashes disagree with pinned source descriptor")
if manifest["project_count"] != pin["expected_rows"] or manifest["solar_count"] != pin["expected_solar"]:
raise ValueError("wrong canonical population or scope")
if manifest["source_record_count"] != pin["original_source_population"]:
raise ValueError("original source population is a different scope")
rows = []
for part in manifest["project_partitions"]:
raw = blobs[base + part["path"]]
if sha(raw) != part["sha256"]:
raise ValueError("partition disagrees with source build manifest")
document = json.loads(raw)
if document["record_count"] != part["record_count"] or len(document["projects"]) != part["record_count"]:
raise ValueError("partition count mismatch")
rows.extend(document["projects"])
solar = json.loads(blobs[base + "solar1000/manifest.json"])
ids = solar["ids"]
if len(ids) != 1000 or len(set(ids)) != 1000 or ids != sorted(ids, key=int):
raise ValueError("Solar-1000 ordered selection changed")
if solar["record_count"] != pin["expected_rows"] or solar["solar_count"] != pin["expected_solar"]:
raise ValueError("Solar-1000 source scope mismatch")
if sha(blobs[base + "solar1000/manifest.json"]) != pin["solar1000_manifest_sha256"]:
raise ValueError("Solar-1000 seed manifest changed")
if len(rows) != pin["expected_rows"] or sum(r["technology"] == "solar" for r in rows) != pin["expected_solar"]:
raise ValueError("actual rows disagree with pinned scope")
if len({r["repd_ref"] for r in rows}) != len(rows) or len({r["gg_project_id"] for r in rows}) != len(rows):
raise ValueError("duplicate canonical identity")
by_ref = {r["repd_ref"]: r for r in rows}
if any(i not in by_ref or by_ref[i]["technology"] != "solar" for i in ids):
raise ValueError("Solar-1000 identity missing from canonical source")
for r in rows:
if not {"repd_ref", "gg_project_id", "technology", "capacity_mw", "capacity_known", *DATES} <= r.keys():
raise ValueError("missing required canonical field")
if not isinstance(r["repd_ref"], str) or r["gg_project_id"] != "GG2050-REPD-" + r["repd_ref"]:
raise ValueError("canonical ID changed")
cap = r["capacity_mw"]
if cap is not None and (type(cap) not in (int, float) or not math.isfinite(cap)):
raise ValueError("invalid capacity")
if r.get("capacity_known") is False and cap is not None:
raise ValueError("unknown capacity cannot become a numeric value")
for f in DATES:
if r.get(f) is not None and (not isinstance(r[f], str) or dt.date.fromisoformat(r[f]).isoformat() != r[f]):
raise ValueError("date must remain a source calendar day or null")
return rows, solar, blobs, manifest
def _q(name):
return '"' + name.replace('"', '""') + '"'
def schema_for(rows):
keys = sorted(rows[0])
if any(sorted(r) != keys for r in rows):
raise ValueError("heterogeneous record field sets")
if set(keys) & {"source_ordinal", "solar1000_ordinal", "record_json"}:
raise ValueError("reserved column collision")
result = []
for key in keys:
types = {type(r[key]) for r in rows if r[key] is not None}
if key in DATES:
typ = "DATE"
elif not types or types <= {str}:
typ = "VARCHAR"
elif types <= {bool}:
typ = "BOOLEAN"
elif types <= {int}:
typ = "BIGINT"
elif types <= {int, float}:
typ = "DOUBLE"
elif types <= {list, dict}:
typ = "JSON"
else:
raise ValueError("unhandled field types: " + key)
result.append((key, typ))
return result
def filters(technology=None, submitted_year=None, updated_year=None, operational_year=None):
clauses, values = [], []
if technology is not None:
if technology not in TECH:
raise ValueError("unsupported technology")
clauses.append("technology = ?")
values.append(technology)
for field, year in [("planning_application_submitted", submitted_year), ("repd_record_updated", updated_year), ("operational", operational_year)]:
if year is None:
continue
if year == "missing":
clauses.append(_q(field) + " IS NULL")
elif isinstance(year, str) and re.fullmatch(r"[0-9]{4}", year) and 1 <= int(year) <= 9999:
clauses.append("EXTRACT(YEAR FROM " + _q(field) + ") = ?")
values.append(int(year))
else:
raise ValueError("year must be YYYY or missing")
return (" WHERE " + " AND ".join(clauses) if clauses else ""), values
def projection(parquet, limit=100, **query):
import duckdb
if type(limit) is not int or not 1 <= limit <= 1000:
raise ValueError("projection limit must be 1..1000")
where, params = filters(**query)
with duckdb.connect() as db:
total = db.execute("SELECT count(*) FROM read_parquet(?)" + where, [str(parquet), *params]).fetchone()[0]
records = db.execute("SELECT record_json FROM read_parquet(?)" + where + " ORDER BY source_ordinal LIMIT ?", [str(parquet), *params, limit]).fetchall()
return {"schema": "data-grid-gb.repd-filtered-view.v1", "matching_count": total,
"returned_count": len(records), "limit": limit, "truncated": total > len(records),
"rows": [json.loads(r[0]) for r in records]}
def _matches(row, query):
if query.get("technology") is not None and row["technology"] != query["technology"]:
return False
for f, param in [("planning_application_submitted", "submitted_year"), ("repd_record_updated", "updated_year"), ("operational", "operational_year")]:
y = query.get(param)
if y is not None and (row[f] is not None if y == "missing" else not row[f] or row[f][:4] != y):
return False
return True
def measure(json_path, parquet, limit, query):
samples = []
reference = None
for i in range(3):
for mode in (["json", "parquet"] if i % 2 == 0 else ["parquet", "json"]):
start, cpu = time.perf_counter(), time.process_time()
if mode == "json":
rows = json.loads(json_path.read_bytes())
selected = [r for r in rows if _matches(r, query)]
value = {"matching_count": len(selected), "rows": selected[:limit]}
else:
value = projection(parquet, limit=limit, **query)
samples.append({"format": mode, "iteration": i, "elapsed_ms": (time.perf_counter() - start) * 1000,
"cpu_ms": (time.process_time() - cpu) * 1000, "matching_count": value["matching_count"],
"returned_count": len(value["rows"])})
selection = {"matching_count": value["matching_count"], "rows": value["rows"]}
if reference is not None and selection != reference:
raise ValueError("JSON and Parquet measured selections differ")
reference = selection
return {"scope": "One workload; fresh DuckDB connection per Parquet sample; file read/parse/filter/decode included; connection startup included for Parquet",
"cache": "OS file cache uncontrolled; not a cold-cache benchmark; no browser transfer/WASM or GPU speedup claim",
"query": query, "limit": limit, "same_selection": "PASS", "alternating_order": True, "samples": samples}
def export_product(source_root, output, pin, limit=100, **query):
import duckdb
if duckdb.__version__ != "1.3.2":
raise ValueError("prototype requires pinned duckdb==1.3.2")
# Validate inputs/query and output boundaries before creating any output.
filters(**query)
if type(limit) is not int or not 1 <= limit <= 1000:
raise ValueError("projection limit must be 1..1000")
if ".." in Path(output).parts:
raise ValueError("output path traversal is not allowed")
source_root, output = Path(source_root).resolve(), Path(output).resolve()
own_root = HERE.parent.resolve()
if output == source_root or source_root in output.parents or output == own_root or own_root in output.parents:
raise ValueError("output must be caller-owned, outside source and data repositories")
if output.exists():
raise ValueError("refusing to overwrite an existing output path")
ancestor = output.parent
while not ancestor.exists() and ancestor != ancestor.parent:
ancestor = ancestor.parent
inside = subprocess.run(["git", "-C", str(ancestor), "rev-parse", "--is-inside-work-tree"], capture_output=True, text=True)
if inside.returncode == 0 and inside.stdout.strip() == "true":
raise ValueError("output must be outside every Git source/product worktree")
rows, solar, blobs, source_manifest = load_source(source_root, pin)
columns = schema_for(rows)
ranks = {ref: i for i, ref in enumerate(solar["ids"])}
tuples = []
for i, r in enumerate(rows):
values = [json.dumps(r[k], ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) if typ == "JSON" and r[k] is not None else r[k] for k, typ in columns]
tuples.append((i, ranks.get(r["repd_ref"]), *values, encoded(r).decode()))
output.mkdir(parents=True)
parquet = output / "repd.parquet"
load_path = output / "source-load.json"
load_path.write_bytes(encoded([{**r, "source_ordinal": i, "solar1000_ordinal": ranks.get(r["repd_ref"]),
"record_json": encoded(r).decode()} for i, r in enumerate(rows)]))
with duckdb.connect() as db:
definition = "source_ordinal BIGINT PRIMARY KEY, solar1000_ordinal BIGINT," + ",".join(_q(k) + " " + t for k, t in columns) + ",record_json VARCHAR"
db.execute("CREATE TABLE repd(" + definition + ")")
load_columns = {"source_ordinal": "BIGINT", "solar1000_ordinal": "BIGINT", **dict(columns), "record_json": "VARCHAR"}
db.read_json(str(load_path), columns=load_columns).insert_into("repd")
load_path.unlink()
db.sql("SELECT * FROM repd ORDER BY source_ordinal").write_parquet(str(parquet), compression="zstd")
readback = db.execute("SELECT * FROM read_parquet(?,hive_partitioning=false) ORDER BY source_ordinal", [str(parquet)]).fetchall()
if len(readback) != len(tuples):
raise ValueError("Parquet readback row count differs")
for expected, actual, row in zip(tuples, readback, rows):
if actual[0:2] != expected[0:2] or json.loads(actual[-1]) != row:
raise ValueError("record identity/order/complete-field JSON roundtrip differs")
for j, (key, typ) in enumerate(columns, 2):
value = actual[j]
if typ == "DATE" and value is not None:
value = value.isoformat()
if typ == "JSON" and value is not None:
value = json.loads(value)
if value != row[key]:
raise ValueError("typed field roundtrip differs: " + key)
if db.execute("SELECT DISTINCT compression FROM parquet_metadata(?)", [str(parquet)]).fetchall() != [("ZSTD",)]:
raise ValueError("Parquet compression differs")
pilot = db.execute("SELECT repd_ref FROM read_parquet(?) WHERE solar1000_ordinal IS NOT NULL ORDER BY solar1000_ordinal", [str(parquet)]).fetchall()
if [r[0] for r in pilot] != solar["ids"]:
raise ValueError("Solar-1000 order differs")
baseline = output / "benchmark-baseline.json"
baseline.write_bytes(encoded(rows))
filtered = projection(parquet, limit=limit, **query)
(output / "filtered.json").write_bytes(encoded(filtered))
solar_raw = blobs[pin["edition_path"] + "/solar1000/manifest.json"]
(output / "solar1000-manifest.json").write_bytes(solar_raw)
measurements = measure(baseline, parquet, limit, query)
(output / "measurements.json").write_bytes(encoded(measurements))
outputs = [{"path": name, "bytes": (output / name).stat().st_size, "sha256": sha((output / name).read_bytes())}
for name in ["repd.parquet", "filtered.json", "solar1000-manifest.json", "benchmark-baseline.json", "measurements.json"]]
source_package_sha = sha(encoded(pin["files"]))
manifest = {"schema": "data-grid-gb.repd-columnar-export.v1", "engine": "duckdb-" + duckdb.__version__,
"source_commit": pin["source_commit"], "edition_path": pin["edition_path"], "source_package_sha256": source_package_sha,
"raw_dataset_hashes": pin["raw_dataset_hashes"], "source_identity_sha256": source_manifest["source_identity_sha256"],
"raw_hash_evidence": "Reference hashes checked against pinned product release descriptor; raw CSV/workbook not fetched or rehashed by this export",
"rows": len(rows), "solar_rows": sum(r["technology"] == "solar" for r in rows), "columns": columns,
"full_row_and_typed_field_readback": "PASS", "solar1000_order_readback": "PASS", "solar1000_manifest_sha256": sha(solar_raw),
"first_seen_last_seen": "Preserved if present; absent in this frozen source and never inferred from REPD update, submission or export time",
"date_precision": "Calendar day (DATE), null preserved; no time zone or instant invented",
"capacity_policy": "Unknown remains null; no default zero", "outputs": outputs,
"output_package_sha256": sha(encoded({"source_package_sha256": source_package_sha, "outputs": outputs})),
"browser_delivery": "Prototype filtered.json only; no current JSON switch or DuckDB-WASM/GPU dependency",
"benchmark_json": "benchmark-baseline.json is offline comparison only, not a browser payload",
"size_context": {"parquet_codec": "ZSTD", "json_file_codec": "uncompressed",
"json_gzip_bytes_reference_only": len(gzip.compress(baseline.read_bytes(), mtime=0)),
"note": "Gzip size is an in-memory reference, not a measured browser transfer or gzip query benchmark"},
"measurements": "measurements.json reports all alternating samples, OS cache uncontrolled"}
(output / "manifest.json").write_bytes(encoded(manifest))
return manifest
def main(argv=None):
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--source-root", required=True, type=Path)
p.add_argument("--pin", type=Path, default=HERE / "pins/v939-source.json")
p.add_argument("--out", required=True, type=Path)
p.add_argument("--limit", type=int, default=100)
p.add_argument("--technology", choices=sorted(TECH))
p.add_argument("--submitted-year")
p.add_argument("--updated-year")
p.add_argument("--operational-year")
args = p.parse_args(argv)
manifest = export_product(args.source_root, args.out, json.loads(args.pin.read_bytes()), limit=args.limit,
technology=args.technology, submitted_year=args.submitted_year,
updated_year=args.updated_year, operational_year=args.operational_year)
print(json.dumps({"rows": manifest["rows"], "solar_rows": manifest["solar_rows"], "outputs": manifest["outputs"]}, indent=2))