In this section
- Test Download Retries test · lightning / tests/test_download_retries.py lines 407–422
- Test Grid test · lightning / tests/test_grid.py lines 1–221
- Test Heartbeat test · lightning / tests/test_heartbeat.py lines 1–162
Test Download Retries
A test in the tests folder of Lightning that checks Backfill Parallel and Collect. It reads timeout (`ReadTimeout`), reads timeout sub (`ReadTimeoutSub`) and sets up (`setUp`).
testlightning / tests/test_download_retries.py · lines 407–422 of 422 (continued from section 1825) · Entry point · pattern _update_token_data (shared by 2 files)
- What it does
- It tests its inputs. Defines 53 functions or classes, including ProtocolError, ChunkedEncodingError, RequestsConnectionError, ReadTimeout, Timeout. Uses libraries http.client, io, json, sys, tempfile. Side effects: reads or writes files; makes network requests.
- Inputs & outputs
- In: JSON file rb.json; JSON file status.json; JSON file index.json; GeoJSON file feed.geojson.
- Downstream impact
- Used directly by 4 files: Backfill Lightning Workflow (lightning); Backfill Parallel Lightning Workflow (lightning); Test Lightning Workflow (lightning); Update Lightning Workflow (lightning).
- What it achieves
- A single transient download error must not stop a whole search.
- Why it matters
- Run by Backfill Lightning Workflow, Backfill Parallel Lightning Workflow and Update Lightning Workflow. Checked by Test Lightning Workflow.
- Application
- lightning · tests · test
- Uses
- Backfill Parallel (import), Collect (import), Status (import), Test Unreadable Product (import), http.client, io, json, sys, tempfile, unittest, datetime, pathlib
- Used by
- run by Backfill Lightning Workflow (workflow run), run by Backfill Parallel Lightning Workflow (workflow run), run by Test Lightning Workflow (workflow run), run by Update Lightning Workflow (workflow run)
- Produces
- ProtocolError, ChunkedEncodingError, RequestsConnectionError, ReadTimeout, Timeout, ReadTimeoutSub, FakeResponse, HTTPError, ProductError, incident_error, FakeProduct, FlakyEumetsat
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- lightning@2882145e28a0412de3a5bcfa40a12d7cd894ba90 tests/test_download_retries.py:407-422 · blob 4d99379aa47a13cce57472ebdcdcb69ee11cd73d · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: unknown · users: none · canonical: unknown
with self.assertRaises(collect.DownloadOutage):
collect.main(["--hours", "6", "--out", str(self.base / "feed.geojson"),
"--status", str(self.base / "status.json"), "--history-dir", str(self.base / "h"),
"--run-record", str(self.record)], now=now)
rec = self.load()
self.assertEqual(rec["outcome"], "failure")
self.assertEqual(rec["download_retries"]["products_failed"], 5)
self.assertEqual(rec["products_unparsed"], 5)
self.assertFalse((self.base / "feed.geojson").exists())
status = status_mod.build_status(now=now, previous={}, record=rec, archive_result=None,
collect_outcome="failure", archive_outcome="skipped")
self.assertEqual(status["last_download_retries"]["products_failed"], 5)
if __name__ == "__main__":
unittest.main()Test Grid
A test in the tests folder of Lightning that checks Collect and Grid, using SHA-256.
testlightning / tests/test_grid.py · lines 1–221 of 221 · Entry point · pattern archive (shared by 3 files)
- What it does
- It tests its inputs. Defines 22 functions or classes, including flash, scan, load, summed, GridTests. Uses libraries json, subprocess, sys, tempfile, unittest. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file index.json; JSON file 2026-09.json; JSON file 2026-10.json; JSON file 2025-10.json; JSON file 2025-11.json; JSON file 2026-12.json; JSON file rb.json. Out: JSON file 2026-09.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 flash step (`flash`) and the scan step (`scan`). Month density grids (`grid/YYYY-MM.json`, uk-lightning-history-grid.v1); no 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 (import), Grid (import), History (import), Test Backfill (import), json, subprocess, 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
- flash, scan, load, summed, GridTests
- Defines here
- flash, scan, load, summed, GridTests, setUp, tearDown, archive, seed, test_cell_rule_is_a_clamped_0_1_degree_grid_over_the_view_bounds, test_ingest_writes_one_grid_per_retention_month_summing_exactly_to_the_index, test_unknown_days_are_null_not_zero_and_a_searched_empty_day_is_zero, test_days_carry_the_shard_sha256_the_client_compares_with_the_index, test_split_days_sum_their_hourly_parts, test_rerun_is_byte_identical_and_a_rebuild_from_scratch_gives_the_same_bytes, test_a_new_flash_rewrites_only_its_month_and_rereads_only_its_day, test_months_leaving_retention_are_removed, test_a_grid_that_differs_from_the_index_is_stale_and_verify_refuses_it, test_a_corrupt_grid_is_rebuilt_and_bad_cell_rows_are_refused, test_a_grid_failure_never_blocks_the_archive, test_backfill_regenerates_the_month_of_the_filled_date, test_cli_build_is_the_one_off_generator_and_is_idempotent
- 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_grid.py:1-221 · blob d752475751ee97368472618df41b2801543ab426 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Month density grids (grid/YYYY-MM.json, uk-lightning-history-grid.v1); no network.
The grid is derived from the day shards only: each day's cells sum exactly to
its index count, never-searched days stay unknown (count null, no cells), a
grid day that differs from the index is stale, and the bytes are a pure
function of the archive (deterministic, rewritten only when a month changes).
Synthetic features exist ONLY inside temporary directories created by these
tests (ids start with "TEST-"); nothing synthetic is ever published.
"""
import json
import subprocess
import sys
import tempfile
import unittest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "tests"))
import collect
import grid
import history
from collect import build_feature
from history import archive_observations, successful_scan
from test_backfill import FakeDownloader
NOW = datetime(2026, 10, 26, 14, 0, tzinfo=timezone.utc)
def flash(moment, tag, index=0, lon=-2.12, lat=51.11):
return build_feature(lon, lat, moment, "TEST-" + tag, index)
def scan(start, end):
return successful_scan(start.isoformat(), end.isoformat(), 18)
def load(root, month):
return json.loads((root / "grid" / f"{month}.json").read_text())
def summed(grid_obj, day):
entries, cells = grid.parse_grid(json.dumps(grid_obj), grid_obj["month"])
return cells.get(day, {})
class GridTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(self.temp.name) / "history"
def tearDown(self):
self.temp.cleanup()
def archive(self, flashes, *, now=NOW, windows=(), **kwargs):
return archive_observations(self.root, flashes, now=now, scanned_windows=list(windows), **kwargs)
def seed(self):
d1 = datetime(2026, 10, 24, tzinfo=timezone.utc)
d2 = datetime(2026, 9, 30, tzinfo=timezone.utc)
flashes = [flash(d1 + timedelta(hours=3), "a", 0, -2.12, 51.11), flash(d1 + timedelta(hours=4), "b", 1, -2.11, 51.13),
flash(d1 + timedelta(hours=5), "c", 2, 0.5, 52.0), flash(d2 + timedelta(hours=9), "d", 0, -4.0, 55.0)]
return self.archive(flashes, windows=[scan(d1, d1 + timedelta(days=1)), scan(d2, d2 + timedelta(days=1)),
scan(datetime(2026, 10, 25, tzinfo=timezone.utc),
datetime(2026, 10, 25, 12, tzinfo=timezone.utc))])
# --- cell rule -------------------------------------------------------
def test_cell_rule_is_a_clamped_0_1_degree_grid_over_the_view_bounds(self):
self.assertEqual((grid.COLS, grid.ROWS, grid.CELL_DEG), (140, 120, 0.1))
self.assertEqual(grid.cell_of(-11.0, 49.5), 0)
self.assertEqual(grid.cell_of(3.0, 61.5), grid.COLS * grid.ROWS - 1) # the closed east/north edges clamp
self.assertEqual(grid.cell_of(-10.9, 49.5), 1) # exact 0.1 steps never fall into the cell below
self.assertEqual(grid.cell_of(-11.0, 49.6), grid.COLS)
self.assertEqual(grid.cell_of(-10.95, 49.55), 0)
self.assertEqual(grid.cell_of(-2.12, 51.11), 16 * 140 + 88) # row floor(16.1), col floor(88.8)
# --- contents --------------------------------------------------------
def test_ingest_writes_one_grid_per_retention_month_summing_exactly_to_the_index(self):
result = self.seed()
self.assertIsNone(result["grid"]["error"])
index = result["index"]
months = sorted({r["date"][:7] for r in index["days"]})
self.assertEqual(len(months), 13) # 2025-10 .. 2026-10: any window sums from at most 13 files
self.assertEqual(sorted(p.name for p in (self.root / "grid").iterdir()), [f"{m}.json" for m in months])
total = 0
for m in months:
g = load(self.root, m)
self.assertEqual(g["schema"], grid.SCHEMA_GRID)
self.assertIn("not ground strikes", g["observation"])
entries, cells = grid.parse_grid(json.dumps(g), m)
for e in entries:
self.assertEqual(sum(cells.get(e["date"], {}).values()), e["count"] or 0)
total += g["total"]
self.assertEqual(total, index["archived_observations"])
oct_ = load(self.root, "2026-10")
self.assertEqual(summed(oct_, "2026-10-24"), {grid.cell_of(-2.12, 51.11): 2, grid.cell_of(0.5, 52.0): 1})
self.assertEqual(grid.verify_grids(self.root, deep=True), {"months": 13})
def test_unknown_days_are_null_not_zero_and_a_searched_empty_day_is_zero(self):
self.seed()
days = {e["date"]: e for e in load(self.root, "2026-10")["days"]}
self.assertEqual((days["2026-10-20"]["coverage"], days["2026-10-20"]["count"]), ("none", None))
self.assertEqual(days["2026-10-20"]["sha256"], [])
self.assertEqual((days["2026-10-25"]["coverage"], days["2026-10-25"]["count"]), ("partial", 0))
self.assertNotIn("2026-10-27", days) # the future is not listed at all
first = load(self.root, "2025-10")["days"]
self.assertEqual(first[0]["date"], "2025-10-26") # days before the cutoff are not listed
self.assertEqual(load(self.root, "2025-10")["cells"], [])
def test_days_carry_the_shard_sha256_the_client_compares_with_the_index(self):
index = self.seed()["index"]
row = {r["date"]: r for r in index["days"]}["2026-10-24"]
entry = {e["date"]: e for e in load(self.root, "2026-10")["days"]}["2026-10-24"]
self.assertEqual(entry, {"date": "2026-10-24", "coverage": "full", "count": 3, "sha256": [row["sha256"]]})
def test_split_days_sum_their_hourly_parts(self):
day = datetime(2026, 10, 24, tzinfo=timezone.utc)
flashes = [flash(day + timedelta(hours=h, minutes=m), f"s{h}-{m}", m) for h in (3, 4, 17) for m in range(4)]
result = self.archive(flashes, windows=[scan(day, day + timedelta(days=1))], target_shard_bytes=2000)
row = {r["date"]: r for r in result["index"]["days"]}["2026-10-24"]
entry = {e["date"]: e for e in load(self.root, "2026-10")["days"]}["2026-10-24"]
self.assertEqual(entry["sha256"], [p["sha256"] for p in row["parts"]])
self.assertEqual(sum(summed(load(self.root, "2026-10"), "2026-10-24").values()), 12)
# --- determinism and incremental refresh ----------------------------------
def test_rerun_is_byte_identical_and_a_rebuild_from_scratch_gives_the_same_bytes(self):
self.seed()
before = {p.name: p.read_bytes() for p in (self.root / "grid").iterdir()}
again = self.archive([], windows=[])
self.assertEqual((again["grid"]["written"], again["grid"]["days_read"]), ([], 0))
for p in (self.root / "grid").iterdir():
p.unlink()
index = json.loads((self.root / "index.json").read_text())
grid.refresh_grids(self.root, index)
self.assertEqual({p.name: p.read_bytes() for p in (self.root / "grid").iterdir()}, before)
def test_a_new_flash_rewrites_only_its_month_and_rereads_only_its_day(self):
self.seed()
sept = (self.root / "grid" / "2026-09.json").read_bytes()
result = self.archive([flash(datetime(2026, 10, 24, 20, tzinfo=timezone.utc), "late", 7, 1.0, 53.0)])
self.assertEqual(result["grid"]["written"], ["grid/2026-10.json"])
self.assertEqual(result["grid"]["days_read"], 1)
self.assertEqual((self.root / "grid" / "2026-09.json").read_bytes(), sept)
self.assertEqual(sum(summed(load(self.root, "2026-10"), "2026-10-24").values()), 4)
grid.verify_grids(self.root, deep=True)
def test_months_leaving_retention_are_removed(self):
self.seed()
later = NOW + timedelta(days=40)
result = self.archive([], now=later)
self.assertIn("grid/2025-10.json", result["grid"]["removed"])
self.assertIn("grid/2025-11.json", result["grid"]["removed"])
self.assertTrue((self.root / "grid" / "2026-12.json").exists())
first = load(self.root, "2025-12")["days"][0]["date"]
self.assertEqual(first, "2025-12-05")
grid.verify_grids(self.root, deep=True)
# --- staleness and failure handling ---------------------------------------
def test_a_grid_that_differs_from_the_index_is_stale_and_verify_refuses_it(self):
self.seed()
path = self.root / "grid" / "2026-10.json"
g = json.loads(path.read_text())
for e in g["days"]:
if e["date"] == "2026-10-24":
e["sha256"] = ["0" * 64]
path.write_text(json.dumps(g))
with self.assertRaisesRegex(ValueError, "stale"):
grid.verify_grids(self.root)
# The next archive run repairs it from the shards.
result = self.archive([])
self.assertEqual(result["grid"]["written"], ["grid/2026-10.json"])
grid.verify_grids(self.root, deep=True)
def test_a_corrupt_grid_is_rebuilt_and_bad_cell_rows_are_refused(self):
self.seed()
(self.root / "grid" / "2026-09.json").write_text("{not json")
self.assertEqual(self.archive([])["grid"]["written"], ["grid/2026-09.json"])
g = load(self.root, "2026-10")
for bad in ([[999999, 24, 1]], [[1, 32, 1]], [[1, 24, 0]], [[1, 24]], ["x"]):
with self.assertRaises(ValueError):
grid.parse_grid(json.dumps({**g, "cells": bad}), "2026-10")
with self.assertRaisesRegex(ValueError, "sum"):
grid.parse_grid(json.dumps({**g, "cells": g["cells"][:-1]}), "2026-10")
def test_a_grid_failure_never_blocks_the_archive(self):
with mock.patch.object(grid, "refresh_grids", side_effect=ValueError("boom")):
result = self.seed()
self.assertEqual(result["grid"]["error"], "ValueError: boom")
self.assertEqual(result["index"]["archived_observations"], 4)
history.verify_archive(self.root)
def test_backfill_regenerates_the_month_of_the_filled_date(self):
self.seed()
target = datetime(2026, 10, 20, tzinfo=timezone.utc)
record = Path(self.temp.name) / "rb.json"
flashes = [flash(target + timedelta(hours=h, minutes=3), f"bf{h}") for h in (2, 9)]
collect.rebuild_day_record("2026-10-20", record, now=NOW, downloader=FakeDownloader(flashes=flashes))
result = history.backfill_day(self.root, "2026-10-20", now=NOW, rebuild_record=record)
self.assertEqual(result["grid"]["written"], ["grid/2026-10.json"])
entry = {e["date"]: e for e in load(self.root, "2026-10")["days"]}["2026-10-20"]
self.assertEqual((entry["coverage"], entry["count"]), ("full", 2))
grid.verify_grids(self.root, deep=True)
def test_cli_build_is_the_one_off_generator_and_is_idempotent(self):
self.seed()
for p in (self.root / "grid").iterdir():
p.unlink()
run = subprocess.run([sys.executable, str(ROOT / "grid.py"), "build", "--archive-dir", str(self.root)],
capture_output=True, text=True, cwd=ROOT)
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(len(json.loads(run.stdout)["written"]), 13)
run = subprocess.run([sys.executable, str(ROOT / "grid.py"), "verify", "--deep", "--archive-dir", str(self.root)],
capture_output=True, text=True, cwd=ROOT)
self.assertEqual((run.returncode, json.loads(run.stdout)), (0, {"months": 13}))
if __name__ == "__main__":
unittest.main()Test Heartbeat
A test in the tests folder of Lightning that checks Status. It is built from the record step (`record`), the write step (`write`) and the heartbeat tests class (`HeartbeatTests`).
testlightning / tests/test_heartbeat.py · lines 1–162 of 162 · Entry point · pattern record (shared by 46 files)
- What it does
- It tests its inputs. Defines 16 functions or classes, including record, write, HeartbeatTests, test_on_time_run, test_the_08_55_run_names_both_the_scheduler_and_the_queue. 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 rec.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
- `status.json` explains staleness: when the collector last ran, what started it, and why the gap was long.
- 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
- record, write, HeartbeatTests, DueTests
- Defines here
- record, write, HeartbeatTests, test_on_time_run, test_the_08_55_run_names_both_the_scheduler_and_the_queue, test_the_15_19_run_blames_the_scheduler_not_the_collector, test_queue_only, test_manual_start_and_unknown_creation_time, test_first_heartbeat_and_failed_run, test_if_late_never_claims_zero, test_heartbeat_survives_a_backfill_status_write, test_next_cron_slot, DueTests, test_only_a_scheduled_run_after_a_recent_success_skips, test_cli_writes_the_github_output, test_cli_write_accepts_the_timing_flags
- 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_heartbeat.py:1-162 · blob 8d56f778608934cff1cc05a4038f2ed4c7b631dd · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""status.json explains staleness: when the collector last ran, what started it, and why the gap was long.
Timings are the real 27 Oct 2026 runs of Ventusltd/lightning (gh api .../actions/runs):
00:26 scheduled run; 03:14-07:01 and 07:02-10:26 backfills in the shared group;
run 40476905747 created 08:55:15, job started 10:26:22 (91 min queued);
no run created again until 15:19:46 although the group was free from 10:43.
"""
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, is_due, next_cron_slot
UTC = timezone.utc
def record(run_utc: str, end_utc: str) -> dict:
return {"schema": "uk-lightning-run-record.v1", "run_utc": run_utc, "outcome": "success", "error": None,
"products_examined": 36, "slots_parsed": True,
"scanned_ranges": [{"start_utc": "2026-10-27T00:00:00.000Z", "end_utc": end_utc}]}
def write(previous, rec, *, now, trigger="schedule", created=None, started=None, collect="success"):
return build_status(now=now, previous=previous, record=rec, archive_result=None, collect_outcome=collect,
archive_outcome="success" if collect == "success" else "skipped", trigger=trigger,
run_id="1", run_created_utc=created, job_started_utc=started)
PREV = {"last_attempt_utc": "2026-10-27T00:27:10.000Z", "last_attempt_outcome": "success",
"last_successful_scan_end_utc": "2026-10-27T00:20:09.000Z"}
class HeartbeatTests(unittest.TestCase):
def test_on_time_run(self):
prev = {**PREV, "last_attempt_utc": "2026-10-27T14:18:00.000Z"}
hb = write(prev, record("2026-10-27T15:20:03.957Z", "2026-10-27T15:10:09.000Z"),
now=datetime(2026, 10, 27, 15, 24, tzinfo=UTC), created="2026-10-27T15:19:46Z",
started="2026-10-27T15:19:49Z")["heartbeat"]
self.assertEqual(hb["gap_before_this_run"]["cause"], "on_time")
self.assertEqual(hb["this_run"]["queued_minutes"], 0.1)
self.assertIn("on schedule", hb["explanation"])
self.assertEqual(hb["next_expected_run_utc"], "2026-10-27T15:47:00.000Z")
self.assertEqual(hb["late_after_utc"], "2026-10-27T16:50:03.957Z")
def test_the_08_55_run_names_both_the_scheduler_and_the_queue(self):
hb = write(PREV, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC), created="2026-10-27T08:55:15Z",
started="2026-10-27T10:26:22Z")["heartbeat"]
gap = hb["gap_before_this_run"]
self.assertEqual(gap["cause"], "github_schedule_late_then_queued")
self.assertEqual(hb["this_run"]["queued_minutes"], 91.1)
self.assertEqual(gap["hourly_slots_without_a_run"], 7) # 01:17..08:17 minus the one this run served
self.assertIn("GitHub's scheduler started no run on time", hb["explanation"])
self.assertIn("waited 1 h 31 min in the queue behind another run", hb["explanation"])
def test_the_15_19_run_blames_the_scheduler_not_the_collector(self):
prev = {**PREV, "last_attempt_utc": "2026-10-27T10:26:40.000Z"}
hb = write(prev, record("2026-10-27T15:20:03.957Z", "2026-10-27T15:10:09.000Z"),
now=datetime(2026, 10, 27, 15, 24, tzinfo=UTC), created="2026-10-27T15:19:46Z",
started="2026-10-27T15:19:49Z")["heartbeat"]
self.assertEqual(hb["gap_before_this_run"]["cause"], "github_schedule_late_or_dropped")
self.assertEqual(hb["gap_before_this_run"]["hourly_slots_without_a_run"], 4) # 11:17..14:17
self.assertIn("no run for 4 h 53 min (since 27 Oct 10:26 UTC)", hb["explanation"])
self.assertIn("not a collector or EUMETSAT failure", hb["explanation"])
def test_queue_only(self):
prev = {**PREV, "last_attempt_utc": "2026-10-27T07:20:00.000Z"}
hb = write(prev, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC), created="2026-10-27T08:17:30Z",
started="2026-10-27T10:26:22Z")["heartbeat"]
self.assertEqual(hb["gap_before_this_run"]["cause"], "queued_behind_another_run")
def test_manual_start_and_unknown_creation_time(self):
hb = write(PREV, record("2026-10-27T02:38:30.000Z", "2026-10-27T02:30:09.000Z"),
now=datetime(2026, 10, 27, 3, 13, tzinfo=UTC), trigger="workflow_dispatch",
created="2026-10-27T02:38:11Z", started="2026-10-27T02:38:14Z")["heartbeat"]
self.assertEqual(hb["gap_before_this_run"]["cause"], "no_scheduled_run_until_manual_start")
self.assertIn("started manually", hb["explanation"])
hb = write(PREV, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC))["heartbeat"]
self.assertEqual(hb["gap_before_this_run"]["cause"], "unknown")
self.assertIsNone(hb["this_run"]["queued_minutes"])
self.assertIn("cause unknown", hb["explanation"])
def test_first_heartbeat_and_failed_run(self):
hb = write(None, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC))["heartbeat"]
self.assertIsNone(hb["gap_before_this_run"])
failed = write(PREV, None, now=datetime(2026, 10, 27, 1, 20, tzinfo=UTC), collect="failure",
created="2026-10-27T01:17:40Z", started="2026-10-27T01:17:44Z")
self.assertEqual(failed["heartbeat"]["this_run"]["outcome"], "failure")
self.assertIn("(schedule, failure)", failed["heartbeat"]["explanation"])
def test_if_late_never_claims_zero(self):
hb = write(PREV, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC))["heartbeat"]
self.assertIn("unknown, not zero", hb["if_late"])
self.assertIn("since 27 Oct 10:26 UTC", hb["if_late"])
def test_heartbeat_survives_a_backfill_status_write(self):
st = write(PREV, record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z"),
now=datetime(2026, 10, 27, 10, 43, tzinfo=UTC))
after = status_module.backfill_status(st, now=datetime(2026, 10, 27, 11, tzinfo=UTC), planned=["2026-10-01"],
filled=["2026-10-01"], stopped="completed", error=None, index=None)
self.assertEqual(after["heartbeat"], st["heartbeat"])
def test_next_cron_slot(self):
self.assertEqual(next_cron_slot(datetime(2026, 10, 27, 10, 17, tzinfo=UTC)), datetime(2026, 10, 27, 10, 47, tzinfo=UTC))
self.assertEqual(next_cron_slot(datetime(2026, 10, 27, 10, 50, tzinfo=UTC)), datetime(2026, 10, 27, 11, 17, tzinfo=UTC))
self.assertEqual(next_cron_slot(datetime(2026, 10, 27, 23, 59, tzinfo=UTC)), datetime(2026, 10, 28, 0, 17, tzinfo=UTC))
class DueTests(unittest.TestCase):
NOW = datetime(2026, 10, 27, 15, 47, 30, tzinfo=UTC)
def test_only_a_scheduled_run_after_a_recent_success_skips(self):
recent = {"last_attempt_utc": "2026-10-27T15:20:03.957Z", "last_attempt_outcome": "success"}
self.assertEqual(is_due(recent, now=self.NOW, event="schedule")[0], False)
self.assertEqual(is_due(recent, now=self.NOW, event="workflow_dispatch")[0], True)
self.assertEqual(is_due({**recent, "last_attempt_outcome": "failure"}, now=self.NOW, event="schedule")[0], True)
old = {**recent, "last_attempt_utc": "2026-10-27T14:20:00.000Z"}
self.assertEqual(is_due(old, now=self.NOW, event="schedule")[0], True)
self.assertEqual(is_due(None, now=self.NOW, event="schedule")[0], True)
self.assertEqual(is_due({"last_attempt_utc": "garbage"}, now=self.NOW, event="schedule")[0], True)
def test_cli_writes_the_github_output(self):
with tempfile.TemporaryDirectory() as tmp:
st, out = Path(tmp) / "status.json", Path(tmp) / "out"
st.write_text(json.dumps({"last_attempt_utc": "2026-10-27T15:20:03.957Z", "last_attempt_outcome": "success"}))
self.assertEqual(status_module.main(["due", "--status", str(st), "--event", "schedule",
"--github-output", str(out), "--now", self.NOW.isoformat()]), 0)
self.assertEqual(out.read_text(), "due=false\n")
status_module.main(["due", "--status", str(Path(tmp) / "missing.json"), "--event", "schedule",
"--github-output", str(out), "--now", self.NOW.isoformat()])
self.assertEqual(out.read_text(), "due=false\ndue=true\n")
def test_cli_write_accepts_the_timing_flags(self):
with tempfile.TemporaryDirectory() as tmp:
st, rec = Path(tmp) / "status.json", Path(tmp) / "rec.json"
st.write_text(json.dumps(PREV))
rec.write_text(json.dumps(record("2026-10-27T10:26:40.000Z", "2026-10-27T10:20:09.000Z")))
code = status_module.main(["write", "--status", str(st), "--run-record", str(rec), "--collect-outcome",
"success", "--archive-outcome", "skipped", "--trigger", "schedule",
"--run-id", "40476905747", "--run-created", "2026-10-27T08:55:15Z",
"--job-started", "2026-10-27T10:26:22Z", "--now", "2026-10-27T10:43:00Z"])
self.assertEqual(code, 0)
hb = json.loads(st.read_text())["heartbeat"]
self.assertEqual(hb["this_run"]["run_id"], "40476905747")
self.assertEqual(hb["gap_before_this_run"]["cause"], "github_schedule_late_then_queued")
# Empty flags (gh api unavailable) are unknown, never an error.
code = status_module.main(["write", "--status", str(st), "--run-record", str(rec), "--collect-outcome",
"success", "--run-created", "", "--job-started", "", "--now", "2026-10-27T10:43:00Z"])
self.assertEqual(code, 0)
if __name__ == "__main__":
unittest.main()