GLOBALGRID2050 / EXPLORE CODE

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

Test Shard Lost and 1 more file

A test in the tests folder of Lightning that checks History and Collect, using SHA-256. It sets up (`setUp`), indexes bytes (`index_bytes`) and rebuilds record (`rebuild_record`).

639 lines of Python from lightning, in 2 files. Topic: Automation and CI. Section 1830 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 Shard Budget test · lightning / tests/test_shard_budget.py lines 1–312
  2. Test Shard Lost test · lightning / tests/test_shard_lost.py lines 1–327

Test Shard Budget

A test in the tests folder of Lightning that checks Backfill Parallel and Collect.

testlightning / tests/test_shard_budget.py · lines 1–312 of 312 · Entry point · pattern Session (shared by 2 files)

What it does
It tests its inputs. Defines 40 functions or classes, including SilentServer, __init__, _serve, close, HangingProduct. Uses libraries json, socket, sys, tempfile, threading. Side effects: reads or writes files; makes network requests.
Inputs & outputs
In: JSON file shard-3.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
It sets up (`setUp`) and is built from the silent server class (`SilentServer`) and the close step (`close`). A stalled EUMETSAT read must never hang a shard (and so the whole backfill).
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), Test Unreadable Product (import), Test Backfill Parallel (import), json, socket, sys, tempfile, threading, types, unittest, datetime
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
SilentServer, HangingProduct, RequestTimeoutTests, ShardWallClockTests, WorkflowTimeoutTests
Defines here
SilentServer, __init__, _serve, close, HangingProduct, __init__, __str__, open, Stream, __enter__, read, __exit__, RequestTimeoutTests, setUp, test_hanging_read_times_out_is_retried_then_unparsed, test_read_timeouts_are_transient_by_name, test_too_many_timed_out_slots_still_trip_the_per_day_threshold, _fake_requests, Session, request, get, test_every_session_call_gets_the_explicit_timeout, test_real_requests_read_times_out_on_a_stalled_server, test_search_products_installs_the_timeout_before_eumdac, ShardWallClockTests, setUp, good, test_defaults_match_the_workflow, test_hanging_collect_subprocess_is_killed_and_earlier_records_kept, collector
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_shard_budget.py:1-312 · blob c119b652bce45b7b64f9d2e08d89bba57581a10d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
"""A stalled EUMETSAT read must never hang a shard (and so the whole backfill).

Incident (parallel backfill run 40564980740, 27-28 Oct 2026): shards 1 and 2
finished in 178 and 208 min, shard 3 was still "in_progress" after 5 h and
nothing was committed, because finalize waits for every shard. eumdac passes
no ``timeout`` to requests, so one stalled TCP read blocks for ever, and the
shard budget (290 min) was only checked between dates, inside a 340-minute
job timeout.

Now:
- every HTTP call gets an explicit (connect, read) timeout, ``collect.HTTP_TIMEOUT``
  (15, 60); a read timeout is transient, retried, and once the retries are used
  up the product's slot is UNPARSED (unknown, never zero);
- the per-day unparsed threshold still stops a date with too many such slots;
- a shard starts no new date after ``SHARD_BUDGET_MINUTES`` (170) and kills a
  date still running at the hard stop (190) or after 45 min, keeps what it
  collected and uploads it inside the 200-minute job timeout;
- finalize runs ``always()`` and ingests whatever shard artifacts exist.

The hanging reads below are REAL sockets to a local server that accepts and
never answers; only the timeouts are shortened. No EUMETSAT, no network.
"""
import json
import socket
import sys
import tempfile
import threading
import types
import unittest
from datetime import date, timedelta
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
from test_unreadable_product import DAY0, fake_body, good_zip, slot_name

WORKFLOW = ROOT / ".github" / "workflows" / "backfill-parallel-lightning.yml"
SHORT = (0.5, 0.2)  # (connect, read) seconds for the tests


class SilentServer:
    """Accepts TCP connections and never sends a byte: a stalled read."""

    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind(("127.0.0.1", 0))
        self.sock.listen(16)
        self.port = self.sock.getsockname()[1]
        self.conns, self.stop = [], threading.Event()
        self.thread = threading.Thread(target=self._serve, daemon=True)
        self.thread.start()

    def _serve(self):
        self.sock.settimeout(0.1)
        while not self.stop.is_set():
            try:
                conn, _ = self.sock.accept()
                self.conns.append(conn)  # hold it open, never answer
            except OSError:
                continue

    def close(self):
        self.stop.set()
        self.thread.join(2)
        for conn in self.conns:
            conn.close()
        self.sock.close()


