GLOBALGRID2050 / EXPLORE CODE

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

Backfill Parallel Lightning Workflow and 3 more files

A GitHub Actions workflow. Runs by hand.

599 lines of YAML from lightning, in 4 files. Topic: Automation and CI. Section 1819 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. Backfill Parallel Lightning Workflow automation · lightning / .github/workflows/backfill-parallel-lightning.yml lines 1–263
  2. Collector Watchdog Workflow automation · lightning / .github/workflows/collector-watchdog.yml lines 1–49
  3. Test Lightning Workflow test · lightning / .github/workflows/test-lightning.yml lines 1–83
  4. Update Lightning Workflow automation · lightning / .github/workflows/update-lightning.yml lines 1–204

Backfill Parallel Lightning Workflow

A GitHub Actions workflow. Runs by hand.

automationlightning / .github/workflows/backfill-parallel-lightning.yml · lines 1–263 of 263 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
Inputs & outputs
Out: commits pushed to the repository.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “UK lightning archive backfill (parallel)”; runs Backfill Parallel (`backfill_parallel.py`), History (`history.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
Test Backfill (workflow run), Test Backfill Parallel (workflow run), Test Backfill Workflow (workflow run), Test CI Verify (workflow run), Test Collect (workflow run), Test Collector Health (workflow run), Test Concurrent Writers (workflow run), Test Download Retries (workflow run), and 16 more
Used by
none found
Produces
none declared
Defines here
UK lightning archive backfill (parallel)
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/backfill-parallel-lightning.yml:1-263 · blob a630779eacae1adef802d70ef6ebe50c73580113 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: UK lightning archive backfill (parallel)
# Manual only. The parallel form of backfill-lightning.yml: fills UTC dates the
# archive index marks NEVER SEARCHED (coverage none / count null, not
# shard_lost) from fresh whole-day EUMETSAT searches, split over at most six
# date shards (EUMETSAT fair use). Shards only write run records, uploaded as
# artifacts; ONE finalize job ingests them all sequentially, verifies and makes
# ONE commit. Gaps stay unknown, never zero. See docs/HISTORY_ONE_YEAR.md,
# "Parallel backfill".
on:
  workflow_dispatch:
    inputs:
      end_date:
        description: "Newest UTC date to consider (YYYY-MM-DD). Empty = yesterday UTC."
        default: ""
        required: false
      days:
        description: "UTC dates to consider back from end_date (1-366). Only never-searched dates are searched."
        default: "90"
        required: false
      shards:
        description: "Parallel date shards (1-6; EUMETSAT fair use cap is 6)."
        default: "6"
        required: false
      dry_run:
        description: "Only plan the shards: no EUMETSAT calls, no commit."
        type: boolean
        default: false

permissions:
  contents: read

# Its OWN group, never uk-lightning-update: a backfill must never hold the
# hourly collector in its queue (GitHub keeps one pending run per group, so a
# shared group can also cancel a pending hourly run). Shards do not touch the
# repository; only the minutes-long finalize job pushes, after waiting for an
# active hourly run, and re-ingests on the new main if its push is rejected.
concurrency:
  group: uk-lightning-backfill
  cancel-in-progress: false

jobs:
  plan:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    outputs:
      count: ${{ steps.plan.outputs.count }}
      shards: ${{ steps.plan.outputs.shards }}
      matrix: ${{ steps.plan.outputs.matrix }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - run: pip install -r requirements.txt
      - name: Test pure-Python data contracts
        run: python -m unittest discover -s tests -v

      # Refuses days outside 1-366, shards outside 1-6, an end_date that is
      # today or later, a missing index, and (unless dry_run) any ref but main.
      - name: Plan never-searched UTC dates and shards
        id: plan
        env:
          END_DATE: ${{ inputs.end_date }}
          DAYS: ${{ inputs.days }}
          SHARDS: ${{ inputs.shards }}
          DRY_RUN: ${{ inputs.dry_run }}
        run: |
          if [ "$DRY_RUN" != "true" ] && [ "$GITHUB_REF" != "refs/heads/main" ]; then
            echo "::error::A backfill writes the archive and must run on main (got $GITHUB_REF); use dry_run elsewhere."
            exit 1
          fi
          python backfill_parallel.py plan --archive-dir data/history \
            --end-date "$END_DATE" --days "$DAYS" --shards "$SHARDS" \
            --plan-out "$RUNNER_TEMP/backfill-plan.txt"
          mkdir -p "$RUNNER_TEMP/plan-artifact"
          cp "$RUNNER_TEMP/backfill-plan.txt" "$RUNNER_TEMP/plan-artifact/backfill-plan.txt"
      - uses: actions/upload-artifact@v4
        with:
          name: backfill-plan
          path: ${{ runner.temp }}/plan-artifact
          retention-days: 7

  shard:
    needs: plan
    if: ${{ !inputs.dry_run && needs.plan.outputs.count != '0' }}
    runs-on: ubuntu-latest
    # About 18.5 min per whole-day search (run 40464739813: 11 dates in 203 min).
    # No new date starts after SHARD_BUDGET_MINUTES (170); a date still running
    # at SHARD_HARD_STOP_MINUTES (190) is killed and left unknown, so the search
    # step ends, and its records upload, inside the 200-minute job timeout.
    # Run 40564980740's shard 3 hung on a stalled EUMETSAT read (no HTTP timeout)
    # for over 5 h and held finalize for every shard; that can no longer happen.
    timeout-minutes: 200
    strategy:
      # An EUMETSAT error fails its shard AFTER its records are uploaded; fail-fast
      # then cancels the other shards (rate limits are per account), whose
      # always() upload still keeps every record they finished.
      fail-fast: true
      max-parallel: 6
      matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
    env:
      SHARD_BUDGET_MINUTES: "170"
      SHARD_HARD_STOP_MINUTES: "190"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - run: pip install -r requirements.txt

      # Run records only (never the feed, status or archive). Exits 0 for every
      # stop so the upload below always runs; the stop is surfaced after it.
      - name: Search this shard's dates (run records only)
        id: search
        # Backstop for the in-process wall clock: the step fails, the always()
        # upload below still runs before the job timeout.
        timeout-minutes: 195
        env:
          EUMETSAT_CONSUMER_KEY: ${{ secrets.EUMETSAT_CONSUMER_KEY }}
          EUMETSAT_CONSUMER_SECRET: ${{ secrets.EUMETSAT_CONSUMER_SECRET }}
          SHARD: ${{ matrix.shard }}
          DATES: ${{ matrix.dates }}
        run: |
          python backfill_parallel.py shard --shard "$SHARD" --dates "$DATES" \
            --out-dir "$RUNNER_TEMP/records" --budget-minutes "${SHARD_BUDGET_MINUTES:-170}" \
            --hard-stop-minutes "${SHARD_HARD_STOP_MINUTES:-190}" \
            --stagger-step-seconds "${SHARD_STAGGER_STEP_SECONDS:-20}" < /dev/null
      - uses: actions/upload-artifact@v4
        if: ${{ always() }}
        with:
          name: backfill-shard-${{ matrix.shard }}
          path: ${{ runner.temp }}/records
          include-hidden-files: false
          if-no-files-found: warn
          retention-days: 7
      - name: Surface shard stop
        if: ${{ always() }}
        env:
          STOPPED: ${{ steps.search.outputs.stopped }}
          ERROR: ${{ steps.search.outputs.error }}
        run: |
          case "$STOPPED" in
            completed) echo "Shard searched all its dates" ;;
            time_budget) echo "::warning::Shard stopped at its time budget; its remaining dates stay never searched." ;;
            *)
              echo "::error::Shard stopped (${STOPPED:-unknown}): $ERROR"
              exit 1 ;;
          esac

  finalize:
    needs: [plan, shard]
    # always(): records of shards that stopped early (rate limit, fail-fast
    # cancel, time budget) are still ingested; their missing dates stay unknown.
    if: ${{ always() && !inputs.dry_run && needs.plan.result == 'success' && needs.plan.outputs.count != '0' }}
    runs-on: ubuntu-latest
    timeout-minutes: 90
    permissions:
      contents: write
      actions: read
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 0
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - run: pip install -r requirements.txt
      - uses: actions/download-artifact@v4
        with:
          name: backfill-plan
          path: ${{ runner.temp }}/plan
      # Whatever shard artifacts exist: a shard that uploaded nothing is
      # "shard_missing" in finalize and its dates stay unknown; it never blocks
      # the records of the other shards.
      - name: Download shard records (whatever exists)
        continue-on-error: true
        uses: actions/download-artifact@v4
        with:
          pattern: backfill-shard-*
          merge-multiple: true
          path: ${{ runner.temp }}/records

      # Ingest every record sequentially on the newest main, verify, ONE commit.
      # If the push is rejected (the hourly job committed meanwhile), reset to
      # the new main and re-ingest from the same records: never a rebase merge
      # of index.json. Dates without a verified record stay never searched.
      - name: Ingest, verify and commit (one commit)
        id: finalize
        env:
          GH_TOKEN: ${{ github.token }}
          SHARDS: ${{ needs.plan.outputs.shards }}
          HOURLY_WAIT_MINUTES: "20"
          PUSH_ATTEMPTS: "5"
        run: |
          if [ "$GITHUB_REF" != "refs/heads/main" ]; then
            echo "::error::A backfill writes the archive and must run on main (got $GITHUB_REF)."
            exit 1
          fi
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          pushed=no
          attempt=0
          while [ "$attempt" -lt "${PUSH_ATTEMPTS:-5}" ]; do
            attempt=$((attempt + 1))
            python backfill_parallel.py wait-hourly --repo "${GITHUB_REPOSITORY:-}" --gh "${GH_BIN:-gh}" \
              --max-minutes "${HOURLY_WAIT_MINUTES:-20}" --poll-seconds "${HOURLY_POLL_SECONDS:-30}" || true
            git fetch -q origin main
            git reset -q --hard origin/main
            git clean -fdq -- data
            : > "$GITHUB_OUTPUT.attempt"
            GITHUB_OUTPUT="$GITHUB_OUTPUT.attempt" python backfill_parallel.py finalize \
              --plan "$RUNNER_TEMP/plan/backfill-plan.txt" --shards "$SHARDS" \
              --records-dir "$RUNNER_TEMP/records" --archive-dir data/history --status data/status.json \
              --filled-out "$RUNNER_TEMP/backfill-filled.txt" < /dev/null
            # Nothing unverified is committed.
            python history.py verify --archive-dir data/history
            git add -A -- data/status.json data/history
            if git diff --cached --quiet; then
              echo "No backfilled dates or status change to commit"
              pushed=nothing
              break
            fi
            # The same quick verify the hourly and sequential backfill commits
            # run before pushing (feed/status/archive parts that are staged).
            python ci/verify_data.py --staged
            stopped=$(sed -n 's/^stopped=//p' "$GITHUB_OUTPUT.attempt")
            filled=$(grep -c . "$RUNNER_TEMP/backfill-filled.txt" || true)
            range=$(paste -sd, "$RUNNER_TEMP/backfill-filled.txt")
            git commit -q -m "data: parallel backfill of ${filled} never-searched UTC day(s) of the one-year archive" \
                       -m "Dates: ${range:-none}. Shards: ${SHARDS}. Stopped: ${stopped}."
            if git push -q origin HEAD:main; then
              pushed=yes
              break
            fi
            echo "::notice::Push attempt $attempt rejected (main moved); re-ingesting on the new main."
          done
          cat "$GITHUB_OUTPUT.attempt" >> "$GITHUB_OUTPUT"
          echo "pushed=$pushed" >> "$GITHUB_OUTPUT"
          if [ "$pushed" = "no" ]; then
            echo "::error::Backfill commit not pushed after $attempt attempts; the records stay in the artifacts for 7 days."
            exit 1
          fi

      # An EUMETSAT error, an archive refusal, a cancelled or missing shard turns
      # the run red AFTER the verified dates were committed; a time-budget stop warns.
      - name: Surface backfill stop
        if: ${{ always() }}
        env:
          STOPPED: ${{ steps.finalize.outputs.stopped }}
          ERROR: ${{ steps.finalize.outputs.error }}
          OUTCOME: ${{ steps.finalize.outcome }}
        run: |
          case "$STOPPED" in
            completed) echo "Parallel backfill completed" ;;
            time_budget) echo "::warning::Backfill stopped at the time budget; remaining dates stay never searched. Run again." ;;
            *)
              echo "::error::Backfill stopped (${STOPPED:-step $OUTCOME}): $ERROR. Remaining dates stay never searched (unknown, not zero)."
              exit 1 ;;
          esac

Collector Watchdog Workflow

A GitHub Actions workflow in Lightning. Runs by hand.

automationlightning / .github/workflows/collector-watchdog.yml · lines 1–49 of 49 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: starts processes.
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)"
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “UK lightning collector watchdog”; runs CI Collector Health (`ci/collector_health.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
CI Collector Health (workflow run)
Used by
none found
Produces
none declared
Defines here
UK lightning collector watchdog
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/collector-watchdog.yml:1-49 · blob 5d0df222a864bda8bc96be2c69261ada33995db6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: unknown · effects: process · domain stage: unknown · users: none · canonical: unknown
name: UK lightning collector watchdog
# Why this one scheduled workflow exists (docs/OPERATIONS.md, "Watchdog"):
# the health check also runs at the end of every hourly run and in
# verify-lightning-data.yml, but both only run when a writer has run. When the
# GitHub cron AND the hourly nudge both stop, no writer runs, so no in-workflow
# check can ever see the silence. This independent schedule reads the
# committed data/status.json and opens the "collector-stale" issue once the
# heartbeat is past late_after_utc + 90 min. It also probes the public
# raw.githubusercontent.com path the map reads ("feed-delivery" issue).
#
# Tiny on purpose: sparse checkout of two files, stdlib Python already on the
# runner (no setup-python, no pip), read-only contents, about 15 s a run. It
# never collects, never commits and never dispatches another workflow. Two
# slots an hour, away from :17/:47 (collector) and :29 (nudge), because
# GitHub drops scheduled runs (28 Oct 2026: 10 of 48 collector slots ran).
# A red watchdog run is a second alarm: GitHub e-mails scheduled-run failures
# to the person who last edited this cron.
on:
  # Schedule removed 1 Nov 2026: the collector is now manual-only, so a
  # timed staleness check would always alarm. Run by hand if needed.
  workflow_dispatch:

permissions:
  contents: read
  issues: write

concurrency:
  group: uk-lightning-watchdog
  cancel-in-progress: true

jobs:
  watchdog:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          sparse-checkout: |
            ci/collector_health.py
            data/status.json
          sparse-checkout-cone-mode: false
      - name: Collector heartbeat and raw delivery (collector-stale, feed-delivery)
        env:
          GH_TOKEN: ${{ github.token }}
          SOURCE: collector-watchdog run ${{ github.run_id }} (${{ github.event_name }})
        run: |
          python3 ci/collector_health.py --status data/status.json --issue --raw \
            --fail-when-unhealthy --source "$SOURCE" --summary "$GITHUB_STEP_SUMMARY"

Test Lightning Workflow

A GitHub Actions workflow. Runs on push and on pull requests.

testlightning / .github/workflows/test-lightning.yml · lines 1–83 of 83 · Entry point

What it does
It tests its inputs. Side effects: changes the web page (DOM); starts processes.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “Validate UK lightning data pipeline”.
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
Test Backfill (workflow run), Test Backfill Parallel (workflow run), Test Backfill Workflow (workflow run), Test CI Verify (workflow run), Test Collect (workflow run), Test Collector Health (workflow run), Test Concurrent Writers (workflow run), Test Download Retries (workflow run), and 14 more
Used by
none found
Produces
none declared
Defines here
Validate UK lightning data pipeline
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/test-lightning.yml:1-83 · blob a12dd6901dd3f3b11eec975696797f1fe17e67dc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: unknown · users: none · canonical: unknown
name: Validate UK lightning data pipeline
on:
  push:
    paths:
      - "collect.py"
      - "history.py"
      - "grid.py"
      - "status.py"
      - "backfill_parallel.py"
      - "reproduce.py"
      - "history-window.mjs"
      - "tests/**"
      - "ci/**"
      - ".github/workflows/test-lightning.yml"
      - ".github/workflows/update-lightning.yml"
      - ".github/workflows/backfill-lightning.yml"
      - ".github/workflows/backfill-parallel-lightning.yml"
      - ".github/workflows/verify-lightning-data.yml"
      - ".github/workflows/collector-watchdog.yml"
      - "requirements.txt"
  pull_request:
    paths:
      - "collect.py"
      - "history.py"
      - "grid.py"
      - "status.py"
      - "backfill_parallel.py"
      - "reproduce.py"
      - "history-window.mjs"
      - "tests/**"
      - "ci/**"
      - ".github/workflows/test-lightning.yml"
      - ".github/workflows/update-lightning.yml"
      - ".github/workflows/backfill-lightning.yml"
      - ".github/workflows/backfill-parallel-lightning.yml"
      - ".github/workflows/verify-lightning-data.yml"
      - ".github/workflows/collector-watchdog.yml"
      - "requirements.txt"

jobs:
  test:
    # Two legs (28 Oct 2026): "requirements" is the environment production runs
    # (update/backfill jobs pip install -r requirements.txt); before this leg CI
    # had no requests/eumdac/netCDF4, so tests had to inject every dependency and
    # the default-argument NameError of PR #15 (backfill run 40699133665) passed.
    # "bare" keeps the pure-Python contracts runnable without the packages.
    name: test (${{ matrix.deps }})
    runs-on: ubuntu-latest
    timeout-minutes: 15
    strategy:
      fail-fast: false
      matrix:
        deps: [requirements, bare]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - name: Install requirements.txt
        if: matrix.deps == 'requirements'
        run: pip install -r requirements.txt
      - name: Static check (undefined names, the class of the PR #15 NameError)
        run: |
          pip install pyflakes==3.2.0
          python -m pyflakes *.py ci/*.py tests/*.py > "$RUNNER_TEMP/pyflakes.txt" || true
          cat "$RUNNER_TEMP/pyflakes.txt"
          if grep -E "undefined name|referenced before assignment|unable to detect undefined names" "$RUNNER_TEMP/pyflakes.txt"; then
            echo "::error::pyflakes found an undefined name"
            exit 1
          fi
      - name: Test pure-Python data contracts and the default-path smoke test
        env:
          # The full-pipeline smoke test may not skip on the requirements leg.
          LIGHTNING_SMOKE_REQUIRE_DEPS: ${{ matrix.deps == 'requirements' && '1' || '0' }}
        run: python -m unittest discover -s tests -v
      - uses: actions/setup-node@v4
        if: matrix.deps == 'requirements'
        with:
          node-version: "24"
      - name: Test archive date-window loader (Node)
        if: matrix.deps == 'requirements'
        run: node --test tests/test_history_window.mjs

Update Lightning Workflow

A GitHub Actions workflow. Runs by hand.

automationlightning / .github/workflows/update-lightning.yml · lines 1–204 of 204 · Entry point

What it does
It runs automated jobs on GitHub Actions. Side effects: changes the web page (DOM); starts processes.
Why it exists in the grid workflow
README: "`.github/workflows/update-lightning.yml`: hourly update"
Inputs & outputs
In: JSON file lightning-run-record.json; GeoJSON file lightning-feed.geojson; GeoJSON file uk_lightning.geojson; JSON file lightning-archive-result.json.
Downstream impact
It is itself an entry point (workflow); no other file was found loading it.
What it achieves
Named “UK lightning optical flashes”; runs Status (`status.py`), Collect (`collect.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
Status (workflow run), Test Backfill (workflow run), Test Backfill Parallel (workflow run), Test Backfill Workflow (workflow run), Test CI Verify (workflow run), Test Collect (workflow run), Test Collector Health (workflow run), Test Concurrent Writers (workflow run), and 20 more
Used by
none found
Produces
none declared
Defines here
UK lightning optical flashes
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/update-lightning.yml:1-204 · blob b55538a74b09ae30b9beb8f06747349891eb6895 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, process · domain stage: unknown · users: none · canonical: unknown
name: UK lightning optical flashes
on:
  # Manual only (1 Nov 2026): run from the Actions tab when needed. The
  # self-healing lookback covers up to 48 h; for longer gaps use backfill.
  workflow_dispatch:
    inputs:
      hours:
        description: "Explicit lookback in hours (1-48). Leave empty for the automatic self-healing window."
        default: ""
        required: false

permissions:
  contents: write
  actions: read   # read this run's created_at for the heartbeat (queue time)
  issues: write   # open/update/close the "collector-stale" issue (ci/collector_health.py)

# The hourly feed's own group. NO other workflow may use it: the backfill has
# `uk-lightning-backfill`, so a multi-hour backfill can never queue the hourly
# job (27 Oct 2026: run 40476905747 waited 91 min behind backfill 40464739813
# while both shared `uk-lightning-update`). Within this group a run lasts at
# most timeout-minutes (55), so a queued hourly run waits under an hour; GitHub
# keeps one pending run per group and a newer one replaces it, which is
# harmless because the self-healing lookback covers the skipped slot.
concurrency:
  group: uk-lightning-update
  cancel-in-progress: false

jobs:
  # Cheap guard for the :47 fallback slot: skip when a run succeeded < 40 min ago.
  gate:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      due: ${{ steps.due.outputs.due }}
    steps:
      - uses: actions/checkout@v4
        with:
          # The branch tip now, not the SHA the (possibly queued) run was created
          # at: the gate must see the heartbeat of a run that just finished.
          ref: ${{ github.ref }}
          sparse-checkout: |
            status.py
            collect.py
            data/status.json
          sparse-checkout-cone-mode: false
      - name: Decide whether this slot collects
        id: due
        run: |
          python3 status.py due --status data/status.json --event "${{ github.event_name }}" \
            --github-output "$GITHUB_OUTPUT"

  collect:
    needs: gate
    if: needs.gate.outputs.due == 'true'
    runs-on: ubuntu-latest
    timeout-minutes: 55
    steps:
      - name: Record run timing for the heartbeat
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          echo "JOB_STARTED_UTC=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_ENV"
          created=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" --jq .created_at 2>/dev/null || true)
          echo "RUN_CREATED_UTC=$created" >> "$GITHUB_ENV"
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"
      - run: pip install -r requirements.txt
      - name: Test pure-Python data contracts
        run: python -m unittest discover -s tests -v

      # 1. Collect. Writes the 7-day feed and leaves an uncapped run record in
      #    the runner's temp dir (never committed). The record carries the
      #    examined 10-minute product slots, the searched ranges and the gaps.
      - name: EUMETSAT collection (feed first)
        id: collect
        continue-on-error: true
        env:
          EUMETSAT_CONSUMER_KEY: ${{ secrets.EUMETSAT_CONSUMER_KEY }}
          EUMETSAT_CONSUMER_SECRET: ${{ secrets.EUMETSAT_CONSUMER_SECRET }}
          HOURS: ${{ inputs.hours }}
        run: |
          if [ -n "$HOURS" ]; then
            WINDOW=(--hours "$HOURS")
          else
            WINDOW=(--auto-window)
          fi
          python collect.py "${WINDOW[@]}" \
            --out data/uk_lightning.geojson \
            --status data/status.json \
            --history-dir data/history \
            --run-record "$RUNNER_TEMP/lightning-run-record.json"

      # 2. Commit the public feed on its own, before anything touches the archive.
      #    Only this job writes the feed; a rejected push (a backfill commit
      #    landed) is replayed by restoring the saved feed onto the new main.
      - name: Commit latest public GeoJSON (feed commit)
        if: steps.collect.outcome == 'success'
        env:
          # Quick verify of what this commit changes, before every push attempt
          # (also after a replay): nothing malformed reaches main.
          PUSH_VERIFY: python ci/verify_data.py --staged
        run: |
          if git diff --quiet -- data/uk_lightning.geojson; then
            echo "No changed feed output"
            exit 0
          fi
          cp data/uk_lightning.geojson "$RUNNER_TEMP/lightning-feed.geojson"
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          bash ci/push-with-replay.sh "data: refresh UK satellite lightning flash layer" \
            'cp "$RUNNER_TEMP/lightning-feed.geojson" data/uk_lightning.geojson' \
            data/uk_lightning.geojson

      # 3. Append to the one-year UTC archive (index v2 + day shards). A failure
      #    here (for example a shard above max_shard_bytes) never blocks the feed.
      - name: Append to the one-year UTC archive
        id: archive
        if: steps.collect.outcome == 'success'
        continue-on-error: true
        run: |
          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"
          # Nothing unverified is committed: bytes, sha256 and counts vs the index.
          python history.py verify --archive-dir data/history

      # 4. Always record the outcome: last attempt, last error, consecutive
      #    failures and the last successful scan end the next run looks back to.
      - name: Write data/status.json (always)
        if: always()
        run: |
          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 "${{ steps.collect.outcome }}" \
            --archive-outcome "${{ steps.archive.outcome }}" \
            --trigger "${{ github.event_name }}" --run-id "${{ github.run_id }}" \
            --run-created "${RUN_CREATED_UTC:-}" --job-started "${JOB_STARTED_UTC:-}"

      # 5. Commit archive and status separately from the feed. If a backfill
      #    pushed in the meantime, the push is rejected and the archive ingest
      #    and status write are REPLAYED on top of the backfill's commit from
      #    the run record (no textual merge of index.json / status.json).
      - name: Commit archive and status (archive commit)
        if: always()
        env:
          ARCHIVE_OUTCOME: ${{ steps.archive.outcome }}
          COLLECT_OUTCOME: ${{ steps.collect.outcome }}
          TRIGGER: ${{ github.event_name }}
          RUN_ID: ${{ github.run_id }}
          # Quick verify of the staged archive/status before every push attempt
          # (also after a replay). Only the parts this commit changes are
          # checked, so a heartbeat-only commit is never blocked by the archive.
          PUSH_VERIFY: python ci/verify_data.py --staged
        run: |
          if [ "$ARCHIVE_OUTCOME" != "success" ] && [ -d data/history ]; then
            # A failed or unverified archive step is never committed: drop any
            # half-written shard/index and keep the last committed archive.
            git checkout -- data/history 2>/dev/null || true
            git clean -fdq -- data/history
          fi
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          # Paths are staged one by one inside the helper: before the first
          # successful archive write data/history does not exist and a combined
          # pathspec aborts with 128, losing the heartbeat.
          bash ci/push-with-replay.sh "data: archive UTC day shards, index v2 and collector status" \
            'bash ci/replay-hourly-archive.sh' \
            data/status.json data/history

      # 6. Open, refresh or close the "collector-stale" issue from the status
      #    just written (docs/OPERATIONS.md). A fresh heartbeat closes it on
      #    recovery; 3+ consecutive failures (e.g. rejected EUMETSAT
      #    credentials) open it. Monitoring never changes the run's outcome.
      - name: Collector health issue (collector-stale)
        if: always()
        continue-on-error: true
        env:
          GH_TOKEN: ${{ github.token }}
          SOURCE: update-lightning run ${{ github.run_id }}
        run: |
          python ci/collector_health.py --status data/status.json --issue \
            --source "$SOURCE" --summary "$GITHUB_STEP_SUMMARY"

      # 7. Make a failed collection or archive visible in the Actions UI even
      #    though the steps above were allowed to continue. A shard_lost
      #    integrity alert also turns the run red, AFTER healthy days and the
      #    status were committed, until `history.py recover` clears it.
      - name: Surface collection, archive or integrity failure
        if: always()
        run: |
          fail=0
          if [ "${{ steps.collect.outcome }}" != "success" ] || [ "${{ steps.archive.outcome }}" = "failure" ]; then
            echo "::error::collect=${{ steps.collect.outcome }} archive=${{ steps.archive.outcome }} (see data/status.json)"
            fail=1
          fi
          python status.py alert --status data/status.json || fail=1
          exit "$fail"