GLOBALGRID2050 / EXPLORE CODE

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

Test Download Retries and 1 more file

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It reads timeout (`ReadTimeout`), reads timeout sub (`ReadTimeoutSub`) and sets up (`setUp`).

700 lines of Python from lightning, in 2 files. Topic: Automation and CI. Section 1825 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 Concurrent Writers test · lightning / tests/test_concurrent_writers.py lines 1–294
  2. Test Download Retries test · lightning / tests/test_download_retries.py lines 1–406

Test Concurrent Writers

A test in the tests folder of Lightning that checks History and Collect. It sets up (`setUp`), backfills search (`backfill_search`) and backfills commit (`backfill_commit`).

testlightning / tests/test_concurrent_writers.py · lines 1–294 of 294 · Entry point · pattern runner (shared by 3 files)

What it does
It tests its inputs. Defines 25 functions or classes, including ConcurrencyDesignTests, group, test_no_other_workflow_shares_the_hourly_group, test_hourly_run_is_bounded_under_an_hour_and_never_cancelled, test_two_cron_slots_and_a_gate_that_only_scheduled_runs_can_skip. 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; JSON file lightning-run-record.json.
Downstream impact
Used directly by 4 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning).
What it achieves
The hourly collector and a backfill commit to main at the same time.
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), Test Backfill Workflow (import), CI Push with Replay (script call), 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)
Produces
ConcurrencyDesignTests, PushRaceTests
Defines here
ConcurrencyDesignTests, group, test_no_other_workflow_shares_the_hourly_group, test_hourly_run_is_bounded_under_an_hour_and_never_cancelled, test_two_cron_slots_and_a_gate_that_only_scheduled_runs_can_skip, test_status_write_records_trigger_and_run_timing, test_no_pull_rebase_of_generated_files_in_any_writer, PushRaceTests, setUp, tearDown, clone, git, runner, sh, hourly_collect, hourly_commit, backfill_search, backfill_commit, main_view, test_hourly_push_loses_to_a_backfill_and_replays_its_archive_and_heartbeat, test_backfill_push_loses_to_the_hourly_job_and_skips_a_date_the_hourly_job_searched, test_feed_push_loses_to_a_backfill_and_the_archive_then_builds_on_the_backfill, test_refuses_to_reset_over_unrelated_uncommitted_changes, test_pushes_to_the_checked_out_branch_never_to_main, test_gives_up_loudly_after_the_attempt_limit
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_concurrent_writers.py:1-294 · blob a8421b7f635da7995df35f9dbd84a46e319daaa8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""The hourly collector and a backfill commit to main at the same time.

