GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / lightning / /

Collect

A Python command-line tool in Lightning that fetches UK lightning. It downloads outage (`DownloadOutage`), classifies download error (`classify_download_error`) and refreshes access token (`refresh_access_token`).

700 lines of Python from lightning, in 1 file. Topic: Websites and apps. Section 2001 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. Collect render · lightning / collect.py lines 1–700

Collect

A Python command-line tool in Lightning that fetches UK lightning. It downloads outage (`DownloadOutage`), classifies download error (`classify_download_error`) and refreshes access token (`refresh_access_token`).

renderlightning / collect.py · lines 1–700 of 1079 · Entry point · pattern run_search (shared by 2 files)

What it does
It fetches UK lightning. Defines 47 functions or classes, including TooManyUnparsed, __init__, DownloadOutage, __init__, _sleep. Uses libraries __future__, argparse, io, json, math. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
Why it exists in the grid workflow
README: "`collect.py`: downloads genuine LFL products with `eumdac`, reads NetCDF BODY data, filters UK coordinates and exports GeoJSON."
Inputs & outputs
In: JSON file index.json; GeoJSON file uk_lightning.geojson; JSON file status.json; command-line arguments.
Downstream impact
Used directly by 25 files: Backfill Lightning Workflow (lightning); Update Lightning Workflow (lightning); Test Backfill (lightning); Test Backfill Parallel (lightning); and 21 more. Reached from 9 other entry points, including Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Verify Lightning Data Workflow (lightning).
What it achieves
UK lightning flash GeoJSON from EUMETSAT Meteosat LI L2-LFL. It accepts `--hours`, `--auto-window` and `--rebuild-day`.
Why it matters
Imported by Grid, History and Status. Run by 4 workflows and scripts, including Backfill Lightning Workflow, Update Lightning Workflow and Backfill Parallel. Checked by 18 tests, including Test Backfill.
Application
lightning · / · Python CLI
Uses
__future__, argparse, io, json, math, os, random, re
Used by
run by Backfill Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run), imported by Test Backfill (import), imported by Test Backfill Parallel (import), imported by Test Backfill Workflow (import), imported by Test CI Verify (import), imported by Test Collect (import), imported by Test Concurrent Writers (import), and 17 more
Produces
TooManyUnparsed, DownloadOutage, http_status, retry_after_seconds, classify_download_error, backoff_seconds, refresh_access_token, new_retry_stats, fetch_product, parse_utc, iso_utc, inside_uk_view
Defines here
TooManyUnparsed, __init__, DownloadOutage, __init__, _sleep, _error_chain, http_status, retry_after_seconds, classify_download_error, backoff_seconds, refresh_access_token, new_retry_stats, fetch_product, parse_utc, iso_utc, inside_uk_view, build_feature, decode_body, decode_product, install_http_timeouts, request, search_products, run_search, search_with_retries, unparsed_entry, download_products, download, unpack_download, check_unparsed, unparsed_slot_starts
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 collect.py:1-700 · blob f97c7322fa6fb321a18a55c3d9e5c184bfcb35ae · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""UK lightning flash GeoJSON from EUMETSAT Meteosat LI L2-LFL.

Optical flashes observed from orbit (including intracloud), NOT proven
cloud-to-ground strikes. This produces public map data, not safety advice.
Only genuine downloaded detections are published; no sample points.

Collection model (data plane only, nothing here touches GridAtlas):
- hourly runs; each run searches a self-healing lookback window
  ``max(6 h, now - last successful scan end + 30 min)`` capped at 48 h, so a
  late or failed run is caught up by the next one instead of leaving a gap;
- every examined EUMETSAT product is a 10-minute sensing slot; the run records
  the slots it actually examined, and only those slots count as "searched".
  The slot containing ``now`` is normally not yet published, so the tail of
  the query window is unobserved and is recorded as such (unknown, not zero);
- one unreadable product (ZIP without a BODY NetCDF, corrupt ZIP or NetCDF)
  does not stop the run: its slot is UNPARSED, i.e. not searched time, so it
  stays unknown (never zero) and is listed with its reason in the run record;
- each product download 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), waits out up to 3 HTTP 429 Retry-Afters (at most 60 s each)
  and re-requests the access token once on 401. A product still failing is
  UNPARSED too (unknown, never zero, with its reason) and the run carries on.
  Every HTTP call has an explicit (connect, read) timeout, ``HTTP_TIMEOUT``
  (15, 60) s, so a stalled read raises a (transient) ReadTimeout instead of
  hanging for ever. The run stops on ``MAX_CONSECUTIVE_FAILED_PRODUCTS`` failed downloads in a
  row (likely outage), on any other HTTP/auth error, and on a UTC date with
  more than ``MAX_UNPARSED_DAY_FRACTION`` of its slots unparsed;
