GLOBALGRID2050 / EXPLORE CODE

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

Test Slot Span and 1 more file

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It makes archive (`make_archive`), sets up (`setUp`) and decodes never drops silently tests (`DecodeNeverDropsSilentlyTests`).

681 lines of Python from lightning, in 2 files. Topic: Automation and CI. Section 1831 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 Slot Edge test · lightning / tests/test_slot_edge.py lines 1–327
  2. Test Slot Span test · lightning / tests/test_slot_span.py lines 1–354

Test Slot Edge

A test in the tests folder of Lightning that checks Backfill Parallel and Collect, using SHA-256. It makes archive (`make_archive`), rebuilds outside day tests (`RebuildOutsideDayTests`) and sets up (`setUp`).

testlightning / tests/test_slot_edge.py · lines 1–327 of 327 · Entry point · pattern product_name (shared by 2 files)

What it does
It tests its inputs. Defines 44 functions or classes, including product_name, iso, EdgeEumetsat, __init__, slots. Uses libraries json, sys, tempfile, unittest, datetime. Side effects: reads or writes files.
Inputs & outputs
In: JSON file index.json; JSON file rb.json; JSON file status.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
Slot-edge flashes: attribution to the product's nominal slot, outside-day drops, and a finalize that never loses a whole run to one refused date.
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), History (import), Test Unreadable Product (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
product_name, iso, EdgeEumetsat, incident_flashes, make_archive, rows, SlotAttributionTests, RebuildOutsideDayTests, BackfillEdgeTests, FinalizeContinuesTests
Defines here
product_name, iso, EdgeEumetsat, __init__, slots, products, __call__, incident_flashes, make_archive, rows, SlotAttributionTests, test_flash_slot_is_its_products_nominal_slot, test_flashes_prove_their_products_slot_not_the_slot_of_their_timestamp, test_edge_tolerance_is_the_documented_sixty_seconds, RebuildOutsideDayTests, setUp, tearDown, test_rebuild_drops_previous_day_flashes_and_counts_them_outside_day, BackfillEdgeTests, setUp, tearDown, rebuild, write, backfill, test_incident_edge_flash_before_its_products_nominal_start_is_accepted, test_previous_day_flash_inside_a_record_is_dropped_and_counted_not_refused, test_next_day_flash_inside_a_record_is_dropped_and_counted, test_flash_two_minutes_outside_its_product_but_in_examined_time_is_accepted, test_flash_of_a_product_that_was_not_examined_is_refused, test_flash_without_a_product_slot_still_needs_an_examined_span
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_slot_edge.py:1-327 · blob a73930a0872192107cc48664abd07bf134d1fd9e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Slot-edge flashes: attribution to the product's nominal slot, outside-day drops,
and a finalize that never loses a whole run to one refused date.

Incident (parallel backfill run 40608108170): the rebuild of 2026-08-28 held
flash ``..._OPE_20260828000049_20260828001009_...:203``, timed just before its
product's nominal sensing start 00:00:49. The examined spans had a 40 s hole
(the previous product ends 00:00:09), so ``history.backfill_day`` refused the
date ("lies outside the examined slots") and finalize stopped, leaving six
other verified records un-ingested. Real LFL flashes sit up to about 0.4 s
before their product's nominal start (observed: 0.361 s); the genuineness
tolerance is +-60 s. (The real 2026-08-28 flash turned out to lie more than 60 s
outside its product's name span; see tests/test_slot_span.py.)

Synthetic features exist ONLY inside temporary directories (fake products,
fake decoder); nothing synthetic is ever published.
"""
import json
import sys
import tempfile
import unittest
from datetime import date, datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import backfill_parallel as bp
import collect
import history
from collect import build_feature
from test_unreadable_product import FakeProduct, fake_body, good_zip

NOW = datetime(2026, 10, 27, 6, 0, tzinfo=timezone.utc)
TARGET = "2026-10-20"
DAY0 = datetime(2026, 10, 20, tzinfo=timezone.utc)
EDGE = timedelta(seconds=0.361)  # observed: a flash 0.361 s before its product's nominal start


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


def iso(moment: datetime) -> str:
    return collect.iso_utc(moment)


class EdgeEumetsat:
    """A day laid out like the incident, through the REAL download/decode path.

    P0 = previous-day product 23:50:09-00:00:09, P1 = 00:00:49-00:10:09 (the
    incident's first product), then 10-minute products from 00:10:09 on. The
    examined spans therefore have a 40 s hole 00:00:09-00:00:49.
    ``flashes`` maps a product start to [(lon, lat, time)].
    """

    def __init__(self, day: datetime, flashes: dict, skip=()):
        self.day, self.flashes, self.skip = day, flashes, set(skip)

    def slots(self):
        p0 = self.day - timedelta(seconds=591)                     # 23:50:09 of the previous day
        yield p0, self.day + timedelta(seconds=9)                  # -> 00:00:09
        yield self.day + timedelta(seconds=49), self.day + timedelta(minutes=10, seconds=9)
        cursor = self.day + timedelta(minutes=10, seconds=9)
        while cursor < self.day + timedelta(days=1):
            yield cursor, cursor + timedelta(minutes=10)
            cursor += timedelta(minutes=10)

    def products(self):
        for start, end in self.slots():
            if start in self.skip:
                continue
            name = product_name(start, end)
            rows = [(lon, lat, iso(t)) for lon, lat, t in self.flashes.get(start, [])]
            yield FakeProduct(name, good_zip(name, rows))

    def __call__(self, start, end):
        return collect.download_products(self.products(), start, end, body_decoder=fake_body)


def incident_flashes(day: datetime) -> dict:
    p0 = day - timedelta(seconds=591)
    p1 = day + timedelta(seconds=49)
    p5 = day + timedelta(hours=5, seconds=9)
    return {
        p0: [(-2.0, 52.0, day - timedelta(seconds=30)),     # previous UTC day: outside_day
             (-2.1, 52.1, day + timedelta(seconds=5))],     # in the day, attributed to P0
        p1: [(-2.2, 52.2, p1 - EDGE),                       # the incident: 0.361 s before P1
             (-2.3, 52.3, p1 + timedelta(minutes=4))],
        p5: [(-2.4, 52.4, p5 + timedelta(minutes=3))],
    }


def make_archive(root: Path) -> None:
    hourly = datetime(2026, 10, 26, tzinfo=timezone.utc)
    history.archive_observations(
        root, [build_feature(-2.12, 51.11, hourly + timedelta(hours=3), "TEST-hourly", 0)],
        now=NOW - timedelta(hours=1),
        scanned_windows=[history.successful_scan((hourly + timedelta(hours=1)).isoformat(),
                                                 (hourly + timedelta(hours=7)).isoformat(), 36)],
        lookback_hours=6.0)


def rows(root: Path) -> dict:
    return {r["date"]: r for r in json.loads((root / "index.json").read_text())["days"]}


class SlotAttributionTests(unittest.TestCase):
    def test_flash_slot_is_its_products_nominal_slot(self):
        start = datetime(2026, 10, 23, 19, 50, 9, tzinfo=timezone.utc)
        feature = build_feature(-2.0, 52.0, start - EDGE, product_name(start, start + timedelta(minutes=10)), 322)
        self.assertEqual(collect.flash_slot(feature), (start, start + timedelta(minutes=10)))
        self.assertIsNone(collect.flash_slot(build_feature(-2.0, 52.0, start, "TEST-x", 0)))

    def test_flashes_prove_their_products_slot_not_the_slot_of_their_timestamp(self):
        start = datetime(2026, 10, 23, 19, 50, 9, tzinfo=timezone.utc)
        name = product_name(start, start + timedelta(minutes=10))
        edge = build_feature(-2.0, 52.0, start - EDGE, name, 322)          # 19:50:08.639
        inner = build_feature(-2.0, 52.0, start + timedelta(minutes=5), name, 1)
        self.assertEqual(history.slots_proved_by_flashes([edge, inner]), 600)

    def test_edge_tolerance_is_the_documented_sixty_seconds(self):
        self.assertEqual(collect.SLOT_EDGE_TOLERANCE_SECONDS, 60)


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

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

    def test_rebuild_drops_previous_day_flashes_and_counts_them_outside_day(self):
        collect.rebuild_day_record(TARGET, self.record, now=NOW, downloader=EdgeEumetsat(DAY0, incident_flashes(DAY0)))
        record = json.loads(self.record.read_text())
        times = sorted(f["properties"]["time_utc"] for f in record["features"])
        self.assertEqual(record["outside_day"], 1)
        self.assertTrue(all(t.startswith(TARGET) for t in times), times)
        self.assertEqual(len(times), 4)
        self.assertIn("2026-10-20T00:00:48.639Z", times)


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

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

    def rebuild(self, flashes=None, skip=()):
        fake = EdgeEumetsat(DAY0, incident_flashes(DAY0) if flashes is None else flashes, skip=skip)
        collect.rebuild_day_record(TARGET, self.record, now=NOW, downloader=fake)
        return json.loads(self.record.read_text())

    def write(self, record):
        self.record.write_text(json.dumps(record))

    def backfill(self):
        return history.backfill_day(self.root, TARGET, now=NOW, rebuild_record=self.record)

    def test_incident_edge_flash_before_its_products_nominal_start_is_accepted(self):
        self.rebuild()
        result = self.backfill()
        row = rows(self.root)[TARGET]
        self.assertEqual(row["count"], 4)
        self.assertEqual(row["coverage"], "partial")       # the 40 s hole stays unknown
        self.assertEqual(row["scanned_seconds"], 86400 - 40)
        self.assertEqual(result["outside_day"], 1)
        self.assertEqual(history.verify_archive(self.root)["integrity"], "ok")

    def test_previous_day_flash_inside_a_record_is_dropped_and_counted_not_refused(self):
        record = self.rebuild()
        p0 = DAY0 - timedelta(seconds=591)
        name = product_name(p0, DAY0 + timedelta(seconds=9))
        record["features"].append(build_feature(-2.5, 52.5, DAY0 - timedelta(seconds=0.2), name, 77))
        self.write(record)
        result = self.backfill()
        self.assertEqual(rows(self.root)[TARGET]["count"], 4)
        self.assertEqual(result["outside_day"], 2)          # 1 dropped by collect + 1 in the record
        self.assertEqual(result["outside_day_in_record"], 1)

    def test_next_day_flash_inside_a_record_is_dropped_and_counted(self):
        record = self.rebuild()
        last = DAY0 + timedelta(hours=23, minutes=50, seconds=9)
        name = product_name(last, last + timedelta(minutes=10))
        record["features"].append(build_feature(-2.5, 52.5, DAY0 + timedelta(days=1, seconds=3), name, 5))
        self.write(record)
        result = self.backfill()
        self.assertEqual(rows(self.root)[TARGET]["count"], 4)
        self.assertEqual(result["outside_day_in_record"], 1)

    def test_flash_two_minutes_outside_its_product_but_in_examined_time_is_accepted(self):
        # Contract since claude/fix-slot-span-attribution: a product's name span does
        # not bound its flashes' times (2026-04-12 / 2026-08-28 refusals); the flash's
        # OWN time is checked against the examined spans (see tests/test_slot_span.py).
        record = self.rebuild()
        p5 = DAY0 + timedelta(hours=5, seconds=9)
        name = product_name(p5, p5 + timedelta(minutes=10))
        # inside the examined spans (the 04:50:09 product), 120 s before its own product
        record["features"].append(build_feature(-2.5, 52.5, p5 - timedelta(seconds=120), name, 9))
        self.write(record)
        result = self.backfill()
        self.assertEqual(rows(self.root)[TARGET]["count"], 5)
        self.assertEqual(result["unexamined_time_flashes"], 0)

    def test_flash_of_a_product_that_was_not_examined_is_refused(self):
        p5 = DAY0 + timedelta(hours=5, seconds=9)
        record = self.rebuild(skip={p5})
        name = product_name(p5, p5 + timedelta(minutes=10))
        record["features"].append(build_feature(-2.5, 52.5, p5 + timedelta(minutes=2), name, 9))
        self.write(record)
        with self.assertRaisesRegex(ValueError, "lies outside the examined slots"):
            self.backfill()

    def test_flash_without_a_product_slot_still_needs_an_examined_span(self):
        record = self.rebuild()
        record["features"].append(build_feature(-2.5, 52.5, DAY0 + timedelta(seconds=20), "TEST-noslot", 0))
        self.write(record)                                  # 00:00:20 lies in the 40 s hole
        with self.assertRaisesRegex(ValueError, "lies outside the examined slots"):
            self.backfill()


class FinalizeContinuesTests(unittest.TestCase):
    """One refused date is skipped (left unknown, reason recorded); the others are ingested."""

    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        base = Path(self.temp.name)
        self.root, self.records, self.status = base / "history", base / "records", base / "status.json"
        make_archive(self.root)
        self.status.write_text(json.dumps({"schema": "uk-lightning-status.v1", "health": "ok", "freshness": "ok"}))
        self.plan = ["2026-10-22", "2026-10-21", "2026-10-20", "2026-10-19"]

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

    def collector(self):
        def run(day, record, log, timeout=None):
            start = datetime.combine(date.fromisoformat(day), datetime.min.time(), tzinfo=timezone.utc)
            collect.rebuild_day_record(day, record, now=NOW, downloader=EdgeEumetsat(start, incident_flashes(start)))
        return run

    def shards(self, n=2):
        for m in bp.split_shards(self.plan, n):
            bp.run_shard(m["shard"], m["dates"].split(), self.records, budget_minutes=290, collector=self.collector())

    def tamper(self, day, mutate, resign=True):
        record = self.records / f"rb-{day}.json"
        data = json.loads(record.read_text())
        mutate(data)
        record.write_text(json.dumps(data))
        if resign:  # the shard summary agrees: the record reaches history.backfill_day's own gates
            for summary_path in self.records.glob("shard-*.json"):
                summary = json.loads(summary_path.read_text())
                for item in summary["collected"]:
                    if item["date"] == day:
                        item["sha256"] = bp.sha256_file(record)
                summary_path.write_text(json.dumps(summary))

    def finalize(self, n=2):
        return bp.finalize(plan_dates=self.plan, shards=n, records_dir=self.records, archive_dir=self.root,
                           status_path=self.status, now=NOW)

    def test_incident_records_with_edge_flashes_are_all_ingested(self):
        self.shards()
        result = self.finalize()
        self.assertEqual(result["stopped"], "completed")
        self.assertEqual(result["filled"], self.plan)
        status = json.loads(self.status.read_text())["backfill"]
        self.assertEqual(status["refused_days"], {})
        self.assertEqual(status["outside_day_by_day"], {d: 1 for d in self.plan})

    def test_one_inconsistent_date_is_skipped_and_the_rest_are_ingested(self):
        self.shards()

        def bad(data):  # a flash of a product the search never examined: an inconsistent record
            p = datetime.combine(date(2026, 10, 21), datetime.min.time(), tzinfo=timezone.utc) + timedelta(hours=5, minutes=3)
            data["features"].append(build_feature(-2.5, 52.5, p + timedelta(seconds=30),
                                                  product_name(p, p + timedelta(minutes=10)), 9))
        self.tamper("2026-10-21", bad)
        result = self.finalize()
        self.assertEqual(result["stopped"], "archive_refused")
        self.assertEqual(result["filled"], ["2026-10-22", "2026-10-20", "2026-10-19"])
        self.assertIn("2026-10-21", result["refused"])
        r = rows(self.root)
        self.assertEqual((r["2026-10-21"]["coverage"], r["2026-10-21"]["count"]), ("none", None))
        for d in ("2026-10-22", "2026-10-20", "2026-10-19"):
            self.assertEqual(r[d]["count"], 4, d)
        status = json.loads(self.status.read_text())["backfill"]
        self.assertEqual(status["remaining_unknown_days"], ["2026-10-21"])
        self.assertIn("lies outside the examined slots", status["refused_days"]["2026-10-21"])
        self.assertIn("2026-10-21", status["error"])
        self.assertEqual(history.verify_archive(self.root)["integrity"], "ok")

    def test_a_record_changed_in_transit_is_skipped_and_later_dates_still_ingested(self):
        self.shards()
        self.tamper("2026-10-22", lambda data: data.update(features=[]), resign=False)
        result = self.finalize()
        self.assertEqual(result["stopped"], "archive_refused")
        self.assertEqual(result["filled"], ["2026-10-21", "2026-10-20", "2026-10-19"])
        self.assertIn("sha256", json.loads(self.status.read_text())["backfill"]["refused_days"]["2026-10-22"])
        self.assertIsNone(rows(self.root)["2026-10-22"]["count"])

    def test_an_unexpected_ingest_error_is_contained_to_its_date(self):
        self.shards()
        real = history.backfill_day

        def flaky(archive_dir, day, **kw):
            if day == "2026-10-20":
                raise OSError("disk hiccup")
            return real(archive_dir, day, **kw)
        bp.history.backfill_day = flaky
        try:
            result = self.finalize()
        finally:
            bp.history.backfill_day = real
        self.assertEqual(result["filled"], ["2026-10-22", "2026-10-21", "2026-10-19"])
        self.assertIn("OSError", result["refused"]["2026-10-20"])
        self.assertIsNone(rows(self.root)["2026-10-20"]["count"])


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

Test Slot Span

A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It makes archive (`make_archive`), sets up (`setUp`) and decodes never drops silently tests (`DecodeNeverDropsSilentlyTests`).

testlightning / tests/test_slot_span.py · lines 1–354 of 354 · Entry point · pattern FinalizeTests (shared by 2 files)

What it does
It tests its inputs. Defines 35 functions or classes, including lfl_name, april_layout, august_layout, LayoutEumetsat, __init__. Uses libraries json, sys, tempfile, unittest, datetime. Side effects: reads or writes files.
Inputs & outputs
In: JSON file index.json; JSON file rb.json; JSON file status.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
Flashes timed outside their product's NAME span: the and refusals.
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), History (import), Test Unreadable Product (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
lfl_name, april_layout, august_layout, LayoutEumetsat, indexed_body, make_archive, rows, Harness, April12Tests, August28Tests, DecodeNeverDropsSilentlyTests, FinalizeTests
Defines here
lfl_name, april_layout, august_layout, LayoutEumetsat, __init__, name, products, __call__, indexed_body, make_archive, rows, Harness, setUp, tearDown, rebuild, backfill, ids, April12Tests, test_incident_flash_in_its_cycle_before_the_late_start_is_kept_and_its_slot_stays_unknown, test_incident_flash_after_the_span_inside_the_next_product_is_accepted_and_counted_once, test_incident_flash_after_the_span_listed_only_by_its_own_product_is_accepted, August28Tests, test_previous_date_flash_of_the_product_is_dropped_and_counted_never_refused, test_previous_date_flash_left_in_the_record_is_dropped_and_counted, test_incident_flash_after_the_span_in_the_next_examined_product_is_accepted, test_incident_flash_in_a_slot_whose_product_was_not_examined_keeps_that_slot_unknown, test_flash_of_an_unexamined_product_is_still_refused, DecodeNeverDropsSilentlyTests, test_download_keeps_flashes_far_outside_the_products_span_for_callers_to_count, test_second_body_file_gets_distinct_ids
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_slot_span.py:1-354 · blob b0e52f8d6796f93ba34a245ee08ba62ecb406dde · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Flashes timed outside their product's NAME span: the 2026-04-12 and 2026-08-28 refusals.

Parallel backfill runs 40620556193 (on c17b65d, PR #12) and 40657338115 refused
two whole UTC dates with "flash ... lies outside the examined slots (its
product's nominal slot +- 60 s)":

* 2026-04-12, ``..._OPE_20260412001255_20260412002005_N__O_0002_0000:2326``.
  Repeat cycle 0002 is 00:10-00:20, but the product's name span starts late,
  at 00:12:55, and ends 00:20:05, across the next slot edge.
* 2026-08-28, ``..._OPE_20260828000049_20260828001009_N__O_0001_0000:203``.
  A flash of the PREVIOUS date (27 Aug 23:5x) cannot be the cause: it is dropped
  as ``outside_day`` before the gate. Every 28 Aug moment before 00:00:49 is
  within 60 s of the product's start, so the flash lay after 00:11:09.

Root cause: the gate (PR #12) took a product's "nominal slot" from the sensing
start/end in its NAME and required every flash to lie within +-60 s of it. That
span does not bound the flashes the product holds. Both products lie at the start
of the day, where cycles start late. Their flashes lay more than 60 s outside the
span, so whole dates were refused although every flash came from an examined
product. collect.py also decoded only the product's span +- 60 s (or the query
window), which would drop such flashes silently in other paths.

The fix checks a flash's OWN time:
- it decides the UTC date;
- it is consistent if it lies within 60 s of its product's span OR inside ANY
  examined span;
- otherwise the flash (of an examined product) is kept and counted, and its
  slot stays unsearched (the date is partial there, never zero, never refused).

A flash of an unexamined product is still refused. The same flash listed by two
products is archived once.

The exact flash times are not recoverable here: run logs and artifacts are
behind GitHub storage this sandbox cannot reach, and the EUMETSAT credentials
exist only as workflow secrets. The fixtures therefore cover every place such a
flash can lie, through the REAL collect download/decode path (fake products,
fake BODY decoder) and the real backfill gate and finalize. Synthetic features
exist ONLY inside temporary directories.
"""
import json
import sys
import tempfile
import unittest
from datetime import date, datetime, timedelta, timezone
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import backfill_parallel as bp
import collect
import history
from collect import build_feature
from test_unreadable_product import FakeProduct, fake_body, good_zip, make_zip

NOW = datetime(2026, 10, 28, 9, 0, tzinfo=timezone.utc)
APR12 = datetime(2026, 4, 12, tzinfo=timezone.utc)
AUG28 = datetime(2026, 8, 28, tzinfo=timezone.utc)
S = timedelta(seconds=1)
M = timedelta(minutes=1)


def lfl_name(start: datetime, end: datetime, created: datetime | None = None, cycle: int = 1) -> str:
    created = created or end + 15 * M
    return ("W_XX-EUMETSAT-Darmstadt,IMG+SAT,MTI1+LI-2-LFL--FD--x-x--ARC-x_C_EUMT_"
            f"{created:%Y%m%d%H%M%S}_L2PF_OPE_{start:%Y%m%d%H%M%S}_{end:%Y%m%d%H%M%S}_N__O_{cycle:04d}_0000")


def april_layout(day: datetime) -> list[tuple[datetime, datetime, int]]:
    """2026-04-12 as the error shows it. Cycle 0001 runs 00:00:09-00:10:09. Cycle 0002 is
    the incident product, 00:12:55-00:20:05, so 00:10:09-00:12:55 is a hole. Then
    regular products follow from 00:20:09 (a 4 s hole). The previous date's last
    product ends 00:00:09."""
    out = [(day - 591 * S, day + 9 * S, 144), (day + 9 * S, day + 10 * M + 9 * S, 1),
           (day + 12 * M + 55 * S, day + 20 * M + 5 * S, 2)]
    cursor, cycle = day + 20 * M + 9 * S, 3
    while cursor < day + timedelta(days=1):
        out.append((cursor, cursor + 10 * M, cycle))
        cursor, cycle = cursor + 10 * M, cycle + 1
    return out


def august_layout(day: datetime) -> list[tuple[datetime, datetime, int]]:
    """2026-08-28: the previous date's last product ends 00:00:09. Cycle 0001 is the
    incident product, 00:00:49-00:10:09 (a 40 s hole before it), then regular
    10-minute products follow."""
    out = [(day - 591 * S, day + 9 * S, 144), (day + 49 * S, day + 10 * M + 9 * S, 1)]
    cursor, cycle = day + 10 * M + 9 * S, 2
    while cursor < day + timedelta(days=1):
        out.append((cursor, cursor + 10 * M, cycle))
        cursor, cycle = cursor + 10 * M, cycle + 1
    return out


APRIL_INCIDENT = lfl_name(APR12 + 12 * M + 55 * S, APR12 + 20 * M + 5 * S,
                          created=datetime(2026, 4, 12, 0, 29, 15, tzinfo=timezone.utc), cycle=2)
AUGUST_INCIDENT = lfl_name(AUG28 + 49 * S, AUG28 + 10 * M + 9 * S,
                           created=datetime(2026, 8, 28, 0, 15, 13, tzinfo=timezone.utc), cycle=1)


class LayoutEumetsat:
    """Fake whole-day search over a product layout, through the REAL download/decode path.

    ``flashes`` maps a product start to [(index, lon, lat, time)]. The index is the
    flash's position in its BODY, so the incident ids (``:2326``, ``:203``) are
    reproduced. ``skip`` leaves products out of the search (e.g. not yet published).
    """

    def __init__(self, layout, flashes: dict, skip=()):
        self.layout, self.flashes, self.skip = layout, flashes, set(skip)

    def name(self, start):
        if start == APR12 + 12 * M + 55 * S:
            return APRIL_INCIDENT
        if start == AUG28 + 49 * S:
            return AUGUST_INCIDENT
        end, cycle = next((e, c) for s, e, c in self.layout if s == start)
        return lfl_name(start, end, cycle=cycle)

    def products(self):
        for start, _, _ in self.layout:
            if start in self.skip:
                continue
            body = {str(index): [lon, lat, collect.iso_utc(moment)]
                    for index, lon, lat, moment in self.flashes.get(start, [])}
            name = self.name(start)
            yield FakeProduct(name, make_zip({f"{name}/{name}_BODY_0001.nc": json.dumps(body).encode()}))

    def __call__(self, start, end):
        return collect.download_products(self.products(), start, end, body_decoder=indexed_body)


def indexed_body(content: bytes, product_name: str, start: datetime, end: datetime):
    """Stand-in for decode_body: a JSON {BODY index: [lon, lat, time]}, filtered like decode_body."""
    out = []
    for index, (lon, lat, t) in sorted(json.loads(content).items(), key=lambda kv: int(kv[0])):
        moment = collect.parse_utc(t)
        if start <= moment < end:
            feature = build_feature(lon, lat, moment, product_name, int(index))
            if feature:
                out.append(feature)
    return out


def make_archive(root: Path) -> None:
    hourly = datetime(2026, 10, 27, tzinfo=timezone.utc)
    history.archive_observations(
        root, [build_feature(-2.12, 51.11, hourly + timedelta(hours=3), "TEST-hourly", 0)],
        now=NOW - timedelta(hours=1),
        scanned_windows=[history.successful_scan((hourly + timedelta(hours=1)).isoformat(),
                                                 (hourly + timedelta(hours=7)).isoformat(), 36)],
        lookback_hours=6.0)


def rows(root: Path) -> dict:
    return {r["date"]: r for r in json.loads((root / "index.json").read_text())["days"]}


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

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

    def rebuild(self, day: datetime, fake) -> dict:
        collect.rebuild_day_record(day.date().isoformat(), self.record, now=NOW, downloader=fake)
        return json.loads(self.record.read_text())

    def backfill(self, day: datetime) -> dict:
        return history.backfill_day(self.root, day.date().isoformat(), now=NOW, rebuild_record=self.record)

    def ids(self, day: datetime) -> list[str]:
        key = day.date().isoformat()
        return [f["id"] for f in history._read_features(self.root / rows(self.root)[key]["path"], key)]


class April12Tests(Harness):
    """``..._O_0002_..._OPE_20260412001255_20260412002005_...:2326``."""

    P2 = APR12 + 12 * M + 55 * S

    def test_incident_flash_in_its_cycle_before_the_late_start_is_kept_and_its_slot_stays_unknown(self):
        # 00:10:40 lies in repeat cycle 0002 (00:10-00:20) but 135 s before the name's start,
        # inside the 00:10:09-00:12:55 hole that no product covers.
        flash = APR12 + 10 * M + 40 * S
        fake = LayoutEumetsat(april_layout(APR12), {self.P2: [(2326, -2.0, 52.0, flash), (5, -2.1, 52.1, self.P2 + M)]})
        record = self.rebuild(APR12, fake)
        incident = next(f for f in record["features"] if f["id"] == f"{APRIL_INCIDENT}:2326")
        examined = {collect.parse_utc(s) for s in record["slots_examined_utc"]}
        spans = [(collect.parse_utc(w["start_utc"]), collect.parse_utc(w["end_utc"])) for w in record["scanned_ranges"]]
        # The pre-fix gate (product name span +- 60 s) is exactly what refused the date.
        self.assertEqual(collect.classify_flash(incident, examined, spans), collect.FLASH_IN_UNEXAMINED_TIME)

        result = self.backfill(APR12)
        row = rows(self.root)["2026-04-12"]
        self.assertEqual(row["count"], 2)                         # kept: never silently dropped
        self.assertEqual(row["coverage"], "partial")              # never zero, never full
        self.assertEqual(row["scanned_seconds"], 86400 - 166 - 4)  # the 00:10:09-00:12:55 and 00:20:05-00:20:09 holes
        self.assertEqual(result["unexamined_time_flashes"], 1)
        self.assertEqual(result["unexamined_time_slots_utc"], ["2026-04-12T00:10:09.000Z"])
        self.assertIn(f"{APRIL_INCIDENT}:2326", self.ids(APR12))
        self.assertEqual(history.verify_archive(self.root)["integrity"], "ok")

    def test_incident_flash_after_the_span_inside_the_next_product_is_accepted_and_counted_once(self):
        # 00:21:30 lies 85 s after the name's end, inside the 00:20:09 product, which lists the same flash too.
        flash = APR12 + 21 * M + 30 * S
        nxt = APR12 + 20 * M + 9 * S
        fake = LayoutEumetsat(april_layout(APR12), {self.P2: [(2326, -2.0, 52.0, flash)],
                                                    nxt: [(40, -2.0, 52.0, flash), (41, -2.3, 52.3, nxt + 5 * M)]})
        self.rebuild(APR12, fake)
        result = self.backfill(APR12)
        row = rows(self.root)["2026-04-12"]
        self.assertEqual(row["count"], 2)                         # the one flash once, plus the other flash
        self.assertEqual(result["cross_product_duplicates"], 1)
        self.assertEqual(result["unexamined_time_flashes"], 0)
        ids = self.ids(APR12)
        self.assertIn(lfl_name(nxt, nxt + 10 * M, cycle=3) + ":40", ids)  # the copy inside its own product's span
        self.assertNotIn(f"{APRIL_INCIDENT}:2326", ids)

    def test_incident_flash_after_the_span_listed_only_by_its_own_product_is_accepted(self):
        flash = APR12 + 21 * M + 30 * S
        fake = LayoutEumetsat(april_layout(APR12), {self.P2: [(2326, -2.0, 52.0, flash)]})
        self.rebuild(APR12, fake)
        result = self.backfill(APR12)
        self.assertEqual(rows(self.root)["2026-04-12"]["count"], 1)
        self.assertEqual((result["unexamined_time_flashes"], result["cross_product_duplicates"]), (0, 0))


class August28Tests(Harness):
    """``..._O_0001_..._OPE_20260828000049_20260828001009_...:203``."""

    P1 = AUG28 + 49 * S

    def test_previous_date_flash_of_the_product_is_dropped_and_counted_never_refused(self):
        # 27 Aug 23:58:30: belongs to 27 Aug, so it can never refuse 28 Aug.
        fake = LayoutEumetsat(august_layout(AUG28), {self.P1: [(203, -2.0, 52.0, AUG28 - 90 * S),
                                                               (204, -2.1, 52.1, self.P1 + M)]})
        record = self.rebuild(AUG28, fake)
        self.assertEqual(record["outside_day"], 1)                # decoded, then dropped and counted
        result = self.backfill(AUG28)
        self.assertEqual(rows(self.root)["2026-08-28"]["count"], 1)
        self.assertEqual(result["outside_day"], 1)

    def test_previous_date_flash_left_in_the_record_is_dropped_and_counted(self):
        record = self.rebuild(AUG28, LayoutEumetsat(august_layout(AUG28), {self.P1: [(204, -2.1, 52.1, self.P1 + M)]}))
        record["features"].append(build_feature(-2.0, 52.0, AUG28 - 90 * S, AUGUST_INCIDENT, 203))
        self.record.write_text(json.dumps(record))
        result = self.backfill(AUG28)
        self.assertEqual(result["outside_day_in_record"], 1)
        self.assertEqual(rows(self.root)["2026-08-28"]["count"], 1)

    def test_incident_flash_after_the_span_in_the_next_examined_product_is_accepted(self):
        # 00:11:30: 81 s after the name's end 00:10:09 (the only 28 Aug times the old gate refused).
        flash = AUG28 + 11 * M + 30 * S
        fake = LayoutEumetsat(august_layout(AUG28), {self.P1: [(203, -2.0, 52.0, flash)]})
        record = self.rebuild(AUG28, fake)
        examined = {collect.parse_utc(s) for s in record["slots_examined_utc"]}
        spans = [(collect.parse_utc(w["start_utc"]), collect.parse_utc(w["end_utc"])) for w in record["scanned_ranges"]]
        feature = next(f for f in record["features"] if f["id"].endswith(":203"))
        self.assertEqual(collect.classify_flash(feature, examined, spans), collect.FLASH_IN_EXAMINED_SPAN)
        result = self.backfill(AUG28)
        row = rows(self.root)["2026-08-28"]
        self.assertEqual((row["count"], row["coverage"], row["scanned_seconds"]), (1, "partial", 86400 - 40))
        self.assertEqual(result["unexamined_time_flashes"], 0)

    def test_incident_flash_in_a_slot_whose_product_was_not_examined_keeps_that_slot_unknown(self):
        flash = AUG28 + 11 * M + 30 * S
        nxt = AUG28 + 10 * M + 9 * S
        fake = LayoutEumetsat(august_layout(AUG28), {self.P1: [(203, -2.0, 52.0, flash)]}, skip={nxt})
        self.rebuild(AUG28, fake)
        result = self.backfill(AUG28)
        row = rows(self.root)["2026-08-28"]
        self.assertEqual(row["count"], 1)
        self.assertEqual(row["scanned_seconds"], 86400 - 40 - 600)   # the hole and the missing slot stay unknown
        self.assertEqual(result["unexamined_time_slots_utc"], ["2026-08-28T00:10:09.000Z"])

    def test_flash_of_an_unexamined_product_is_still_refused(self):
        nxt = AUG28 + 10 * M + 9 * S
        record = self.rebuild(AUG28, LayoutEumetsat(august_layout(AUG28), {self.P1: [(1, -2.0, 52.0, self.P1 + M)]},
                                                    skip={nxt}))
        record["features"].append(build_feature(-2.5, 52.5, nxt + M, lfl_name(nxt, nxt + 10 * M, cycle=2), 7))
        self.record.write_text(json.dumps(record))
        before = (self.root / "index.json").read_bytes()
        with self.assertRaisesRegex(ValueError, "lies outside the examined slots"):
            self.backfill(AUG28)
        self.assertEqual((self.root / "index.json").read_bytes(), before)


class DecodeNeverDropsSilentlyTests(unittest.TestCase):
    def test_download_keeps_flashes_far_outside_the_products_span_for_callers_to_count(self):
        start = APR12 + 12 * M + 55 * S
        name = lfl_name(start, start + 7 * M + 10 * S, cycle=2)
        rows_ = [[-2.0, 52.0, collect.iso_utc(APR12 + 10 * M + 40 * S)], [-2.0, 52.0, collect.iso_utc(APR12 + 2 * M)]]
        window = (APR12 + 12 * M, APR12 + 30 * M)
        features, count, names, unparsed, _ = collect.download_products(
            [FakeProduct(name, good_zip(name, rows_))], *window, body_decoder=fake_body)
        self.assertEqual(len(features), 2)                  # before: the 00:02:00 flash was dropped uncounted
        inside, outside = collect.split_by_window(features, *window)
        self.assertEqual((len(inside), outside), (0, 2))

    def test_second_body_file_gets_distinct_ids(self):
        name = lfl_name(APR12 + 9 * S, APR12 + 10 * M + 9 * S)
        one = json.dumps([[-2.0, 52.0, collect.iso_utc(APR12 + M)]]).encode()
        two = json.dumps([[-2.1, 52.1, collect.iso_utc(APR12 + 2 * M)]]).encode()
        blob = make_zip({f"{name}/{name}_BODY_0001.nc": one, f"{name}/{name}_BODY_0002.nc": two})
        features = collect.decode_product(blob, name, *collect.DECODE_ALL_TIMES, body_decoder=fake_body)
        self.assertEqual([f["id"] for f in features], [f"{name}:0", f"{name}:b1.0"])
        self.assertEqual({collect.flash_slot(f) for f in features}, {(APR12 + 9 * S, APR12 + 10 * M + 9 * S)})


class FinalizeTests(unittest.TestCase):
    """Both incident dates are ingested by finalize; the run is not refused."""

    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        base = Path(self.temp.name)
        self.root, self.records, self.status = base / "history", base / "records", base / "status.json"
        make_archive(self.root)
        self.status.write_text(json.dumps({"schema": "uk-lightning-status.v1", "health": "ok", "freshness": "ok"}))
        self.plan = ["2026-08-28", "2026-04-12"]

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

    def collector(self, day, record, log, timeout=None):
        if day == "2026-04-12":
            fake = LayoutEumetsat(april_layout(APR12), {APR12 + 12 * M + 55 * S: [(2326, -2.0, 52.0, APR12 + 10 * M + 40 * S)]})
        else:
            fake = LayoutEumetsat(august_layout(AUG28), {AUG28 + 49 * S: [(203, -2.0, 52.0, AUG28 + 11 * M + 30 * S)]})
        collect.rebuild_day_record(day, record, now=NOW, downloader=fake)

    def test_both_incident_dates_are_filled(self):
        for m in bp.split_shards(self.plan, 2):
            bp.run_shard(m["shard"], m["dates"].split(), self.records, budget_minutes=290, collector=self.collector)
        result = bp.finalize(plan_dates=self.plan, shards=2, records_dir=self.records, archive_dir=self.root,
                             status_path=self.status, now=NOW)
        self.assertEqual(result["stopped"], "completed")
        self.assertEqual(result["filled"], self.plan)
        self.assertEqual(result["refused"], {})
        status = json.loads(self.status.read_text())["backfill"]
        self.assertEqual(status["unexamined_time_flashes_by_day"],
                         {"2026-04-12": {"flashes": 1, "slots_utc": ["2026-04-12T00:10:09.000Z"]}})
        r = rows(self.root)
        self.assertEqual((r["2026-04-12"]["count"], r["2026-04-12"]["coverage"]), (1, "partial"))
        self.assertEqual((r["2026-08-28"]["count"], r["2026-08-28"]["coverage"]), (1, "partial"))
        self.assertEqual(history.verify_archive(self.root)["integrity"], "ok")


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