GLOBALGRID2050 / EXPLORE CODE

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

Test Backfill Workflow and 1 more file

A test in the tests folder of Lightning that checks History and Collect. It backfills workflow text tests (`BackfillWorkflowTextTests`), backfills workflow shell tests (`BackfillWorkflowShellTests`) and sets up (`setUp`).

490 lines of Python from lightning, in 2 files. Topic: Automation and CI. Section 1823 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 Backfill Workflow test · lightning / tests/test_backfill_workflow.py lines 1–282
  2. Test CI Verify test · lightning / tests/test_ci_verify.py lines 1–208

Test Backfill Workflow

A test in the tests folder of Lightning that checks History and Collect. It backfills workflow text tests (`BackfillWorkflowTextTests`), backfills workflow shell tests (`BackfillWorkflowShellTests`) and sets up (`setUp`).

testlightning / tests/test_backfill_workflow.py · lines 1–282 of 282 · Entry point · pattern test_plan_lists_never_searched_dates_newest_first (shared by 2 files)

What it does
It tests its inputs. Defines 24 functions or classes, including download, step, substitute, value, outputs. Uses libraries json, os, re, shutil, subprocess. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file index.json; JSON file status.json. Out: JSON file status.json.
Downstream impact
Used directly by 6 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning); and 2 more. Reached from 1 other entry point, including Test Shard Budget (lightning).
What it achieves
Executes the shell of `backfill-lightning.yml` in throwaway git repositories.
Why it matters
Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by 3 tests, including Test Lightning Workflow.
Application
lightning · tests · test
Uses
History (import), Collect (import), Grid (script call), Status (script call), json, os, re, shutil, subprocess, sys, tempfile, unittest
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 Backfill Parallel (import), imported by Test Concurrent Writers (import)
Produces
download, step, substitute, outputs, BackfillWorkflowTextTests, BackfillWorkflowShellTests
Defines here
download, step, substitute, value, outputs, BackfillWorkflowTextTests, test_manual_dispatch_only_with_the_three_inputs, test_has_its_own_concurrency_group_so_it_never_queues_the_hourly_feed, group, test_search_step_uses_the_eumetsat_secrets_and_rebuild_day, BackfillWorkflowShellTests, setUp, tearDown, git, run_step, rows, full_run, test_plan_lists_never_searched_dates_newest_first, test_plan_rejects_more_than_31_days_and_an_unfinished_end_date, test_full_backfill_is_one_verified_commit_and_leaves_the_heartbeat_alone, test_rate_limit_stops_cleanly_commits_verified_dates_and_leaves_the_rest_unknown, test_archive_refusal_stops_and_keeps_that_date_unknown, test_time_budget_stops_before_any_search_and_only_warns, test_refuses_to_write_outside_main
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_backfill_workflow.py:1-282 · blob 68b14fb20d317de8acd7e2a5e552c6348185df96 · 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 backfill-lightning.yml in throwaway git repositories.

No network, no EUMETSAT, no GitHub. Each test builds a temporary repository
with a local bare 'origin', a real archive (history.py) and status, and a copy
of collect.py whose ``download`` is replaced by a FAKE downloader (10-minute
slot names, one synthetic "TEST-" flash per date, or a fake 429 rate-limit
error). The real history.py and status.py run unchanged.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from datetime import datetime, time, timedelta, timezone
from pathlib import Path

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

BACKFILL = ROOT / ".github" / "workflows" / "backfill-lightning.yml"
HOURLY = ROOT / ".github" / "workflows" / "update-lightning.yml"
PLAN = "Plan never-searched UTC dates"
SEARCH = "Search and ingest each date"
COMMIT = "Verify and commit backfilled dates (one commit)"
SURFACE = "Surface backfill stop"