- the live 7-day feed is written first; the one-year archive and the status
  file are produced by separate steps from the run record this module leaves
  behind, so an archive failure can never block the feed.
"""
from __future__ import annotations

import argparse
import io
import json
import math
import os
import random
import re
import sys
import zipfile
import zlib
from datetime import datetime, timedelta, timezone
from pathlib import Path

COLLECTION = "EO:EUM:DAT:0691"  # LI Lightning Flashes - MTG 0 degree
PROVIDER = "EUMETSAT MTG Lightning Imager L2-LFL"
SOURCE_URL = "https://api.eumetsat.int/data/browse/collections/EO%3AEUM%3ADAT%3A0691?format=html"
# UK coverage AND neighbouring waters; this rectangle is NOT the UK border.
UK_BOUNDS = (-11.0, 49.5, 3.0, 61.5)  # west, south, east, north
MAX_RENDER_POINTS = 40000

# Self-healing lookback window (hours / minutes); see lookback_window().
LOOKBACK_MIN_HOURS = 6
LOOKBACK_MAX_HOURS = 48
LOOKBACK_MARGIN_MINUTES = 30
# LI L2-LFL "ARC" products cover 10-minute sensing slots (144 per UTC day).
SLOT_SECONDS = 600
# Products appear a few minutes after the slot ends; a gap ending within this
# many seconds of ``now`` is "not yet published", not a source outage.
PUBLICATION_GRACE_SECONDS = 15 * 60
RUN_RECORD_SCHEMA = "uk-lightning-run-record.v1"
# ..._L2PF_OPE_<sensing start YYYYMMDDHHMMSS>_<sensing end YYYYMMDDHHMMSS>_N__O_<slot>_0000
PRODUCT_SLOT = re.compile(r"_OPE_(\d{14})_(\d{14})_")
# A product's "nominal slot" is the sensing start/end in its NAME (PRODUCT_SLOT),
# not its repeat-cycle counter (``_O_<NNNN>_``, 10-minute cycle NNNN of the day)
# and not the times of its flashes. The name's span is NOT a bound on the flash
# times inside it: real LFL flashes sit up to about 0.4 s outside it (observed:
# ..._OPE_20261023195009_... flash 322 at 19:50:08.639, 0.361 s early), and
# products that start late in their cycle (..._OPE_20260412001255_20260412002005_
# ..._O_0002_..., cycle 00:10-00:20) or right after midnight (..._OPE_
# 20260828000049_20260828001009_..._O_0001_...) held flashes more than 60 s
# outside their name's span (backfill runs 40620556193, 40657338115). A flash is
# therefore checked by ITS OWN TIME (see classify_flash): it is consistent when it
# lies within this tolerance of its product's span, or inside any examined span.
SLOT_EDGE_TOLERANCE_SECONDS = 60
# Every flash of an examined product is decoded, whatever its time; callers then
# drop (and count) those outside their window or UTC date, so none is lost silently.
DECODE_ALL_TIMES = (datetime(1970, 1, 1, tzinfo=timezone.utc), datetime(9999, 1, 1, tzinfo=timezone.utc))
# A UTC date with more unparsed slots than this fraction of its slots in the
# query window is not recorded at all: the run stops and the date stays unknown.
MAX_UNPARSED_DAY_FRACTION = 0.20
# Per-product CONTENT errors raised while decoding bytes already downloaded
# (ZIP without BODY, corrupt ZIP, corrupt/odd NetCDF: netCDF4 raises OSError or
# RuntimeError). Downloading happens outside the decode, so network, auth and
# rate-limit errors are never caught here; nor is a missing netCDF4 (ImportError).
PRODUCT_CONTENT_ERRORS = (ValueError, zipfile.BadZipFile, zipfile.LargeZipFile, zlib.error, EOFError,
                          OSError, RuntimeError, KeyError, IndexError, TypeError)

# Per-product DOWNLOAD retries (open + read of one product). Transient errors are
# matched by class name anywhere in the exception's MRO or cause chain, so the
# urllib3/requests/http.client classes match without importing those packages.
TRANSIENT_ERROR_NAMES = frozenset({
    "IncompleteRead", "ProtocolError", "ConnectionError", "ChunkedEncodingError",
    "Timeout", "TimeoutError", "ReadTimeout", "ConnectTimeout", "ReadTimeoutError", "ConnectTimeoutError",
    "RemoteDisconnected",
})
TRANSIENT_HTTP_STATUS = frozenset({500, 502, 503, 504})
# A single product the search LISTED but the Data Store will not serve (backfill
# run 40737353777: eumdac ProductError "Could not download Product ..." on one
# 2025-12-14 slot killed the shard). Such a product is FAILED: its slot becomes
# unparsed (unknown, never zero), bounded by MAX_UNPARSED_DAY_FRACTION and the
# consecutive-failure stop, instead of stopping the whole run. 401/403/429 keep
# their own handling: they are account-wide, not one product.
PRODUCT_FAILED_HTTP_STATUS = frozenset({400, 404, 409, 410, 416, 422, 423})
TRANSIENT_RETRIES = 4
RETRY_BACKOFF_SECONDS = (2, 4, 8, 16)  # exponential; up to +50 % jitter, never above the cap
RETRY_MAX_BACKOFF_SECONDS = 30
RATE_LIMIT_MAX_WAITS = 3
RATE_LIMIT_MAX_WAIT_SECONDS = 60
# This many products in a row failing to download is a likely EUMETSAT outage: stop.
MAX_CONSECUTIVE_FAILED_PRODUCTS = 5
MAX_RETRY_EVENTS = 200  # cap the per-event list kept in the run record
# Every HTTP call (token, search, product download) gets this explicit
# (connect, read) timeout in seconds. eumdac passes no timeout to requests, so
# without it one stalled TCP read blocks for ever (parallel backfill run
# 40564980740, shard 3: still "in_progress" after 5 h). The read timeout
# bounds each socket read; a ReadTimeout is transient, so it is retried and a
# product still timing out after its retries is UNPARSED (unknown, never zero).
HTTP_TIMEOUT = (15, 60)
_HTTP_STATUS_IN_TEXT = re.compile(r"\bHTTP (\d{3})\b|\b(?:error|Unauthorised|Not found) \((\d{3})\)")


class TooManyUnparsed(RuntimeError):
    """A date has too many unreadable products (or none readable): stop, leave it unknown."""

    def __init__(self, message: str, unparsed=(), retries=None):
        super().__init__(message)
        self.unparsed = list(unparsed)
        self.retries = retries


class DownloadOutage(RuntimeError):
    """``MAX_CONSECUTIVE_FAILED_PRODUCTS`` products in a row failed to download: stop the search."""

    def __init__(self, message: str, unparsed=(), retries=None):
        super().__init__(message)
        self.unparsed = list(unparsed)
        self.retries = retries


def _sleep(seconds: float) -> None:
    import time
    time.sleep(seconds)


def _error_chain(error: BaseException):
    seen = set()
    while error is not None and id(error) not in seen:
        seen.add(id(error))
        yield error
        error = error.__cause__ or error.__context__


def http_status(error: BaseException) -> int | None:
    """HTTP status carried by an eumdac/requests error (or its cause), else None."""
    for item in _error_chain(error):
        for value in (getattr(getattr(item, "response", None), "status_code", None),
                      getattr(item, "status_code", None),
                      (getattr(item, "extra_info", None) or {}).get("status")
                      if isinstance(getattr(item, "extra_info", None), dict) else None):
            if isinstance(value, int) and 100 <= value <= 599:
                return value
    match = _HTTP_STATUS_IN_TEXT.search(str(error))
    if match:
        return int(match.group(1) or match.group(2))
    return None


def retry_after_seconds(error: BaseException, *, now: datetime | None = None) -> float | None:
    """Retry-After (seconds or HTTP date) from the error's response headers, else None."""
    from email.utils import parsedate_to_datetime
    for item in _error_chain(error):
        headers = getattr(getattr(item, "response", None), "headers", None) or getattr(item, "headers", None)
        if not headers:
            continue
        value = next((v for k, v in dict(headers).items() if str(k).lower() == "retry-after"), None)
        if value is None:
            continue
        text = str(value).strip()
        try:
            return max(0.0, float(text))
        except ValueError:
            pass
        try:
            when = parsedate_to_datetime(text)
        except (TypeError, ValueError):
            continue
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
        return max(0.0, (when - (now or datetime.now(timezone.utc))).total_seconds())
    return None