They run in separate concurrency groups (a backfill can no longer queue the
hourly feed), so either one can find main moved under it. These tests run the
real commit-step shells of BOTH workflows in two clones of one bare 'origin'
(no network, no EUMETSAT, no GitHub) and check that the loser of the push race
replays its own inputs on top of the winner's commit: nothing is lost, nothing
is textually merged, the archive verifies, and status.json keeps the hourly
heartbeat and the backfill block side by side.
"""
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))
sys.path.insert(0, str(ROOT / "tests"))
import history
from collect import build_feature
from test_backfill_workflow import BACKFILL, FAKE_DOWNLOAD, HOURLY, outputs, step, substitute

HOURLY_ARCHIVE_COMMIT = "Commit archive and status (archive commit)"
HOURLY_FEED_COMMIT = "Commit latest public GeoJSON (feed commit)"
BF_PLAN, BF_SEARCH, BF_COMMIT = ("Plan never-searched UTC dates", "Search and ingest each date",
                                 "Verify and commit backfilled dates (one commit)")
WORKFLOWS = ROOT / ".github" / "workflows"


class ConcurrencyDesignTests(unittest.TestCase):
    """The hourly group belongs to the hourly workflow alone; no textual rebase of generated files."""

    @staticmethod
    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)

    def test_no_other_workflow_shares_the_hourly_group(self):
        for path in WORKFLOWS.glob("*.yml"):
            if path.name != HOURLY.name and "\nconcurrency:\n" in path.read_text():
                self.assertNotEqual(self.group(path), self.group(HOURLY), path.name)

    def test_hourly_run_is_bounded_under_an_hour_and_never_cancelled(self):
        text = HOURLY.read_text()
        self.assertRegex(text, r"concurrency:\n  group: uk-lightning-update\n  cancel-in-progress: false")
        timeouts = [int(t) for t in re.findall(r"timeout-minutes:\s*(\d+)", text)]
        self.assertTrue(timeouts and max(timeouts) <= 55, timeouts)

    def test_two_cron_slots_and_a_gate_that_only_scheduled_runs_can_skip(self):
        text = HOURLY.read_text()
        on_block = text.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
        self.assertEqual(re.findall(r'cron: "([^"]+)"', on_block), ["17 * * * *", "47 * * * *"])
        self.assertIn("needs: gate", text)
        self.assertIn("if: needs.gate.outputs.due == 'true'", text)
        self.assertIn('status.py due --status data/status.json --event "${{ github.event_name }}"', text)

    def test_status_write_records_trigger_and_run_timing(self):
        text = HOURLY.read_text()
        self.assertIn("actions: read", text)
        for flag in ("--trigger", "--run-id", "--run-created", "--job-started"):
            self.assertIn(flag, text)

    def test_no_pull_rebase_of_generated_files_in_any_writer(self):
        for path in (HOURLY, BACKFILL):
            self.assertNotIn("pull --rebase", path.read_text(), path.name)
            self.assertIn("ci/push-with-replay.sh", path.read_text(), path.name)


@unittest.skipUnless(shutil.which("git") and shutil.which("bash"), "git and bash are required")
class PushRaceTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        self.env = {**os.environ, "HOME": str(self.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",
                    "GITHUB_REF": "refs/heads/main", "PYTHONDONTWRITEBYTECODE": "1", "PUSH_RETRY_SLEEP": "0"}
        bin_dir = self.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 = self.base / "origin.git"
        seed = self.base / "seed"
        self.git(self.base, "init", "-q", "--bare", "-b", "main", str(self.origin))
        self.git(self.base, "init", "-q", "-b", "main", str(seed))
        self.git(seed, "remote", "add", "origin", str(self.origin))
        for name in ("history.py", "grid.py", "status.py"):
            shutil.copy(ROOT / name, seed / 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__":')
        (seed / "collect.py").write_text(source)
        shutil.copytree(ROOT / "ci", seed / "ci")
        (seed / ".gitignore").write_text("__pycache__/\n")

        self.now = datetime.now(timezone.utc)
        self.today = self.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(
            seed / "data" / "history", [build_feature(-2.0, 52.0, searched + timedelta(hours=2), "TEST-hourly", 0)],
            now=self.now, scanned_windows=[history.successful_scan((searched + timedelta(hours=1)).isoformat(),
                                                                   (searched + timedelta(hours=7)).isoformat(), 36)],
            lookback_hours=6.0)
        (seed / "data" / "status.json").write_text(json.dumps({
            "schema": "uk-lightning-status.v1", "health": "ok", "freshness": "ok",
            "last_attempt_utc": (self.now - timedelta(hours=1)).isoformat(), "last_attempt_outcome": "success",
            "consecutive_failures": 0, "last_successful_scan_end_utc": (self.now - timedelta(hours=1)).isoformat(),
            "integrity": {"state": "ok", "alert": None, "lost_days": []}}, indent=1) + "\n")
        (seed / "data" / "uk_lightning.geojson").write_text('{"features": []}\n')
        self.git(seed, "add", "-A")
        self.git(seed, "commit", "-q", "-m", "initial archive")
        self.git(seed, "push", "-q", "-u", "origin", "main")
        self.hourly = self.clone("hourly")
        self.backfill = self.clone("backfill")

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

    def clone(self, name):
        path = self.base / name
        self.git(self.base, "clone", "-q", str(self.origin), str(path))
        (self.base / f"{name}-runner").mkdir()
        return path

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

    def runner(self, repo):
        return self.base / f"{repo.name}-runner"

    def sh(self, repo, script, extra=None):
        env = {**self.env, "RUNNER_TEMP": str(self.runner(repo)), "GITHUB_OUTPUT": str(self.runner(repo) / "out"),
               **(extra or {})}
        return subprocess.run(["bash", "-e", "-c", script], cwd=repo, env=env, capture_output=True, text=True)

    # --- the two writers, using the real workflow step shells -----------------
    def hourly_collect(self, start, end, flash_at, flash_id):
        """Step 1 of update-lightning.yml (EUMETSAT) replaced by its outputs: run record and feed."""
        record = {"schema": "uk-lightning-run-record.v1", "outcome": "success", "error": None,
                  "run_utc": history.format_utc(self.now), "products_examined": 6, "lookback_hours": 6.0,
                  "slots_parsed": True, "scanned_ranges": [{"start_utc": history.format_utc(start),
                                                            "end_utc": history.format_utc(end)}],
                  "features": [build_feature(-2.0, 52.0, flash_at, flash_id, 0)]}
        (self.runner(self.hourly) / "lightning-run-record.json").write_text(json.dumps(record))
        (self.hourly / "data" / "uk_lightning.geojson").write_text(json.dumps({"features": [flash_id]}) + "\n")
        self.hourly_env = {"ARCHIVE_OUTCOME": "success", "COLLECT_OUTCOME": "success", "TRIGGER": "schedule",
                           "RUN_ID": "4242", "RUN_CREATED_UTC": history.format_utc(self.now - timedelta(minutes=2)),
                           "JOB_STARTED_UTC": history.format_utc(self.now - timedelta(minutes=1))}

    def hourly_commit(self, before_feed=None, before_archive_commit=None):
        """Steps 2-5 of update-lightning.yml in order; the hooks let the other writer push in between."""
        if before_feed:
            before_feed()
        feed = self.sh(self.hourly, substitute(step(HOURLY, HOURLY_FEED_COMMIT), {}))
        self.assertEqual(feed.returncode, 0, feed.stdout + feed.stderr)
        archive = self.sh(self.hourly, substitute(step(HOURLY, "Append to the one-year UTC archive"), {}))
        self.assertEqual(archive.returncode, 0, archive.stderr)
        status = self.sh(self.hourly, substitute(step(HOURLY, "Write data/status.json (always)"), {
            "steps.collect.outcome": "success", "steps.archive.outcome": "success", "github.event_name": "schedule",
            "github.run_id": "4242"}), self.hourly_env)
        self.assertEqual(status.returncode, 0, status.stderr)
        if before_archive_commit:
            before_archive_commit()
        done = self.sh(self.hourly, substitute(step(HOURLY, HOURLY_ARCHIVE_COMMIT), {}), self.hourly_env)
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        return feed, done

    def backfill_search(self):
        plan = self.sh(self.backfill, substitute(step(BACKFILL, BF_PLAN), {}), {"END_DATE": "", "DAYS": "4"})
        self.assertEqual(plan.returncode, 0, plan.stderr)
        search = self.sh(self.backfill, substitute(step(BACKFILL, BF_SEARCH), {}))
        self.assertEqual(search.returncode, 0, search.stderr)
        return outputs(self.runner(self.backfill) / "out")

    def backfill_commit(self, out):
        done = self.sh(self.backfill, substitute(step(BACKFILL, BF_COMMIT), {}),
                       {"STOPPED": out["stopped"], "ERROR": out.get("error", "")})
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        return done

    # --- what landed on origin/main --------------------------------------------
    def main_view(self):
        check = self.base / "check"
        if check.exists():
            shutil.rmtree(check)
        self.git(self.base, "clone", "-q", str(self.origin), str(check))
        self.assertEqual(history.main(["verify", "--archive-dir", str(check / "data" / "history")]), 0)
        index = json.loads((check / "data" / "history" / "index.json").read_text())
        status = json.loads((check / "data" / "status.json").read_text())
        ids = set()
        for f in (check / "data" / "history" / "days").rglob("*.json"):
            ids |= {feat["id"] for feat in json.loads(f.read_text()).get("features", [])}
        return {r["date"]: r for r in index["days"]}, status, ids, check

    def test_hourly_push_loses_to_a_backfill_and_replays_its_archive_and_heartbeat(self):
        out = self.backfill_search()
        start = self.now - timedelta(hours=2)
        self.hourly_collect(start, self.now - timedelta(minutes=10), self.now - timedelta(hours=1), "TEST-hourly-new")
        # The backfill pushes after the hourly job ingested but before it committed the archive.
        feed, done = self.hourly_commit(before_archive_commit=lambda: self.backfill_commit(out))
        self.assertIn("pushed on attempt 1", feed.stdout)
        self.assertIn("push rejected (attempt 1/5)", done.stdout)
        self.assertIn("pushed on attempt 2", done.stdout)
        rows, status, ids, check = self.main_view()
        d1, d2, d3, d4 = self.days
        for d in (d3, d4):
            self.assertEqual((rows[d]["coverage"], rows[d]["count"]), ("full", 1), d)
        self.assertIn("TEST-hourly-new:0", ids)          # the hourly flash survived the replay
        self.assertIn(f"TEST-fake-{d3}:0", ids)          # and the backfill's flashes were not overwritten
        self.assertEqual(status["backfill"]["filled_days"], [d1, d3, d4])
        self.assertEqual(status["last_attempt_utc"], history.format_utc(self.now))
        self.assertEqual(status["heartbeat"]["this_run"]["run_id"], "4242")
        self.assertEqual(status["heartbeat"]["this_run"]["trigger"], "schedule")
        self.assertEqual(json.loads((check / "data" / "uk_lightning.geojson").read_text()), {"features": ["TEST-hourly-new"]})
        log = self.git(check, "log", "--format=%s")
        self.assertIn("data: backfill 3 never-searched", log)
        self.assertIn("data: archive UTC day shards", log)

    def test_backfill_push_loses_to_the_hourly_job_and_skips_a_date_the_hourly_job_searched(self):
        out = self.backfill_search()
        d1, d2, d3, d4 = self.days
        d1_start = datetime.combine(self.today - timedelta(days=1), time(22, 0), tzinfo=timezone.utc)
        self.hourly_collect(d1_start, d1_start + timedelta(minutes=110), d1_start + timedelta(minutes=30), "TEST-hourly-d1")
        self.hourly_commit()                            # the hourly job wins; it touched d1 (yesterday)
        done = self.backfill_commit(out)                # rejected, replayed: d1 is no longer never searched
        self.assertIn("push rejected (attempt 1/5)", done.stdout)
        self.assertIn(f"replay: {d1} is no longer never-searched", done.stdout)
        rows, status, ids, _ = self.main_view()
        self.assertEqual(rows[d1]["coverage"], "partial")   # the hourly job's row is kept, not overwritten
        self.assertIn("TEST-hourly-d1:0", ids)
        self.assertNotIn(f"TEST-fake-{d1}:0", ids)
        for d in (d3, d4):
            self.assertEqual((rows[d]["coverage"], rows[d]["count"]), ("full", 1), d)
        self.assertEqual(status["backfill"]["filled_days"], [d3, d4])
        self.assertEqual(status["backfill"]["remaining_unknown_days"], [d1])
        # The hourly heartbeat committed by the winner is untouched by the backfill replay.
        self.assertEqual(status["last_attempt_utc"], history.format_utc(self.now))
        self.assertEqual(status["heartbeat"]["this_run"]["run_id"], "4242")

    def test_feed_push_loses_to_a_backfill_and_the_archive_then_builds_on_the_backfill(self):
        out = self.backfill_search()
        self.hourly_collect(self.now - timedelta(hours=2), self.now - timedelta(minutes=10),
                            self.now - timedelta(hours=1), "TEST-hourly-feed")
        feed, done = self.hourly_commit(before_feed=lambda: self.backfill_commit(out))
        self.assertIn("push rejected (attempt 1/5)", feed.stdout)
        self.assertIn("pushed on attempt 2", feed.stdout)
        self.assertIn("pushed on attempt 1", done.stdout)  # the archive step already ran on the new main
        rows, status, ids, check = self.main_view()
        self.assertEqual(json.loads((check / "data" / "uk_lightning.geojson").read_text()), {"features": ["TEST-hourly-feed"]})
        self.assertTrue({"TEST-hourly-feed:0", f"TEST-fake-{self.days[2]}:0"} <= ids)
        self.assertEqual(status["backfill"]["filled_days"], [self.days[0], self.days[2], self.days[3]])
        self.assertEqual(status["heartbeat"]["this_run"]["run_id"], "4242")

    def test_refuses_to_reset_over_unrelated_uncommitted_changes(self):
        out = self.backfill_search()
        self.backfill_commit(out)
        (self.hourly / "data" / "uk_lightning.geojson").write_text('{"features": ["x"]}\n')
        (self.hourly / "history.py").write_text("# local edit that a reset would destroy\n")
        done = self.sh(self.hourly, substitute(step(HOURLY, HOURLY_FEED_COMMIT), {}))
        self.assertNotEqual(done.returncode, 0)
        self.assertIn("refusing to reset over uncommitted changes outside the step's paths: history.py", done.stdout)
        self.assertEqual((self.hourly / "history.py").read_text(), "# local edit that a reset would destroy\n")

    def test_pushes_to_the_checked_out_branch_never_to_main(self):
        main_before = self.git(self.hourly, "rev-parse", "origin/main")
        self.git(self.hourly, "checkout", "-q", "-b", "feature")
        (self.hourly / "data" / "uk_lightning.geojson").write_text('{"features": ["branch"]}\n')
        done = self.sh(self.hourly, "bash ci/push-with-replay.sh 'feed on a branch' true data/uk_lightning.geojson")
        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
        self.git(self.hourly, "fetch", "-q", "origin")
        self.assertEqual(self.git(self.hourly, "rev-parse", "origin/main"), main_before)
        self.assertEqual(self.git(self.hourly, "log", "-1", "--format=%s", "origin/feature").strip(), "feed on a branch")

    def test_gives_up_loudly_after_the_attempt_limit(self):
        out = self.backfill_search()
        self.hourly_collect(self.now - timedelta(hours=2), self.now - timedelta(minutes=10),
                            self.now - timedelta(hours=1), "TEST-hourly-x")
        self.hourly_commit()
        done = self.sh(self.backfill, substitute(step(BACKFILL, BF_COMMIT), {}),
                       {"STOPPED": out["stopped"], "ERROR": "", "PUSH_ATTEMPTS": "1"})
        self.assertNotEqual(done.returncode, 0)
        self.assertIn("::error::push-with-replay: push rejected 1 times", done.stdout)


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

Test Download Retries

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It reads timeout (`ReadTimeout`), reads timeout sub (`ReadTimeoutSub`) and sets up (`setUp`).

testlightning / tests/test_download_retries.py · lines 1–406 of 422 · Entry point · pattern _update_token_data (shared by 2 files)

What it does
It tests its inputs. Defines 53 functions or classes, including ProtocolError, ChunkedEncodingError, RequestsConnectionError, ReadTimeout, Timeout. Uses libraries http.client, io, json, sys, tempfile. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: JSON file rb.json; JSON file status.json; JSON file index.json; GeoJSON file feed.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
A single transient download error must not stop a whole search.
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
Backfill Parallel (import), Collect (import), Status (import), Test Unreadable Product (import), http.client, io, json, sys, tempfile, unittest, datetime, pathlib
Used by
run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run)
Produces
ProtocolError, ChunkedEncodingError, RequestsConnectionError, ReadTimeout, Timeout, ReadTimeoutSub, FakeResponse, HTTPError, ProductError, incident_error, FakeProduct, FlakyEumetsat
Defines here
ProtocolError, ChunkedEncodingError, RequestsConnectionError, ReadTimeout, Timeout, ReadTimeoutSub, FakeResponse, __init__, HTTPError, __init__, ProductError, __init__, incident_error, FakeProduct, __init__, __str__, open, FlakyEumetsat, __init__, products, __call__, Base, setUp, tearDown, rebuild, load, assertBackoff, TransientRetryTests, test_incomplete_read_twice_then_success_fills_the_day_with_no_unparsed_slot, test_every_transient_kind_is_retried
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_download_retries.py:1-406 · blob 4d99379aa47a13cce57472ebdcdcb69ee11cd73d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""A single transient download error must not stop a whole search.

Incident (parallel backfill run 40553623176, shard 2, 2026-09-16): one product
download broke mid-stream with
``urllib3.exceptions.ProtocolError: ('Connection broken: IncompleteRead(4955
bytes read, 233290 more expected)', ...)``; collect.py raised, the shard stopped
and only 3 dates were filled. The product download now retries transient
errors (IncompleteRead, ProtocolError, ConnectionError, ChunkedEncodingError,
timeouts, HTTP 500/502/503/504) 4 times with exponential backoff and jitter
(2, 4, 8, 16 s, capped at 30 s), honours Retry-After on 429 (at most 3 waits of
at most 60 s) and re-requests the access token once on 401. A product that
still fails becomes an UNPARSED slot (unknown, never zero, with its reason) and
the day carries on. The search stops only when a date exceeds the unparsed-slot
threshold or 5 consecutive products fail (a likely outage). Retry counts and
reasons are in the run record and status.json.

The fakes below go through the REAL ``collect.download_products`` retry loop
and ZIP decode; only the network (``product.open``), the sleep and the BODY
NetCDF reader are faked. No real sleeping happens.
"""
import http.client
import io
import json
import sys
import tempfile
import unittest
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
from unittest import mock

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))
import backfill_parallel as bp
import collect
import status as status_mod
from test_unreadable_product import DAY0, NOW, TARGET, fake_body, good_zip, make_archive, slot_name


