GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / data-gb-electricity / tests

Test Bounded Monthly Update and 5 more files

A test in the tests folder of Data GB Electricity that checks Fetch Elexon API to Parquet Hardened and Fetch Latest Month.

674 lines of YAML and Python from data-gb-electricity, data-grid-gb, in 6 files. Topic: Automation and CI. Section 1697 of 2044.

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

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

In this section

  1. Test Bounded Monthly Update test · data-gb-electricity / tests/test_bounded_monthly_update.py lines 1–277
  2. Datacentre Addresses Workflow automation · data-grid-gb / .github/workflows/datacentre-addresses.yml lines 1–44
  3. Fetch Assets Workflow automation · data-grid-gb / .github/workflows/fetch-assets.yml lines 1–176
  4. Refresh Network Products Workflow automation · data-grid-gb / .github/workflows/refresh_network_products.yml lines 1–83
  5. Renewable Energy Planning Database (REPD) Columnar Workflow automation · data-grid-gb / .github/workflows/repd-columnar.yml lines 1–53
  6. SSEN Substations Workflow automation · data-grid-gb / .github/workflows/ssen-substations.yml lines 1–41

Test Bounded Monthly Update

A test in the tests folder of Data GB Electricity that checks Fetch Elexon API to Parquet Hardened and Fetch Latest Month.

testdata-gb-electricity / tests/test_bounded_monthly_update.py · lines 1–277 of 277 · Entry point · pattern evaluate (shared by 18 files)

What it does
It tests its inputs. Defines 32 functions or classes, including PlanningTests, test_existing_partition_is_frozen, test_repair_is_explicit_in_plan, test_dataset_month_budget_fails_closed, test_month_range_is_calendar_bounded. Uses libraries __future__, datetime, io, json, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: Parquet file data_0.parquet; Parquet file data_1.parquet; JSON file fetch_latest_month_latest.json; CSV file raw.csv.
Downstream impact
Used directly by 2 files: Monthly Update Workflow (data-gb-electricity); Refresh Price Decade Rollup Workflow (data-gb-electricity).
What it achieves
It sets up (`setUp`) and is built from the planning tests class (`PlanningTests`) and the Parquet write tests class (`ParquetWriteTests`). Defines `PlanningTests`, `test_existing_partition_is_frozen`, `test_repair_is_explicit_in_plan` and 29 more.
Why it matters
Run by Monthly Update Workflow and Refresh Price Decade Rollup Workflow.
Application
data-gb-electricity · tests · test
Uses
Fetch Elexon API to Parquet Hardened (sys.path import), Fetch Latest Month (sys.path import), GB Calendar (sys.path import), Monthly Growth Policy (sys.path import), Verify Bounded Growth (sys.path import), __future__, datetime, io, json, subprocess, sys, tempfile, unittest
Used by
run by Monthly Update Workflow (workflow run), run by Refresh Price Decade Rollup Workflow (workflow run)
Produces
PlanningTests, ParquetWriteTests, CheckedInSchemaTests, MonthlyIntegrationTests, GrowthGateTests
Defines here
PlanningTests, test_existing_partition_is_frozen, test_repair_is_explicit_in_plan, test_dataset_month_budget_fails_closed, test_month_range_is_calendar_bounded, test_rows_outside_authorised_month_fail, test_gb_settlement_days_have_46_and_50_periods, test_london_date_crosses_midnight_during_bst, test_settlement_endpoints_get_boundary_buffer_then_filter_to_utc_month, test_api_request_estimate_is_bounded_before_network, ParquetWriteTests, setUp, tearDown, price_row, test_new_partition_uses_verified_pending_write, test_new_partition_refuses_race, test_explicit_repair_removes_stale_shards_only_after_readback, CheckedInSchemaTests, test_every_historical_parquet_file_matches_the_writer_schema, MonthlyIntegrationTests, test_first_run_adds_missing_month_and_second_run_makes_no_api_call, GrowthGateTests, setUp, tearDown, evaluate, test_clean_addition_passes, test_historical_modification_fires, test_unplanned_partition_fires, test_raw_artifact_fires, test_byte_budget_fires
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
data-gb-electricity@e888f35c1a65589b3eb7c78bcc542022bc707298 tests/test_bounded_monthly_update.py:1-277 · blob c3623ae7864295b66ea0e4440f2931560c41abcb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
from __future__ import annotations

import datetime as dt
import io
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock

import pyarrow.parquet as pq

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "pipelines"))

