GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / lightning / tests

Test Unreadable Product and 3 more files

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It makes zip (`make_zip`), makes archive (`make_archive`) and sets up (`setUp`).

626 lines of Python and YAML from lightning, neural-link-between-agents, in 4 files. Topic: Automation and CI. Section 1833 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 Unreadable Product test · lightning / tests/test_unreadable_product.py lines 1–351
  2. Test Workflow test · lightning / tests/test_workflow.py lines 1–155
  3. Operations Index Workflow automation · neural-link-between-agents / .github/workflows/operations-index.yml lines 1–30
  4. Overnight V928 01 Release Workflow automation · neural-link-between-agents / .github/workflows/overnight-v928-01-release.yml lines 1–90

Test Unreadable Product

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It makes zip (`make_zip`), makes archive (`make_archive`) and sets up (`setUp`).

testlightning / tests/test_unreadable_product.py · lines 1–351 of 351 · Entry point · pattern FakeEumetsat (shared by 2 files)

What it does
It tests its inputs. Defines 40 functions or classes, including slot_name, make_zip, good_zip, no_body_zip, corrupt_body_zip. Uses libraries io, json, sys, tempfile, unittest. Side effects: reads or writes files.
Inputs & outputs
In: JSON file rb.json; JSON file status.json; JSON file index.json; JSON file rb-2026-10-20.json; GeoJSON file feed.geojson.
Downstream impact
Used directly by 8 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning); and 4 more.
What it achieves
One unreadable EUMETSAT product must not stop a whole search.
Why it matters
Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by 5 tests, including Test Lightning Workflow.
Application
lightning · tests · test
Uses
Backfill Parallel (import), Collect (import), History (import), Status (import), io, json, sys, tempfile, unittest, zipfile, datetime, pathlib
Used by
run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run), imported by Test Download Retries (import), imported by Test Shard Budget (import), imported by Test Slot Edge (import), imported by Test Slot Span (import)
Produces
slot_name, make_zip, good_zip, no_body_zip, corrupt_body_zip, fake_body, FakeProduct, FakeEumetsat, make_archive, Base, RebuildDayTests, ShardTests
Defines here
slot_name, make_zip, good_zip, no_body_zip, corrupt_body_zip, fake_body, FakeProduct, __init__, __str__, open, FakeEumetsat, __init__, products, __call__, make_archive, Base, setUp, tearDown, rebuild, load, RebuildDayTests, test_zip_without_body_becomes_an_unparsed_slot_and_the_run_carries_on, test_the_incident_product_name_is_recorded_and_does_not_stop_the_day, test_corrupt_netcdf_and_corrupt_zip_are_unparsed_slots_too, products, test_backfill_ingests_the_day_as_partial_with_the_unparsed_slot_unknown, test_up_to_twenty_percent_unparsed_slots_still_succeed, test_more_than_twenty_percent_unparsed_slots_stop_the_date, test_non_retryable_http_and_auth_errors_still_stop, test_persistent_transient_errors_leave_one_unparsed_slot_after_retries
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 tests/test_unreadable_product.py:1-351 · blob 6420c0743610444cc55f28c4d1c235bdcc603b5f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""One unreadable EUMETSAT product must not stop a whole search.

Incident (parallel backfill, shard 2, 2026-09-18): one product ZIP had no BODY
NetCDF, collect.py raised ValueError and the shard stopped, leaving 22 dates
unknown. A per-product CONTENT error (ZIP without BODY, corrupt ZIP, corrupt
NetCDF) now makes that product's 10-minute slot UNPARSED: it is not searched
time (D-3), so the day becomes partial with that slot unknown, never zero, and
the run carries on. Network/auth/rate-limit errors, a missing decoder library,
and a day with more than 20 % unparsed slots still stop the run.