# --- stand-ins for the exceptions urllib3 / requests / eumdac raise ---------
# CI installs neither urllib3 nor requests, so classes with the same NAMES
# stand in; collect.py classifies by class name, so the real ones match too.

class ProtocolError(Exception):  # urllib3.exceptions.ProtocolError
    pass


class ChunkedEncodingError(Exception):  # requests.exceptions.ChunkedEncodingError
    pass


class RequestsConnectionError(OSError):  # requests.exceptions.ConnectionError
    pass


RequestsConnectionError.__name__ = "ConnectionError"


class ReadTimeout(Exception):  # requests.exceptions.ReadTimeout -> Timeout
    pass


class Timeout(Exception):
    pass


class ReadTimeoutSub(Timeout):
    pass


class FakeResponse:
    def __init__(self, status_code, headers=None):
        self.status_code, self.headers = status_code, dict(headers or {})


class HTTPError(Exception):  # requests.HTTPError
    def __init__(self, status, headers=None):
        super().__init__(f"{status} Client Error")
        self.response = FakeResponse(status, headers)


class ProductError(Exception):  # eumdac.product.ProductError (raised "from" the HTTPError)
    def __init__(self, status, headers=None):
        super().__init__(f"Could not download Product x of Collection {collect.COLLECTION}")
        self.extra_info = {"status": status}
        self.__cause__ = HTTPError(status, headers)