def classify_download_error(error: BaseException) -> tuple[str, str]:
    """(kind, label): kind is 'rate_limit', 'auth', 'transient' or 'fatal'."""
    status = http_status(error)
    if status == 429:
        return "rate_limit", "HTTP 429"
    if status == 401:
        return "auth", "HTTP 401"
    if status in TRANSIENT_HTTP_STATUS:
        return "transient", f"HTTP {status}"
    if status in PRODUCT_FAILED_HTTP_STATUS:
        return "product_failed", f"HTTP {status}"
    if status is not None:
        return "fatal", f"HTTP {status}"
    for item in _error_chain(error):
        names = [cls.__name__ for cls in type(item).__mro__]
        hit = next((n for n in names if n in TRANSIENT_ERROR_NAMES), None)
        if hit:
            return "transient", type(error).__name__ if type(error).__name__ in TRANSIENT_ERROR_NAMES else hit
    return "fatal", type(error).__name__


def backoff_seconds(retry: int, rng) -> float:
    """Wait before transient retry ``retry`` (1-based): base * (1..1.5), capped at 30 s."""
    base = RETRY_BACKOFF_SECONDS[min(retry, len(RETRY_BACKOFF_SECONDS)) - 1]
    if base >= RETRY_MAX_BACKOFF_SECONDS:
        return float(RETRY_MAX_BACKOFF_SECONDS)
    return round(min(RETRY_MAX_BACKOFF_SECONDS, base * (1 + 0.5 * rng())), 3)