The fake downloader builds real ZIP bytes and goes through the real
``collect.download_products`` / ``decode_product``; only the BODY NetCDF reader
is faked (a JSON stand-in) because CI has no netCDF4. Synthetic features
("TEST-") exist only in temporary directories.
"""
import io
import json
import sys
import tempfile
import unittest
import zipfile
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from unittest import mock

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import backfill_parallel as bp
import collect
import history
import status as status_mod
from collect import build_feature

NOW = datetime(2026, 10, 27, 6, 0, tzinfo=timezone.utc)
TARGET = "2026-10-20"
DAY0 = datetime(2026, 10, 20, tzinfo=timezone.utc)
INCIDENT = ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD-PART-x-x--ARC-x_C_EUMT_20260918003140_L2PF_OPE_"
            "20260918002945_20260918003005_N__O_0003_0000")


def slot_name(start: datetime) -> str:
    end = start + timedelta(minutes=10)
    return ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
            f"{end:%Y%m%d%H%M%S}_L2PF_OPE_{start:%Y%m%d%H%M%S}_{end:%Y%m%d%H%M%S}_N__O_0001_0000")


def make_zip(members: dict) -> bytes:
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as z:
        for name, data in members.items():
            z.writestr(name, data)
    return buf.getvalue()


def good_zip(name: str, flashes) -> bytes:
    body = json.dumps([[lon, lat, t] for lon, lat, t in flashes]).encode()
    return make_zip({f"{name}/EOPMetadata.xml": b"<x/>", f"{name}/{name}_BODY_0001.nc": body,
                     f"{name}/{name}_TRAIL.nc": b"trail"})


def no_body_zip(name: str) -> bytes:
    """The incident: a product ZIP with manifest and TRAIL but no BODY member."""
    return make_zip({f"{name}/EOPMetadata.xml": b"<x/>", f"{name}/{name}_TRAIL.nc": b"trail"})


def corrupt_body_zip(name: str) -> bytes:
    return make_zip({f"{name}/{name}_BODY_0001.nc": b"\x00garbage, not HDF5"})


def fake_body(content: bytes, product_name: str, start: datetime, end: datetime):
    """JSON stand-in for decode_body; garbage raises like netCDF4 does on a corrupt file."""
    try:
        rows = json.loads(content)
    except ValueError:
        raise OSError(-51, "NetCDF: Unknown file format") from None
    out = []
    for i, (lon, lat, t) in enumerate(rows):
        moment = collect.parse_utc(t)
        if start <= moment < end:
            out.append(build_feature(lon, lat, moment, product_name, i))
    return out


class FakeProduct:
    def __init__(self, name, blob=b"", error=None):
        self.name, self.blob, self.error = name, blob, error

    def __str__(self):
        return self.name

    def open(self):
        if self.error:
            raise self.error
        return io.BytesIO(self.blob)


class FakeEumetsat:
    """Fake downloader: one product ZIP per 10-minute slot through the REAL decode path.

    ``no_body``/``corrupt`` are slot indexes whose ZIP lacks a BODY member or has
    a corrupt BODY; ``net_error`` raises on opening that slot (network failure);
    ``extra`` adds whole extra products (name, blob).
    """

    def __init__(self, no_body=(), corrupt=(), net_error=None, extra=(), body_decoder=fake_body):
        self.no_body, self.corrupt, self.net_error = set(no_body), set(corrupt), net_error or {}
        self.extra, self.body_decoder, self.calls = list(extra), body_decoder, []

    def products(self, start, end):
        cursor, i = start, 0
        while cursor < end:
            name = slot_name(cursor)
            if i in self.net_error:
                yield FakeProduct(name, error=self.net_error[i])
            elif i in self.no_body:
                yield FakeProduct(name, no_body_zip(name))
            elif i in self.corrupt:
                yield FakeProduct(name, corrupt_body_zip(name))
            else:
                t = (cursor + timedelta(minutes=3)).isoformat()
                yield FakeProduct(name, good_zip(name, [(-2.0, 52.0, t)] if i % 6 == 0 else []))
            cursor += timedelta(minutes=10)
            i += 1
        for name, blob in self.extra:
            yield FakeProduct(name, blob)

    def __call__(self, start, end):
        self.calls.append((start, end))
        return collect.download_products(self.products(start, end), start, end, body_decoder=self.body_decoder)


def make_archive(root: Path, now: datetime, searched: date) -> None:
    start = datetime.combine(searched, datetime.min.time(), tzinfo=timezone.utc)
    history.archive_observations(
        root, [build_feature(-2.0, 52.0, start + timedelta(hours=2), "TEST-hourly", 0)], now=now,
        scanned_windows=[history.successful_scan((start + timedelta(hours=1)).isoformat(),
                                                 (start + timedelta(hours=7)).isoformat(), 36)],
        lookback_hours=6.0)


class Base(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        self.record = self.base / "rb.json"
        self.sleeps = []  # download retries never really sleep in tests
        patcher = mock.patch.object(collect, "_sleep", self.sleeps.append)
        patcher.start()
        self.addCleanup(patcher.stop)

    def tearDown(self):
        self.temp.cleanup()

    def rebuild(self, fake, day=TARGET):
        return collect.rebuild_day_record(day, self.record, now=NOW, downloader=fake)

    def load(self):
        return json.loads(self.record.read_text())


class RebuildDayTests(Base):
    def test_zip_without_body_becomes_an_unparsed_slot_and_the_run_carries_on(self):
        self.assertEqual(self.rebuild(FakeEumetsat(no_body={3})), 0)
        rec = self.load()
        bad = slot_name(DAY0 + timedelta(minutes=30))
        self.assertEqual(rec["outcome"], "success")
        self.assertIs(rec["slots_parsed"], True)
        self.assertEqual(rec["products_unparsed"], 1)
        self.assertEqual(rec["products_examined"], 143)
        self.assertEqual(rec["slots_examined"], 143)
        [entry] = rec["unparsed_products"]
        self.assertEqual(entry["product"], bad)
        self.assertIn("ZIP contained no BODY NetCDF", entry["reason"])
        self.assertEqual((entry["slot_start_utc"], entry["slot_end_utc"]),
                         ("2026-10-20T00:30:00.000Z", "2026-10-20T00:40:00.000Z"))
        self.assertEqual(rec["unparsed_slots_utc"], ["2026-10-20T00:30:00.000Z"])
        # The unparsed slot is NOT searched time: it is a hole in scanned_ranges.
        self.assertEqual(rec["unscanned_ranges"], [{"start_utc": "2026-10-20T00:30:00.000Z",
                                                    "end_utc": "2026-10-20T00:40:00.000Z"}])
        self.assertEqual(len(rec["features"]), 24)  # flashes of the readable products are kept

    def test_the_incident_product_name_is_recorded_and_does_not_stop_the_day(self):
        fake = FakeEumetsat(extra=[(INCIDENT, no_body_zip(INCIDENT))])
        day = "2026-09-18"
        self.assertEqual(collect.rebuild_day_record(day, self.record, now=NOW, downloader=fake), 0)
        rec = self.load()
        self.assertEqual(rec["outcome"], "success")
        self.assertEqual([e["product"] for e in rec["unparsed_products"]], [INCIDENT])
        self.assertEqual(rec["unparsed_products"][0]["reason"],
                         f"ValueError: {INCIDENT}: ZIP contained no BODY NetCDF")
        # Its 20-second PART slot is covered by readable regular products: nothing left unknown.
        self.assertEqual(rec["unparsed_slots_utc"], [])
        self.assertEqual(rec["unscanned_ranges"], [])

    def test_corrupt_netcdf_and_corrupt_zip_are_unparsed_slots_too(self):
        bad_zip = slot_name(DAY0 + timedelta(hours=5))
        fake = FakeEumetsat(corrupt={10})
        fake.products_orig = fake.products

        def products(start, end):
            for p in fake.products_orig(start, end):
                if str(p) == bad_zip:
                    p.blob = b"PK\x03\x04 truncated"
                yield p
        fake.products = products
        self.rebuild(fake)
        rec = self.load()
        reasons = {e["product"]: e["reason"] for e in rec["unparsed_products"]}
        self.assertEqual(rec["products_unparsed"], 2)
        self.assertIn("NetCDF: Unknown file format", reasons[slot_name(DAY0 + timedelta(minutes=100))])
        self.assertIn("expected EUMETSAT product ZIP", reasons[bad_zip])
        self.assertEqual(len(rec["unscanned_ranges"]), 2)

    def test_backfill_ingests_the_day_as_partial_with_the_unparsed_slot_unknown(self):
        root = self.base / "history"
        make_archive(root, NOW - timedelta(hours=1), date(2026, 10, 26))
        self.rebuild(FakeEumetsat(no_body={3, 4}))
        result = history.backfill_day(root, TARGET, now=NOW, rebuild_record=self.record)
        row = result["row"]
        self.assertEqual(row["coverage"], "partial")
        self.assertEqual(row["scanned_seconds"], 86400 - 1200)
        self.assertEqual(row["count"], 24)
        self.assertEqual(result["unscanned_ranges"], [{"start_utc": "2026-10-20T00:30:00.000Z",
                                                       "end_utc": "2026-10-20T00:50:00.000Z"}])

    def test_up_to_twenty_percent_unparsed_slots_still_succeed(self):
        self.rebuild(FakeEumetsat(no_body=set(range(28))))  # 28/144 = 19.4 %
        rec = self.load()
        self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 28))

    def test_more_than_twenty_percent_unparsed_slots_stop_the_date(self):
        with self.assertRaises(collect.TooManyUnparsed) as caught:
            self.rebuild(FakeEumetsat(no_body=set(range(29))))  # 29/144 = 20.1 %
        self.assertIn("2026-10-20", str(caught.exception))
        self.assertIn("29 of 144", str(caught.exception))
        rec = self.load()
        self.assertEqual(rec["outcome"], "failure")
        self.assertEqual(rec["products_unparsed"], 29)
        self.assertEqual(len(rec["unparsed_products"]), 29)
        self.assertEqual(rec["features"], [])

    def test_non_retryable_http_and_auth_errors_still_stop(self):
        # 401 here: the fake product has no eumdac token to re-request, so it stops too.
        # A 404/410/400 on ONE product is now an unparsed slot (test_download_retries:
        # test_one_product_the_store_will_not_serve_becomes_an_unparsed_slot).
        for error in (RuntimeError("HTTP 401 Unauthorized"), RuntimeError("HTTP 403 Forbidden"),
                      PermissionError("denied")):
            with self.subTest(error=error):
                self.record.unlink(missing_ok=True)
                with self.assertRaises(type(error)):
                    self.rebuild(FakeEumetsat(net_error={7: error}))
                self.assertFalse(self.record.exists() and self.load().get("outcome") == "success")

    def test_persistent_transient_errors_leave_one_unparsed_slot_after_retries(self):
        # Since the download-retry fix: retried, then the slot is unknown and the day carries on.
        for error in (RuntimeError("HTTP 429 Too Many Requests"), RuntimeError("HTTP 503 Service Unavailable"),
                      TimeoutError("read timed out"), ConnectionResetError(104, "Connection reset by peer")):
            with self.subTest(error=error):
                self.assertEqual(self.rebuild(FakeEumetsat(net_error={7: error})), 0)
                rec = self.load()
                self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 1))
                self.assertEqual(rec["unparsed_products"][0]["kind"], "download")

    @unittest.skipIf(__import__("importlib").util.find_spec("netCDF4") is not None, "netCDF4 installed")
    def test_a_missing_netcdf_library_is_not_an_unparsed_product(self):
        with self.assertRaises(ImportError):
            self.rebuild(FakeEumetsat(body_decoder=None))

    @unittest.skipUnless(__import__("importlib").util.find_spec("netCDF4") is not None, "netCDF4 not installed")
    def test_real_netcdf_reader_on_corrupt_body_is_an_unparsed_slot(self):
        fake = FakeEumetsat(corrupt={1})
        fake.products_orig = fake.products
        fake.products = lambda s, e: (p for p in fake.products_orig(s, e) if str(p) == slot_name(DAY0 + timedelta(minutes=10)))
        fake.body_decoder = None
        with self.assertRaises(RuntimeError):  # the only product is unreadable: nothing was searched
            self.rebuild(fake)


class ShardTests(Base):
    def test_shard_and_finalize_fill_the_day_and_surface_the_count_in_status(self):
        root, out, status_path = self.base / "history", self.base / "records", self.base / "status.json"
        make_archive(root, NOW - timedelta(hours=1), date(2026, 10, 26))
        dates = ["2026-10-20", "2026-10-19"]
        fakes = {"2026-10-20": FakeEumetsat(no_body={3}), "2026-10-19": FakeEumetsat()}
        collector = lambda day, record, log, timeout=None: collect.rebuild_day_record(day, record, now=NOW, downloader=fakes[day])
        summary = bp.run_shard(1, dates, out, budget_minutes=290, collector=collector)
        self.assertEqual((summary["stopped"], len(summary["collected"])), ("completed", 2))
        result = bp.finalize(plan_dates=dates, shards=1, records_dir=out, archive_dir=root,
                             status_path=status_path, now=NOW)
        self.assertEqual(result["filled"], dates)
        block = json.loads(status_path.read_text())["backfill"]
        self.assertEqual(block["unparsed_products"], 1)
        self.assertEqual(block["unparsed_products_by_day"], {"2026-10-20": 1})
        rows = {r["date"]: r for r in json.loads((root / "index.json").read_text())["days"]}
        self.assertEqual(rows["2026-10-20"]["coverage"], "partial")
        self.assertEqual(rows["2026-10-19"]["coverage"], "full")

    def test_a_date_over_the_threshold_stops_the_shard_and_stays_unknown(self):
        out = self.base / "records"
        fake = FakeEumetsat(no_body=set(range(40)))
        collector = lambda day, record, log, timeout=None: collect.rebuild_day_record(day, record, now=NOW, downloader=fake)
        summary = bp.run_shard(1, ["2026-10-20", "2026-10-19"], out, budget_minutes=290, collector=collector)
        self.assertEqual(summary["stopped"], "eumetsat_error")
        self.assertEqual(summary["collected"], [])
        self.assertIn("unparsed", summary["error"])
        self.assertFalse((out / "rb-2026-10-20.json").exists())


class HourlyTests(Base):
    def run_main(self, fake, now):
        out, status_path = self.base / "feed.geojson", self.base / "status.json"
        with mock.patch.object(collect, "download", fake):
            code = collect.main(["--hours", "6", "--out", str(out), "--status", str(status_path),
                                 "--history-dir", str(self.base / "history"), "--run-record", str(self.record)],
                                now=now)
        return code, out

    def test_hourly_run_publishes_and_records_the_unparsed_slot(self):
        now = datetime(2026, 10, 20, 12, 5, tzinfo=timezone.utc)
        code, out = self.run_main(FakeEumetsat(no_body={5}), now)
        self.assertEqual(code, 0)
        self.assertTrue(out.exists())
        rec = self.load()
        self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 1))
        self.assertIn("ZIP contained no BODY NetCDF", rec["unparsed_products"][0]["reason"])
        self.assertIn({"start_utc": "2026-10-20T06:55:00.000Z", "end_utc": "2026-10-20T07:05:00.000Z"},
                      rec["unscanned_ranges"])
        self.assertEqual(json.loads(out.read_text())["metadata"]["products_unparsed"], 1)
        status = status_mod.build_status(now=now, previous={}, record=rec, archive_result=None,
                                         collect_outcome="success", archive_outcome="skipped")
        self.assertEqual(status["last_products_unparsed"], 1)
        self.assertEqual(status["last_unparsed_products"][0]["product"], rec["unparsed_products"][0]["product"])

    def test_hourly_run_over_the_threshold_stops_and_leaves_the_feed_alone(self):
        now = datetime(2026, 10, 20, 12, 5, tzinfo=timezone.utc)
        with self.assertRaises(collect.TooManyUnparsed):
            self.run_main(FakeEumetsat(no_body=set(range(10))), now)  # 10 of 36 slots of 2026-10-20
        rec = self.load()
        self.assertEqual(rec["outcome"], "failure")
        self.assertEqual(rec["products_unparsed"], 10)
        self.assertFalse((self.base / "feed.geojson").exists())

    def test_hourly_non_retryable_error_still_stops(self):
        now = datetime(2026, 10, 20, 12, 5, tzinfo=timezone.utc)
        with self.assertRaises(RuntimeError):
            self.run_main(FakeEumetsat(net_error={2: RuntimeError("HTTP 403 Forbidden")}), now)
        self.assertEqual(self.load()["outcome"], "failure")


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

Test Workflow

A test in the tests folder of Lightning that checks History and Status. It sets up (`setUp`) and runs step (`run_step`).

testlightning / tests/test_workflow.py · lines 1–155 of 155 · Entry point · pattern substitute (shared by 2 files)

What it does
It tests its inputs. Defines 14 functions or classes, including step_script, substitute, value, WorkflowShellTests, setUp. Uses libraries os, re, shutil, subprocess, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file status.json; JSON file index.json; JSON file partial.json; command-line arguments. Out: GeoJSON file uk_lightning.geojson; JSON file status.json; JSON file index.json; JSON file partial.json.
Downstream impact
Used directly by 4 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning).
What it achieves
Executes the shell of `update-lightning.yml` steps in throwaway git repositories.
Why it matters
Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by Test Lightning Workflow.
Application
lightning · tests · test
Uses
History (script call), Status (script call), Collect (script call), os, re, shutil, subprocess, sys, tempfile, unittest, pathlib
Used by
run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run)
Produces
step_script, substitute, WorkflowShellTests
Defines here
step_script, substitute, value, WorkflowShellTests, setUp, tearDown, git, run_step, pushed_files, test_status_is_committed_when_data_history_does_not_exist_yet, test_archive_and_status_are_committed_together_after_a_good_run, test_archive_step_runs_verify_after_ingest_and_fails_when_verify_fails, test_failed_archive_step_commits_status_only_and_restores_the_archive, test_surface_step_fails_on_an_integrity_alert_even_when_collect_and_archive_succeed
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 tests/test_workflow.py:1-155 · blob 81ca2cd0c4ca1c7b29f907ffb4719232bc68ee6d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Executes the shell of update-lightning.yml steps in throwaway git repositories.

No network, no EUMETSAT, no GitHub: each test builds a temporary repository
with a local bare 'origin', substitutes the ${{ ... }} expressions the step
uses, and runs the step's script with bash -e (the GitHub Actions default).
"""
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
WORKFLOW = ROOT / ".github" / "workflows" / "update-lightning.yml"
ARCHIVE_COMMIT = "Commit archive and status (archive commit)"
ARCHIVE_STEP = "Append to the one-year UTC archive"
SURFACE_STEP = "Surface collection, archive or integrity failure"


