GLOBALGRID2050 / EXPLORE CODE

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

Test Smoke Default Paths and 1 more file

A test in the tests folder of Lightning that checks Collect and History. It reads timeout (`ReadTimeout`), gets collection (`get_collection`) and sets up (`setUp`).

469 lines of Python from lightning, in 2 files. Topic: Automation and CI. Section 1832 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 Smoke Default Paths test · lightning / tests/test_smoke_default_paths.py lines 1–305
  2. Test Status test · lightning / tests/test_status.py lines 1–164

Test Smoke Default Paths

A test in the tests folder of Lightning that checks Collect and History. It reads timeout (`ReadTimeout`), gets collection (`get_collection`) and sets up (`setUp`).

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

What it does
It tests its inputs. Defines 41 functions or classes, including ReadTimeout, _maybe_fail, AccessToken, __init__, _update_token_data. Uses libraries importlib, importlib.util, io, json, os. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file rb.json; GeoJSON file uk_lightning.geojson; JSON file status.json; JSON file run.json; JSON file archive-result.json; JSON file no-seed.json; JSON file index.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
Smoke test: the REAL entry points on their DEFAULT code paths, faked only at the network.
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
Collect (script call), History (script call), Grid (script call), Status (script call), Backfill Parallel (script call), importlib, importlib.util, io, json, os, subprocess, sys, tempfile
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
ReadTimeout, AccessToken, DataStore, product_name, slot_floor, body_netcdf, product_zip, SmokeBase, ImportSmokeTests, DefaultSearchAndDownloadSmokeTests, FullPipelineSmokeTests
Defines here
ReadTimeout, _maybe_fail, AccessToken, __init__, _update_token_data, _Stream, __init__, __enter__, __exit__, read, _Product, __init__, __str__, open, _Results, __init__, __iter__, _Collection, __init__, search, DataStore, __init__, get_collection, product_name, slot_floor, body_netcdf, product_zip, SmokeBase, setUp, tearDown
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_smoke_default_paths.py:1-305 · blob 56b7d0188f7bb3a3bb229a445de1c1931e9ae3ac · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Smoke test: the REAL entry points on their DEFAULT code paths, faked only at the network.

Every other test injects its collaborators (``sleep=``, ``rng=``, ``downloader=``,
``body_decoder=``, stub modules). That is how a ``NameError`` in a default
argument path (``rng or random.random`` without ``import random``, PR #15,
backfill run 40699133665) passed CI and reached the production backfill.

Here nothing is injected. ``collect.py``, ``history.py``, ``grid.py`` and
``status.py`` run as subprocesses, exactly as the workflows run them. The only
fake is a stand-in ``eumdac`` package placed first on ``PYTHONPATH`` (the
EUMETSAT Data Store is the network boundary): it lists product ZIPs from a
local folder and raises ``ReadTimeout`` on the first search and the first
product open, so the default retry, backoff (``random``) and sleep paths
really run (about 2-3 s each).