def incident_error():
    """The exact shape of the run 40553623176 failure."""
    inner = http.client.IncompleteRead(b"x" * 4955, 233290)
    return ProtocolError(f"Connection broken: {inner!r}", inner)


class FakeProduct:
    """Each open() pops the next scripted outcome: an exception, or success (None)."""

    def __init__(self, name, blob, script, opened):
        self.name, self.blob, self.script, self.opened = name, blob, list(script), opened

    def __str__(self):
        return self.name

    def open(self):
        self.opened.append(self.name)
        outcome = self.script.pop(0) if self.script else None
        if callable(outcome):
            outcome = outcome()
        if outcome is not None:
            raise outcome
        return io.BytesIO(self.blob)


class FlakyEumetsat:
    """Fake downloader: one product per 10-minute slot; ``scripts[i]`` lists the
    outcomes of successive open() calls of slot i (exception or None = success).
    ``always[i]`` is an exception raised on every open() of slot i."""

    def __init__(self, scripts=None, always=None, token_refresher=None):
        self.scripts, self.always = dict(scripts or {}), dict(always or {})
        self.sleeps, self.opened, self.calls = [], [], []
        self.token_refresher = token_refresher

    def products(self, start, end):
        cursor, i = start, 0
        while cursor < end:
            name = slot_name(cursor)
            if i in self.always:
                script = [self.always[i]] * 100
            else:
                script = self.scripts.get(i, [])
            t = (cursor + timedelta(minutes=3)).isoformat()
            yield FakeProduct(name, good_zip(name, [(-2.0, 52.0, t)] if i % 6 == 0 else []), script, self.opened)
            cursor += timedelta(minutes=10)
            i += 1

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