def step_script(name: str) -> str:
    """The literal 'run: |' block of the named step (no YAML library needed)."""
    lines = WORKFLOW.read_text(encoding="utf-8").splitlines()
    start = next(i for i, line in enumerate(lines) if line.strip() == f"- name: {name}")
    run = next(i for i in range(start + 1, len(lines)) if lines[i].strip() == "run: |")
    body, indent = [], None
    for line in lines[run + 1:]:
        if line.strip() and indent is None:
            indent = len(line) - len(line.lstrip())
        if line.strip() and len(line) - len(line.lstrip()) < indent:
            break
        body.append(line[indent:] if line.strip() else "")
    return "\n".join(body) + "\n"


def substitute(script: str, outcomes: dict) -> str:
    def value(match):
        key = match.group(1).strip()
        if key in outcomes:
            return outcomes[key]
        raise KeyError(f"unhandled workflow expression {key}")
    return re.sub(r"\$\{\{\s*([^}]+?)\s*\}\}", value, script)


@unittest.skipUnless(shutil.which("git") and shutil.which("bash"), "git and bash are required")
class WorkflowShellTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        base = Path(self.temp.name)
        self.env = {**os.environ, "HOME": str(base), "GIT_CONFIG_NOSYSTEM": "1",
                    "GIT_AUTHOR_NAME": "test", "GIT_AUTHOR_EMAIL": "test@example.invalid",
                    "GIT_COMMITTER_NAME": "test", "GIT_COMMITTER_EMAIL": "test@example.invalid"}
        self.origin = base / "origin.git"
        self.repo = base / "repo"
        self.git("init", "-q", "--bare", "-b", "main", str(self.origin), cwd=base)
        self.git("init", "-q", "-b", "main", str(self.repo), cwd=base)
        self.git("remote", "add", "origin", str(self.origin))
        (self.repo / "data").mkdir()
        (self.repo / "data" / "uk_lightning.geojson").write_text("{}\n")
        shutil.copytree(ROOT / "ci", self.repo / "ci")
        self.git("add", "-A")
        self.git("commit", "-q", "-m", "initial")
        self.git("push", "-q", "-u", "origin", "main")

    def tearDown(self):
        self.temp.cleanup()

    def git(self, *args, cwd=None):
        return subprocess.run(["git", *args], cwd=cwd or self.repo, env=self.env, check=True,
                              capture_output=True, text=True).stdout

    def run_step(self, name, outcomes, extra_env=None):
        script = substitute(step_script(name), outcomes)
        return subprocess.run(["bash", "-e", "-c", script], cwd=self.repo, env={**self.env, **(extra_env or {})},
                              capture_output=True, text=True)

    def pushed_files(self):
        return set(self.git("ls-tree", "-r", "--name-only", "origin/main").split())

    # --- D-4: the heartbeat is committed before data/history exists ---------------
    def test_status_is_committed_when_data_history_does_not_exist_yet(self):
        (self.repo / "data" / "status.json").write_text('{"last_attempt_outcome": "failure"}\n')
        self.assertFalse((self.repo / "data" / "history").exists())
        done = self.run_step(ARCHIVE_COMMIT, {}, {"ARCHIVE_OUTCOME": "skipped"})
        self.assertEqual(done.returncode, 0, done.stderr)
        self.git("fetch", "-q", "origin")
        self.assertIn("data/status.json", self.pushed_files())

    def test_archive_and_status_are_committed_together_after_a_good_run(self):
        (self.repo / "data" / "status.json").write_text('{"last_attempt_outcome": "success"}\n')
        (self.repo / "data" / "history" / "days").mkdir(parents=True)
        (self.repo / "data" / "history" / "index.json").write_text("{}\n")
        done = self.run_step(ARCHIVE_COMMIT, {}, {"ARCHIVE_OUTCOME": "success"})
        self.assertEqual(done.returncode, 0, done.stderr)
        self.git("fetch", "-q", "origin")
        self.assertTrue({"data/status.json", "data/history/index.json"} <= self.pushed_files())


    # --- verify gate: nothing unverified is committed ---------------------------
    def test_archive_step_runs_verify_after_ingest_and_fails_when_verify_fails(self):
        bin_dir = Path(self.temp.name) / "bin"
        bin_dir.mkdir()
        (bin_dir / "python").symlink_to(sys.executable)
        log = Path(self.temp.name) / "calls.log"
        (self.repo / "history.py").write_text(  # stub: records the sub-command, fails on request
            "import os, sys\n"
            f"open({str(log)!r}, 'a').write(sys.argv[1] + '\\n')\n"
            "sys.exit(1 if os.environ.get('FAIL_' + sys.argv[1].upper()) else 0)\n")
        env = {"PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}", "RUNNER_TEMP": self.temp.name}
        good = self.run_step(ARCHIVE_STEP, {}, env)
        self.assertEqual(good.returncode, 0, good.stderr)
        self.assertEqual(log.read_text().split(), ["ingest", "verify"])
        bad = self.run_step(ARCHIVE_STEP, {}, {**env, "FAIL_VERIFY": "1"})
        self.assertNotEqual(bad.returncode, 0)

    def test_failed_archive_step_commits_status_only_and_restores_the_archive(self):
        history_dir = self.repo / "data" / "history"
        (history_dir / "days").mkdir(parents=True)
        (history_dir / "index.json").write_text('{"committed": true}\n')
        self.git("add", "-A")
        self.git("commit", "-q", "-m", "archive v1")
        self.git("push", "-q")
        (history_dir / "index.json").write_text('{"half": "written"}\n')  # ingest/verify failed mid-way
        (history_dir / "days" / "partial.json").write_text("{}\n")
        (self.repo / "data" / "status.json").write_text('{"archive": {"outcome": "failure"}}\n')
        done = self.run_step(ARCHIVE_COMMIT, {}, {"ARCHIVE_OUTCOME": "failure"})
        self.assertEqual(done.returncode, 0, done.stderr)
        self.git("fetch", "-q", "origin")
        files = self.pushed_files()
        self.assertIn("data/status.json", files)
        self.assertNotIn("data/history/days/partial.json", files)
        self.assertEqual(self.git("show", "origin/main:data/history/index.json"), '{"committed": true}\n')
        self.assertEqual(self.git("status", "--porcelain", "--", "data/history"), "")

    # --- shard_lost: an integrity alert turns the run red after everything is committed ---
    def test_surface_step_fails_on_an_integrity_alert_even_when_collect_and_archive_succeed(self):
        for name in ("status.py", "collect.py"):
            shutil.copy(ROOT / name, self.repo / name)
        ok = {"steps.collect.outcome": "success", "steps.archive.outcome": "success"}
        (self.repo / "data" / "status.json").write_text('{"integrity": {"state": "ok", "alert": null}}\n')
        done = self.run_step(SURFACE_STEP, ok)
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        (self.repo / "data" / "status.json").write_text(
            '{"integrity": {"state": "shard_lost", "alert": "INTEGRITY ALERT: 2026-10-24 lost"}}\n')
        done = self.run_step(SURFACE_STEP, ok)
        self.assertNotEqual(done.returncode, 0)
        self.assertIn("::error::INTEGRITY ALERT: 2026-10-24 lost", done.stdout)
        done = self.run_step(SURFACE_STEP, {**ok, "steps.collect.outcome": "failure"})
        self.assertNotEqual(done.returncode, 0)
        self.assertIn("::error::collect=failure", done.stdout)

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