def refresh_access_token(product) -> None:
    """Force eumdac to request a new access token for this product's data store."""
    token = getattr(getattr(product, "datastore", None), "token", None)
    if token is None or not hasattr(token, "_update_token_data"):
        raise RuntimeError("cannot re-request the EUMETSAT access token (no eumdac token on the product)")
    token._update_token_data()


def new_retry_stats() -> dict:
    return {"retries": 0, "products_retried": 0, "products_failed": 0, "failed_products": [],
            "rate_limit_waits": 0, "rate_limit_wait_seconds": 0, "backoff_seconds": 0,
            "token_refreshes": 0, "max_consecutive_failed_products": 0, "reasons": {}, "events": [],
            "policy": {"transient_retries": TRANSIENT_RETRIES, "backoff_seconds": list(RETRY_BACKOFF_SECONDS),
                       "max_backoff_seconds": RETRY_MAX_BACKOFF_SECONDS, "rate_limit_max_waits": RATE_LIMIT_MAX_WAITS,
                       "rate_limit_max_wait_seconds": RATE_LIMIT_MAX_WAIT_SECONDS,
                       "max_consecutive_failed_products": MAX_CONSECUTIVE_FAILED_PRODUCTS}}


def fetch_product(product, name: str, stats: dict, *, sleep, rng, token_refresher):
    """Open and read one product, retrying transient errors; (blob, None) or (None, (error, attempts)).

    Transient errors: up to ``TRANSIENT_RETRIES`` retries with exponential backoff
    and jitter. 429: up to ``RATE_LIMIT_MAX_WAITS`` waits of Retry-After (at most
    60 s). 401: the access token is re-requested once. When these are used up
    the product FAILED: (None, ...) is returned, the caller marks its slot
    unparsed. A second 401, any other HTTP status and any other error propagate.
    """
    transient = waits = refreshes = attempts = 0
    retried = False
    while True:
        attempts += 1
        try:
            with product.open() as stream:
                return stream.read(), None
        except Exception as error:  # noqa: BLE001 - classified below; unknown kinds re-raised
            kind, label = classify_download_error(error)
            if kind == "fatal" or (kind == "auth" and refreshes >= 1):
                raise
            if kind == "transient" and transient < TRANSIENT_RETRIES:
                transient += 1
                wait = backoff_seconds(transient, rng)
                stats["backoff_seconds"] = round(stats["backoff_seconds"] + wait, 3)
            elif kind == "rate_limit" and waits < RATE_LIMIT_MAX_WAITS:
                waits += 1
                after = retry_after_seconds(error)
                wait = min(RATE_LIMIT_MAX_WAIT_SECONDS, after if after is not None else RATE_LIMIT_MAX_WAIT_SECONDS)
                stats["rate_limit_waits"] += 1
                stats["rate_limit_wait_seconds"] = round(stats["rate_limit_wait_seconds"] + wait, 3)
            elif kind == "auth":
                refreshes += 1
                wait = 0
                stats["token_refreshes"] += 1
                (token_refresher or refresh_access_token)(product)
            else:
                return None, (error, attempts, label)
            stats["retries"] += 1
            stats["reasons"][label] = stats["reasons"].get(label, 0) + 1
            if not retried:
                retried = True
                stats["products_retried"] += 1
            if len(stats["events"]) < MAX_RETRY_EVENTS:
                stats["events"].append({"product": name, "attempt": attempts, "reason": label,
                                        "error": f"{type(error).__name__}: {error}"[:300], "wait_seconds": wait})
            print(f"RETRY product {name} after attempt {attempts} ({label}: {error}); waiting {wait} s",
                  file=sys.stderr)
            if wait:
                sleep(wait)