``requests``, ``netCDF4`` and ``numpy`` are the real packages when installed.
With ``LIGHTNING_SMOKE_REQUIRE_DEPS=1`` (the CI "with requirements" leg)
missing packages fail instead of skip, so the full pipeline can never be
skipped silently there. Without the requirements (the "bare" leg) the
search, retry and download defaults still run up to the NetCDF decode.
"""
import importlib
import importlib.util
import io
import json
import os
import subprocess
import sys
import tempfile
import unittest
import zipfile
from datetime import datetime, timedelta, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
REQUIRE_DEPS = os.environ.get("LIGHTNING_SMOKE_REQUIRE_DEPS") == "1"
DEPS = ("requests", "netCDF4", "numpy")
MISSING = [name for name in DEPS if importlib.util.find_spec(name) is None]

# The network boundary only. Mirrors the eumdac surface collect.py uses:
# AccessToken, DataStore.get_collection(id).search(dtstart=, dtend=) with
# total_results, str(product), product.open() as a stream, product.datastore.token.
FAKE_EUMDAC = r'''
"""FAKE eumdac (tests only): serves product ZIPs from $FAKE_EUMDAC_PRODUCTS."""
import os
import re
from datetime import datetime
from pathlib import Path

_SLOT = re.compile(r"_OPE_(\d{14})_(\d{14})_")
_FAILS = {"search": int(os.environ.get("FAKE_EUMDAC_SEARCH_TIMEOUTS", "0")),
          "open": int(os.environ.get("FAKE_EUMDAC_OPEN_TIMEOUTS", "0"))}
CALLS = []


class ReadTimeout(Exception):  # classified as transient by class name, like requests'
    pass


def _maybe_fail(kind):
    CALLS.append(kind)
    if _FAILS[kind] > 0:
        _FAILS[kind] -= 1
        raise ReadTimeout(f"HTTPSConnectionPool(host='api.eumetsat.int', port=443): Read timed out. (fake {kind})")


class AccessToken:
    def __init__(self, credentials):
        key, secret = credentials
        assert key and secret
        self.credentials = credentials

    def _update_token_data(self):
        pass


class _Stream:
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        return self

    def __exit__(self, *exc):
        return False

    def read(self):
        return self.path.read_bytes()


class _Product:
    def __init__(self, path, datastore):
        self.path, self.datastore = path, datastore

    def __str__(self):
        return self.path.name

    def open(self):
        _maybe_fail("open")
        return _Stream(self.path)


class _Results:
    def __init__(self, products):
        self.products = products
        self.total_results = len(products)

    def __iter__(self):
        return iter(self.products)


class _Collection:
    def __init__(self, datastore, collection_id):
        self.datastore, self.collection_id = datastore, collection_id

    def search(self, dtstart, dtend):
        _maybe_fail("search")
        assert dtstart.tzinfo is None and dtend.tzinfo is None  # collect.py passes naive UTC
        found = []
        for path in sorted(Path(os.environ["FAKE_EUMDAC_PRODUCTS"]).iterdir()):
            m = _SLOT.search(path.name)
            start, end = (datetime.strptime(x, "%Y%m%d%H%M%S") for x in m.groups())
            if start < dtend and end > dtstart:
                found.append(_Product(path, self.datastore))
        return _Results(found)


class DataStore:
    def __init__(self, token):
        self.token = token

    def get_collection(self, collection_id):
        assert collection_id == "EO:EUM:DAT:0691"
        return _Collection(self, collection_id)
'''


def product_name(start: datetime) -> str:
    stop = start + timedelta(minutes=10)
    return ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
            f"{stop:%Y%m%d%H%M%S}_L2PF_OPE_{start:%Y%m%d%H%M%S}_{stop:%Y%m%d%H%M%S}_N__O_0001_0000")


def slot_floor(value: datetime) -> datetime:
    return value.replace(minute=value.minute - value.minute % 10, second=0, microsecond=0)


def body_netcdf(flashes) -> bytes:
    """A real LFL-like BODY NetCDF (longitude, latitude, flash_time) written with netCDF4."""
    from netCDF4 import Dataset
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "BODY.nc"
        with Dataset(path, "w") as ds:
            ds.createDimension("flashes", len(flashes))
            lon = ds.createVariable("longitude", "f4", ("flashes",))
            lat = ds.createVariable("latitude", "f4", ("flashes",))
            t = ds.createVariable("flash_time", "f8", ("flashes",))
            t.units = "seconds since 2000-01-01 00:00:00"
            t.calendar = "standard"
            epoch = datetime(2000, 1, 1, tzinfo=timezone.utc)
            lon[:] = [f[0] for f in flashes]
            lat[:] = [f[1] for f in flashes]
            t[:] = [(f[2] - epoch).total_seconds() for f in flashes]
        return path.read_bytes()


def product_zip(name: str, body: bytes) -> bytes:
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as archive:
        archive.writestr(f"{name}/{name}_BODY.nc", body)
        archive.writestr(f"{name}/EOPMetadata.xml", "<fake/>")
    return buf.getvalue()


class SmokeBase(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        fake = self.base / "fakes" / "eumdac"
        fake.mkdir(parents=True)
        (fake / "__init__.py").write_text(FAKE_EUMDAC)
        self.products = self.base / "products"
        self.products.mkdir()
        self.data = self.base / "data"
        self.data.mkdir()
        self.env = {**os.environ, "PYTHONPATH": str(self.base / "fakes"), "PYTHONDONTWRITEBYTECODE": "1",
                    "EUMETSAT_CONSUMER_KEY": "fake-key", "EUMETSAT_CONSUMER_SECRET": "fake-secret",
                    "FAKE_EUMDAC_PRODUCTS": str(self.products)}
        self.now = datetime.now(timezone.utc)

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

    def run_py(self, *args, extra_env=None, check=True):
        done = subprocess.run([sys.executable, *map(str, args)], cwd=self.base, capture_output=True, text=True,
                              env={**self.env, **(extra_env or {})}, timeout=180)
        if check:
            self.assertEqual(done.returncode, 0, f"{args}\nSTDOUT:\n{done.stdout}\nSTDERR:\n{done.stderr}")
        return done

    def assert_no_crash_of_our_own(self, done):
        for marker in ("NameError", "UnboundLocalError", "AttributeError: module", "ImportError: cannot import"):
            self.assertNotIn(marker, done.stderr, done.stderr)


class ImportSmokeTests(unittest.TestCase):
    def test_every_module_imports_in_a_fresh_interpreter(self):
        for name in ("collect", "history", "grid", "status", "backfill_parallel"):
            done = subprocess.run([sys.executable, "-c", f"import {name}"], cwd=ROOT, capture_output=True, text=True)
            self.assertEqual(done.returncode, 0, f"import {name}: {done.stderr}")

    def test_every_cli_answers_help(self):
        for script in ("collect.py", "history.py", "grid.py", "status.py", "backfill_parallel.py"):
            done = subprocess.run([sys.executable, str(ROOT / script), "--help"], cwd=ROOT,
                                  capture_output=True, text=True)
            self.assertEqual(done.returncode, 0, f"{script} --help: {done.stderr}")


class DefaultSearchAndDownloadSmokeTests(SmokeBase):
    """Runs with or without the requirements: the decode is never reached."""

    def test_rebuild_day_runs_default_search_retry_and_download_paths(self):
        day = (self.now - timedelta(days=3)).date()
        start = datetime.combine(day, datetime.min.time(), tzinfo=timezone.utc) + timedelta(hours=12)
        # Not a ZIP: decode fails with ValueError (no netCDF4 needed), every slot is
        # unparsed and collect.py stops with TooManyUnparsed AFTER the defaults ran.
        (self.products / product_name(start)).write_bytes(b"not a zip")
        record = self.base / "rb.json"
        done = self.run_py(ROOT / "collect.py", "--rebuild-day", day.isoformat(), "--run-record", record,
                           extra_env={"FAKE_EUMDAC_SEARCH_TIMEOUTS": "1", "FAKE_EUMDAC_OPEN_TIMEOUTS": "1"},
                           check=False)
        self.assert_no_crash_of_our_own(done)
        self.assertIn("RETRY search after attempt 1", done.stderr)
        self.assertIn("RETRY product", done.stderr)
        self.assertNotEqual(done.returncode, 0)
        failure = json.loads(record.read_text())
        self.assertEqual(failure["outcome"], "failure")
        self.assertTrue(failure["error"].startswith("TooManyUnparsed"), failure["error"])
        self.assertEqual(failure["download_retries"]["retries"], 1)


class FullPipelineSmokeTests(SmokeBase):
    """collect -> history ingest -> verify -> grid verify --deep -> status, and a rebuild-day backfill."""

    def setUp(self):
        if MISSING:
            if REQUIRE_DEPS:
                self.fail(f"LIGHTNING_SMOKE_REQUIRE_DEPS=1 but {MISSING} not installed (pip install -r requirements.txt)")
            self.skipTest(f"requirements not installed: {MISSING}")
        super().setUp()

    def add_product(self, start: datetime, flashes):
        name = product_name(start)
        (self.products / name).write_bytes(product_zip(name, body_netcdf(flashes)))
        return name

    def test_hourly_and_backfill_paths_end_to_end(self):
        # Hourly: three readable 10-minute products inside a 6 h window.
        slot = slot_floor(self.now - timedelta(hours=2))
        for i in range(3):
            s = slot + timedelta(minutes=10 * i)
            self.add_product(s, [(-2.0 + i * 0.1, 52.0, s + timedelta(minutes=3)),
                                 (20.0, 10.0, s + timedelta(minutes=4))])  # outside the UK view: dropped
        feed, status, history_dir = self.data / "uk_lightning.geojson", self.data / "status.json", self.data / "history"
        run = self.base / "run.json"
        done = self.run_py(ROOT / "collect.py", "--hours", "6", "--out", feed, "--status", status,
                           "--history-dir", history_dir, "--run-record", run,
                           extra_env={"FAKE_EUMDAC_SEARCH_TIMEOUTS": "1", "FAKE_EUMDAC_OPEN_TIMEOUTS": "1"})
        self.assert_no_crash_of_our_own(done)
        self.assertIn("RETRY search after attempt 1", done.stderr)
        self.assertEqual(len(json.loads(feed.read_text())["features"]), 3)
        record = json.loads(run.read_text())
        self.assertEqual((record["outcome"], record["download_retries"]["retries"]), ("success", 1))

        result = self.base / "archive-result.json"
        self.run_py(ROOT / "history.py", "ingest", "--archive-dir", history_dir, "--run-record", run,
                    "--seed-scan-windows", self.base / "no-seed.json", "--result-out", result)
        self.run_py(ROOT / "history.py", "verify", "--archive-dir", history_dir)
        self.run_py(ROOT / "grid.py", "verify", "--deep", "--archive-dir", history_dir)
        self.run_py(ROOT / "status.py", "write", "--status", status, "--run-record", run, "--archive-result", result,
                    "--collect-outcome", "success", "--archive-outcome", "success", "--trigger", "schedule")
        self.assertEqual(json.loads(status.read_text())["last_attempt_outcome"], "success")

        # Backfill: a whole-day rebuild of a never-searched date, then its ingest.
        day = (self.now - timedelta(days=3)).date()
        noon = datetime.combine(day, datetime.min.time(), tzinfo=timezone.utc) + timedelta(hours=12)
        for i in range(3):
            s = noon + timedelta(minutes=10 * i)
            self.add_product(s, [(-1.0, 53.0, s + timedelta(minutes=5))])
        rb = self.base / "rb.json"
        done = self.run_py(ROOT / "collect.py", "--rebuild-day", day.isoformat(), "--run-record", rb)
        self.assert_no_crash_of_our_own(done)
        self.run_py(ROOT / "history.py", "backfill", "--archive-dir", history_dir, "--day", day.isoformat(),
                    "--rebuild-record", rb)
        self.run_py(ROOT / "history.py", "verify", "--archive-dir", history_dir)
        self.run_py(ROOT / "grid.py", "verify", "--deep", "--archive-dir", history_dir)
        rows = {r["date"]: r for r in json.loads((history_dir / "index.json").read_text())["days"]}
        self.assertEqual(rows[day.isoformat()]["count"], 3)

        # The same checks the data workflows run before every push.
        self.run_py(ROOT / "ci" / "verify_data.py", "--data-dir", self.data, "--deep")


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

Test Status

A test in the tests folder of Lightning that checks Status. It is built from the status tests class (`StatusTests`).

testlightning / tests/test_status.py · lines 1–164 of 164 · Entry point

What it does
It tests its inputs. Defines 12 functions or classes, including StatusTests, test_success_records_the_examined_scan_end_not_now, test_failure_keeps_previous_success_and_counts_consecutive_failures, test_archive_failure_is_recorded_without_touching_feed_success, test_unparsed_slots_do_not_advance_the_scan_end. Uses libraries json, sys, tempfile, unittest, datetime. Side effects: reads or writes files.
Inputs & outputs
In: JSON file status.json; JSON file missing.json; JSON file run.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
`data/status.json` is written after every run; failures leave a trace, never a zero.
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
Status (import), 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
StatusTests
Defines here
StatusTests, test_success_records_the_examined_scan_end_not_now, test_failure_keeps_previous_success_and_counts_consecutive_failures, test_archive_failure_is_recorded_without_touching_feed_success, test_unparsed_slots_do_not_advance_the_scan_end, test_lost_days_reach_the_status_file, test_shard_lost_degrades_health_and_raises_an_integrity_alert, test_integrity_alert_is_carried_when_the_archive_step_fails_or_is_skipped, test_recovered_archive_reports_ok_again, test_alert_command_exits_nonzero_while_a_shard_is_lost, test_health_thresholds, test_cli_writes_the_file_even_without_a_run_record
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_status.py:1-164 · blob 2557c7c0862d4bf3787908fefefabafd2e0a5121 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""data/status.json is written after every run; failures leave a trace, never a zero."""
import json
import sys
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import status as status_module
from status import build_status, health