Operations Index Workflow

A GitHub Actions workflow in Neural Link Between Agents. Runs on push, on pull requests and by hand.

automationneural-link-between-agents / .github/workflows/operations-index.yml · lines 1–30 of 30 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file STATUS.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Validate agent operations index”; runs Validate Operations (`automation/validate_operations.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · .github/workflows · workflow
Uses
Validate Operations (workflow run)
Used by
none found
Produces
none declared
Defines here
Validate agent operations index
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 .github/workflows/operations-index.yml:1-30 · blob 631baec16e90ff96cbc43b0be2376ebe117c9e8c · GitHub at these lines
State
achieves: comment · context: auto · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unknown
name: Validate agent operations index
on:
  pull_request:
    paths:
      - 'STATUS.json'
      - 'OPERATIONS.md'
      - 'automation/validate_operations.py'
      - '.github/workflows/operations-index.yml'
  push:
    branches: [main]
    paths:
      - 'STATUS.json'
      - 'automation/validate_operations.py'
      - '.github/workflows/operations-index.yml'
  workflow_dispatch:
permissions:
  contents: read
concurrency:
  group: operations-index-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true
jobs:
  validate:
    runs-on: ubuntu-latest
    timeout-minutes: 3
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - name: Validate compact index without dependency installation
        run: python3 automation/validate_operations.py

Overnight V928 01 Release Workflow

A GitHub Actions workflow in Neural Link Between Agents. Runs on push and by hand.

automationneural-link-between-agents / .github/workflows/overnight-v928-01-release.yml · lines 1–90 of 90 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'agents'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Overnight five / 01-release / Release contracts and browser”; runs `automation/pipeline_release/verify.py`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
neural-link-between-agents · .github/workflows · workflow
Uses
none found
Used by
none found
Produces
none declared
Defines here
Overnight five / 01-release / Release contracts and browser
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
neural-link-between-agents@598eff3f59afe11738d64cb14cb8befe5e37cdc2 .github/workflows/overnight-v928-01-release.yml:1-90 · blob f2da39978c4d7920560d17df23e117d2f2fc8f5a · GitHub at these lines
State
achieves: comment · context: auto · stage: output · effects: dom, filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
name: Overnight five / 01-release / Release contracts and browser
# Read-only tests on current product main. No auto-merge, publication or unsupported evidence claims.
on:
  workflow_dispatch:
  push:
    branches: [main]
    paths:
      - '.github/workflows/overnight-v928-01-release.yml'
permissions:
  contents: read
concurrency:
  group: overnight-v928-01-release
  cancel-in-progress: false
jobs:
  verify:
    runs-on: ubuntu-latest
    timeout-minutes: 40
    steps:
      - name: Hard UTC timebox - expires 17 November 2026 08:00 UTC
        id: window
        shell: bash
        run: |
          python3 - <<'PY'
          from datetime import datetime, timezone
          import os
          now = datetime.now(timezone.utc)
          active = now < datetime(2026, 11, 17, 8, tzinfo=timezone.utc)
          with open(os.environ['GITHUB_OUTPUT'], 'a') as f:
              f.write('active=' + str(active).lower() + '\n')
          print('ACTIVE' if active else 'EXPIRED_NOT_TESTED', now.isoformat())
          PY
      - name: Read exact current GlobalGrid2050 source
        if: steps.window.outputs.active == 'true'
        uses: actions/checkout@v4
        with:
          repository: Ventusltd/globalgrid2050
          ref: main
          filter: blob:none
          persist-credentials: false
          path: product
          # Frozen pages also load accepted cartridges outside their edition.
          sparse-checkout: |
            automation
            uk_renewables_pipeline
            dist/news
      - uses: actions/setup-python@v5
        if: steps.window.outputs.active == 'true'
        with:
          python-version: '3.12'
      - uses: actions/setup-node@v4
        if: steps.window.outputs.active == 'true'
        with:
          node-version: '22'
      - name: Source identity
        if: steps.window.outputs.active == 'true'
        working-directory: product
        run: git rev-parse HEAD | tee "$RUNNER_TEMP/checkout-sha.txt"
      - name: Install test dependencies
        if: steps.window.outputs.active == 'true'
        working-directory: product
        run: python -m pip install -r automation/news/acquisition/requirements.txt
      - name: Release contracts and browser
        if: steps.window.outputs.active == 'true'
        working-directory: product
        shell: bash
        run: |
          set -euo pipefail
          python -m pytest -q automation/news/tests/test_release_audit.py automation/news/tests/test_release_feature_migrations.py
          python automation/pipeline_release/verify.py --browser --check 2>&1 | tee "$RUNNER_TEMP/overnight-release-verify.log"
      - name: Auditable verdict
        if: always()
        shell: bash
        run: |
          echo '## Release contracts and browser' >> "$GITHUB_STEP_SUMMARY"
          echo "Execution gate: ${{ steps.window.outputs.active }}" >> "$GITHUB_STEP_SUMMARY"
          echo "Job status: ${{ job.status }}" >> "$GITHUB_STEP_SUMMARY"
          echo "Source SHA: $(cat "$RUNNER_TEMP/checkout-sha.txt" 2>/dev/null || echo not-checked-out)" >> "$GITHUB_STEP_SUMMARY"
          echo 'Read-only tests; never a public release or verified project-evidence assertion.' >> "$GITHUB_STEP_SUMMARY"
      - uses: actions/upload-artifact@v4
        if: always() && steps.window.outputs.active == 'true'
        with:
          name: overnight-01-release-receipt
          path: |
            ${{ runner.temp }}/checkout-sha.txt
            ${{ runner.temp }}/overnight-release-verify.log
            ${{ runner.temp }}/v924-links.json
            ${{ runner.temp }}/v927-links.json
            ${{ runner.temp }}/public-receipt.json
          if-no-files-found: ignore
          retention-days: 5