def parse_utc(value: str) -> datetime:
    result = datetime.fromisoformat(value.replace("Z", "+00:00"))
    if result.tzinfo is None:
        result = result.replace(tzinfo=timezone.utc)
    return result.astimezone(timezone.utc)


def iso_utc(value) -> str:
    """Handle Python datetime, cftime and numpy-style date representations."""
    if isinstance(value, datetime):
        return value.replace(tzinfo=value.tzinfo or timezone.utc).astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    text = value.strftime("%Y-%m-%dT%H:%M:%S.%f") if hasattr(value, "strftime") else str(value)
    if text.endswith("Z"):
        return text
    # Only fractional seconds may lose trailing zeros; "12:32:20" must stay "12:32:20".
    if "." in text:
        text = text.rstrip("0").rstrip(".")
    return text + "Z"


def inside_uk_view(longitude: float, latitude: float) -> bool:
    w, s, e, n = UK_BOUNDS
    return math.isfinite(longitude) and math.isfinite(latitude) and w <= longitude <= e and s <= latitude <= n


def build_feature(lon, lat, timestamp, product_name: str, index: int):
    lon, lat = float(lon), float(lat)
    if not inside_uk_view(lon, lat):
        return None
    observed = iso_utc(timestamp)
    key = f"{product_name}:{index}"
    return {
        "type": "Feature",
        "id": key,
        "geometry": {"type": "Point", "coordinates": [round(lon, 6), round(lat, 6)]},
        "properties": {
            "name": "Lightning flash " + observed[:16].replace("T", " ") + " UTC",
            "raw_tech": "EUMETSAT optical flash (not a confirmed ground strike)",
            "status": "Satellite detection",
            "time_utc": observed,
            "source": "EUMETSAT",
            "source_product": "MTG LI L2-LFL",
            "observation_kind": "optical_lightning_flash",
        },
    }


def decode_body(content: bytes, product_name: str, start: datetime, end: datetime):
    """Read actual LFL BODY NetCDF with CF scale/offset and UTC flash times."""
    from netCDF4 import Dataset, num2date

    with Dataset("lightning-body", memory=content) as ds:
        vars_ = ds.variables
        for field in ("longitude", "latitude", "flash_time"):
            if field not in vars_:
                raise ValueError(f"{product_name}: missing expected LFL field {field}")
        lons = vars_["longitude"][:]
        lats = vars_["latitude"][:]
        times_var = vars_["flash_time"]
        times = times_var[:]
        if len(lons) != len(lats) or len(lons) != len(times):
            raise ValueError(f"{product_name}: coordinate/time dimensions do not match")
        units = getattr(times_var, "units", "seconds since 2000-01-01 00:00:00")
        calendar = getattr(times_var, "calendar", "standard")
        dates = num2date(times, units=units, calendar=calendar)
        results = []
        for i in range(len(lons)):
            try:
                if any(getattr(x, "mask", False) is True for x in (lons[i], lats[i], times[i])):
                    continue
                dt = parse_utc(iso_utc(dates[i]))
                if not start <= dt < end:
                    continue
                feat = build_feature(lons[i], lats[i], dt, product_name, i)
                if feat:
                    results.append(feat)
            except (ValueError, TypeError, OverflowError):
                continue
        return results


def decode_product(blob: bytes, product_name: str, start: datetime, end: datetime, *, body_decoder=None):
    """EUMETSAT packages products as ZIP archives with *BODY*.nc."""
    body_decoder = body_decoder or decode_body
    if not zipfile.is_zipfile(io.BytesIO(blob)):
        raise ValueError(f"{product_name}: expected EUMETSAT product ZIP")
    bodies = 0
    features = []
    with zipfile.ZipFile(io.BytesIO(blob)) as archive:
        for name in sorted(archive.namelist()):
            if name.upper().endswith(".NC") and "BODY" in Path(name).name.upper():
                decoded = body_decoder(archive.read(name), product_name, start, end)
                if bodies:
                    # Flash indexes restart in every BODY file: without a body
                    # ordinal a second BODY's ids would collide with the first's
                    # and be deduplicated away silently. The first BODY keeps
                    # "<product>:<i>" (the ids already archived).
                    for feature in decoded:
                        product, _, index = str(feature["id"]).rpartition(":")
                        feature["id"] = f"{product}:b{bodies}.{index}"
                features.extend(decoded)
                bodies += 1
    found = bodies > 0
    if not found:
        raise ValueError(f"{product_name}: ZIP contained no BODY NetCDF")
    return features