from fetch_elexon_api_to_parquet_hardened import SCHEMAS, period_start_from_date_period, partition_file, write_records
import fetch_latest_month as monthly
from fetch_latest_month import api_bounds, estimated_api_requests, fail_if_outside_month, months_from_range, rows_in_utc_partition_month, shift_month
from gb_calendar import london_date_at, london_midnight_utc
from monthly_growth_policy import build_plan, enforce_plan_bound, writable_plan
from verify_bounded_growth import evaluate_changes


class PlanningTests(unittest.TestCase):
    def test_existing_partition_is_frozen(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            path = root / "prices/year=2026/month=7/data_0.parquet"
            path.parent.mkdir(parents=True)
            path.write_bytes(b"existing")
            plan = build_plan(root, ["prices"], [(2026, 7), (2026, 8)], repair_existing=False)
            self.assertEqual([item["action"] for item in plan], ["SKIP_FROZEN", "ADD_MISSING"])
            self.assertEqual(len(writable_plan(plan)), 1)

    def test_repair_is_explicit_in_plan(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            path = root / "prices/year=2026/month=7/data_0.parquet"
            path.parent.mkdir(parents=True)
            path.write_bytes(b"existing")
            plan = build_plan(root, ["prices"], [(2026, 7)], repair_existing=True)
            self.assertEqual(plan[0]["action"], "REPAIR_EXISTING")

    def test_dataset_month_budget_fails_closed(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            plan = build_plan(Path(tmp), ["fuelinst", "fuelhh", "prices"], [(2026, 7), (2026, 8)], repair_existing=False)
            with self.assertRaisesRegex(RuntimeError, "6 dataset-months exceed"):
                enforce_plan_bound(plan, 5)

    def test_month_range_is_calendar_bounded(self) -> None:
        self.assertEqual(months_from_range(dt.date(2025, 12, 20), dt.date(2026, 2, 1)), [(2025, 12), (2026, 1), (2026, 2)])
        self.assertEqual(shift_month(2026, 1, -1), (2025, 12))

    def test_rows_outside_authorised_month_fail(self) -> None:
        rows = [{"periodStartUTC": "2026-07-31T23:30:00Z"}, {"periodStartUTC": "2026-08-01T00:00:00Z"}]
        with self.assertRaisesRegex(RuntimeError, "1 rows outside"):
            fail_if_outside_month("prices", rows, 2026, 7)

    def test_gb_settlement_days_have_46_and_50_periods(self) -> None:
        spring = dt.date(2026, 3, 29)
        autumn = dt.date(2026, 10, 25)
        self.assertEqual((london_midnight_utc(spring + dt.timedelta(days=1)) - london_midnight_utc(spring)).total_seconds(), 23 * 3600)
        self.assertEqual((london_midnight_utc(autumn + dt.timedelta(days=1)) - london_midnight_utc(autumn)).total_seconds(), 25 * 3600)
        self.assertIsNotNone(period_start_from_date_period(spring.isoformat(), 46))
        self.assertIsNone(period_start_from_date_period(spring.isoformat(), 47))
        self.assertIsNotNone(period_start_from_date_period(autumn.isoformat(), 50))
        self.assertIsNone(period_start_from_date_period(autumn.isoformat(), 51))

    def test_london_date_crosses_midnight_during_bst(self) -> None:
        instant = dt.datetime(2026, 8, 31, 23, 30, tzinfo=dt.timezone.utc)
        self.assertEqual(london_date_at(instant), dt.date(2026, 9, 1))

    def test_settlement_endpoints_get_boundary_buffer_then_filter_to_utc_month(self) -> None:
        self.assertEqual(api_bounds("prices", 2026, 7), (dt.date(2026, 6, 30), dt.date(2026, 8, 1)))
        rows = [
            {"periodStartUTC": "2026-06-30T23:30:00Z"},
            {"periodStartUTC": "2026-07-01T00:00:00Z"},
            {"periodStartUTC": "2026-07-31T23:30:00Z"},
            {"periodStartUTC": "2026-08-01T00:00:00Z"},
        ]
        kept = rows_in_utc_partition_month("prices", rows, 2026, 7)
        self.assertEqual([row["periodStartUTC"] for row in kept], ["2026-07-01T00:00:00Z", "2026-07-31T23:30:00Z"])

    def test_api_request_estimate_is_bounded_before_network(self) -> None:
        self.assertEqual(estimated_api_requests("fuelinst", 2026, 7, 1, 7), 31)
        self.assertEqual(estimated_api_requests("fuelhh", 2026, 7, 1, 7), 5)
        self.assertEqual(estimated_api_requests("prices", 2026, 7, 1, 7), 33)


class ParquetWriteTests(unittest.TestCase):
    def setUp(self) -> None:
        self.old_cwd = Path.cwd()
        self.temp = tempfile.TemporaryDirectory()
        self.root = Path(self.temp.name)
        import os
        os.chdir(self.root)

    def tearDown(self) -> None:
        import os
        os.chdir(self.old_cwd)
        self.temp.cleanup()

    @staticmethod
    def price_row(stamp: str, value: float) -> dict[str, object]:
        return {
            "source": "fixture",
            "settlementDate": dt.date.fromisoformat(stamp[:10]),
            "settlementPeriod": 1,
            "periodStartUTC": dt.datetime.fromisoformat(stamp.replace("Z", "+00:00")),
            "systemBuyPriceGBPperMWh": value,
            "systemSellPriceGBPperMWh": value,
            "netImbalanceVolumeMWh": 0.0,
            "fetchedAtUTC": dt.datetime(2026, 9, 1, tzinfo=dt.timezone.utc),
        }

    def test_new_partition_uses_verified_pending_write(self) -> None:
        result = write_records("prices", [self.price_row("2026-07-01T00:00:00Z", 20.0)], True, refuse_existing=True)
        path = partition_file("prices", 2026, 7)
        self.assertTrue(path.exists())
        self.assertFalse(path.with_name("data_0.parquet.pending").exists())
        self.assertEqual(result["partitions"][0]["readbackValidation"]["duplicateKeyGroups"], 0)

    def test_new_partition_refuses_race(self) -> None:
        path = partition_file("prices", 2026, 7)
        path.parent.mkdir(parents=True)
        path.write_bytes(b"race")
        with self.assertRaisesRegex(RuntimeError, "appeared after planning"):
            write_records("prices", [self.price_row("2026-07-01T00:00:00Z", 20.0)], True, refuse_existing=True)

    def test_explicit_repair_removes_stale_shards_only_after_readback(self) -> None:
        write_records("prices", [self.price_row("2026-07-01T00:00:00Z", 20.0)], True, refuse_existing=True)
        path = partition_file("prices", 2026, 7)
        stale = path.with_name("data_1.parquet")
        stale.write_bytes(path.read_bytes())
        result = write_records("prices", [self.price_row("2026-07-01T00:00:00Z", 30.0)], True, replace_existing=True)
        self.assertFalse(stale.exists())
        self.assertEqual(result["partitions"][0]["writeMode"], "replace-explicit-repair")


class CheckedInSchemaTests(unittest.TestCase):
    def test_every_historical_parquet_file_matches_the_writer_schema(self) -> None:
        patterns = {
            "fuelinst": "generation/dataset=fuelinst/**/*.parquet",
            "fuelhh": "generation/dataset=fuelhh/**/*.parquet",
            "prices": "prices/**/*.parquet",
        }
        checked = 0
        for dataset, pattern in patterns.items():
            files = sorted(ROOT.glob(pattern))
            self.assertTrue(files, f"no checked-in {dataset} fixture files")
            for path in files:
                actual = pq.ParquetFile(path).schema_arrow
                self.assertTrue(
                    actual.equals(SCHEMAS[dataset], check_metadata=False),
                    f"{path} schema differs from the monthly writer: {actual}",
                )
                checked += 1
        self.assertGreaterEqual(checked, 456)


class MonthlyIntegrationTests(unittest.TestCase):
    def test_first_run_adds_missing_month_and_second_run_makes_no_api_call(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            old_cwd = Path.cwd()
            import os
            os.chdir(tmp)
            try:
                inside = ParquetWriteTests.price_row("2025-07-01T00:00:00Z", 20.0)
                outside = ParquetWriteTests.price_row("2025-06-30T23:30:00Z", 10.0)
                argv = [
                    "fetch_latest_month.py", "--apply", "--datasets", "prices",
                    "--start-date", "2025-07-01", "--end-date", "2025-07-31",
                ]
                with mock.patch.object(sys, "argv", argv), mock.patch.object(monthly, "fetch_prices", return_value=[outside, inside]) as fetch, mock.patch.object(sys, "stdout", io.StringIO()):
                    self.assertEqual(monthly.main(), 0)
                    fetch.assert_called_once()
                self.assertTrue(Path("prices/year=2025/month=7/data_0.parquet").exists())
                first = json.loads(Path("reports/fetch_latest_month_latest.json").read_text(encoding="utf-8"))
                self.assertEqual(first["perMonth"]["2025-07"]["prices"]["boundaryRowsDiscarded"], 1)

                with mock.patch.object(sys, "argv", argv), mock.patch.object(monthly, "fetch_prices") as fetch, mock.patch.object(sys, "stdout", io.StringIO()):
                    self.assertEqual(monthly.main(), 0)
                    fetch.assert_not_called()
                second = json.loads(Path("reports/fetch_latest_month_latest.json").read_text(encoding="utf-8"))
                self.assertEqual(second["plan"][0]["action"], "SKIP_FROZEN")
            finally:
                os.chdir(old_cwd)


class GrowthGateTests(unittest.TestCase):
    def setUp(self) -> None:
        self.temp = tempfile.TemporaryDirectory()
        self.root = Path(self.temp.name)
        self.partition = "prices/year=2026/month=8"
        self.path = self.root / self.partition / "data_0.parquet"
        self.path.parent.mkdir(parents=True)
        self.path.write_bytes(b"1234")
        self.audit = {
            "apply": True,
            "mode": "FILL_MISSING",
            "plan": [{"partition": self.partition, "action": "ADD_MISSING"}],
        }

    def tearDown(self) -> None:
        self.temp.cleanup()

    def evaluate(self, changes: list[tuple[str, str]], files: int = 9, size: int = 1024) -> dict[str, object]:
        return evaluate_changes(self.audit, changes, self.root, max_new_parquet_files=files, max_new_parquet_bytes=size)

    def test_clean_addition_passes(self) -> None:
        result = self.evaluate([("A", f"{self.partition}/data_0.parquet")])
        self.assertEqual(result["status"], "PASS")

    def test_historical_modification_fires(self) -> None:
        result = self.evaluate([("M", f"{self.partition}/data_0.parquet")])
        self.assertEqual(result["status"], "FAIL")
        self.assertTrue(any("must only add" in error for error in result["errors"]))

    def test_unplanned_partition_fires(self) -> None:
        result = self.evaluate([("A", "prices/year=2026/month=7/data_0.parquet")])
        self.assertEqual(result["status"], "FAIL")
        self.assertTrue(any("outside the audited plan" in error for error in result["errors"]))

    def test_raw_artifact_fires(self) -> None:
        result = self.evaluate([("A", f"{self.partition}/raw.csv")])
        self.assertEqual(result["status"], "FAIL")
        self.assertTrue(any("non-Parquet" in error for error in result["errors"]))

    def test_byte_budget_fires(self) -> None:
        result = self.evaluate([("A", f"{self.partition}/data_0.parquet")], size=3)
        self.assertEqual(result["status"], "FAIL")
        self.assertTrue(any("bytes exceed" in error for error in result["errors"]))

    def test_identical_explicit_repair_is_a_clean_noop(self) -> None:
        repair = {
            "apply": True,
            "mode": "EXPLICIT_REPAIR",
            "plan": [{"partition": self.partition, "action": "REPAIR_EXISTING"}],
        }
        result = evaluate_changes(repair, [], self.root, max_new_parquet_files=9, max_new_parquet_bytes=1024)
        self.assertEqual(result["status"], "PASS")
        self.assertEqual(result["limits"]["actualChangedParquetFiles"], 0)

    def test_cli_reads_gits_actual_diff(self) -> None:
        with tempfile.TemporaryDirectory() as tmp:
            repo = Path(tmp)
            subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
            subprocess.run(["git", "config", "user.name", "fixture"], cwd=repo, check=True)
            subprocess.run(["git", "config", "user.email", "fixture@example.invalid"], cwd=repo, check=True)
            (repo / "seed.txt").write_text("baseline\n", encoding="utf-8")
            subprocess.run(["git", "add", "seed.txt"], cwd=repo, check=True)
            subprocess.run(["git", "commit", "-q", "-m", "baseline"], cwd=repo, check=True)
            partition = "prices/year=2026/month=8"
            data = repo / partition / "data_0.parquet"
            data.parent.mkdir(parents=True)
            data.write_bytes(b"fixture")
            audit = repo / "reports/fetch_latest_month_latest.json"
            audit.parent.mkdir(parents=True)
            audit.write_text(json.dumps({
                "apply": True,
                "mode": "FILL_MISSING",
                "plan": [{"partition": partition, "action": "ADD_MISSING"}],
            }), encoding="utf-8")
            result = subprocess.run(
                [sys.executable, str(ROOT / "pipelines/verify_bounded_growth.py"), "--audit", str(audit), "--base", "HEAD", "--report", ""],
                cwd=repo,
                text=True,
                capture_output=True,
            )
            self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
            self.assertEqual(json.loads(result.stdout)["status"], "PASS")


if __name__ == "__main__":
    unittest.main()

Datacentre Addresses Workflow

A GitHub Actions workflow in Data Grid GB. Runs on pull requests and by hand.

automationdata-grid-gb / .github/workflows/datacentre-addresses.yml · lines 1–44 of 44 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'datacentre'): 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: DuckDB queries.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Data centre address locations”.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · .github/workflows · workflow
Uses
Test DC Address Locations (workflow run)
Used by
none found
Produces
none declared
Defines here
Data centre address locations
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 .github/workflows/datacentre-addresses.yml:1-44 · blob 8d22cb67b99288860e913f2a239b8b4aff65b322 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
name: Data centre address locations

on:
  workflow_dispatch:
  pull_request:
    paths:
      - 'datacentres/locations/**'
      - 'tests/test_dc_address_locations.py'
      - '.github/workflows/datacentre-addresses.yml'

permissions:
  contents: read

concurrency:
  group: dc-addresses-${{ github.event_name }}-${{ github.ref }}
  cancel-in-progress: false

jobs:
  verify:
    runs-on: ubuntu-24.04
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      - run: python -m pip install duckdb==1.3.2
      - name: Offline synthetic source and location boundaries
        run: python -B -m unittest discover -s tests -p 'test_dc_address_locations.py' -v
      - name: Collect bounded original source facts and build GeoJSON plus Parquet
        if: github.event_name == 'workflow_dispatch'
        run: python -B -m datacentres.locations.pipeline collect --output artifacts/dc-addresses --parquet
      - name: Replay actual captured sources independently offline
        if: github.event_name == 'workflow_dispatch'
        run: |
          python -B -m datacentres.locations.pipeline build --snapshot artifacts/dc-addresses --output artifacts/dc-addresses-replay --parquet
          cmp artifacts/dc-addresses/datacentre-locations.geojson artifacts/dc-addresses-replay/datacentre-locations.geojson
          cmp artifacts/dc-addresses/datacentre-locations.parquet artifacts/dc-addresses-replay/datacentre-locations.parquet
      - uses: actions/upload-artifact@v4
        if: github.event_name == 'workflow_dispatch'
        with:
          name: datacentre-address-source-proof
          path: artifacts/
          if-no-files-found: error

Fetch Assets Workflow

A GitHub Actions workflow in Data Grid GB that builds and publishes the site. Runs by hand.

automationdata-grid-gb / .github/workflows/fetch-assets.yml · lines 1–176 of 176 · Entry point

What it does
It builds and publishes its content. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file reproduction.json; command-line arguments. Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Fetch every data-centre and conventional-generation source for real, by hand.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · .github/workflows · workflow
Uses
Fetch Assets (workflow run), Run Lanes (workflow run), CI Verify (workflow run), Reproduce (workflow run)
Used by
none found
Produces
none declared
Defines here
Fetch the asset sources (manual)
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 .github/workflows/fetch-assets.yml:1-176 · blob 6111d6fe407022741cbce5d292212a2a55337fb8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
# Fetch every data-centre and conventional-generation source for real, by hand.
#
# WHERE THE FETCHERS RUN
#
# The sandbox that wrote the lane scripts cannot reach gov.uk, api.neso.energy,
# Overpass or Wikidata; a GitHub-hosted runner can. So this workflow is the one
# place every fetcher runs against the live sources:
#   assetpipe sources  datacentres/ + conventional/ sources.json   (dukes-5-11 snapshot, ...)
#   DC-A1 fetch_neso.py   NESO TEC + Embedded registers  (licence unverified: only with include_unverified)
#   DC-A2 dc_planning_fetch.py  planning.data.gov.uk, PINS NSIP download, LPA open feeds
#   DC-A3 gov_sites.py    GOV.UK / gov.scot / gov.wales pages behind each record, quotes re-checked
#   DC-A4 dc_a4.py        Overpass + Wikidata SPARQL
#   DC-A5 dno_fetch.py    DNO ECRs and queues: SSEN, NGED, NPg (licence unverified: only with include_unverified)
# then rebuilds every lane offline (DC-A2, DC-A3, DC-A4, DC-A6, then the DC-A7 merge),
# verifies, reproduces, commits raw snapshots + outputs with their sha256 pins
# to a NEW branch and opens a draft pull request with the diff summary. It
# never pushes to main.
#
# WHY THERE IS NO SCHEDULE
#
# The sources move on different clocks (DUKES yearly, WRI frozen since 2021,
# OSM and Wikidata continuously, NESO registers twice weekly) and a changed pin
# is a decision for a person who reads the diff. Add a per-source schedule once
# a source has a published cadence and a named reviewer.
#
# HOW TO RUN (once this file is on the default branch)
#   Actions tab -> "Fetch the asset sources (manual)" -> Run workflow, or
#   gh workflow run fetch-assets.yml --repo Ventusltd/data-grid-gb --ref main \
#     -f domain=all -f include_unverified=false
name: Fetch the asset sources (manual)

on:
  workflow_dispatch:
    inputs:
      domain:
        description: 'datacentres, conventional or all'
        required: true
        default: 'all'
        type: choice
        options: [all, datacentres, conventional]
      include_unverified:
        description: 'also run sources whose licence is unverified (NESO DC-A1, DNO DC-A5); the PR is then marked do-not-merge'
        required: false
        default: false
        type: boolean
      update_pins:
        description: 'accept assetpipe source bytes that differ from the pinned sha256'
        required: false
        default: false
        type: boolean
      open_pr:
        description: 'commit to a new branch fetch/<run id> and open a draft PR (never main)'
        required: false
        default: true
        type: boolean

permissions:
  contents: write
  pull-requests: write

concurrency:
  group: asset-fetch
  cancel-in-progress: false

jobs:
  fetch:
    runs-on: ubuntu-24.04
    timeout-minutes: 60
    env:
      DOMAIN: ${{ inputs.domain }}
      INCLUDE_UNVERIFIED: ${{ inputs.include_unverified }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install -r requirements.txt

      - name: Fetch and pin the registered sources (fully open only)
        env:
          UPDATE_PINS: ${{ inputs.update_pins }}
        run: |
          set -euo pipefail
          args=(fetch "$DOMAIN")
          if [ "$UPDATE_PINS" = "true" ]; then args+=(--update-pins); fi
          if [ "$INCLUDE_UNVERIFIED" = "true" ]; then args+=(--include-unverified); fi
          python pipelines/fetch_assets.py "${args[@]}"

      # A blocked or failing lane fetch is recorded in lanes/MANIFEST.json
      # (last_fetch.codes) and the previous snapshot is kept: unknown, not zero.
      - name: Run the lane fetchers (network)
        run: |
          set -euo pipefail
          args=(fetch "$DOMAIN")
          if [ "$INCLUDE_UNVERIFIED" = "true" ]; then args+=(--include-unverified); fi
          python pipelines/run_lanes.py "${args[@]}"

      - name: Rebuild every lane and normalise (offline)
        run: |
          set -euo pipefail
          args=(build "$DOMAIN")
          if [ "$INCLUDE_UNVERIFIED" = "true" ]; then args+=(--include-unverified); fi
          python pipelines/run_lanes.py "${args[@]}"
          python pipelines/fetch_assets.py normalise "$DOMAIN"

      - name: Verify and reproduce (fail closed)
        env:
          ASSETS_REQUIRE_DEPS: '1'
          ASSETS_REQUIRE_INPUTS: '1'
        run: |
          set -euo pipefail
          if [ "$INCLUDE_UNVERIFIED" = "true" ]; then
            python ci/verify.py --allow-unverified-lanes
          else
            python ci/verify.py
          fi
          python reproduce.py check --json "$RUNNER_TEMP/reproduction.json"

      - name: Summarise
        run: |
          set -euo pipefail
          {
            echo "Manual fetch, run ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID} (domain: ${DOMAIN}, include_unverified: ${INCLUDE_UNVERIFIED})."
            echo
            if [ "$INCLUDE_UNVERIFIED" = "true" ]; then
              echo "**DO NOT MERGE as is: this snapshot includes sources whose licence is unverified. The test workflow fails on it until each is confirmed fully open.**"
              echo
            fi
            python pipelines/run_lanes.py summary "$DOMAIN"
            echo "reproduce.py summary_sha256: \`$(python -c "import json,sys;print(json.load(open(sys.argv[1]))['summary_sha256'])" "$RUNNER_TEMP/reproduction.json")\`"
            echo
            echo '```'
            git add -A -- datacentres conventional
            git diff --cached --stat | tail -40
            echo '```'
            echo
            echo "A failed fetch keeps the previous snapshot; its counts are unknown, not zero. A pipeline entry is not a commitment; IT load MW and grid connection MW are never conflated."
          } > "$RUNNER_TEMP/summary.md"
          cat "$RUNNER_TEMP/summary.md" >> "$GITHUB_STEP_SUMMARY"

      - uses: actions/upload-artifact@v4
        with:
          name: asset-snapshot-${{ github.run_id }}
          path: |
            datacentres/
            conventional/
            ${{ runner.temp }}/reproduction.json
            ${{ runner.temp }}/summary.md
          if-no-files-found: ignore

      # Note: a pull request opened with GITHUB_TOKEN does not trigger other
      # workflows. Verify and reproduce have already run above; to run the
      # test workflow on the PR as well, push any commit to the branch or
      # close and reopen the PR.
      - name: Commit to a review branch and open a draft PR
        if: inputs.open_pr
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          set -euo pipefail
          git add -A -- datacentres conventional
          if git diff --cached --quiet; then
            echo "nothing changed; no branch, no PR"
            exit 0
          fi
          branch="fetch/${GITHUB_RUN_ID}-${DOMAIN}"
          git switch -c "$branch"
          git config user.name  "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git commit -q -m "Asset snapshot from manual fetch run ${GITHUB_RUN_ID} (${DOMAIN})"
          git push origin "$branch"
          title="Asset snapshot: ${DOMAIN}, run ${GITHUB_RUN_ID}"
          if [ "$INCLUDE_UNVERIFIED" = "true" ]; then title="[DO NOT MERGE: unverified licence] ${title}"; fi
          gh pr create --draft --base "${{ github.event.repository.default_branch }}" --head "$branch" \
            --title "$title" --body-file "$RUNNER_TEMP/summary.md" \
          || echo "::warning::could not open the PR (Settings > Actions > 'Allow GitHub Actions to create pull requests' may be off); open it from ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/compare/${branch}?expand=1"

Refresh Network Products Workflow

A GitHub Actions workflow in Data Grid GB that builds and publishes the site. Runs on push, on a schedule and by hand.

automationdata-grid-gb / .github/workflows/refresh_network_products.yml · lines 1–83 of 83 · Entry point

What it does
It builds and publishes its content. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file connection-points.v3.json; JSON file gb-transmission-network.v1.json. Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Rebuild the network products from the pinned public sources.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · .github/workflows · workflow
Uses
Fetch Sources (workflow run), Build Network Model (workflow run), Build Connection Points (workflow run), Verify Connection Points (workflow run)
Used by
none found
Produces
none declared
Defines here
Refresh the GB network products
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 .github/workflows/refresh_network_products.yml:1-83 · blob 0d188b6e9ab8e479fba7c6259c5544ee5559a77c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
# Rebuild the network products from the pinned public sources.
#
# WHY IT IS NOT ON A CLOCK
#
# ETYS is published once a year. A nightly job against an annual
# publication is noise that trains everyone to ignore the one run that
# matters. This fires on a change to the pipelines, on manual dispatch,
# and on a monthly heartbeat that exists to notice when NESO's documents
# move underneath their pinned ids - which is the only thing that can
# quietly break this repository.
#
# The sources are pinned by document id and recorded by SHA-256. If a
# digest changes, the run says so and commits the new products together
# with the new manifest, so the change is visible in one diff rather than
# discovered later in a map.

name: Refresh the GB network products

on:
  workflow_dispatch:
  push:
    branches: [main]
    paths:
      - 'pipelines/**'
      - 'derived/build_connection_points.py'
      - 'derived/verify_connection_points.py'
      - '.github/workflows/refresh_network_products.yml'
  schedule:
    # Monthly, to notice a source that moved under its pinned id.
    - cron: '17 6 1 * *'

permissions:
  contents: write

concurrency:
  group: gb-network-products
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Dependencies
        run: pip install --quiet openpyxl

      - name: Fetch and pin the public sources
        run: python pipelines/fetch_sources.py

      - name: Build the network model and the connection points
        run: |
          python pipelines/build_network_model.py
          python derived/build_connection_points.py

      - name: Verify, fail closed
        run: python derived/verify_connection_points.py

      # The products are arithmetic over the pinned sources. If the sources
      # have not moved, neither have they, and a run that changes nothing
      # should leave no trace.
      - name: Commit only what changed
        run: |
          set -euo pipefail
          git add -- derived sources/sources-manifest.json
          if git diff --cached --quiet; then
            echo "the products are unchanged; nothing to commit"
            exit 0
          fi
          git config user.name  "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          POINTS=$(python -c "import json;print(json.load(open('derived/connection-points.v3.json'))['counts']['connection_points'])")
          CIRCUITS=$(python -c "import json;print(json.load(open('derived/gb-transmission-network.v1.json'))['counts']['circuits'])")
          git commit -m "Refresh the GB network products: ${POINTS} connection points, ${CIRCUITS} circuits

          Derived from the pinned NESO ETYS appendices by pipelines/ and
          derived/. Parameters as published; no power flow is solved."
          git push

Renewable Energy Planning Database (REPD) Columnar Workflow

A GitHub Actions workflow in Data Grid GB. Runs on pull requests and by hand.

automationdata-grid-gb / .github/workflows/repd-columnar.yml · lines 1–53 of 53 · Entry point

What it does
It runs the REPD register. Side effects: 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. Domain terms in the code: the REPD register.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Offline pinned REPD columnar prototype”.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · .github/workflows · workflow
Uses
Test Export (workflow run)
Used by
none found
Produces
none declared
Defines here
Offline pinned REPD columnar prototype
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 .github/workflows/repd-columnar.yml:1-53 · blob 4a60f8ac59dd70e015cc8f7b2ab4f6c38d16bee9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
name: Offline pinned REPD columnar prototype

on:
  pull_request:
    paths:
      - 'repd_columnar/**'
      - '.github/workflows/repd-columnar.yml'
  workflow_dispatch:

permissions:
  contents: read

jobs:
  cpu-readback:
    runs-on: ubuntu-24.04
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
        with:
          path: data-owner
          persist-credentials: false
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
        with:
          repository: Ventusltd/globalgrid2050
          ref: 3a3106e248131f6e430c1ea03b4858d659755303
          path: source-repd
          persist-credentials: false
          sparse-checkout-cone-mode: false
          sparse-checkout: |
            /automation/repd/releases/2026q3.json
            /uk_renewables_pipeline/202611171609/data/v9.1/build_manifest.json
            /uk_renewables_pipeline/202611171609/data/v9.1/projects/*.json
            /uk_renewables_pipeline/202611171609/contracts/release.v9.1.json
            /uk_renewables_pipeline/202611171609/solar1000/manifest.json
            /uk_renewables_pipeline/202611171609/prospecting/manifest.json
      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
        with:
          python-version: '3.13'
      - name: Install pinned CPU dependency (setup uses network)
        run: python -m pip install -r data-owner/repd_columnar/requirements.txt
      - name: Offline synthetic and actual pinned all-row readback tests
        working-directory: data-owner
        env:
          REPD_SOURCE_ROOT: ${{ github.workspace }}/source-repd
        run: python -B -m unittest discover -s repd_columnar/tests -v
      - name: Offline actual export and measured JSON/Parquet workload
        working-directory: data-owner
        run: python -B -m repd_columnar --source-root ../source-repd --out "${{ runner.temp }}/repd-columnar-output" --technology solar --limit 100
      - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        with:
          name: repd-columnar-candidate-proof
          path: ${{ runner.temp }}/repd-columnar-output
          retention-days: 14

SSEN Substations Workflow

A GitHub Actions workflow in Data Grid GB. Runs on push and by hand.

automationdata-grid-gb / .github/workflows/ssen-substations.yml · lines 1–41 of 41 · Entry point

What it does
It runs substations. Side effects: starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'ssen'): 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: substations.
Inputs & outputs
In: DuckDB queries. Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Acquire official SSEN substation register”; runs Fetch (`ssen-substations/fetch.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
data-grid-gb · .github/workflows · workflow
Uses
Fetch (workflow run)
Used by
none found
Produces
none declared
Defines here
Acquire official SSEN substation register
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 .github/workflows/ssen-substations.yml:1-41 · blob ea35c44bef28e219a86783d18934c26c90a50ee7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: process, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: supporting_data
name: Acquire official SSEN substation register
on:
  push:
    branches: [main]
    paths:
      - '.github/workflows/ssen-substations.yml'
      - 'ssen-substations/fetch.py'
  workflow_dispatch:
permissions:
  contents: write
concurrency:
  group: ssen-substations-acquisition
  cancel-in-progress: false
jobs:
  acquire:
    runs-on: ubuntu-24.04
    timeout-minutes: 25
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
        with:
          python-version: '3.12'
      - name: Install pinned DuckDB
        run: python -m pip install duckdb==1.3.2
      - name: Acquire and verify actual records
        run: |
          python -m py_compile ssen-substations/fetch.py
          python ssen-substations/fetch.py --output "$RUNNER_TEMP/ssen-snapshot"
      - name: Publish immutable verified snapshot
        shell: bash
        run: |
          set -euo pipefail
          test "$GITHUB_REF" = refs/heads/main
          target="ssen-substations/$(date -u +%Y%m%d%H%M)-${GITHUB_RUN_ID}"
          test ! -e "$target"
          mkdir "$target"
          cp "$RUNNER_TEMP/ssen-snapshot/"* "$target/"
          git add -- "$target"
          git -c user.name='github-actions[bot]' -c user.email='41898282+github-actions[bot]@users.noreply.github.com' commit -m "Store verified official SSEN substation snapshot"
          git push origin HEAD:main
          git ls-remote --exit-code origin refs/heads/main