NOW = datetime(2026, 10, 26, 14, 20, tzinfo=timezone.utc)
RECORD = {
    "schema": "uk-lightning-run-record.v1", "run_utc": "2026-10-26T14:17:00.000Z", "outcome": "success", "error": None,
    "query_start_utc": "2026-10-26T08:17:00.000Z", "query_end_utc": "2026-10-26T14:17:00.000Z", "lookback_hours": 6.0,
    "lookback_source": "status", "lookback_capped": False, "products_examined": 36, "slots_examined": 36,
    "slots_examined_utc": ["2026-10-26T08:10:09.000Z"], "scanned_ranges": [
        {"start_utc": "2026-10-26T08:17:00.000Z", "end_utc": "2026-10-26T14:10:09.000Z"}],
    "unscanned_ranges": [], "tail_unobserved_seconds": 411, "incoming_features": 3, "feed_features": 411,
    "feed_total_before_display_cap": 411, "feed_latest_detection_utc": "2026-10-26T13:58:00.000Z", "features": [],
}


class StatusTests(unittest.TestCase):
    def test_success_records_the_examined_scan_end_not_now(self):
        result = build_status(now=NOW, previous=None, record=RECORD, archive_result={
            "outcome": "success", "archived_observations": 411, "files_changed": 2, "index_generated_utc": "2026-10-26T14:18:00.000Z"},
            collect_outcome="success", archive_outcome="success")
        self.assertEqual(result["schema"], "uk-lightning-status.v1")
        self.assertEqual(result["last_attempt_outcome"], "success")
        self.assertEqual(result["consecutive_failures"], 0)
        self.assertEqual(result["last_successful_scan_end_utc"], "2026-10-26T14:10:09.000Z")
        self.assertEqual(result["last_successful_scan_start_utc"], "2026-10-26T08:17:00.000Z")
        self.assertEqual(result["health"], "ok")
        self.assertEqual(result["last_tail_unobserved_seconds"], 411)
        self.assertEqual(result["archive"]["archived_observations"], 411)
        self.assertIsNone(result["last_error"])
        self.assertIn("unknown, not zero", result["note"])

    def test_failure_keeps_previous_success_and_counts_consecutive_failures(self):
        previous = build_status(now=NOW - timedelta(hours=1), previous=None, record=RECORD, archive_result=None,
                                collect_outcome="success", archive_outcome="success")
        failed_record = {**RECORD, "run_utc": "2026-10-26T15:17:00.000Z", "outcome": "failure",
                         "error": "RuntimeError: No EUMETSAT product files returned", "scanned_ranges": [], "products_examined": 0}
        first = build_status(now=NOW + timedelta(hours=1), previous=previous, record=failed_record, archive_result=None,
                             collect_outcome="failure", archive_outcome="skipped")
        self.assertEqual(first["last_attempt_outcome"], "failure")
        self.assertEqual(first["consecutive_failures"], 1)
        self.assertIn("No EUMETSAT product files", first["last_error"])
        self.assertEqual(first["last_successful_scan_end_utc"], "2026-10-26T14:10:09.000Z")
        self.assertEqual(first["last_successful_run_utc"], "2026-10-26T14:17:00.000Z")
        self.assertIsNone(first["last_scanned_ranges"])
        second = build_status(now=NOW + timedelta(hours=2), previous=first, record=None, archive_result=None,
                              collect_outcome="failure", archive_outcome="skipped")
        self.assertEqual(second["consecutive_failures"], 2)
        self.assertIn("no run record", second["last_error"])
        self.assertEqual(second["last_successful_scan_end_utc"], "2026-10-26T14:10:09.000Z")
        recovered = build_status(now=NOW + timedelta(hours=3), previous=second,
                                 record={**RECORD, "run_utc": "2026-10-26T17:17:00.000Z", "scanned_ranges": [
                                     {"start_utc": "2026-10-26T13:40:09.000Z", "end_utc": "2026-10-26T17:10:09.000Z"}]},
                                 archive_result=None, collect_outcome="success", archive_outcome="success")
        self.assertEqual(recovered["consecutive_failures"], 0)
        self.assertEqual(recovered["last_successful_scan_end_utc"], "2026-10-26T17:10:09.000Z")

    def test_archive_failure_is_recorded_without_touching_feed_success(self):
        result = build_status(now=NOW, previous=None, record=RECORD, archive_result=None,
                              collect_outcome="success", archive_outcome="failure")
        self.assertEqual(result["last_attempt_outcome"], "success")
        self.assertEqual(result["archive"]["outcome"], "failure")
        self.assertIn("archive step failed", result["archive"]["error"])
        self.assertEqual(result["feed"]["features"], 411)

    def test_unparsed_slots_do_not_advance_the_scan_end(self):
        previous = build_status(now=NOW - timedelta(hours=1), previous=None, record=RECORD, archive_result=None,
                                collect_outcome="success", archive_outcome="success")
        opaque = {**RECORD, "run_utc": "2026-10-26T15:17:00.000Z", "slots_parsed": False, "scanned_ranges": [
            {"start_utc": "2026-10-26T09:17:00.000Z", "end_utc": "2026-10-26T15:17:00.000Z"}]}
        result = build_status(now=NOW + timedelta(hours=1), previous=previous, record=opaque, archive_result=None,
                              collect_outcome="success", archive_outcome="success")
        self.assertEqual(result["last_successful_scan_end_utc"], "2026-10-26T14:10:09.000Z")  # not the query end
        self.assertIs(result["last_slots_parsed"], False)
        self.assertEqual(result["consecutive_failures"], 0)  # the feed run itself succeeded

    def test_lost_days_reach_the_status_file(self):
        result = build_status(now=NOW, previous=None, record=RECORD, archive_result={
            "outcome": "success", "lost_days": ["2026-10-24"], "dropped_lost_day": 1},
            collect_outcome="success", archive_outcome="success")
        self.assertEqual(result["archive"]["lost_days"], ["2026-10-24"])
        self.assertEqual(result["archive"]["dropped_lost_day"], 1)

    # --- shard_lost: explicit integrity alert, never reported entirely healthy ---------
    LOST_RESULT = {"outcome": "success", "lost_days": ["2026-10-24"], "dropped_lost_day": 0,
                   "integrity": {"state": "shard_lost", "lost_days": ["2026-10-24"], "quarantined_observations": 1,
                                 "alert": "INTEGRITY ALERT: 1 UTC date lost its listed shard (2026-10-24); unknown, not zero"}}

    def test_shard_lost_degrades_health_and_raises_an_integrity_alert(self):
        result = build_status(now=NOW, previous=None, record=RECORD, archive_result=self.LOST_RESULT,
                              collect_outcome="success", archive_outcome="success")
        self.assertEqual(result["freshness"], "ok")
        self.assertEqual(result["health"], "degraded")  # fresh, but not entirely healthy
        self.assertEqual(result["integrity"]["state"], "shard_lost")
        self.assertEqual(result["integrity"]["lost_days"], ["2026-10-24"])
        self.assertIn("INTEGRITY ALERT", result["integrity"]["alert"])
        self.assertEqual(result["integrity"]["source"], "this_run")

    def test_integrity_alert_is_carried_when_the_archive_step_fails_or_is_skipped(self):
        lost = build_status(now=NOW, previous=None, record=RECORD, archive_result=self.LOST_RESULT,
                            collect_outcome="success", archive_outcome="success")
        for outcome in ("failure", "skipped"):
            later = build_status(now=NOW + timedelta(hours=1), previous=lost, record=RECORD, archive_result=None,
                                 collect_outcome="success", archive_outcome=outcome)
            self.assertEqual(later["integrity"]["state"], "shard_lost", outcome)
            self.assertEqual(later["integrity"]["source"], "previous_status", outcome)
            self.assertEqual(later["health"], "degraded", outcome)

    def test_recovered_archive_reports_ok_again(self):
        lost = build_status(now=NOW, previous=None, record=RECORD, archive_result=self.LOST_RESULT,
                            collect_outcome="success", archive_outcome="success")
        ok = build_status(now=NOW, previous=lost, record=RECORD, archive_result={
            "outcome": "success", "integrity": {"state": "ok", "lost_days": [], "alert": None}},
            collect_outcome="success", archive_outcome="success")
        self.assertEqual((ok["health"], ok["integrity"]["state"], ok["integrity"]["alert"]), ("ok", "ok", None))

    def test_alert_command_exits_nonzero_while_a_shard_is_lost(self):
        with tempfile.TemporaryDirectory() as tmp:
            target = Path(tmp) / "status.json"
            status_module.write_status(target, build_status(
                now=NOW, previous=None, record=RECORD, archive_result=self.LOST_RESULT,
                collect_outcome="success", archive_outcome="success"))
            self.assertEqual(status_module.main(["alert", "--status", str(target)]), 1)
            status_module.write_status(target, build_status(
                now=NOW, previous=None, record=RECORD, archive_result={"outcome": "success", "integrity": {"state": "ok"}},
                collect_outcome="success", archive_outcome="success"))
            self.assertEqual(status_module.main(["alert", "--status", str(target)]), 0)

    def test_health_thresholds(self):
        self.assertEqual(health(NOW, None), "never")
        self.assertEqual(health(NOW, NOW - timedelta(hours=5)), "ok")
        self.assertEqual(health(NOW, NOW - timedelta(hours=7)), "warn")
        self.assertEqual(health(NOW, NOW - timedelta(hours=13)), "stale")
        self.assertEqual(health(NOW, NOW - timedelta(hours=25)), "stopped")

    def test_cli_writes_the_file_even_without_a_run_record(self):
        with tempfile.TemporaryDirectory() as tmp:
            target = Path(tmp) / "data" / "status.json"
            code = status_module.main(["write", "--status", str(target), "--run-record", str(Path(tmp) / "missing.json"),
                                       "--collect-outcome", "failure", "--archive-outcome", "skipped", "--now", NOW.isoformat()])
            self.assertEqual(code, 0)
            written = json.loads(target.read_text())
            self.assertEqual(written["last_attempt_outcome"], "failure")
            self.assertEqual(written["consecutive_failures"], 1)
            self.assertEqual(written["health"], "never")
            record = Path(tmp) / "run.json"
            record.write_text(json.dumps(RECORD))
            status_module.main(["write", "--status", str(target), "--run-record", str(record), "--collect-outcome", "success",
                                "--archive-outcome", "success", "--now", NOW.isoformat()])
            written = json.loads(target.read_text())
            self.assertEqual(written["consecutive_failures"], 0)
            self.assertEqual(written["last_successful_scan_end_utc"], "2026-10-26T14:10:09.000Z")


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