def install_http_timeouts(timeout=None, *, requests_module=None) -> bool:
    """Give every ``requests`` call without an explicit timeout ``HTTP_TIMEOUT``.

    eumdac (token, search, ``Product.open``) calls ``requests.Session`` methods
    without ``timeout``, which means "wait for ever". This wraps
    ``Session.request`` once per process so a missing or None timeout becomes
    the (connect, read) default; an explicit timeout is kept. The socket
    default timeout is set too, for any socket opened without one. Returns
    False when requests is not installed (nothing to wrap).
    """
    import socket
    timeout = tuple(timeout or HTTP_TIMEOUT)
    socket.setdefaulttimeout(float(max(timeout)))
    if requests_module is None:
        try:
            import requests as requests_module
        except ImportError:
            return False
    session_cls = requests_module.Session
    original = getattr(session_cls.request, "_uk_lightning_original", session_cls.request)

    def request(self, method, url, *args, **kwargs):
        # Session.request(method, url, params, data, headers, cookies, files, auth, timeout, ...)
        if len(args) > 6:
            if args[6] is None:
                args = args[:6] + (request.http_timeout,) + args[7:]
        elif kwargs.get("timeout") is None:
            kwargs["timeout"] = request.http_timeout
        return original(self, method, url, *args, **kwargs)

    request._uk_lightning_original = original
    request.http_timeout = timeout
    session_cls.request = request
    return True


def search_products(start: datetime, end: datetime):
    """The real EUMETSAT product search (network); products are opened lazily."""
    key = os.environ.get("EUMETSAT_CONSUMER_KEY", "").strip()
    secret = os.environ.get("EUMETSAT_CONSUMER_SECRET", "").strip()
    if not key or not secret:
        raise RuntimeError("Missing EUMETSAT_CONSUMER_KEY / EUMETSAT_CONSUMER_SECRET. Never commit credentials.")
    install_http_timeouts()
    import eumdac

    datastore = eumdac.DataStore(eumdac.AccessToken((key, secret)))

    def run_search():
        return datastore.get_collection(COLLECTION).search(
            dtstart=start.replace(tzinfo=None), dtend=end.replace(tzinfo=None)
        )

    return search_with_retries(run_search)


def search_with_retries(run_search, *, sleep=None, rng=None):
    """Run a product search and LIST its results, retrying transient errors.

    The search and its paging are network calls too: backfill run 40690260149
    lost a whole run to one search ``Read timed out`` that nothing retried. A
    transient error (classify_download_error) is retried TRANSIENT_RETRIES times
    with the download backoff; anything else, or the last failure, propagates.
    Returns the products as a list, so no paging happens later, unretried.
    """
    sleep = sleep or _sleep
    rng = rng or random.random
    attempt = 0
    while True:
        attempt += 1
        try:
            products = run_search()
            count = getattr(products, "total_results", None)
            listed = list(products)
        except Exception as error:  # noqa: BLE001 - classified below
            kind, label = classify_download_error(error)
            if kind != "transient" or attempt > TRANSIENT_RETRIES:
                raise
            wait = backoff_seconds(attempt, rng)
            print(f"RETRY search after attempt {attempt} ({label}: {error}); waiting {wait} s", file=sys.stderr)
            sleep(wait)
            continue
        if count == 0:
            raise RuntimeError("No EUMETSAT product files returned. Existing map data left unchanged.")
        return listed


def unparsed_entry(product_name: str, error: BaseException, *, kind: str = "content", reason: str | None = None,
                   attempts: int | None = None) -> dict:
    slot = product_slot(product_name)
    entry = {
        "product": product_name,
        "kind": kind,
        "reason": (reason or f"{type(error).__name__}: {error}")[:1000],
        "slot_start_utc": iso_utc(slot[0]) if slot else None,
        "slot_end_utc": iso_utc(slot[1]) if slot else None,
    }
    if attempts is not None:
        entry["attempts"] = attempts
    return entry