FAKE_DOWNLOAD = '''

def download(start, end):  # FAKE (tests only): replaces the EUMETSAT download
    sys.stdin.read()  # a child that drains stdin must not eat the plan the loop reads
    day = start.date().isoformat()
    if day in os.environ.get("FAKE_FAIL_DAYS", "").split(","):
        raise RuntimeError("HTTP 429 Too Many Requests (fake EUMETSAT rate limit)")
    ghost = day in os.environ.get("FAKE_GHOST_DAYS", "").split(",")
    names, cursor, i = [], start, 0
    while cursor < end:
        if not (ghost and i == 5):
            stop = cursor + timedelta(minutes=10)
            names.append("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
                         f"{stop:%Y%m%d%H%M%S}_L2PF_OPE_{cursor:%Y%m%d%H%M%S}_{stop:%Y%m%d%H%M%S}_N__O_0001_0000")
        cursor += timedelta(minutes=10)
        i += 1
    flashes = [build_feature(-2.0, 52.0, start + timedelta(hours=1, minutes=3), "TEST-fake-" + day, 0)]
    if ghost:  # a flash inside the slot the fake search did not examine: history.py must refuse it
        flashes.append(build_feature(-2.0, 52.0, start + timedelta(minutes=55), "TEST-ghost-" + day, 0))
    return flashes, len(names), names

'''


def step(workflow: Path, name: str) -> str:
    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, values: dict) -> str:
    def value(match):
        key = match.group(1).strip()
        if key in values:
            return values[key]
        raise KeyError(f"unhandled workflow expression {key}")
    return re.sub(r"\$\{\{\s*([^}]+?)\s*\}\}", value, script)


def outputs(path: Path) -> dict:
    out, lines, i = {}, path.read_text().splitlines() if path.exists() else [], 0
    while i < len(lines):
        line = lines[i]
        if "<<" in line:
            key, marker = line.split("<<", 1)
            j = lines.index(marker, i + 1)
            out[key] = "\n".join(lines[i + 1:j])
            i = j + 1
            continue
        key, _, val = line.partition("=")
        out[key] = val
        i += 1
    return out


class BackfillWorkflowTextTests(unittest.TestCase):
    """Structure checks without a YAML library (CI's Python has none installed)."""

    def test_manual_dispatch_only_with_the_three_inputs(self):
        text = BACKFILL.read_text()
        on_block = text.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
        self.assertIn("workflow_dispatch:", on_block)
        for trigger in ("schedule:", "push:", "pull_request:", "cron:"):
            self.assertNotIn(trigger, on_block)
        for name in ("end_date:", "days:", "dry_run:"):
            self.assertIn(name, on_block)
        self.assertRegex(on_block, r'days:\n(?:\s+.*\n)*?\s+default: "7"')
        self.assertRegex(on_block, r"dry_run:\n(?:\s+.*\n)*?\s+type: boolean")

    def test_has_its_own_concurrency_group_so_it_never_queues_the_hourly_feed(self):
        def group(path):
            block = path.read_text().split("\nconcurrency:\n", 1)[1].split("\n\n", 1)[0]
            return (re.search(r"group:\s*(\S+)", block).group(1), re.search(r"cancel-in-progress:\s*(\S+)", block).group(1))
        self.assertEqual(group(BACKFILL), ("uk-lightning-backfill", "false"))
        self.assertEqual(group(HOURLY), ("uk-lightning-update", "false"))
        self.assertNotEqual(group(BACKFILL)[0], group(HOURLY)[0])

    def test_search_step_uses_the_eumetsat_secrets_and_rebuild_day(self):
        text = BACKFILL.read_text()
        self.assertIn("${{ secrets.EUMETSAT_CONSUMER_KEY }}", text)
        self.assertIn("${{ secrets.EUMETSAT_CONSUMER_SECRET }}", text)
        script = step(BACKFILL, SEARCH)
        self.assertIn('collect.py --rebuild-day "$D" --run-record "$rec"', script)
        self.assertIn('"$RUNNER_TEMP/rb-$D.json"', script)
        self.assertIn("history.py backfill", script)