class HangingProduct:
    """Fake eumdac product whose ``open().read()`` is a real stalled socket read.

    The stream reads with the read timeout ``collect.HTTP_TIMEOUT`` gives it, as
    urllib3 does once requests passes the timeout down.
    """

    def __init__(self, name, port, *, hang=True, blob=None):
        self.name, self.port, self.hang, self.blob, self.opens = name, port, hang, blob, 0

    def __str__(self):
        return self.name

    def open(self):
        product = self

        class Stream:
            def __enter__(self):
                product.opens += 1
                connect, read = collect.HTTP_TIMEOUT
                self.sock = socket.create_connection(("127.0.0.1", product.port), timeout=connect)
                self.sock.settimeout(read)
                return self

            def read(self):
                if not product.hang:
                    return product.blob
                return self.sock.recv(1)  # stalls: raises TimeoutError after the read timeout

            def __exit__(self, *exc):
                self.sock.close()
                return False
        return Stream()


class RequestTimeoutTests(unittest.TestCase):
    def setUp(self):
        self.server = SilentServer()
        self.addCleanup(self.server.close)

    def test_hanging_read_times_out_is_retried_then_unparsed(self):
        start = DAY0
        names = [slot_name(start + timedelta(minutes=10 * i)) for i in range(4)]
        products = [HangingProduct(names[0], self.server.port, hang=False, blob=good_zip(names[0], [])),
                    HangingProduct(names[1], self.server.port, hang=True),
                    HangingProduct(names[2], self.server.port, hang=False, blob=good_zip(names[2], [])),
                    HangingProduct(names[3], self.server.port, hang=False, blob=good_zip(names[3], []))]
        slept = []
        with mock.patch.object(collect, "HTTP_TIMEOUT", SHORT):
            found, count, readable, unparsed, stats = collect.download_products(
                products, start, start + timedelta(minutes=40), body_decoder=fake_body,
                sleep=slept.append, rng=lambda: 0.0)
        self.assertEqual(count, 3)
        self.assertEqual(products[1].opens, 1 + collect.TRANSIENT_RETRIES)  # retried, then given up
        self.assertEqual([u["product"] for u in unparsed], [names[1]])
        self.assertEqual(unparsed[0]["kind"], "download")
        self.assertIn("TimeoutError", unparsed[0]["reason"])
        self.assertEqual(stats["products_failed"], 1)
        self.assertEqual(stats["retries"], collect.TRANSIENT_RETRIES)
        self.assertEqual(slept, [2.0, 4.0, 8.0, 16.0])
        self.assertNotIn(names[1], readable)  # unknown, never zero

    def test_read_timeouts_are_transient_by_name(self):
        for cls_name in ("ReadTimeout", "ReadTimeoutError", "ConnectTimeout", "TimeoutError"):
            error = type(cls_name, (Exception,), {})("stalled")
            self.assertEqual(collect.classify_download_error(error)[0], "transient", cls_name)
        self.assertEqual(collect.classify_download_error(socket.timeout("timed out"))[0], "transient")

    def test_too_many_timed_out_slots_still_trip_the_per_day_threshold(self):
        start = DAY0
        names = [slot_name(start + timedelta(minutes=10 * i)) for i in range(144)]
        unparsed = [collect.unparsed_entry(n, TimeoutError("timed out"), kind="download") for n in names[:30]]
        with self.assertRaises(collect.TooManyUnparsed):
            collect.check_unparsed(unparsed, names[30:], start, start + timedelta(days=1))
        collect.check_unparsed(unparsed[:28], names[28:], start, start + timedelta(days=1))  # 28/144 < 20 %

    def _fake_requests(self):
        seen = []

        class Session:
            def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None,
                        auth=None, timeout=None, **rest):
                seen.append(timeout)
                return timeout

            def get(self, url, **kwargs):  # what eumdac.request.get ends up calling
                return self.request("GET", url, **kwargs)
        return types.SimpleNamespace(Session=Session), seen

    def test_every_session_call_gets_the_explicit_timeout(self):
        fake, seen = self._fake_requests()
        old_default = socket.getdefaulttimeout()
        self.addCleanup(socket.setdefaulttimeout, old_default)
        self.assertTrue(collect.install_http_timeouts(requests_module=fake))
        session = fake.Session()
        session.get("https://example.invalid/token")                    # eumdac: no timeout at all
        session.request("GET", "https://example.invalid/x", timeout=None)
        session.get("https://example.invalid/y", timeout=5)             # explicit one is kept
        session.request("GET", "u", None, None, None, None, None, None, None)  # positional None
        self.assertEqual(seen, [(15, 60), (15, 60), 5, (15, 60)])
        self.assertEqual(socket.getdefaulttimeout(), 60.0)
        collect.install_http_timeouts(requests_module=fake)  # idempotent: never double-wrapped
        session.get("z")
        self.assertEqual(seen[-1], (15, 60))
        self.assertEqual(len(seen), 5)

    def test_real_requests_read_times_out_on_a_stalled_server(self):
        try:
            import requests
        except ImportError:
            self.skipTest("requests not installed")
        original = requests.Session.request
        old_default = socket.getdefaulttimeout()
        self.addCleanup(setattr, requests.Session, "request", original)
        self.addCleanup(socket.setdefaulttimeout, old_default)
        collect.install_http_timeouts(SHORT)
        with self.assertRaises(requests.exceptions.ReadTimeout) as caught:
            requests.Session().get(f"http://127.0.0.1:{self.server.port}/product", stream=True)
        self.assertEqual(collect.classify_download_error(caught.exception)[0], "transient")

    def test_search_products_installs_the_timeout_before_eumdac(self):
        calls = []
        with mock.patch.dict("os.environ", {"EUMETSAT_CONSUMER_KEY": "k", "EUMETSAT_CONSUMER_SECRET": "s"}), \
                mock.patch.object(collect, "install_http_timeouts", side_effect=lambda: calls.append("t")), \
                mock.patch.dict(sys.modules, {"eumdac": None}):
            with self.assertRaises(ImportError):
                collect.search_products(DAY0, DAY0 + timedelta(days=1))
        self.assertEqual(calls, ["t"])


class ShardWallClockTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.out = Path(self.temp.name) / "records"
        self.dates = ["2026-10-20", "2026-10-17", "2026-10-14"]

    def good(self, day, record, log, timeout=None):
        from test_backfill_parallel import FakeEumetsat
        FakeEumetsat().collector()(day, record, log)

    def test_defaults_match_the_workflow(self):
        self.assertEqual(bp.DEFAULT_SHARD_BUDGET_MINUTES, 170)
        self.assertEqual(bp.DEFAULT_SHARD_BUDGET_MINUTES + bp.HARD_STOP_GRACE_MINUTES, 190)
        text = WORKFLOW.read_text()
        self.assertIn('SHARD_BUDGET_MINUTES: "170"', text)
        self.assertIn('SHARD_HARD_STOP_MINUTES: "190"', text)

    def test_hanging_collect_subprocess_is_killed_and_earlier_records_kept(self):
        """A real child process that hangs (like a stalled read) is killed at the date limit."""
        hang = [sys.executable, "-c", "import time; time.sleep(120)"]

        def collector(day, record, log, timeout=None):
            if day == self.dates[1]:
                with mock.patch.object(bp, "collect_command", lambda d, r: hang):
                    return bp.collect_subprocess(day, record, log, timeout=timeout)
            return self.good(day, record, log)
        summary = bp.run_shard(3, self.dates, self.out, budget_minutes=170,
                               date_timeout_minutes=1.5 / 60, collector=collector)
        self.assertEqual(summary["stopped"], "time_budget")
        self.assertIn(self.dates[1], summary["error"])
        self.assertIn("unknown", summary["error"])
        self.assertEqual([c["date"] for c in summary["collected"]], [self.dates[0]])
        self.assertFalse((self.out / f"rb-{self.dates[1]}.json").exists())
        self.assertFalse(list(self.out.glob(".partial-*")))
        on_disk = json.loads((self.out / "shard-3.json").read_text())
        self.assertEqual(on_disk["stopped"], "time_budget")

    def test_date_limit_never_runs_past_the_hard_stop(self):
        clock, limits = [0.0], []

        def collector(day, record, log, timeout=None):
            limits.append(timeout)
            self.good(day, record, log)
            clock[0] += 80 * 60  # each date "takes" 80 minutes
        summary = bp.run_shard(1, self.dates, self.out, budget_minutes=170, collector=collector,
                               clock=lambda: clock[0])
        # starts at 0 and 80 (< 170), the third at 160 gets only 190 - 160 = 30 min
        self.assertEqual(limits, [45 * 60, 45 * 60, 30 * 60])
        self.assertEqual(summary["hard_stop_minutes"], 190)
        self.assertEqual(summary["stopped"], "completed")

    def test_no_new_date_after_the_budget(self):
        clock, calls = [0.0], []

        def collector(day, record, log, timeout=None):
            calls.append(day)
            self.good(day, record, log)
            clock[0] += 90 * 60
        summary = bp.run_shard(1, self.dates, self.out, budget_minutes=170, collector=collector,
                               clock=lambda: clock[0])
        self.assertEqual(summary["stopped"], "time_budget")
        self.assertEqual(calls, self.dates[:2])  # 0 and 90 min start; 180 >= 170 does not

    def test_cli_default_budget_is_170(self):
        seen = {}

        def fake_run_shard(shard, dates, out_dir, **kw):
            seen.update(kw)
            return {"stopped": "completed", "collected": [], "dates": dates, "error": None}
        with mock.patch.object(bp, "run_shard", fake_run_shard), mock.patch("signal.signal"), \
                mock.patch.dict("os.environ", {}, clear=False):
            bp.main(["shard", "--shard", "1", "--dates", "2026-10-20", "--out-dir", str(self.out)])
        self.assertEqual(seen["budget_minutes"], 170)
        self.assertIsNone(seen["hard_stop_minutes"])
        self.assertEqual(seen["date_timeout_minutes"], 45)


