GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / lightning / .github/workflows

CI Collector Health and 4 more files

A Python command-line tool in Lightning that fetches UK lightning from GitHub API. It parses utc (`parse_utc`), loads status (`load_status`) and opens issues (`open_issues`).

637 lines of Python and Shell and YAML from lightning, in 5 files. Topic: Automation and CI. Section 1820 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. Verify Lightning Data Workflow automation · lightning / .github/workflows/verify-lightning-data.yml lines 1–113
  2. CI Collector Health automation · lightning / ci/collector_health.py lines 1–369
  3. CI Push with Replay automation · lightning / ci/push-with-replay.sh lines 1–92
  4. CI Replay Backfill automation · lightning / ci/replay-backfill.sh lines 1–28
  5. CI Replay Hourly Archive automation · lightning / ci/replay-hourly-archive.sh lines 1–35

Verify Lightning Data Workflow

A GitHub Actions workflow. Runs on push, on pull requests and by hand.

automationlightning / .github/workflows/verify-lightning-data.yml · lines 1–113 of 113 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Inputs & outputs
In: JSON file reproduction.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Verify UK lightning data on main”; runs History (`history.py`), Grid (`grid.py`) and CI Verify Data (`ci/verify_data.py`).
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
lightning · .github/workflows · workflow
Uses
History (workflow run), Grid (workflow run), CI Verify Data (workflow run), Reproduce (workflow run), CI Collector Health (workflow run)
Used by
none found
Produces
none declared
Defines here
Verify UK lightning data on 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 .github/workflows/verify-lightning-data.yml:1-113 · blob caf20bd576b24b3c19079493cde8a71a01d9bc61 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: Verify UK lightning data on main
# Deep check of the COMMITTED data on main: index rows vs shard bytes, sha256
# and counts (history.py verify), every month grid recounted from its shards
# (grid.py verify --deep), the feed/status JSON (ci/verify_data.py) and an
# independent recomputation of every row, total and grid (reproduce.py check).
#
# Triggers. The hourly and backfill workflows push with GITHUB_TOKEN, and
# GitHub starts NO workflow for a GITHUB_TOKEN push, so `push: data/**` alone
# would only ever see human pushes. `workflow_run` (completion of the three
# data-writing workflows, on main) covers every bot data commit; it runs this
# file from main and checks out the newest main. The writers themselves run
# the quick check (ci/verify_data.py --staged) before every push.
# A pull request that changes a checker (or this file) runs the same deep check
# on its own head commit, so a new or changed step is proven before it guards main.
on:
  push:
    branches: [main]
    paths:
      - "data/**"
      - "reproduce.py"
  pull_request:
    paths:
      - "reproduce.py"
      - "history.py"
      - "grid.py"
      - "ci/verify_data.py"
      - ".github/workflows/verify-lightning-data.yml"
  workflow_run:
    workflows:
      - "UK lightning optical flashes"
      - "UK lightning archive backfill"
      - "UK lightning archive backfill (parallel)"
    types: [completed]
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read

# Its own group (never uk-lightning-update / uk-lightning-backfill): a newer
# data commit supersedes a queued check of an older one. A pull request gets
# its own group, so it can never cancel the check of a data commit on main.
concurrency:
  group: uk-lightning-data-verify${{ github.event_name == 'pull_request' && format('-pr-{0}', github.event.number) || '' }}
  cancel-in-progress: true