class Base(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        self.record = self.base / "rb.json"

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

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

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

    def assertBackoff(self, sleeps, bases):
        """Exponential backoff with jitter: each wait is in [base, min(30, 1.5 * base)]."""
        self.assertEqual(len(sleeps), len(bases), sleeps)
        for wait, base in zip(sleeps, bases):
            self.assertGreaterEqual(wait, base)
            self.assertLessEqual(wait, min(30, base * 1.5))


class TransientRetryTests(Base):
    def test_incomplete_read_twice_then_success_fills_the_day_with_no_unparsed_slot(self):
        fake = FlakyEumetsat(scripts={4: [incident_error(), http.client.IncompleteRead(b"", 10), None]})
        self.assertEqual(self.rebuild(fake), 0)
        rec = self.load()
        self.assertEqual(rec["outcome"], "success")
        self.assertEqual((rec["products_unparsed"], rec["products_examined"], rec["slots_examined"]), (0, 144, 144))
        self.assertEqual(rec["unscanned_ranges"], [])
        self.assertEqual(fake.opened.count(slot_name(DAY0 + timedelta(minutes=40))), 3)
        self.assertBackoff(fake.sleeps, [2, 4])
        retries = rec["download_retries"]
        self.assertEqual(retries["retries"], 2)
        self.assertEqual(retries["products_retried"], 1)
        self.assertEqual(retries["products_failed"], 0)
        self.assertEqual(retries["reasons"], {"ProtocolError": 1, "IncompleteRead": 1})
        self.assertEqual([e["product"] for e in retries["events"]], [slot_name(DAY0 + timedelta(minutes=40))] * 2)
        self.assertIn("Connection broken: IncompleteRead(4955 bytes read, 233290 more expected)",
                      retries["events"][0]["error"])

    def test_every_transient_kind_is_retried(self):
        kinds = [incident_error(), http.client.IncompleteRead(b"", 5), RequestsConnectionError("reset"),
                 ConnectionResetError(104, "Connection reset by peer"), ChunkedEncodingError("broken chunk"),
                 TimeoutError("read timed out"), ReadTimeoutSub("read timeout"),
                 ProductError(500), ProductError(502), ProductError(503), ProductError(504), HTTPError(503)]
        for error in kinds:
            with self.subTest(error=repr(error)):
                fake = FlakyEumetsat(scripts={2: [error, None]})
                self.assertEqual(self.rebuild(fake), 0)
                rec = self.load()
                self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 0))
                self.assertEqual(rec["download_retries"]["retries"], 1)
                self.assertBackoff(fake.sleeps, [2])

    def test_a_product_that_always_fails_becomes_an_unparsed_slot_and_the_day_carries_on(self):
        fake = FlakyEumetsat(always={7: incident_error()})
        self.assertEqual(self.rebuild(fake), 0)
        rec = self.load()
        bad = slot_name(DAY0 + timedelta(minutes=70))
        self.assertEqual(rec["outcome"], "success")
        self.assertEqual(fake.opened.count(bad), 5)  # 1 try + 4 retries
        self.assertBackoff(fake.sleeps, [2, 4, 8, 16])
        self.assertEqual((rec["products_unparsed"], rec["products_examined"]), (1, 143))
        [entry] = rec["unparsed_products"]
        self.assertEqual(entry["product"], bad)
        self.assertEqual(entry["kind"], "download")
        self.assertEqual(entry["attempts"], 5)
        self.assertIn("download failed after 5 attempts", entry["reason"])
        self.assertIn("ProtocolError", entry["reason"])
        self.assertEqual(rec["unparsed_slots_utc"], ["2026-10-20T01:10:00.000Z"])
        # Unknown, not zero: the failed slot is a hole in the searched coverage.
        self.assertEqual(rec["unscanned_ranges"], [{"start_utc": "2026-10-20T01:10:00.000Z",
                                                    "end_utc": "2026-10-20T01:20:00.000Z"}])
        retries = rec["download_retries"]
        self.assertEqual((retries["retries"], retries["products_failed"]), (4, 1))
        self.assertEqual(retries["failed_products"], [bad])

    def test_backoff_never_exceeds_thirty_seconds(self):
        with mock.patch.object(collect, "RETRY_BACKOFF_SECONDS", (2, 4, 8, 16, 32, 64)), \
             mock.patch.object(collect, "TRANSIENT_RETRIES", 6):
            fake = FlakyEumetsat(always={1: incident_error()})
            self.rebuild(fake)
        self.assertEqual(len(fake.sleeps), 6)
        self.assertTrue(all(w <= 30 for w in fake.sleeps), fake.sleeps)
        self.assertEqual(fake.sleeps[-2:], [30, 30])

    def test_four_consecutive_failures_then_a_good_product_carry_on(self):
        fake = FlakyEumetsat(always={i: incident_error() for i in range(10, 14)})
        self.assertEqual(self.rebuild(fake), 0)
        rec = self.load()
        self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 4))
        self.assertEqual(rec["download_retries"]["max_consecutive_failed_products"], 4)

    def test_five_consecutive_failed_products_stop_the_search_as_a_likely_outage(self):
        fake = FlakyEumetsat(always={i: incident_error() for i in range(20, 30)})
        with self.assertRaises(collect.DownloadOutage) as caught:
            self.rebuild(fake)
        self.assertIn("5 consecutive products failed", str(caught.exception))
        self.assertEqual(len(set(fake.opened)), 25)  # 20 good products, then stopped at the 5th failure
        rec = self.load()
        self.assertEqual(rec["outcome"], "failure")
        self.assertIn("DownloadOutage", rec["error"])
        self.assertEqual(rec["products_unparsed"], 5)
        self.assertEqual(rec["download_retries"]["products_failed"], 5)
        self.assertEqual(rec["features"], [])

    def test_scattered_failures_over_the_day_threshold_still_stop_the_date(self):
        fake = FlakyEumetsat(always={i: incident_error() for i in range(0, 58, 2)})  # 29 of 144, never 5 in a row
        with self.assertRaises(collect.TooManyUnparsed) as caught:
            self.rebuild(fake)
        self.assertIn("29 of 144", str(caught.exception))
        rec = self.load()
        self.assertEqual(rec["outcome"], "failure")
        self.assertEqual(rec["download_retries"]["products_failed"], 29)

    def test_non_transient_errors_stop_at_once_without_retry(self):
        for error in (ProductError(403), PermissionError("denied"), RuntimeError("HTTP 403 Forbidden")):
            with self.subTest(error=repr(error)):
                self.record.unlink(missing_ok=True)
                fake = FlakyEumetsat(always={3: error})
                with self.assertRaises(type(error)):
                    self.rebuild(fake)
                self.assertEqual(fake.opened.count(slot_name(DAY0 + timedelta(minutes=30))), 1)
                self.assertEqual(fake.sleeps, [])


    def test_one_product_the_store_will_not_serve_becomes_an_unparsed_slot(self):
        """Backfill run 40737353777: one ProductError 'Could not download Product' killed the shard."""
        for error in (ProductError(404), ProductError(410), ProductError(400), HTTPError(400)):
            with self.subTest(error=repr(error)):
                self.record.unlink(missing_ok=True)
                fake = FlakyEumetsat(always={3: error})
                self.assertEqual(self.rebuild(fake), 0)
                rec = self.load()
                bad = slot_name(DAY0 + timedelta(minutes=30))
                self.assertEqual(rec["outcome"], "success")
                self.assertEqual(fake.opened.count(bad), 1)  # no retry: the store refused this product
                self.assertEqual(fake.sleeps, [])
                [entry] = rec["unparsed_products"]
                self.assertEqual(entry["product"], bad)
                self.assertIn("HTTP", entry["reason"])
                self.assertEqual(rec["unparsed_slots_utc"], ["2026-10-20T00:30:00.000Z"])

    def test_five_refused_products_in_a_row_still_stop_as_an_outage(self):
        fake = FlakyEumetsat(always={i: ProductError(404) for i in range(10, 15)})
        with self.assertRaises(collect.DownloadOutage):
            self.rebuild(fake)