@unittest.skipUnless(shutil.which("git") and shutil.which("bash"), "git and bash are required")
class BackfillWorkflowShellTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        base = Path(self.temp.name)
        self.runner_temp = base / "runner"
        self.runner_temp.mkdir()
        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",
                    "RUNNER_TEMP": str(self.runner_temp), "GITHUB_REF": "refs/heads/main",
                    "GITHUB_OUTPUT": str(base / "github_output"), "PYTHONDONTWRITEBYTECODE": "1"}
        bin_dir = base / "bin"
        bin_dir.mkdir()
        (bin_dir / "python").symlink_to(sys.executable)
        self.env["PATH"] = f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"
        self.env.pop("EUMETSAT_CONSUMER_KEY", None)
        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))
        for name in ("history.py", "grid.py", "status.py"):
            shutil.copy(ROOT / name, self.repo / name)
        source = (ROOT / "collect.py").read_text()
        source = source.replace("def download(start: datetime, end: datetime):", "def _real_download(start, end):")
        source = source.replace('\nif __name__ == "__main__":', FAKE_DOWNLOAD + '\nif __name__ == "__main__":')
        (self.repo / "collect.py").write_text(source)
        (self.repo / ".gitignore").write_text("__pycache__/\n")
        shutil.copytree(ROOT / "ci", self.repo / "ci")

        now = datetime.now(timezone.utc)
        self.today = now.date()
        self.days = [(self.today - timedelta(days=n)).isoformat() for n in range(1, 5)]  # d1 newest .. d4
        searched = datetime.combine(self.today - timedelta(days=2), time.min, tzinfo=timezone.utc)
        history.archive_observations(
            self.repo / "data" / "history", [build_feature(-2.0, 52.0, searched + timedelta(hours=2), "TEST-hourly", 0)],
            now=now, scanned_windows=[history.successful_scan((searched + timedelta(hours=1)).isoformat(),
                                                              (searched + timedelta(hours=7)).isoformat(), 36)],
            lookback_hours=6.0)
        self.heartbeat = {"schema": "uk-lightning-status.v1", "written_utc": "2026-10-27T05:18:00.000Z",
                          "health": "ok", "freshness": "ok", "last_attempt_outcome": "success",
                          "consecutive_failures": 0, "last_successful_scan_end_utc": "2026-10-27T05:10:09.000Z",
                          "integrity": {"state": "ok", "alert": None, "lost_days": []},
                          "archive": {"outcome": "success", "archived_observations": 1}}
        (self.repo / "data" / "status.json").write_text(json.dumps(self.heartbeat, indent=1) + "\n")
        self.git("add", "-A")
        self.git("commit", "-q", "-m", "initial archive")
        self.git("push", "-q", "-u", "origin", "main")
        self.base_head = self.git("rev-parse", "HEAD").strip()

    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, extra=None, values=None):
        script = substitute(step(BACKFILL, name), values or {})
        return subprocess.run(["bash", "-e", "-c", script], cwd=self.repo, env={**self.env, **(extra or {})},
                              capture_output=True, text=True)

    def rows(self, ref="origin/main"):
        index = json.loads(self.git("show", f"{ref}:data/history/index.json"))
        return {r["date"]: r for r in index["days"]}

    def full_run(self, extra=None):
        plan = self.run_step(PLAN, {"END_DATE": "", "DAYS": "4"})
        self.assertEqual(plan.returncode, 0, plan.stderr)
        search = self.run_step(SEARCH, extra)
        out = outputs(Path(self.env["GITHUB_OUTPUT"]))
        commit_env = {**(extra or {}), "STOPPED": out.get("stopped", ""), "ERROR": out.get("error", "")}
        commit = self.run_step(COMMIT, commit_env) if search.returncode == 0 else None
        surface = self.run_step(SURFACE, {**(extra or {}), "STOPPED": out.get("stopped", ""), "ERROR": out.get("error", ""),
                                     "OUTCOME": "success" if search.returncode == 0 else "failure"})
        self.git("fetch", "-q", "origin")
        return plan, search, commit, surface, out

    def test_plan_lists_never_searched_dates_newest_first(self):
        plan = self.run_step(PLAN, {"END_DATE": "", "DAYS": "4"})
        self.assertEqual(plan.returncode, 0, plan.stderr)
        d1, d2, d3, d4 = self.days
        self.assertEqual((self.runner_temp / "backfill-plan.txt").read_text().split(), [d1, d3, d4])
        self.assertEqual(outputs(Path(self.env["GITHUB_OUTPUT"]))["count"], "3")

    def test_plan_rejects_more_than_31_days_and_an_unfinished_end_date(self):
        self.assertNotEqual(self.run_step(PLAN, {"END_DATE": "", "DAYS": "32"}).returncode, 0)
        self.assertNotEqual(self.run_step(PLAN, {"END_DATE": self.today.isoformat(), "DAYS": "1"}).returncode, 0)

    def test_full_backfill_is_one_verified_commit_and_leaves_the_heartbeat_alone(self):
        plan, search, commit, surface, out = self.full_run()
        self.assertEqual(search.returncode, 0, search.stderr)
        self.assertEqual(commit.returncode, 0, commit.stderr)
        self.assertEqual(surface.returncode, 0, surface.stdout)
        d1, d2, d3, d4 = self.days
        self.assertEqual(out["stopped"], "completed")
        self.assertEqual(self.git("rev-list", "--count", f"{self.base_head}..origin/main").strip(), "1")
        rows = self.rows()
        for d in (d1, d3, d4):
            self.assertEqual((rows[d]["coverage"], rows[d]["scanned_seconds"], rows[d]["count"]), ("full", 86400, 1), d)
        self.assertEqual(rows[d2]["count"], 1)  # the hourly-searched date is untouched
        status = json.loads(self.git("show", "origin/main:data/status.json"))
        for key in ("written_utc", "last_attempt_outcome", "consecutive_failures", "last_successful_scan_end_utc"):
            self.assertEqual(status[key], self.heartbeat[key], key)
        self.assertEqual(status["backfill"]["filled_days"], [d1, d3, d4])
        self.assertEqual(status["archive"]["archived_observations"], 4)
        self.assertEqual(self.git("status", "--porcelain"), "")

    def test_rate_limit_stops_cleanly_commits_verified_dates_and_leaves_the_rest_unknown(self):
        d1, d2, d3, d4 = self.days
        plan, search, commit, surface, out = self.full_run({"FAKE_FAIL_DAYS": d3})
        self.assertEqual(search.returncode, 0, search.stderr)
        self.assertEqual(commit.returncode, 0, commit.stderr)
        self.assertEqual(out["stopped"], "eumetsat_error")
        self.assertIn("429", out["error"])
        rows = self.rows()
        self.assertEqual(rows[d1]["count"], 1)
        for d in (d3, d4):  # never a zero for a date the search did not cover
            self.assertEqual((rows[d]["coverage"], rows[d]["count"]), ("none", None), d)
        self.assertFalse((self.runner_temp / f"rb-{d4}.json").exists(), "the loop must stop at the first error")
        status = json.loads(self.git("show", "origin/main:data/status.json"))
        self.assertEqual(status["backfill"]["remaining_unknown_days"], [d3, d4])
        self.assertNotEqual(surface.returncode, 0)
        self.assertIn("::error::Backfill stopped (eumetsat_error)", surface.stdout)

    def test_archive_refusal_stops_and_keeps_that_date_unknown(self):
        d1, d2, d3, d4 = self.days
        plan, search, commit, surface, out = self.full_run({"FAKE_GHOST_DAYS": d1})
        self.assertEqual(out["stopped"], "archive_refused")
        self.assertIn("outside the examined slots", out["error"])
        rows = self.rows()
        for d in (d1, d3, d4):
            self.assertIsNone(rows[d]["count"], d)
        self.assertNotEqual(surface.returncode, 0)
        status = json.loads(self.git("show", "origin/main:data/status.json"))
        self.assertEqual(status["backfill"]["stopped_reason"], "archive_refused")

    def test_time_budget_stops_before_any_search_and_only_warns(self):
        plan, search, commit, surface, out = self.full_run({"BACKFILL_BUDGET_MINUTES": "0"})
        self.assertEqual(out["stopped"], "time_budget")
        self.assertEqual(out["filled"], "0")
        self.assertFalse(list(self.runner_temp.glob("rb-*.json")))
        self.assertEqual(surface.returncode, 0)
        self.assertIn("::warning::", surface.stdout)

    def test_refuses_to_write_outside_main(self):
        self.run_step(PLAN, {"END_DATE": "", "DAYS": "4"})
        search = self.run_step(SEARCH, {"GITHUB_REF": "refs/heads/feature"})
        self.assertNotEqual(search.returncode, 0)
        self.assertIn("must run on main", search.stdout)
        self.assertEqual(self.git("status", "--porcelain"), "")


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