jobs:
  verify:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v4
        with:
          # The newest main, not the SHA the triggering run started from; a
          # pull request checks its own head.
          ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || 'main' }}
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Index and shard integrity (history.py verify)
        run: python history.py verify --archive-dir data/history
      - name: Month grids recounted from the shards (grid.py verify --deep)
        run: python grid.py verify --deep --archive-dir data/history
      - name: Feed, status, archive and grids (ci/verify_data.py --deep)
        run: python ci/verify_data.py --deep
      - name: Independent recomputation from the committed files (reproduce.py check)
        # Shares no code with the writer (docs/METHODS.md, section 8); prints the
        # headline numbers and summary_sha256 for this commit.
        # The summary is written on failure too; the step's exit code is the check's.
        run: |
          set +e
          python reproduce.py check --json "$RUNNER_TEMP/reproduction.json" > "$RUNNER_TEMP/reproduction.txt" 2>&1
          rc=$?
          cat "$RUNNER_TEMP/reproduction.txt"
          { echo "Commit $(git rev-parse --short HEAD)"; echo '```'; cat "$RUNNER_TEMP/reproduction.txt"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
          exit $rc
      - name: Keep the reproduction record
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: reproduction-${{ github.run_id }}
          path: ${{ runner.temp }}/reproduction.*
          if-no-files-found: ignore
          retention-days: 30

  # The collector-stale issue (ci/collector_health.py, docs/OPERATIONS.md).
  # This run is started by every hourly AND backfill completion, so a backfill
  # also reports an hourly collector that has stopped. Only this job may write
  # issues; the data checks above stay read-only.
  health:
    # Reads main's status and writes issues: never on a pull request (the PR's
    # checker may not be on main yet, and PR tokens cannot write issues).
    if: github.event_name != 'pull_request'
    runs-on: ubuntu-latest
    timeout-minutes: 5
    permissions:
      contents: read
      issues: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          sparse-checkout: |
            ci/collector_health.py
            data/status.json
          sparse-checkout-cone-mode: false
      - name: Collector health issue (collector-stale)
        env:
          GH_TOKEN: ${{ github.token }}
          SOURCE: verify-lightning-data run ${{ github.run_id }} (${{ github.event_name }})
        run: |
          python3 ci/collector_health.py --status data/status.json --issue \
            --source "$SOURCE" --summary "$GITHUB_STEP_SUMMARY"

CI Collector Health

A Python command-line tool in Lightning that fetches UK lightning from GitHub API. It parses utc (`parse_utc`), loads status (`load_status`) and opens issues (`open_issues`).

automationlightning / ci/collector_health.py · lines 1–369 of 369 · Entry point · pattern create_issue (shared by 2 files)

What it does
It fetches UK lightning. Defines 19 functions or classes, including parse_utc, iso, load_status, evaluate, _fetch. Uses libraries __future__, argparse, json, os, sys. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
README: "`ci/collector_health.py` and `.github/workflows/collector-watchdog.yml`: open, refresh or close the `collector-stale` issue (no heartbeat past `late_after_utc` + 90 min, or repeated failed runs) and the `feed-delivery` issue (raw.githubusercontent.com failing)"
Inputs & outputs
In: data source: GitHub API; JSON file status.json; GeoJSON file uk_lightning.geojson; JSON file index.json; command-line arguments.
Downstream impact
Used directly by 4 files: Collector Watchdog Workflow (lightning); Update Lightning Workflow (lightning); Verify Lightning Data Workflow (lightning); Test Collector Health (lightning). Reached from 3 other entry points, including Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning).
What it achieves
Open, update or close the "collector-stale" GitHub issue. It accepts `--status`, `--now` and `--grace-minutes`.
Why it matters
Run by Collector Watchdog Workflow, Update Lightning Workflow and Verify Lightning Data Workflow. Checked by Test Collector Health.
Application
lightning · ci · Python CLI
Uses
__future__, argparse, json, os, sys, time, urllib.error, urllib.request
Used by
run by Collector Watchdog Workflow (workflow run), run by Update Lightning Workflow (workflow run), run by Verify Lightning Data Workflow (workflow run), imported by Test Collector Health (sys.path import)
Produces
parse_utc, iso, load_status, evaluate, probe_raw, GitHub, sync_issue, stale_issue, delivery_issue, main
Defines here
parse_utc, iso, load_status, evaluate, _fetch, probe_raw, GitHub, __init__, call, open_issues, ensure_label, create_issue, update_issue, comment, sync_issue, _bullets, stale_issue, delivery_issue, 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 ci/collector_health.py:1-369 · blob d21f9b0f50edb3af41fcd13a7ae24f379b219b8f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Collector health: open, update or close the "collector-stale" GitHub issue.

Reads the heartbeat that ``status.py write`` puts in ``data/status.json`` after
every hourly run and decides one of:

  ok        the heartbeat is on time and the collector is not failing
  late      now is past ``heartbeat.late_after_utc`` (no run for 90 min) but
            within the grace period: reported, no issue (GitHub's scheduler
            misses single slots every day; see docs/OPERATIONS.md)
  stale     now is past ``late_after_utc`` + grace (default 90 min, so no
            heartbeat for 3 h), or status.json is missing or unreadable:
            neither the cron nor the hourly nudge has started a run
  failing   runs happen but do not succeed: ``consecutive_failures`` >= 3, or
            ``freshness`` is stale/stopped/never (for example rejected
            EUMETSAT credentials)