class WorkflowTimeoutTests(unittest.TestCase):
    def setUp(self):
        try:
            import yaml
        except ImportError:
            self.skipTest("PyYAML not installed")
        self.jobs = yaml.safe_load(WORKFLOW.read_text())["jobs"]

    def test_shard_job_and_step_timeouts_bound_the_shard(self):
        shard = self.jobs["shard"]
        self.assertEqual(shard["timeout-minutes"], 200)
        budget = int(shard["env"]["SHARD_BUDGET_MINUTES"])
        hard = int(shard["env"]["SHARD_HARD_STOP_MINUTES"])
        search = next(s for s in shard["steps"] if s.get("id") == "search")
        self.assertLess(budget, hard)
        self.assertLess(hard, search["timeout-minutes"])
        self.assertLess(search["timeout-minutes"], shard["timeout-minutes"])
        self.assertIn("--hard-stop-minutes", search["run"])
        upload = next(s for s in shard["steps"] if str(s.get("uses", "")).startswith("actions/upload-artifact"))
        self.assertEqual(upload["if"], "${{ always() }}")

    def test_finalize_runs_always_and_tolerates_missing_artifacts(self):
        fin = self.jobs["finalize"]
        self.assertTrue(fin["if"].startswith("${{ always()"))
        records = next(s for s in fin["steps"] if s.get("with", {}).get("pattern") == "backfill-shard-*")
        self.assertTrue(records["continue-on-error"])
        self.assertTrue(records["with"]["merge-multiple"])


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

Test Shard Lost

A test in the tests folder of Lightning that checks History and Collect, using SHA-256. It sets up (`setUp`), indexes bytes (`index_bytes`) and rebuilds record (`rebuild_record`).

testlightning / tests/test_shard_lost.py · lines 1–327 of 327 · Entry point · pattern flash (shared by 8 files)

What it does
It tests its inputs. Defines 27 functions or classes, including rows, ShardLostTests, setUp, tearDown, flash. Uses libraries json, shutil, sys, tempfile, unittest. Side effects: reads or writes files.
Inputs & outputs
In: JSON file index.json; JSON file 24.json; JSON file run.json; JSON file result.json; JSON file none.json; JSON file partial.json; JSON file earlier-index.json; JSON file 04.json. Out: 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
A listed shard that vanished: unknown (never zero), flagged in index and status, healthy days keep flowing, and recovery only from verified evidence.
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), json, shutil, 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
rows, ShardLostTests
Defines here
rows, ShardLostTests, setUp, tearDown, flash, scan, lose_whole_day, index_bytes, test_lost_day_is_unknown_and_its_last_recorded_entry_is_kept_as_evidence, test_later_flashes_for_a_lost_day_are_quarantined_never_counted_or_discarded, test_index_carries_an_explicit_integrity_alert, test_healthy_archive_reports_integrity_ok, test_cli_ingest_prints_the_alert_and_still_succeeds, test_healthy_days_continue_while_the_archive_stays_flagged, test_verify_rejects_a_silently_cleared_flag_or_a_lost_row_with_a_count, test_recover_from_a_verified_earlier_shard_restores_the_row_and_audits_it, test_recover_refuses_a_partial_or_altered_shard_and_changes_nothing, test_recover_refuses_without_a_recorded_entry_unless_an_earlier_index_is_given, test_recover_split_day_needs_every_missing_part_and_verifies_survivors, test_recover_refuses_a_day_that_is_not_lost, rebuild_record, test_rebuild_must_cover_the_recorded_scan_and_match_the_recorded_count, test_rebuild_must_contain_every_quarantined_flash, test_unanchored_rebuild_needs_an_explicit_flag_and_is_audited_as_such, test_cli_recover, test_collect_rebuild_day_feeds_recover_rebuild_end_to_end, fake_download
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_shard_lost.py:1-327 · blob a9440c74c3caefa0d3b3b5944751817aabfc23af · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""A listed shard that vanished: unknown (never zero), flagged in index and status,
healthy days keep flowing, and recovery only from verified evidence.