def download_products(products, start: datetime, end: datetime, *, body_decoder=None, sleep=None, rng=None,
                      token_refresher=None):
    """Download and decode each product: (features, readable count, readable names, unparsed, retry stats).

    Each download (``open``/``read``) goes through ``fetch_product``: transient
    network errors, 5xx, 429 and one 401 are retried. A product whose retries
    are used up, or whose downloaded bytes cannot be decoded, is UNPARSED: its
    name is NOT among the examined names, so its slot is not searched time
    (unknown, never zero) and the search carries on. ``DownloadOutage`` stops it
    after ``MAX_CONSECUTIVE_FAILED_PRODUCTS`` failed downloads in a row; any
    non-retryable error (403, 404, a second 401, ...) propagates and stops it.
    """
    import random
    sleep = sleep or _sleep
    rng = rng or random.random
    found, names, unparsed = [], [], []
    stats = new_retry_stats()
    downloaded = consecutive = 0
    for product in products:
        downloaded += 1
        if downloaded > 1000:
            raise RuntimeError("Too many products in one run; reduce --hours.")
        name = str(product)
        print(f"Product {downloaded}: {name}", file=sys.stderr)
        blob, failure = fetch_product(product, name, stats, sleep=sleep, rng=rng, token_refresher=token_refresher)
        if failure is not None:
            error, attempts, label = failure
            entry = unparsed_entry(name, error, kind="download", attempts=attempts,
                                   reason=f"download failed after {attempts} attempts ({label}): "
                                          f"{type(error).__name__}: {error}")
            unparsed.append(entry)
            stats["products_failed"] += 1
            stats["failed_products"].append(name)
            consecutive += 1
            stats["max_consecutive_failed_products"] = max(stats["max_consecutive_failed_products"], consecutive)
            print(f"UNPARSED product {name}: {entry['reason']} (slot left unknown)", file=sys.stderr)
            if consecutive >= MAX_CONSECUTIVE_FAILED_PRODUCTS:
                raise DownloadOutage(
                    f"{consecutive} consecutive products failed to download after retries (likely EUMETSAT "
                    f"outage); search stopped, dates left unknown (last: {entry['reason']})"[:2000],
                    unparsed, stats)
            continue
        consecutive = 0
        # Decode EVERY flash of the product, whatever its time (a product's flashes
        # can lie minutes outside its nominal span): callers then drop the ones
        # outside their window or date and COUNT them (split_by_window), instead
        # of losing them silently here.
        lo, hi = DECODE_ALL_TIMES
        try:
            features = decode_product(blob, name, lo, hi, body_decoder=body_decoder)
        except PRODUCT_CONTENT_ERRORS as error:
            entry = unparsed_entry(name, error)
            unparsed.append(entry)
            print(f"UNPARSED product {name}: {entry['reason']} (slot left unknown)", file=sys.stderr)
            continue
        names.append(name)
        found.extend(features)
    if downloaded == 0:
        raise RuntimeError("Empty product search. Existing map data left unchanged.")
    return found, len(names), names, unparsed, stats


def download(start: datetime, end: datetime):
    """Return (features, readable products, readable names, unparsed, retry stats) for a real search."""
    return download_products(search_products(start, end), start, end)


def unpack_download(result):
    """Downloaders return (features, count, names[, unparsed[, retry stats]]); always returns all five."""
    result = tuple(result)
    features, count, names = result[:3]
    unparsed = list(result[3] or []) if len(result) > 3 else []
    stats = result[4] if len(result) > 4 and result[4] is not None else new_retry_stats()
    return features, count, names, unparsed, stats