class RateLimitTests(Base):
    def test_429_with_retry_after_waits_that_long_then_succeeds(self):
        fake = FlakyEumetsat(scripts={5: [ProductError(429, {"Retry-After": "7"}), None]})
        self.assertEqual(self.rebuild(fake), 0)
        rec = self.load()
        self.assertEqual(fake.sleeps, [7])
        self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 0))
        retries = rec["download_retries"]
        self.assertEqual((retries["rate_limit_waits"], retries["rate_limit_wait_seconds"]), (1, 7))
        self.assertEqual(retries["reasons"], {"HTTP 429": 1})

    def test_retry_after_is_capped_at_sixty_seconds_and_http_dates_are_understood(self):
        later = "Wed, 21 Oct 2099 07:28:00 GMT"
        fake = FlakyEumetsat(scripts={5: [HTTPError(429, {"Retry-After": "600"}),
                                          HTTPError(429, {"retry-after": later}), None]})
        self.rebuild(fake)
        self.assertEqual(fake.sleeps, [60, 60])

    def test_at_most_three_rate_limit_waits_then_the_slot_is_unparsed(self):
        fake = FlakyEumetsat(always={5: ProductError(429, {"Retry-After": "1"})})
        self.assertEqual(self.rebuild(fake), 0)
        rec = self.load()
        self.assertEqual(fake.sleeps, [1, 1, 1])
        self.assertEqual(fake.opened.count(slot_name(DAY0 + timedelta(minutes=50))), 4)
        [entry] = rec["unparsed_products"]
        self.assertEqual(entry["kind"], "download")
        self.assertIn("HTTP 429", entry["reason"])
        self.assertEqual(rec["download_retries"]["rate_limit_waits"], 3)