Synthetic features exist ONLY inside temporary directories created by these
tests (ids start with "TEST-"); nothing synthetic is ever published.
"""
import json
import shutil
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 history
from collect import build_feature
from history import archive_observations, day_path, part_path, successful_scan, verify_archive

LOST = "2026-10-24"
HEALTHY = "2026-10-23"


def rows(result_or_index):
    index = result_or_index.get("index", result_or_index)
    return {r["date"]: r for r in index["days"]}


class ShardLostTests(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.base = Path(self.temp.name)
        self.root = self.base / "history"
        self.saved = self.base / "from-git-history"  # outside the archive: an earlier committed copy
        self.saved.mkdir()
        self.now = datetime(2026, 10, 26, 14, 0, 0, tzinfo=timezone.utc)
        self.day = datetime(2026, 10, 24, tzinfo=timezone.utc)

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

    def flash(self, timestamp, product, index=0):
        return build_feature(-2.12, 51.11, timestamp, "TEST-" + product, index)

    def scan(self, start, end):
        return successful_scan(start.isoformat(), end.isoformat(), 18)

    def lose_whole_day(self):
        """Archive two flashes on LOST and one on HEALTHY, save LOST's shard, delete it, re-run."""
        healthy = datetime(2026, 10, 23, tzinfo=timezone.utc)
        first = archive_observations(
            self.root, [self.flash(self.day + timedelta(hours=10), "a"), self.flash(self.day + timedelta(hours=11), "b"),
                        self.flash(healthy + timedelta(hours=9), "h")],
            now=self.now, scanned_windows=[self.scan(healthy, self.day + timedelta(days=1))])
        self.recorded = rows(first)[LOST]
        self.first_index = json.loads((self.root / "index.json").read_text())
        shutil.copy(self.root / day_path(self.day.date()), self.saved / "24.json")
        (self.root / day_path(self.day.date())).unlink()
        return archive_observations(self.root, [], now=self.now)

    def index_bytes(self):
        return (self.root / "index.json").read_bytes()

    # --- condition 1: the affected day is UNKNOWN, never zero --------------------
    def test_lost_day_is_unknown_and_its_last_recorded_entry_is_kept_as_evidence(self):
        result = self.lose_whole_day()
        row = rows(result)[LOST]
        self.assertEqual((row["coverage"], row["scanned_seconds"], row["count"], row["path"]), ("none", 0, None, None))
        self.assertTrue(row["shard_lost"])
        lost = result["index"]["integrity"]["lost_days"]
        self.assertEqual([e["date"] for e in lost], [LOST])
        evidence = lost[0]["last_recorded"]
        self.assertEqual((evidence["count"], evidence["sha256"], evidence["bytes"], evidence["path"]),
                         (2, self.recorded["sha256"], self.recorded["bytes"], self.recorded["path"]))
        self.assertEqual(lost[0]["missing_paths"], [self.recorded["path"]])
        self.assertEqual(lost[0]["detected_utc"], "2026-10-26T14:00:00.000Z")

    def test_later_flashes_for_a_lost_day_are_quarantined_never_counted_or_discarded(self):
        self.lose_whole_day()
        late = archive_observations(self.root, [self.flash(self.day + timedelta(hours=23), "late")], now=self.now)
        self.assertEqual(rows(late)[LOST]["count"], None)
        self.assertEqual((late["quarantined_lost_day"], late["dropped_lost_day"]), (1, 0))
        quarantine = json.loads((self.root / "quarantine" / f"{LOST}.json").read_text())
        self.assertEqual([f["id"] for f in quarantine["features"]], [self.flash(self.day + timedelta(hours=23), "late")["id"]])
        again = archive_observations(self.root, [self.flash(self.day + timedelta(hours=23), "late")], now=self.now)
        self.assertEqual(again["quarantined_lost_day"], 0)  # idempotent by stable id
        self.assertEqual(again["index"]["integrity"]["lost_days"][0]["quarantined_observations"], 1)
        verify_archive(self.root)

    # --- condition 2: index integrity block with an explicit alert ---------------
    def test_index_carries_an_explicit_integrity_alert(self):
        result = self.lose_whole_day()
        integrity = result["index"]["integrity"]
        self.assertEqual(integrity["state"], "shard_lost")
        self.assertIn("INTEGRITY ALERT", integrity["alert"])
        self.assertIn(LOST, integrity["alert"])
        self.assertIn("unknown", integrity["alert"])
        self.assertEqual(result["integrity"]["state"], "shard_lost")  # in the ingest result -> status.json
        self.assertEqual(result["integrity"]["lost_days"], [LOST])

    def test_healthy_archive_reports_integrity_ok(self):
        result = archive_observations(self.root, [self.flash(self.day + timedelta(hours=1), "ok")], now=self.now)
        self.assertEqual(result["index"]["integrity"], {"state": "ok", "alert": None, "lost_days": [], "recoveries": []})

    def test_cli_ingest_prints_the_alert_and_still_succeeds(self):
        self.lose_whole_day()
        record = self.base / "run.json"
        out = self.base / "result.json"
        record.write_text(json.dumps({"schema": "uk-lightning-run-record.v1", "outcome": "success",
                                      "run_utc": "2026-10-26T13:05:58.000Z", "products_examined": 1, "scanned_ranges": [],
                                      "features": []}))
        code = history.main(["ingest", "--archive-dir", str(self.root), "--run-record", str(record), "--result-out", str(out),
                             "--now", self.now.isoformat(), "--seed-scan-windows", str(self.base / "none.json")])
        self.assertEqual(code, 0)
        self.assertEqual(json.loads(out.read_text())["integrity"]["state"], "shard_lost")

    # --- condition 3: healthy days keep flowing, never "entirely healthy" ---------
    def test_healthy_days_continue_while_the_archive_stays_flagged(self):
        self.lose_whole_day()
        today = datetime(2026, 10, 26, tzinfo=timezone.utc)
        later = archive_observations(self.root, [self.flash(today + timedelta(hours=12), "new")], now=self.now,
                                     scanned_window=self.scan(today + timedelta(hours=8), today + timedelta(hours=13)))
        self.assertEqual(rows(later)["2026-10-26"]["count"], 1)
        self.assertEqual(rows(later)[HEALTHY]["count"], 1)
        self.assertEqual(later["index"]["archived_observations"], 2)
        self.assertEqual(later["index"]["integrity"]["state"], "shard_lost")
        self.assertEqual(verify_archive(self.root)["integrity"], "shard_lost")

    def test_verify_rejects_a_silently_cleared_flag_or_a_lost_row_with_a_count(self):
        self.lose_whole_day()
        good = json.loads((self.root / "index.json").read_text())
        cleared = json.loads(json.dumps(good))
        cleared["integrity"] = {"state": "ok", "alert": None, "lost_days": [], "recoveries": []}
        (self.root / "index.json").write_text(json.dumps(cleared))
        with self.assertRaisesRegex(ValueError, "shard_lost"):
            verify_archive(self.root)
        counted = json.loads(json.dumps(good))
        next(r for r in counted["days"] if r["date"] == LOST).update({"coverage": "full", "scanned_seconds": 86400, "count": 0})
        (self.root / "index.json").write_text(json.dumps(counted))
        with self.assertRaisesRegex(ValueError, "shard_lost"):
            verify_archive(self.root)

    # --- condition 4: recovery only from verified evidence -------------------------
    def test_recover_from_a_verified_earlier_shard_restores_the_row_and_audits_it(self):
        self.lose_whole_day()
        archive_observations(self.root, [self.flash(self.day + timedelta(hours=23), "late")], now=self.now)
        result = history.recover_day(self.root, LOST, now=self.now + timedelta(hours=1),
                                     from_shards=[self.saved / "24.json"])
        row = rows(result)[LOST]
        self.assertNotIn("shard_lost", row)
        self.assertEqual(row["count"], 3)  # 2 verified + 1 quarantined flash merged after verification
        self.assertEqual(row["coverage"], "full")
        integrity = result["index"]["integrity"]
        self.assertEqual((integrity["state"], integrity["alert"], integrity["lost_days"]), ("ok", None, []))
        audit = integrity["recoveries"][0]
        self.assertEqual((audit["date"], audit["method"]), (LOST, "from_shard"))
        self.assertEqual(audit["verified_against"]["sha256"], self.recorded["sha256"])
        self.assertEqual(audit["verified_against"]["count"], 2)
        self.assertEqual(audit["inputs"][0]["sha256"], self.recorded["sha256"])
        self.assertEqual(audit["quarantined_merged"], 1)
        self.assertEqual(audit["recovered_utc"], "2026-10-26T15:00:00.000Z")
        self.assertFalse((self.root / "quarantine" / f"{LOST}.json").exists())
        self.assertEqual(verify_archive(self.root)["integrity"], "ok")
        # The audit survives later ingests.
        later = archive_observations(self.root, [], now=self.now + timedelta(hours=2))
        self.assertEqual(len(later["index"]["integrity"]["recoveries"]), 1)

    def test_recover_refuses_a_partial_or_altered_shard_and_changes_nothing(self):
        self.lose_whole_day()
        partial = json.loads((self.saved / "24.json").read_text())
        partial["features"] = partial["features"][:1]
        partial["metadata"]["count"] = 1
        bad = self.saved / "partial.json"
        bad.write_text(history._serialise(partial))
        before = self.index_bytes()
        with self.assertRaisesRegex(ValueError, "sha256"):
            history.recover_day(self.root, LOST, now=self.now, from_shards=[bad])
        self.assertEqual(self.index_bytes(), before)
        self.assertFalse((self.root / day_path(self.day.date())).exists())

    def test_recover_refuses_without_a_recorded_entry_unless_an_earlier_index_is_given(self):
        self.lose_whole_day()
        index = json.loads((self.root / "index.json").read_text())
        index["integrity"]["lost_days"][0]["last_recorded"] = None  # e.g. lost before evidence was kept
        (self.root / "index.json").write_text(history._serialise(index))
        with self.assertRaisesRegex(ValueError, "previously recorded"):
            history.recover_day(self.root, LOST, now=self.now, from_shards=[self.saved / "24.json"])
        earlier = self.base / "earlier-index.json"
        earlier.write_text(json.dumps(self.first_index))
        result = history.recover_day(self.root, LOST, now=self.now, from_shards=[self.saved / "24.json"],
                                     recorded_index=earlier)
        self.assertEqual(rows(result)[LOST]["count"], 2)
        self.assertEqual(result["index"]["integrity"]["recoveries"][0]["verified_against"]["source"], "recorded_index")

    def test_recover_split_day_needs_every_missing_part_and_verifies_survivors(self):
        flashes = [self.flash(self.day + timedelta(hours=h, minutes=m), f"p{h}-{m}", m) for h in (3, 4) for m in range(4)]
        archive_observations(self.root, flashes, now=self.now, scanned_window=self.scan(self.day, self.day + timedelta(days=1)),
                             target_shard_bytes=2000)
        shutil.copy(self.root / part_path(self.day.date(), 4), self.saved / "04.json")
        shutil.copy(self.root / part_path(self.day.date(), 3), self.saved / "03.json")
        (self.root / part_path(self.day.date(), 4)).unlink()
        archive_observations(self.root, [], now=self.now, target_shard_bytes=2000)
        with self.assertRaisesRegex(ValueError, "missing"):
            history.recover_day(self.root, LOST, now=self.now, from_shards=[self.saved / "03.json"],
                                target_shard_bytes=2000)
        result = history.recover_day(self.root, LOST, now=self.now, from_shards=[self.saved / "04.json"],
                                     target_shard_bytes=2000)
        row = rows(result)[LOST]
        self.assertEqual((row["count"], len(row["parts"])), (8, 2))
        self.assertEqual(verify_archive(self.root)["integrity"], "ok")

    def test_recover_refuses_a_day_that_is_not_lost(self):
        archive_observations(self.root, [self.flash(self.day + timedelta(hours=1), "x")], now=self.now)
        with self.assertRaisesRegex(ValueError, "not marked shard_lost"):
            history.recover_day(self.root, LOST, now=self.now, from_shards=[self.root / day_path(self.day.date())])

    def rebuild_record(self, features, start, end, run_utc="2026-10-26T15:00:00.000Z", **over):
        record = {"schema": "uk-lightning-run-record.v1", "outcome": "success", "run_utc": run_utc,
                  "products_examined": 144, "slots_parsed": True, "slots_examined": 144,
                  "scanned_ranges": [{"start_utc": start.isoformat(), "end_utc": end.isoformat()}],
                  "unscanned_ranges": [], "features": features}
        record.update(over)
        path = self.base / "rebuild.json"
        path.write_text(json.dumps(record))
        return path

    def test_rebuild_must_cover_the_recorded_scan_and_match_the_recorded_count(self):
        self.lose_whole_day()
        both = [self.flash(self.day + timedelta(hours=10), "a"), self.flash(self.day + timedelta(hours=11), "b")]
        later = self.now + timedelta(hours=2)
        before = self.index_bytes()
        half = self.rebuild_record(both, self.day, self.day + timedelta(hours=12))
        with self.assertRaisesRegex(ValueError, "does not cover"):
            history.recover_day(self.root, LOST, now=later, rebuild_record=half)
        short = self.rebuild_record(both[:1], self.day, self.day + timedelta(days=1))
        with self.assertRaisesRegex(ValueError, "count"):
            history.recover_day(self.root, LOST, now=later, rebuild_record=short)
        stale = self.rebuild_record(both, self.day, self.day + timedelta(days=1), run_utc="2026-10-26T13:00:00.000Z")
        with self.assertRaisesRegex(ValueError, "independent"):
            history.recover_day(self.root, LOST, now=later, rebuild_record=stale)
        opaque = self.rebuild_record(both, self.day, self.day + timedelta(days=1), slots_parsed=False)
        with self.assertRaisesRegex(ValueError, "slots"):
            history.recover_day(self.root, LOST, now=later, rebuild_record=opaque)
        self.assertEqual(self.index_bytes(), before)
        good = self.rebuild_record(both, self.day, self.day + timedelta(days=1))
        result = history.recover_day(self.root, LOST, now=later, rebuild_record=good)
        self.assertEqual(rows(result)[LOST]["count"], 2)
        audit = result["index"]["integrity"]["recoveries"][0]
        self.assertEqual((audit["method"], audit["rebuild"]["anchored"], audit["byte_identical"]), ("rebuild", True, True))
        self.assertEqual(audit["rebuild"]["uncovered_seconds"], 0)
        self.assertEqual(verify_archive(self.root)["integrity"], "ok")

    def test_rebuild_must_contain_every_quarantined_flash(self):
        self.lose_whole_day()
        archive_observations(self.root, [self.flash(self.day + timedelta(hours=23), "late")], now=self.now)
        both = [self.flash(self.day + timedelta(hours=10), "a"), self.flash(self.day + timedelta(hours=11), "b")]
        record = self.rebuild_record(both, self.day, self.day + timedelta(days=1))
        with self.assertRaisesRegex(ValueError, "quarantined"):
            history.recover_day(self.root, LOST, now=self.now + timedelta(hours=2), rebuild_record=record)

    def test_unanchored_rebuild_needs_an_explicit_flag_and_is_audited_as_such(self):
        self.lose_whole_day()
        index = json.loads((self.root / "index.json").read_text())
        index["integrity"]["lost_days"][0]["last_recorded"] = None
        (self.root / "index.json").write_text(history._serialise(index))
        both = [self.flash(self.day + timedelta(hours=10), "a"), self.flash(self.day + timedelta(hours=11), "b")]
        record = self.rebuild_record(both, self.day, self.day + timedelta(days=1))
        with self.assertRaisesRegex(ValueError, "accept-unanchored"):
            history.recover_day(self.root, LOST, now=self.now + timedelta(hours=2), rebuild_record=record)
        result = history.recover_day(self.root, LOST, now=self.now + timedelta(hours=2), rebuild_record=record,
                                     accept_unanchored=True)
        self.assertIs(result["index"]["integrity"]["recoveries"][0]["rebuild"]["anchored"], False)

    def test_cli_recover(self):
        self.lose_whole_day()
        with self.assertRaises(SystemExit):  # exactly one of --from-shard / --rebuild
            history.main(["recover", "--archive-dir", str(self.root), "--day", LOST])
        bad = self.saved / "empty.json"
        bad.write_text("{}\n")
        with self.assertRaises(ValueError):
            history.main(["recover", "--archive-dir", str(self.root), "--day", LOST, "--from-shard", str(bad),
                          "--now", self.now.isoformat()])
        code = history.main(["recover", "--archive-dir", str(self.root), "--day", LOST,
                             "--from-shard", str(self.saved / "24.json"), "--now", self.now.isoformat()])
        self.assertEqual(code, 0)
        self.assertEqual(verify_archive(self.root)["integrity"], "ok")

    def test_collect_rebuild_day_feeds_recover_rebuild_end_to_end(self):
        """collect.py --rebuild-day writes only a run record for that UTC date (never the feed or
        status); history.py recover --rebuild accepts it only through the same gates."""
        import collect
        self.lose_whole_day()
        both = [self.flash(self.day + timedelta(hours=10), "a"), self.flash(self.day + timedelta(hours=11), "b")]
        names = [("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
                  f"{e:%Y%m%d%H%M%S}_L2PF_OPE_{s:%Y%m%d%H%M%S}_{e:%Y%m%d%H%M%S}_N__O_0001_0000")
                 for s, e in ((self.day + timedelta(minutes=10 * i), self.day + timedelta(minutes=10 * (i + 1)))
                              for i in range(144))]
        calls = []

        def fake_download(start, end):
            calls.append((start, end))
            return both, len(names), names

        feed = self.base / "feed.geojson"
        status = self.base / "status.json"
        record = self.base / "rebuild-record.json"
        run_now = self.now + timedelta(hours=2)
        code = collect.rebuild_day_record(LOST, record, now=run_now, downloader=fake_download)
        self.assertEqual(code, 0)
        self.assertEqual(calls, [(self.day, self.day + timedelta(days=1))])
        self.assertFalse(feed.exists() or status.exists())
        rec = json.loads(record.read_text())
        self.assertEqual((rec["lookback_source"], rec["rebuild_day_utc"], rec["run_utc"]),
                         ("rebuild", LOST, "2026-10-26T16:00:00.000Z"))
        self.assertEqual(len(rec["features"]), 2)
        with self.assertRaises(SystemExit):  # --rebuild-day excludes --hours / --auto-window
            collect.main(["--rebuild-day", LOST, "--hours", "6", "--run-record", str(record)])
        code = history.main(["recover", "--archive-dir", str(self.root), "--day", LOST, "--rebuild",
                             "--rebuild-record", str(record), "--now", run_now.isoformat()])
        self.assertEqual(code, 0)
        index = json.loads((self.root / "index.json").read_text())
        self.assertEqual(rows(index)[LOST]["count"], 2)
        self.assertEqual(index["integrity"]["recoveries"][0]["method"], "rebuild")


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