Test CI Verify

A test in the tests folder of Lightning that checks History and Collect. It verifies tests (`VerifyDataTests`) and sets up (`setUp`).

testlightning / tests/test_ci_verify.py · lines 1–208 of 208 · Entry point · pattern verify (shared by 34 files)

What it does
It tests its inputs. Defines 23 functions or classes, including make_data, corrupt_a_shard, VerifyDataTests, setUp, tearDown. Uses libraries json, os, re, shutil, subprocess. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file index.json; JSON file status.json; GeoJSON file uk_lightning.geojson. Out: JSON file status.json; GeoJSON file uk_lightning.geojson.
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
The `PUSH_VERIFY` gate of `ci/push-with-replay.sh` and the CI wiring.
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 (import), Collect (import), CI Push with Replay (script call), CI Verify Data (script call), Grid (script call), json, os, re, shutil, subprocess, sys, tempfile, unittest
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
make_data, corrupt_a_shard, VerifyDataTests, PushVerifyTests, step_block, CiWiringTests
Defines here
make_data, corrupt_a_shard, VerifyDataTests, setUp, tearDown, verify, test_good_data_passes_quick_and_deep, test_a_shard_differing_from_its_index_row_fails, test_a_malformed_feed_or_status_fails, test_a_grid_problem_warns_in_quick_mode_and_fails_deep, PushVerifyTests, setUp, tearDown, git, push, test_an_unverified_archive_is_never_committed_or_pushed, test_a_heartbeat_commit_is_not_blocked_by_an_unstaged_archive_problem, test_a_good_archive_change_is_pushed, step_block, CiWiringTests, test_every_data_commit_runs_the_quick_verify_before_pushing, test_test_job_installs_requirements_and_the_smoke_test_cannot_skip_there, test_deep_verify_runs_after_every_data_writer_and_human_data_push
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_ci_verify.py:1-208 · blob 6e92122c3eca314e9663d0fc49af1c96100aa33b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""ci/verify_data.py, the PUSH_VERIFY gate of ci/push-with-replay.sh and the CI wiring.