class TokenTests(Base):
    def test_401_re_requests_the_access_token_once_and_retries(self):
        refreshed = []
        fake = FlakyEumetsat(scripts={2: [ProductError(401), None]}, token_refresher=lambda p: refreshed.append(str(p)))
        self.assertEqual(self.rebuild(fake), 0)
        self.assertEqual(refreshed, [slot_name(DAY0 + timedelta(minutes=20))])
        self.assertEqual(self.load()["download_retries"]["token_refreshes"], 1)

    def test_a_second_401_stops_the_search(self):
        refreshed = []
        fake = FlakyEumetsat(always={2: ProductError(401)}, token_refresher=lambda p: refreshed.append(str(p)))
        with self.assertRaises(ProductError):
            self.rebuild(fake)
        self.assertEqual(len(refreshed), 1)

    def test_default_refresher_forces_a_new_eumdac_token(self):
        class Token:
            renewed = 0

            def _update_token_data(self):
                Token.renewed += 1

        product = mock.Mock()
        product.datastore.token = Token()
        collect.refresh_access_token(product)
        self.assertEqual(Token.renewed, 1)


class ShardAndStatusTests(Base):
    def test_shard_completes_through_transient_errors_and_status_surfaces_the_retries(self):
        root, out, status_path = self.base / "history", self.base / "records", self.base / "status.json"
        make_archive(root, NOW - timedelta(hours=1), date(2026, 10, 26))
        dates = ["2026-10-20", "2026-10-19"]
        fakes = {"2026-10-20": FlakyEumetsat(scripts={4: [incident_error(), incident_error(), None]},
                                             always={9: incident_error()}),
                 "2026-10-19": FlakyEumetsat()}
        collector = lambda day, record, log, timeout=None: collect.rebuild_day_record(day, record, now=NOW, downloader=fakes[day])
        summary = bp.run_shard(1, dates, out, budget_minutes=290, collector=collector)
        self.assertEqual((summary["stopped"], len(summary["collected"])), ("completed", 2))
        result = bp.finalize(plan_dates=dates, shards=1, records_dir=out, archive_dir=root,
                             status_path=status_path, now=NOW)
        self.assertEqual(result["filled"], dates)
        block = json.loads(status_path.read_text())["backfill"]
        self.assertEqual(block["unparsed_products_by_day"], {"2026-10-20": 1})
        self.assertEqual(block["download_retries"], 6)
        self.assertEqual(block["download_retries_by_day"]["2026-10-20"]["retries"], 6)
        self.assertEqual(block["download_retries_by_day"]["2026-10-20"]["products_failed"], 1)
        self.assertEqual(block["download_retries_by_day"]["2026-10-20"]["reasons"], {"ProtocolError": 6})
        self.assertNotIn("2026-10-19", block["download_retries_by_day"])
        rows = {r["date"]: r for r in json.loads((root / "index.json").read_text())["days"]}
        self.assertEqual(rows["2026-10-20"]["coverage"], "partial")

    def test_an_outage_stops_the_shard(self):
        out = self.base / "records"
        fake = FlakyEumetsat(always={i: incident_error() for i in range(144)})
        collector = lambda day, record, log, timeout=None: collect.rebuild_day_record(day, record, now=NOW, downloader=fake)
        summary = bp.run_shard(1, ["2026-10-20", "2026-10-19"], out, budget_minutes=290, collector=collector)
        self.assertEqual(summary["stopped"], "eumetsat_error")
        self.assertIn("consecutive products failed", summary["error"])
        self.assertEqual(summary["collected"], [])

    def test_hourly_run_retries_and_status_json_shows_the_counts(self):
        now = datetime(2026, 10, 20, 12, 5, tzinfo=timezone.utc)
        out, status_path = self.base / "feed.geojson", self.base / "status.json"
        fake = FlakyEumetsat(scripts={3: [incident_error(), None]}, always={6: ProductError(503)})
        with mock.patch.object(collect, "download", fake):
            code = collect.main(["--hours", "6", "--out", str(out), "--status", str(status_path),
                                 "--history-dir", str(self.base / "history"), "--run-record", str(self.record)],
                                now=now)
        self.assertEqual(code, 0)
        rec = self.load()
        self.assertEqual((rec["outcome"], rec["products_unparsed"]), ("success", 1))
        self.assertEqual(rec["download_retries"]["retries"], 5)
        self.assertEqual(rec["download_retries"]["reasons"], {"ProtocolError": 1, "HTTP 503": 4})
        status = status_mod.build_status(now=now, previous={}, record=rec, archive_result=None,
                                         collect_outcome="success", archive_outcome="skipped")
        self.assertEqual(status["last_download_retries"]["retries"], 5)
        self.assertEqual(status["last_download_retries"]["products_failed"], 1)

    def test_hourly_outage_writes_a_failure_record_with_the_retries(self):
        now = datetime(2026, 10, 20, 12, 5, tzinfo=timezone.utc)
        fake = FlakyEumetsat(always={i: ProductError(503) for i in range(36)})
        with mock.patch.object(collect, "download", fake):