``stale`` and ``failing`` open (or update) ONE open issue labelled
``collector-stale``; ``ok`` and ``late`` close it with a recovery comment.

``--raw`` adds the delivery probe used by the scheduled watchdog: the public
map reads raw.githubusercontent.com/Ventusltd/lightning/main/data/..., which
has no SLA. When that path fails, or serves a status.json more than an hour
older than the committed one, ONE issue labelled ``feed-delivery`` is opened;
it is closed when the probe passes again.

Standard library only (the watchdog runs it without setup-python or pip).
Exit 0 unless ``--fail-when-unhealthy`` is given and a check is unhealthy, or
the GitHub API cannot be reached with ``--issue`` (exit 2).

  python ci/collector_health.py --status data/status.json                 # report only
  python ci/collector_health.py --status data/status.json --issue         # + sync the issue
  python ci/collector_health.py --status data/status.json --issue --raw --fail-when-unhealthy
"""
from __future__ import annotations

import argparse
import json
import os
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path

STALE_LABEL = "collector-stale"
DELIVERY_LABEL = "feed-delivery"
GRACE_MINUTES = 90          # late_after_utc (attempt + 90 min) + 90 min = no heartbeat for 3 h
LATE_AFTER_FALLBACK_MINUTES = 90  # status.py LATE_AFTER_MINUTES, for a heartbeat block that lacks it
MAX_FAILURES = 3
RAW_BASE = "https://raw.githubusercontent.com/Ventusltd/lightning/main/"
RAW_LAG_MINUTES = 60
MARKER = "<!-- collector-health:{label}:state={state} -->"
UNHEALTHY = ("stale", "failing")
RUNBOOK = "docs/OPERATIONS.md"


def parse_utc(value) -> datetime | None:
    if not value:
        return None
    try:
        text = str(value).strip().replace("Z", "+00:00")
        parsed = datetime.fromisoformat(text)
    except ValueError:
        return None
    return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)


def iso(value: datetime | None) -> str | None:
    return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if value else None


def load_status(path: Path) -> dict | None:
    try:
        obj = json.loads(Path(path).read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return None
    return obj if isinstance(obj, dict) else None


def evaluate(status: dict | None, *, now: datetime, grace_minutes: int = GRACE_MINUTES,
             max_failures: int = MAX_FAILURES) -> dict:
    """The collector verdict from status.json alone (pure: no clock, no network)."""
    if not status:
        return {"state": "stale", "reasons": ["data/status.json is missing or unreadable"],
                "late_after_utc": None, "stale_after_utc": None, "last_attempt_utc": None,
                "last_attempt_outcome": None, "consecutive_failures": None, "freshness": None,
                "last_successful_scan_end_utc": None, "last_error": None, "minutes_since_attempt": None}
    heartbeat = status.get("heartbeat") if isinstance(status.get("heartbeat"), dict) else {}
    attempt = parse_utc(status.get("last_attempt_utc"))
    late_after = parse_utc(heartbeat.get("late_after_utc"))
    if late_after is None and attempt is not None:
        late_after = attempt + timedelta(minutes=LATE_AFTER_FALLBACK_MINUTES)
    stale_after = late_after + timedelta(minutes=grace_minutes) if late_after else None
    failures = status.get("consecutive_failures")
    try:
        failures = int(failures or 0)
    except (TypeError, ValueError):
        failures = 0
    freshness = status.get("freshness")
    last_end = status.get("last_successful_scan_end_utc")
    error = status.get("last_error")
    reasons: list[str] = []
    state = "ok"
    if late_after is None:
        state = "stale"
        reasons.append("status.json has no last_attempt_utc or heartbeat.late_after_utc")
    elif now > stale_after:
        state = "stale"
        reasons.append(f"no collector heartbeat since {iso(attempt) or 'unknown'}: now is past "
                       f"late_after_utc {iso(late_after)} + {grace_minutes} min grace. Neither the GitHub cron "
                       "nor the hourly nudge has started a run")
    if failures >= max_failures or freshness in ("stale", "stopped", "never"):
        if state == "ok":
            state = "failing"
        if failures >= max_failures:
            reasons.append(f"{failures} consecutive failed collector runs (threshold {max_failures})"
                           + (f"; last error: {str(error)[:300]}" if error else ""))
        if freshness in ("stale", "stopped", "never"):
            reasons.append(f"freshness={freshness}: last successful scan end {last_end or 'never'}")
    if state == "ok" and now > late_after:
        state = "late"
        reasons.append(f"heartbeat late: now is past late_after_utc {iso(late_after)} but within the "
                       f"{grace_minutes} min grace (a single dropped cron slot)")
    return {
        "state": state,
        "reasons": reasons,
        "late_after_utc": iso(late_after),
        "stale_after_utc": iso(stale_after),
        "last_attempt_utc": iso(attempt),
        "last_attempt_outcome": status.get("last_attempt_outcome"),
        "consecutive_failures": failures,
        "freshness": freshness,
        "last_successful_scan_end_utc": last_end,
        "last_error": error,
        "minutes_since_attempt": round((now - attempt).total_seconds() / 60, 1) if attempt else None,
    }


# --- delivery probe (raw.githubusercontent.com) --------------------------------

def _fetch(url: str, *, method: str = "GET", timeout: int = 20, attempts: int = 3) -> tuple[int | None, bytes, str]:
    last = ""
    for attempt in range(attempts):
        req = urllib.request.Request(url, method=method, headers={"Cache-Control": "no-cache",
                                                                  "User-Agent": "lightning-collector-health"})
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return resp.status, resp.read() if method == "GET" else b"", ""
        except urllib.error.HTTPError as exc:
            last = f"HTTP {exc.code}"
            if exc.code < 500 and exc.code != 429:
                return exc.code, b"", last
        except (urllib.error.URLError, OSError) as exc:
            last = f"{type(exc).__name__}: {exc}"
        if attempt + 1 < attempts:
            time.sleep(5 * (attempt + 1))
    return None, b"", last


def probe_raw(committed: dict | None, *, base: str = RAW_BASE, fetch=_fetch,
              lag_minutes: int = RAW_LAG_MINUTES) -> dict:
    """Is the public raw path serving the data the map reads, and not far behind main?"""
    reasons: list[str] = []
    stamp = int(time.time())
    code, body, err = fetch(f"{base}data/status.json?health={stamp}")
    served = None
    if code != 200:
        reasons.append(f"data/status.json: {err or f'HTTP {code}'}")
    else:
        try:
            served = json.loads(body.decode("utf-8"))
        except (UnicodeDecodeError, ValueError):
            reasons.append("data/status.json: served bytes are not JSON")
    for rel in ("data/uk_lightning.geojson", "data/history/index.json"):
        code, _, err = fetch(f"{base}{rel}?health={stamp}", method="HEAD")
        if code != 200:
            reasons.append(f"{rel}: {err or f'HTTP {code}'}")
    if isinstance(served, dict) and committed:
        mine, theirs = parse_utc(committed.get("last_attempt_utc")), parse_utc(served.get("last_attempt_utc"))
        if mine and theirs and (mine - theirs) > timedelta(minutes=lag_minutes):
            reasons.append(f"raw serves a status.json from {iso(theirs)}, {round((mine - theirs).total_seconds() / 60)} "
                           f"min behind main ({iso(mine)})")
    return {"state": "failing" if reasons else "ok", "reasons": reasons, "base": base}


# --- GitHub issues ------------------------------------------------------------

class GitHub:
    """The four REST calls the issue sync needs (urllib, GITHUB_TOKEN/GH_TOKEN)."""

    def __init__(self, repo: str, token: str, api: str = "https://api.github.com"):
        self.repo, self.token, self.api = repo, token, api.rstrip("/")

    def call(self, method: str, path: str, payload: dict | None = None):
        data = json.dumps(payload).encode("utf-8") if payload is not None else None
        req = urllib.request.Request(f"{self.api}/repos/{self.repo}{path}", data=data, method=method, headers={
            "Authorization": f"Bearer {self.token}", "Accept": "application/vnd.github+json",
            "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "lightning-collector-health"})
        with urllib.request.urlopen(req, timeout=30) as resp:
            raw = resp.read()
        return json.loads(raw) if raw else None

    def open_issues(self, label: str) -> list[dict]:
        rows = self.call("GET", f"/issues?state=open&labels={label}&per_page=100&sort=created&direction=asc") or []
        return [row for row in rows if "pull_request" not in row]

    def ensure_label(self, label: str, color: str, description: str) -> None:
        try:
            self.call("POST", "/labels", {"name": label, "color": color, "description": description})
        except urllib.error.HTTPError as exc:
            if exc.code != 422:  # 422 = already exists
                raise

    def create_issue(self, title: str, body: str, label: str) -> dict:
        return self.call("POST", "/issues", {"title": title, "body": body, "labels": [label]})

    def update_issue(self, number: int, **fields) -> dict:
        return self.call("PATCH", f"/issues/{number}", fields)

    def comment(self, number: int, body: str) -> None:
        self.call("POST", f"/issues/{number}/comments", {"body": body})


LABELS = {
    STALE_LABEL: ("b60205", "Lightning collector: no heartbeat past late_after_utc + grace, or failing runs"),
    DELIVERY_LABEL: ("d93f0b", "Lightning data: raw.githubusercontent.com path failing or far behind main"),
}


def sync_issue(client, *, label: str, unhealthy: bool, state: str, title: str, body: str,
               recovery: str) -> str:
    """One open issue per label: open or refresh it while unhealthy, close it on recovery.

    The body is replaced on every unhealthy check (no notification); a comment
    is added only when the state changes (for example stale -> failing), so a
    long outage does not post one comment per check. Duplicates left by two
    checks racing are closed onto the oldest issue.
    """
    marker = MARKER.format(label=label, state=state)
    issues = client.open_issues(label)
    if not unhealthy:
        for issue in issues:
            client.comment(issue["number"], recovery)
            client.update_issue(issue["number"], state="closed", state_reason="completed")
        return f"closed #{', #'.join(str(i['number']) for i in issues)}" if issues else "none open; nothing to do"
    full = f"{marker}\n{body}"
    if not issues:
        color, description = LABELS.get(label, ("ededed", ""))
        client.ensure_label(label, color, description)
        created = client.create_issue(title, full, label)
        return f"opened #{created['number']}"
    keep, extras = issues[0], issues[1:]
    previous = keep.get("body") or ""
    client.update_issue(keep["number"], title=title, body=full)
    action = f"updated #{keep['number']}"
    if marker not in previous:
        client.comment(keep["number"], f"State is now **{state}**.\n\n{body}")
        action += " (state changed; commented)"
    for extra in extras:
        client.comment(extra["number"], f"Duplicate of #{keep['number']} (two health checks raced).")
        client.update_issue(extra["number"], state="closed", state_reason="not_planned")
    return action


def _bullets(reasons: list[str]) -> str:
    return "\n".join(f"- {r}" for r in reasons) or "- (none)"


def stale_issue(verdict: dict, *, source: str, now: datetime) -> tuple[str, str]:
    if verdict["state"] == "stale":
        title = f"Lightning collector stale: no heartbeat since {verdict['last_attempt_utc'] or 'unknown'}"
    elif (verdict["consecutive_failures"] or 0) > 0:
        title = f"Lightning collector failing: {verdict['consecutive_failures']} consecutive failed runs"
    else:
        title = (f"Lightning collector failing: no successful scan since "
                 f"{verdict['last_successful_scan_end_utc'] or 'ever'}")
    rows = [("state", verdict["state"]), ("last attempt", verdict["last_attempt_utc"]),
            ("last attempt outcome", verdict["last_attempt_outcome"]),
            ("late_after_utc", verdict["late_after_utc"]), ("stale after (late + grace)", verdict["stale_after_utc"]),
            ("consecutive failures", verdict["consecutive_failures"]), ("freshness", verdict["freshness"]),
            ("last successful scan end", verdict["last_successful_scan_end_utc"])]
    table = "\n".join(f"| {k} | `{v}` |" for k, v in rows)
    body = (f"**{verdict['state'].upper()}**: the UK lightning archive is not being kept current.\n\n"
            f"{_bullets(verdict['reasons'])}\n\n| field | value |\n|---|---|\n{table}\n\n"
            f"Flashes in the gap are unknown, not zero. What to do: see `{RUNBOOK}` (\"collector-stale\"). "
            "The next successful hourly run closes this issue automatically.\n\n"
            f"_Checked {iso(now)} by {source}._")
    return title, body


def delivery_issue(probe: dict, *, source: str, now: datetime) -> tuple[str, str]:
    title = "Lightning data delivery failing: raw.githubusercontent.com"
    body = (f"The public map reads `{probe['base']}data/...`. The delivery probe failed:\n\n"
            f"{_bullets(probe['reasons'])}\n\nThe committed data on main may be fine; this is the public path. "
            f"What to do: see `{RUNBOOK}` (\"feed-delivery\"). Closed automatically when the probe passes.\n\n"
            f"_Checked {iso(now)} by {source}._")
    return title, body


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--status", type=Path, default=Path("data/status.json"))
    parser.add_argument("--now", default=None, help="UTC ISO time to evaluate at (tests); default: the clock")
    parser.add_argument("--grace-minutes", type=int, default=GRACE_MINUTES)
    parser.add_argument("--max-failures", type=int, default=MAX_FAILURES)
    parser.add_argument("--issue", action="store_true", help="Open/update/close the GitHub issue(s)")
    parser.add_argument("--raw", action="store_true", help="Also probe raw.githubusercontent.com (feed-delivery issue)")
    parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", "Ventusltd/lightning"))
    parser.add_argument("--source", default="a manual check")
    parser.add_argument("--summary", type=Path, default=None, help="Append a Markdown line (GITHUB_STEP_SUMMARY)")
    parser.add_argument("--fail-when-unhealthy", action="store_true")
    args = parser.parse_args(argv)

    now = parse_utc(args.now) if args.now else datetime.now(timezone.utc)
    status = load_status(args.status)
    verdict = evaluate(status, now=now, grace_minutes=args.grace_minutes, max_failures=args.max_failures)
    unhealthy = verdict["state"] in UNHEALTHY
    print(f"collector: {verdict['state']} last_attempt={verdict['last_attempt_utc']} "
          f"late_after={verdict['late_after_utc']} stale_after={verdict['stale_after_utc']} "
          f"failures={verdict['consecutive_failures']} freshness={verdict['freshness']}")
    for reason in verdict["reasons"]:
        level = "error" if unhealthy else "warning"
        print(f"::{level} title=collector {verdict['state']}::{reason}")
    probe = probe_raw(status) if args.raw else None
    if probe:
        print(f"delivery: {probe['state']}")
        for reason in probe["reasons"]:
            print(f"::error title=feed-delivery::{reason}")

    actions = []
    if args.issue:
        token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN")
        if not token:
            print("::error::--issue needs GITHUB_TOKEN or GH_TOKEN", file=sys.stderr)
            return 2
        client = GitHub(args.repo, token, os.environ.get("GITHUB_API_URL", "https://api.github.com"))
        try:
            title, body = stale_issue(verdict, source=args.source, now=now)
            recovery = (f"Recovered: collector is **{verdict['state']}** at {iso(now)} (last attempt "
                        f"{verdict['last_attempt_utc']}, outcome {verdict['last_attempt_outcome']}). Closed by {args.source}.")
            actions.append(f"{STALE_LABEL}: " + sync_issue(client, label=STALE_LABEL, unhealthy=unhealthy,
                                                           state=verdict["state"], title=title, body=body,
                                                           recovery=recovery))
            if probe:
                title, body = delivery_issue(probe, source=args.source, now=now)
                actions.append(f"{DELIVERY_LABEL}: " + sync_issue(
                    client, label=DELIVERY_LABEL, unhealthy=probe["state"] != "ok", state=probe["state"],
                    title=title, body=body, recovery=f"Recovered: the raw.githubusercontent.com probe passed at {iso(now)}."))
        except (urllib.error.URLError, OSError, ValueError) as exc:
            print(f"::error title=collector-health issue sync::{type(exc).__name__}: {exc}")
            return 2
        for line in actions:
            print(line)
    if args.summary:
        with open(args.summary, "a", encoding="utf-8") as fh:
            fh.write(f"### Collector health: {verdict['state']}\n\n{_bullets(verdict['reasons'])}\n\n")
            if probe:
                fh.write(f"Delivery (raw): {probe['state']}\n\n{_bullets(probe['reasons'])}\n\n")
            for line in actions:
                fh.write(f"- issue {line}\n")
    if args.fail_when_unhealthy and (unhealthy or (probe and probe["state"] != "ok")):
        return 1
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

CI Push with Replay

A shell script in Lightning.

automationlightning / ci/push-with-replay.sh · lines 1–92 of 92 · Entry point · pattern stage (shared by 7 files)

What it does
Defines stage. Side effects: starts processes.
Downstream impact
Used directly by 5 files: Backfill Lightning Workflow (lightning); Update Lightning Workflow (lightning); CI Verify Data (lightning); Test CI Verify (lightning); and 1 more. Reached from 3 other entry points, including Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Verify Lightning Data Workflow (lightning).
What it achieves
Defines `stage`. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Run by Backfill Lightning Workflow, Update Lightning Workflow and CI Verify Data. Checked by 2 tests, including Test CI Verify.
Application
lightning · ci · shell script
Uses
CI Verify Data (script call)
Used by
run by Backfill Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run), run by CI Verify Data (script call), run by Test CI Verify (script call), run by Test Concurrent Writers (script call)
Produces
stage
Defines here
stage
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 ci/push-with-replay.sh:1-92 · blob c015e5e1ed758ced3ca9590e015d8be1400dbf43 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env bash
# Commit PATHs and push to origin/<current branch>, surviving a
# concurrent writer without a textual merge of generated files.
#
#   ci/push-with-replay.sh MESSAGE REPLAY_COMMAND PATH...
#
# The hourly collector and the backfill run in separate concurrency groups
# (so a long backfill can never hold the hourly feed back) and both write
# data/history/index.json and data/status.json. A `git pull --rebase` of two
# regenerated index.json files conflicts, so on a rejected push this script
# instead resets to the new origin/main and runs REPLAY_COMMAND, which
# regenerates the outputs on top of the other writer's commit from inputs
# kept outside the repository ($RUNNER_TEMP run records). Then it commits and
# pushes again, up to $PUSH_ATTEMPTS times (default 5).
#
# Optional: PUSH_BODY (second -m paragraph), PUSH_RETRY_SLEEP (seconds, default
# 5; multiplied by the attempt number), PUSH_VERIFY (a command run after
# staging and before EVERY commit, the first and each replayed one; if it fails
# nothing is committed or pushed - the data workflows set it to
# `python ci/verify_data.py --staged`).
set -euo pipefail
if [ "$#" -lt 3 ]; then
  echo "usage: $0 MESSAGE REPLAY_COMMAND PATH..." >&2
  exit 2
fi
message=$1
replay=$2
shift 2
# The branch the workflow checked out (main for the schedule), never a fixed
# name: a dispatch on another branch must not push to main.
branch=${PUSH_BRANCH:-$(git rev-parse --abbrev-ref HEAD)}
if [ "$branch" = "HEAD" ]; then
  echo "::error::push-with-replay: detached HEAD; set PUSH_BRANCH" >&2
  exit 2
fi
attempts=${PUSH_ATTEMPTS:-5}
pause=${PUSH_RETRY_SLEEP:-5}

stage() {
  local p
  for p in "$@"; do
    # A path that does not exist yet (data/history before the first archive
    # write) is skipped: a combined pathspec would abort with 128.
    if [ -e "$p" ] || [ -n "$(git ls-files -- "$p")" ]; then
      git add -A -- "$p"
    fi
  done
}

attempt=1
while :; do
  stage "$@"
  if git diff --cached --quiet; then
    echo "push-with-replay: nothing to commit"
    exit 0
  fi
  if [ -n "${PUSH_VERIFY:-}" ] && ! bash -e -c "$PUSH_VERIFY"; then
    echo "::error::push-with-replay: PUSH_VERIFY failed on attempt $attempt; nothing was committed or pushed"
    git reset -q
    exit 1
  fi
  if [ -n "${PUSH_BODY:-}" ]; then
    git commit -q -m "$message" -m "$PUSH_BODY"
  else
    git commit -q -m "$message"
  fi
  if git push -q origin "HEAD:$branch"; then
    echo "push-with-replay: pushed on attempt $attempt"
    exit 0
  fi
  if [ "$attempt" -ge "$attempts" ]; then
    echo "::error::push-with-replay: push rejected $attempt times; nothing was committed"
    exit 1
  fi
  # The replay resets the working tree to the new main. Every output of this
  # step is in PATHs (just committed); refuse rather than silently discard any
  # other uncommitted change.
  others=$(git diff --name-only HEAD)
  if [ -n "$others" ]; then
    echo "::error::push-with-replay: refusing to reset over uncommitted changes outside the step's paths: $others"
    exit 1
  fi
  echo "::warning::push rejected (attempt $attempt/$attempts): another writer moved origin/$branch; replaying onto it"
  sleep $(( pause * attempt ))
  git fetch -q origin "$branch"
  git reset -q --hard "origin/$branch"
  for p in "$@"; do
    if [ -e "$p" ]; then git clean -fdq -- "$p"; fi
  done
  bash -e -c "$replay"
  attempt=$(( attempt + 1 ))
done

CI Replay Backfill

A shell script in Lightning.

automationlightning / ci/replay-backfill.sh · lines 1–28 of 28 · Entry point

What it does
Side effects: starts processes.
Downstream impact
Used directly by 1 file: Backfill Lightning Workflow (lightning).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
Run by Backfill Lightning Workflow.
Application
lightning · ci · shell script
Uses
History (script call), Status (script call)
Used by
run by Backfill Lightning Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 ci/replay-backfill.sh:1-28 · blob 895142b275e16c14bf8996e11b9effb7bdf7475f · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env bash
# Replay of a backfill run's verified dates on top of a newer origin/main
# (called by push-with-replay.sh after a rejected backfill push). Every date in
# $RUNNER_TEMP/backfill-filled.txt is re-ingested from its saved whole-day run
# record ($RUNNER_TEMP/rb-D.json): no EUMETSAT call is repeated. history.py
# backfill refuses a date that is no longer never-searched (for example the
# hourly job has meanwhile archived part of it); such a date is dropped from
# this run's filled list, keeping the hourly job's rows. The backfill status
# block is rewritten from the replayed list, then the archive is verified.
set -euo pipefail
filled="$RUNNER_TEMP/backfill-filled.txt"
kept="$RUNNER_TEMP/backfill-filled.replay.txt"
: > "$kept"
while read -r D; do
  [ -n "$D" ] || continue
  if python history.py backfill --archive-dir data/history --day "$D" \
       --rebuild-record "$RUNNER_TEMP/rb-$D.json" \
       --result-out "$RUNNER_TEMP/bf-$D.json" < /dev/null; then
    echo "$D" >> "$kept"
  else
    echo "::warning::replay: $D is no longer never-searched on main (or was refused); kept main's row"
  fi
done < "$filled"
mv "$kept" "$filled"
python status.py backfill --status data/status.json \
  --plan "$RUNNER_TEMP/backfill-plan.txt" --filled "$filled" \
  --stopped "${STOPPED:-completed}" --error "${ERROR:-}" --archive-dir data/history
python history.py verify --archive-dir data/history

CI Replay Hourly Archive

A shell script in Lightning covering lightning run record and lightning archive result.

automationlightning / ci/replay-hourly-archive.sh · lines 1–35 of 35 · Entry point

What it does
Side effects: starts processes.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file lightning-run-record.json; JSON file lightning-archive-result.json.
Downstream impact
Used directly by 1 file: Update Lightning Workflow (lightning).
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
Run by Update Lightning Workflow.
Application
lightning · ci · shell script
Uses
History (script call), Status (script call)
Used by
run by Update Lightning Workflow (workflow run)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 ci/replay-hourly-archive.sh:1-35 · blob a77333c8d888dfc86b526b8d0991fbde7c8b343e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: experimental · users: none · canonical: unknown
#!/usr/bin/env bash
# Replay of update-lightning.yml steps 3-4 on top of a newer origin/main (called
# by push-with-replay.sh after a rejected archive push). Inputs come from the
# run-local record in $RUNNER_TEMP; ARCHIVE_OUTCOME, COLLECT_OUTCOME, TRIGGER,
# RUN_ID, RUN_CREATED_UTC and JOB_STARTED_UTC come from the step environment.
# The archive is ingested again only if it succeeded the first time; if the
# replayed ingest or verify fails, the archive is restored and only the
# heartbeat (with archive outcome failure) is committed.
set -euo pipefail
archive=${ARCHIVE_OUTCOME:-skipped}
if [ "$archive" = "success" ]; then
  if python history.py ingest \
       --archive-dir data/history \
       --run-record "$RUNNER_TEMP/lightning-run-record.json" \
       --seed-scan-windows data/seed_scan_windows.json \
       --result-out "$RUNNER_TEMP/lightning-archive-result.json" \
     && python history.py verify --archive-dir data/history; then
    archive=success
  else
    echo "::warning::replayed archive ingest failed on the new main; committing the heartbeat only"
    archive=failure
    if [ -d data/history ]; then
      git checkout -- data/history 2>/dev/null || true
      git clean -fdq -- data/history
    fi
  fi
fi
python status.py write \
  --status data/status.json \
  --run-record "$RUNNER_TEMP/lightning-run-record.json" \
  --archive-result "$RUNNER_TEMP/lightning-archive-result.json" \
  --collect-outcome "${COLLECT_OUTCOME:-failure}" \
  --archive-outcome "$archive" \
  --trigger "${TRIGGER:-}" --run-id "${RUN_ID:-}" \
  --run-created "${RUN_CREATED_UTC:-}" --job-started "${JOB_STARTED_UTC:-}"