No network. The archive fixtures are written by the real history.py.
"""
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from datetime import datetime, time, timedelta, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
import history  # noqa: E402
from collect import build_feature  # noqa: E402

WORKFLOWS = ROOT / ".github" / "workflows"
VERIFY = [sys.executable, str(ROOT / "ci" / "verify_data.py")]


def make_data(data: Path) -> None:
    now = datetime.now(timezone.utc)
    start = datetime.combine(now.date() - timedelta(days=2), time.min, tzinfo=timezone.utc)
    history.archive_observations(
        data / "history", [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)
    (data / "status.json").write_text(json.dumps({"schema": "uk-lightning-status.v1"}) + "\n")
    (data / "uk_lightning.geojson").write_text(json.dumps({
        "type": "FeatureCollection", "metadata": {},
        "features": [build_feature(-2.0, 52.0, start + timedelta(hours=2), "TEST-hourly", 0)]}) + "\n")


def corrupt_a_shard(data: Path) -> None:
    index = json.loads((data / "history" / "index.json").read_text())
    row = next(r for r in index["days"] if r.get("path"))
    shard = data / "history" / row["path"]
    shard.write_text(shard.read_text().replace("TEST-hourly", "TEST-hourlx"))


class VerifyDataTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        self.data = self.base / "data"
        make_data(self.data)

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

    def verify(self, *args):
        return subprocess.run([*VERIFY, "--data-dir", str(self.data), *args], cwd=self.base,
                              capture_output=True, text=True)

    def test_good_data_passes_quick_and_deep(self):
        for args in ((), ("--deep",)):
            done = self.verify(*args)
            self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
            self.assertIn("archive ok", done.stdout)
            self.assertIn("grid ok", done.stdout)

    def test_a_shard_differing_from_its_index_row_fails(self):
        corrupt_a_shard(self.data)
        done = self.verify()
        self.assertEqual(done.returncode, 1)
        self.assertIn("::error::verify-data archive", done.stdout)

    def test_a_malformed_feed_or_status_fails(self):
        (self.data / "uk_lightning.geojson").write_text('{"features": []}\n')
        done = self.verify()
        self.assertEqual(done.returncode, 1)
        self.assertIn("::error::verify-data feed", done.stdout)
        make_data(self.data)
        (self.data / "status.json").write_text("{not json\n")
        self.assertIn("::error::verify-data status", self.verify().stdout)

    def test_a_grid_problem_warns_in_quick_mode_and_fails_deep(self):
        # history.py ingest never lets a grid failure block the archive; the deep
        # check on main turns it red instead.
        next((self.data / "history" / "grid").glob("*.json")).unlink()
        quick = self.verify()
        self.assertEqual(quick.returncode, 0, quick.stdout)
        self.assertIn("::warning::verify-data grid", quick.stdout)
        deep = self.verify("--deep")
        self.assertEqual(deep.returncode, 1)
        self.assertIn("::error::verify-data grid", deep.stdout)


@unittest.skipUnless(shutil.which("git") and shutil.which("bash"), "git and bash are required")
class PushVerifyTests(unittest.TestCase):
    """push-with-replay.sh runs PUSH_VERIFY on the staged paths before every commit."""

    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        base = Path(self.temp.name)
        bin_dir = base / "bin"
        bin_dir.mkdir()
        (bin_dir / "python").symlink_to(sys.executable)
        self.env = {**os.environ, "HOME": str(base), "GIT_CONFIG_NOSYSTEM": "1", "PYTHONDONTWRITEBYTECODE": "1",
                    "GIT_AUTHOR_NAME": "test", "GIT_AUTHOR_EMAIL": "test@example.invalid",
                    "GIT_COMMITTER_NAME": "test", "GIT_COMMITTER_EMAIL": "test@example.invalid",
                    "PATH": f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}",
                    "PUSH_VERIFY": "python ci/verify_data.py --staged", "PUSH_RETRY_SLEEP": "0"}
        self.origin, self.repo = base / "origin.git", 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))
        for name in ("history.py", "grid.py", "collect.py"):
            shutil.copy(ROOT / name, self.repo / name)
        shutil.copytree(ROOT / "ci", self.repo / "ci")
        (self.repo / ".gitignore").write_text("__pycache__/\n")
        make_data(self.repo / "data")
        self.git("add", "-A")
        self.git("commit", "-q", "-m", "initial")
        self.git("push", "-q", "-u", "origin", "main")
        self.head = self.git("rev-parse", "HEAD").strip()

    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 push(self, *paths):
        return subprocess.run(["bash", "ci/push-with-replay.sh", "data: test", "true", *paths], cwd=self.repo,
                              env=self.env, capture_output=True, text=True)

    def test_an_unverified_archive_is_never_committed_or_pushed(self):
        corrupt_a_shard(self.repo / "data")
        done = self.push("data/status.json", "data/history")
        self.assertEqual(done.returncode, 1, done.stdout + done.stderr)
        self.assertIn("PUSH_VERIFY failed", done.stdout)
        self.assertEqual(self.git("rev-parse", "HEAD").strip(), self.head)
        self.assertEqual(self.git("ls-remote", "origin", "main").split()[0], self.head)
        self.assertEqual(self.git("diff", "--cached", "--name-only"), "")

    def test_a_heartbeat_commit_is_not_blocked_by_an_unstaged_archive_problem(self):
        corrupt_a_shard(self.repo / "data")
        (self.repo / "data" / "status.json").write_text(json.dumps({"schema": "uk-lightning-status.v1", "n": 2}))
        done = self.push("data/status.json")
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        self.assertNotEqual(self.git("ls-remote", "origin", "main").split()[0], self.head)

    def test_a_good_archive_change_is_pushed(self):
        (self.repo / "data" / "uk_lightning.geojson").write_text(
            json.dumps({"type": "FeatureCollection", "metadata": {"n": 2}, "features": []}) + "\n")
        done = self.push("data/uk_lightning.geojson")
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        self.assertIn("verify-data: feed ok", done.stdout)


def step_block(path: Path, name: str) -> str:
    """The YAML text of one step, from its '- name:' line to the next step."""
    text = path.read_text()
    start = text.index(f"- name: {name}\n")
    nxt = text.find("\n      - ", start + 1)
    return text[start:] if nxt < 0 else text[start:nxt]


class CiWiringTests(unittest.TestCase):
    QUICK = "PUSH_VERIFY: python ci/verify_data.py --staged"

    def test_every_data_commit_runs_the_quick_verify_before_pushing(self):
        hourly = WORKFLOWS / "update-lightning.yml"
        self.assertIn(self.QUICK, step_block(hourly, "Commit latest public GeoJSON (feed commit)"))
        self.assertIn(self.QUICK, step_block(hourly, "Commit archive and status (archive commit)"))
        self.assertIn(self.QUICK, step_block(WORKFLOWS / "backfill-lightning.yml",
                                             "Verify and commit backfilled dates (one commit)"))
        finalize = step_block(WORKFLOWS / "backfill-parallel-lightning.yml", "Ingest, verify and commit (one commit)")
        self.assertLess(finalize.index("python ci/verify_data.py --staged"), finalize.index("git push"))
        for path in WORKFLOWS.glob("*.yml"):  # no data push bypasses the gate
            text = path.read_text()
            if "git push" in text or "push-with-replay.sh" in text:
                self.assertIn("ci/verify_data.py --staged", text, path.name)

    def test_test_job_installs_requirements_and_the_smoke_test_cannot_skip_there(self):
        text = (WORKFLOWS / "test-lightning.yml").read_text()
        self.assertIn("deps: [requirements, bare]", text)
        self.assertIn("run: pip install -r requirements.txt", text)
        self.assertIn("LIGHTNING_SMOKE_REQUIRE_DEPS: ${{ matrix.deps == 'requirements' && '1' || '0' }}", text)
        self.assertIn("pyflakes", text)
        for watched in ("requirements.txt", ".github/workflows/verify-lightning-data.yml"):
            self.assertEqual(text.count(f'- "{watched}"'), 2, watched)  # push and pull_request

    def test_deep_verify_runs_after_every_data_writer_and_human_data_push(self):
        text = (WORKFLOWS / "verify-lightning-data.yml").read_text()
        self.assertIn("python grid.py verify --deep --archive-dir data/history", text)
        self.assertIn("python history.py verify --archive-dir data/history", text)
        self.assertRegex(text, r'push:\n    branches: \[main\]\n    paths:\n      - "data/\*\*"')
        # workflow_run matches by workflow NAME: a renamed writer would silently
        # stop being verified, so the names must be the writers' real names.
        listed = re.findall(r'^      - "([^"]+)"$', text.split("workflow_run:", 1)[1].split("types:", 1)[0], re.M)
        writers = sorted(re.search(r"^name: (.+)$", p.read_text(), re.M).group(1)
                         for p in WORKFLOWS.glob("*.yml")
                         if "git push" in p.read_text() or "push-with-replay.sh" in p.read_text())
        self.assertEqual(sorted(listed), writers)
        group = re.search(r"concurrency:\n  group: (\S+)", text).group(1)
        self.assertNotIn(group, ("uk-lightning-update", "uk-lightning-backfill"))


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