def check_unparsed(unparsed, names, beginning: datetime, end: datetime, *,
                   max_fraction: float = MAX_UNPARSED_DAY_FRACTION) -> dict:
    """Stop (TooManyUnparsed) when no product was readable or a UTC date has too many unparsed slots.

    An unparsed slot already covered by a readable product (e.g. a short PART
    product inside a regular slot) is not unknown time and is not counted. The
    denominator is the number of 10-minute slots of that date inside the query
    window (144 for a whole-day rebuild). Returns {date: unparsed slot count}.
    """
    unparsed = list(unparsed)
    if not unparsed:
        return {}
    if not names:
        raise TooManyUnparsed(f"all {len(unparsed)} product(s) unreadable; nothing was searched "
                              f"(first: {unparsed[0]['reason']})", unparsed)
    readable = merge_ranges([slot for slot in (product_slot(n) for n in names) if slot])
    per_day: dict[str, set] = {}
    day = beginning.date()
    while datetime.combine(day, datetime.min.time(), tzinfo=timezone.utc) < end:
        per_day[day.isoformat()] = set()
        day += timedelta(days=1)
    for entry in unparsed:
        slot = product_slot(entry["product"])
        if slot is None:  # unknown slot: conservatively counts against every date of the window
            for marks in per_day.values():
                marks.add(entry["product"])
            continue
        s, e = max(slot[0], beginning), min(slot[1], end)
        if e <= s or any(rs <= s and e <= re_ for rs, re_ in readable):
            continue
        per_day.setdefault(s.date().isoformat(), set()).add(s)
    counts = {}
    for day_text, marks in per_day.items():
        if not marks:
            continue
        day_start = datetime.combine(datetime.fromisoformat(day_text).date(), datetime.min.time(), tzinfo=timezone.utc)
        span = (min(end, day_start + timedelta(days=1)) - max(beginning, day_start)).total_seconds()
        slots = max(1, math.ceil(span / SLOT_SECONDS))
        counts[day_text] = len(marks)
        if len(marks) > max_fraction * slots:
            raise TooManyUnparsed(
                f"{day_text}: {len(marks)} of {slots} 10-minute slots unparsed (more than "
                f"{max_fraction:.0%}); date not recorded, left unknown (first: {unparsed[0]['reason']})", unparsed)
    return counts


def unparsed_slot_starts(unparsed, names, beginning: datetime, end: datetime) -> list[str]:
    """Slot starts of unparsed products NOT covered by a readable product (unknown time)."""
    readable = merge_ranges([slot for slot in (product_slot(n) for n in names) if slot])
    starts = set()
    for entry in unparsed:
        slot = product_slot(entry["product"])
        if slot is None:
            continue
        s, e = max(slot[0], beginning), min(slot[1], end)
        if e > s and not any(rs <= s and e <= re_ for rs, re_ in readable):
            starts.add(s)
    return [iso_utc(x) for x in sorted(starts)]


def read_previous(path: Path):
    if not path.exists():
        return []
    obj = json.loads(path.read_text(encoding="utf-8"))
    if obj.get("type") != "FeatureCollection":
        raise ValueError("Previous GeoJSON is not a FeatureCollection")
    return obj.get("features", [])


def assemble(previous, incoming, now: datetime, retention_days: int = 7):
    cutoff = now - timedelta(days=retention_days)
    by_id = {}
    for feature in list(previous) + list(incoming):
        if feature.get("type") != "Feature" or feature.get("geometry", {}).get("type") != "Point":
            continue
        props = feature.get("properties", {})
        if props.get("source_product") != "MTG LI L2-LFL":
            continue
        try:
            timestamp = parse_utc(props["time_utc"])
            x, y = feature["geometry"]["coordinates"]
            if cutoff <= timestamp <= now and inside_uk_view(float(x), float(y)):
                by_id[str(feature["id"])] = feature
        except (KeyError, ValueError, TypeError):
            continue
    rows = sorted(by_id.values(), key=lambda f: (f["properties"]["time_utc"], str(f["id"])))
    total = len(rows)
    if total > MAX_RENDER_POINTS:
        rows = rows[-MAX_RENDER_POINTS:]
    return {
        "type": "FeatureCollection",
        "metadata": {
            "source": PROVIDER, "source_url": SOURCE_URL,
            "license": "EUMETSAT data policy: NoConditions; attribution retained",
            "coverage": "UK geographic bounding box and neighbouring waters, not national boundary",
            "bounds_wsen": list(UK_BOUNDS),
            "observation": "satellite optical flashes; not verified ground strike locations",
            "retention_days": retention_days,
            "total_before_display_cap": total,
            "display_cap": MAX_RENDER_POINTS,
            "latest_detection_utc": rows[-1]["properties"]["time_utc"] if rows else None,
            "status": "ready",
        },
        "features": rows,
    }


# --- self-healing lookback -------------------------------------------------

def lookback_window(
    now: datetime,
    last_success_end: datetime | None,
    *,
    minimum_hours: float = LOOKBACK_MIN_HOURS,
    maximum_hours: float = LOOKBACK_MAX_HOURS,
    margin_minutes: float = LOOKBACK_MARGIN_MINUTES,
) -> tuple[timedelta, bool]:
    """``max(minimum, now - last_success_end + margin)`` capped at ``maximum``.

    Returns (window, capped). ``capped`` is True when the gap since the last