test_star_ledger.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The star ledger (issue #296).
  3. The default Actions token cannot read stargazer time stamps (GraphQL and REST are
  4. both refused), so CI records one dated cumulative star count per UTC day instead.
  5. What is proved here:
  6. - the snapshot schema accepts the optional `stars_as_of` and `star_ledger` fields,
  7. an old snapshot without them still validates and keeps its digest, and hostile
  8. ledgers fail: out-of-order or duplicate days, future days, days at or before the
  9. baseline, non-integers, bools, negatives, drops beyond the tolerance, oversize;
  10. - in CI mode the refresh makes NO stargazers request, reads only the repo's
  11. stargazers_count, keeps the baseline star times, appends one point a day and
  12. replaces a same-day point; GITHUB_ACTIONS=true selects CI mode on its own;
  13. - the local path still fetches full time stamps;
  14. - the chart draws baseline plus ledger and says so in the picture.
  15. """
  16. import copy
  17. import datetime
  18. import json
  19. import sys
  20. from pathlib import Path
  21. from unittest import mock
  22. import pytest
  23. from test_growth_bundle import REPO, make_bundle, problems
  24. from test_repo_metrics import fixture
  25. ROOT = Path(__file__).resolve().parent.parent
  26. sys.path.insert(0, str(ROOT / "scripts"))
  27. import gen_repo_metrics as grm
  28. ZERO = {"source_sha256": "0" * 64, "png_sha256": "0" * 64}
  29. @pytest.fixture(autouse=True)
  30. def _not_in_actions(monkeypatch):
  31. monkeypatch.delenv("GITHUB_ACTIONS", raising=False)
  32. def with_ledger(ledger=None, as_of="2026-10-20", fetched="2026-10-25T05:30:00Z"):
  33. snap = fixture()
  34. snap["fetched_at"] = fetched
  35. snap["stars"] = {"2026-10-10": 20, "2026-10-12": 50, "2026-10-19": 30} # 100 by the 19th
  36. snap["stars_as_of"] = as_of
  37. snap["star_ledger"] = {"2026-10-21": 104, "2026-10-22": 110, "2026-10-23": 140} if ledger is None else ledger
  38. return snap
  39. def bad(snap):
  40. return grm.validate_snapshot({**snap, **ZERO})
  41. def test_a_good_ledger_validates_and_counts_the_latest_point():
  42. snap = with_ledger()
  43. assert bad(snap) == []
  44. assert grm.current_stars(snap) == 140
  45. assert grm.totals(snap)["stars"] == 140
  46. def test_an_old_snapshot_is_still_valid_and_keeps_its_digest():
  47. snap = fixture()
  48. assert bad(snap) == []
  49. assert grm.current_stars(snap) == sum(snap["stars"].values())
  50. legacy = json.dumps({k: snap.get(k) for k in ("schema", "repo", "created_on", "fetched_at", "stars", "forks", "merged_prs", "closed_issues", "traffic")}, sort_keys=True, separators=(",", ":"))
  51. import hashlib
  52. assert grm.source_digest(snap) == hashlib.sha256(legacy.encode()).hexdigest()
  53. def test_the_ledger_is_covered_by_the_source_hash():
  54. a, b = with_ledger(), with_ledger()
  55. b["star_ledger"]["2026-10-23"] = 141
  56. assert grm.source_digest(a) != grm.source_digest(b)
  57. @pytest.mark.parametrize(
  58. "mutate, needle",
  59. [
  60. (lambda s: s.update(star_ledger={"2026-10-22": 110, "2026-10-21": 104}), "order"),
  61. (lambda s: s.update(star_ledger={"2026-10-21": 104, "2026-10-26": 110}), "outside"), # after fetched_at
  62. (lambda s: s.update(star_ledger={"2026-10-20": 104}), "outside"), # on the baseline day
  63. (lambda s: s.update(star_ledger={"2026-10-15": 104}), "outside"), # inside the baseline
  64. (lambda s: s.update(star_ledger={"2026-10-21": 104.5}), "bad value"),
  65. (lambda s: s.update(star_ledger={"2026-10-21": "104"}), "bad value"),
  66. (lambda s: s.update(star_ledger={"2026-10-21": True}), "bad value"),
  67. (lambda s: s.update(star_ledger={"2026-10-21": -1}), "bad value"),
  68. (lambda s: s.update(star_ledger={"2026-10-21": 10**9}), "bad value"),
  69. (lambda s: s.update(star_ledger={"2026-10-21": 100, "2026-10-22": 60}), "drop"),
  70. (lambda s: s.update(star_ledger={"2026-10-21": 40}), "drop"), # first point far below the baseline total
  71. (lambda s: s.update(star_ledger={"21-10-2026": 104}), "date"),
  72. (lambda s: s.update(star_ledger={"2026-02-30": 104}), "date"),
  73. (lambda s: s.update(star_ledger=[["2026-10-21", 104]]), "object"),
  74. (lambda s: s.update(star_ledger=None), "object"),
  75. (lambda s: s.pop("stars_as_of"), "stars_as_of"), # a ledger needs its baseline date
  76. (lambda s: s.update(stars_as_of="2026-10-26"), "stars_as_of"), # after fetched_at
  77. (lambda s: s.update(stars_as_of="2026-10-01"), "stars_as_of"), # before created_on
  78. (lambda s: s.update(stars_as_of="soon"), "stars_as_of"),
  79. (lambda s: s["stars"].update({"2026-10-21": 3}), "outside"), # baseline stars after the baseline date
  80. (lambda s: s.update(star_ledger={f"2026-{m:02d}-{d:02d}": 1 for m in range(11, 13) for d in range(1, 29)}), None),
  81. ],
  82. )
  83. def test_hostile_ledgers_fail(mutate, needle):
  84. snap = with_ledger()
  85. mutate(snap)
  86. out = bad(snap)
  87. assert out, "the hostile snapshot was accepted"
  88. if needle:
  89. assert any(needle in p for p in out), out
  90. def test_a_small_drop_from_unstarring_is_tolerated():
  91. assert bad(with_ledger({"2026-10-21": 104, "2026-10-22": 102, "2026-10-23": 140})) == []
  92. def test_an_oversized_ledger_fails():
  93. start = datetime.date(2026, 10, 21)
  94. big = {(start + datetime.timedelta(days=i)).isoformat(): 100 for i in range(grm.MAX_LEDGER_POINTS + 1)}
  95. snap = with_ledger(big, fetched=f"{(start + datetime.timedelta(days=grm.MAX_LEDGER_POINTS + 2)).isoformat()}T00:00:00Z")
  96. assert any("too many" in p for p in bad(snap))
  97. def test_the_bundle_verifier_rejects_a_future_ledger_point(tmp_path):
  98. b = make_bundle(tmp_path / "b", snap=with_ledger({"2026-10-21": 104, "2026-10-26": 110}, fetched="2026-10-26T05:30:00Z"))
  99. assert problems(b) # fetched_at (and the last point) are after NOW
  100. def test_a_ledger_bundle_passes_the_verifier(tmp_path):
  101. snap = with_ledger({"2026-10-21": 104, "2026-10-25": 140})
  102. b = make_bundle(tmp_path / "b", snap=snap)
  103. assert problems(b) == []
  104. # -- the fetch layer in CI mode ---------------------------------------------------------
  105. class CiGh:
  106. def __init__(self, count=150):
  107. self.calls, self.count = [], count
  108. def __call__(self, args):
  109. self.calls.append(args)
  110. text = " ".join(args)
  111. assert "stargazers" != text and "/stargazers" not in text and "graphql" not in text, text
  112. if args[:2] == ["api", f"repos/{REPO}"] and ".stargazers_count" in args:
  113. return f"{self.count}\n"
  114. if "/forks" in text:
  115. return "2026-10-12T00:00:00Z\n"
  116. if args[0] == "api":
  117. return "2026-10-10T00:00:00Z\n"
  118. if args[:2] == ["pr", "list"]:
  119. return json.dumps([{"mergedAt": "2026-10-11T05:00:00Z"}])
  120. if args[:2] == ["issue", "list"]:
  121. return json.dumps([{"closedAt": "2026-10-12T05:00:00Z"}])
  122. raise AssertionError(text)
  123. def baseline():
  124. snap = with_ledger({})
  125. del snap["star_ledger"]
  126. snap["repo"] = REPO
  127. return snap
  128. DAY = datetime.datetime(2026, 10, 24, 6, 0, 0, tzinfo=datetime.UTC)
  129. def test_ci_mode_makes_no_stargazers_request_and_reads_only_the_count():
  130. gh = CiGh()
  131. with mock.patch.object(grm, "run_gh", gh):
  132. snap = grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=baseline())
  133. assert not any("/stargazers" in " ".join(c) or "graphql" in " ".join(c) for c in gh.calls)
  134. assert any(".stargazers_count" in c for c in gh.calls)
  135. assert snap["stars"] == baseline()["stars"] and snap["stars_as_of"] == "2026-10-20"
  136. assert snap["star_ledger"] == {"2026-10-24": 150}
  137. assert grm.validate_snapshot({**snap, **ZERO}) == []
  138. def test_ci_mode_appends_one_point_per_day_and_keeps_old_points():
  139. prev = with_ledger({"2026-10-21": 104, "2026-10-23": 140})
  140. with mock.patch.object(grm, "run_gh", CiGh(150)):
  141. snap = grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=baseline(), ledger_from=prev)
  142. assert snap["star_ledger"] == {"2026-10-21": 104, "2026-10-23": 140, "2026-10-24": 150}
  143. def test_a_same_day_rerun_replaces_that_days_point():
  144. prev = with_ledger({"2026-10-21": 104, "2026-10-24": 140})
  145. with mock.patch.object(grm, "run_gh", CiGh(151)):
  146. snap = grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=baseline(), ledger_from=prev)
  147. assert snap["star_ledger"] == {"2026-10-21": 104, "2026-10-24": 151}
  148. def test_points_at_or_before_the_baseline_date_in_a_carried_ledger_fail_closed():
  149. newer = baseline()
  150. newer["stars_as_of"] = "2026-10-22"
  151. newer["stars"]["2026-10-22"] = 5
  152. prev = with_ledger({"2026-10-21": 104, "2026-10-22": 108, "2026-10-23": 140})
  153. with mock.patch.object(grm, "run_gh", CiGh(150)), pytest.raises(RuntimeError, match="keep every earlier point"):
  154. grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=newer, ledger_from=prev)
  155. def test_ci_mode_without_a_baseline_fails_closed():
  156. with mock.patch.object(grm, "run_gh", CiGh()), pytest.raises(RuntimeError, match="baseline"):
  157. grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=None)
  158. def test_a_baseline_for_another_repository_is_refused():
  159. other = baseline()
  160. other["repo"] = "Other/Thing"
  161. with mock.patch.object(grm, "run_gh", CiGh()), pytest.raises(RuntimeError, match="baseline"):
  162. grm.fetch_snapshot(REPO, now=DAY, star_times=False, baseline=other)
  163. def test_the_local_path_still_asks_for_star_times():
  164. class Local(CiGh):
  165. def __call__(self, args):
  166. text = " ".join(args)
  167. if "/stargazers" in text:
  168. self.calls.append(args)
  169. return "2026-10-10T01:00:00Z\n"
  170. return super().__call__(args)
  171. gh = Local()
  172. with mock.patch.object(grm, "run_gh", gh):
  173. snap = grm.fetch_snapshot(REPO, now=DAY)
  174. assert any("/stargazers" in " ".join(c) for c in gh.calls)
  175. assert snap["stars"] == {"2026-10-10": 1} and "star_ledger" not in snap and "stars_as_of" not in snap
  176. def _fake_write_all(snap, sp, pp, pg, ref):
  177. sp.parent.mkdir(parents=True, exist_ok=True)
  178. sp.write_text(json.dumps(snap))
  179. def write_baseline(tmp_path, snap):
  180. snap = copy.deepcopy(snap)
  181. snap["source_sha256"] = grm.source_digest(snap)
  182. snap["png_sha256"] = "1" * 64
  183. path = tmp_path / "base.json"
  184. path.write_text(json.dumps(snap))
  185. return path
  186. def test_main_selects_ci_mode_from_the_environment_and_never_asks_for_star_times(tmp_path, monkeypatch):
  187. monkeypatch.setenv("GITHUB_ACTIONS", "true")
  188. base = write_baseline(tmp_path, baseline())
  189. gh = CiGh(150)
  190. monkeypatch.setattr(grm, "run_gh", gh)
  191. monkeypatch.setattr(grm, "draw_png", lambda s, out: out.write_bytes(b"\x89PNG\r\n\x1a\n"))
  192. monkeypatch.setattr(grm, "write_all", _fake_write_all)
  193. code = grm.main(["--refresh", "--repo", REPO, "--no-page", "--root", str(tmp_path), "--snapshot", "out/s.json", "--out", "out/c.png", "--baseline", str(base)])
  194. assert code == 0
  195. assert not any("/stargazers" in " ".join(c) or "graphql" in " ".join(c) for c in gh.calls)
  196. out = json.loads((tmp_path / "out" / "s.json").read_text())
  197. assert out["star_ledger"] and out["stars_as_of"] == "2026-10-20"
  198. def test_the_explicit_flag_also_selects_ci_mode(tmp_path, monkeypatch):
  199. base = write_baseline(tmp_path, baseline())
  200. gh = CiGh(150)
  201. monkeypatch.setattr(grm, "run_gh", gh)
  202. monkeypatch.setattr(grm, "write_all", _fake_write_all)
  203. code = grm.main(["--refresh", "--no-star-times", "--repo", REPO, "--no-page", "--root", str(tmp_path), "--snapshot", "out/s.json", "--out", "out/c.png", "--baseline", str(base)])
  204. assert code == 0 and not any("/stargazers" in " ".join(c) for c in gh.calls)
  205. def test_a_tampered_baseline_file_fails_the_refresh(tmp_path, monkeypatch, capsys):
  206. base = write_baseline(tmp_path, baseline())
  207. data = json.loads(base.read_text())
  208. data["stars"]["2026-10-12"] = 99999
  209. base.write_text(json.dumps(data))
  210. monkeypatch.setattr(grm, "run_gh", CiGh())
  211. code = grm.main(["--refresh", "--no-star-times", "--repo", REPO, "--no-page", "--root", str(tmp_path), "--snapshot", "out/s.json", "--out", "out/c.png", "--baseline", str(base)])
  212. assert code == 1 and "baseline" in capsys.readouterr().err
  213. def test_the_ledger_from_file_is_read_with_the_strict_loader(tmp_path, monkeypatch, capsys):
  214. base = write_baseline(tmp_path, baseline())
  215. junk = tmp_path / "prev.json"
  216. junk.write_text('{"star_ledger": {"2026-10-21": 1}, "star_ledger": {}}') # duplicate keys
  217. monkeypatch.setattr(grm, "run_gh", CiGh())
  218. code = grm.main(["--refresh", "--no-star-times", "--repo", REPO, "--no-page", "--root", str(tmp_path), "--snapshot", "out/s.json", "--out", "out/c.png", "--baseline", str(base), "--ledger-from", str(junk)])
  219. assert code == 1
  220. # -- drawing and the page ---------------------------------------------------------------
  221. def test_the_chart_draws_baseline_plus_ledger_and_says_so(tmp_path):
  222. pytest.importorskip("matplotlib")
  223. out = tmp_path / "chart.png"
  224. snap = with_ledger()
  225. grm.draw_png(snap, out)
  226. assert out.read_bytes().startswith(b"\x89PNG")
  227. note = grm.star_note(snap)
  228. assert "2026-10-20" in note and "daily counts" in note and "not per-star times" in note
  229. assert grm.star_note(fixture()) == ""
  230. def test_the_page_says_how_the_star_line_is_built():
  231. page = grm.render_page(fixture())
  232. assert "daily counts" in page and "per-star times" in page
  233. assert "--refresh" in page and "backfill" in page.lower()
  234. # -- a refresh that crosses UTC midnight ---------------------------------------------------
  235. class Clock:
  236. def __init__(self, *stamps):
  237. self.stamps = list(stamps)
  238. self.calls = 0
  239. def __call__(self):
  240. self.calls += 1
  241. return self.stamps.pop(0)
  242. def utc(day, hms):
  243. h, m, sec = map(int, hms.split(":"))
  244. return datetime.datetime(2026, 10, day, h, m, sec, tzinfo=datetime.UTC)
  245. class CountingGh(CiGh):
  246. def __init__(self, *counts):
  247. super().__init__()
  248. self.counts = list(counts)
  249. self.count_calls = 0
  250. def __call__(self, args):
  251. if args[:2] == ["api", f"repos/{REPO}"] and ".stargazers_count" in args:
  252. self.calls.append(args)
  253. self.count_calls += 1
  254. return f"{self.counts.pop(0)}\n"
  255. return super().__call__(args)
  256. def test_a_count_taken_across_midnight_is_requested_again_and_dated_by_the_second_request(monkeypatch):
  257. # first request straddles midnight (23:59:59 -> 00:00:01); the retry is clean (day 25)
  258. clock = Clock(utc(24, "23:58:00"), utc(24, "23:59:59"), utc(25, "00:00:01"), utc(25, "00:00:02"), utc(25, "00:00:03"))
  259. gh = CountingGh(149, 150)
  260. monkeypatch.setattr(grm, "_utcnow", clock)
  261. with mock.patch.object(grm, "run_gh", gh):
  262. snap = grm.fetch_snapshot(REPO, star_times=False, baseline=baseline())
  263. assert gh.count_calls == 2
  264. assert snap["star_ledger"] == {"2026-10-25": 150} # the count from the clean request, on its own day
  265. assert snap["fetched_at"] == "2026-10-25T00:00:03Z"
  266. def test_a_count_that_keeps_crossing_midnight_fails_closed(monkeypatch):
  267. clock = Clock(utc(24, "23:58:00"), utc(24, "23:59:59"), utc(25, "00:00:01"), utc(25, "23:59:59"), utc(26, "00:00:01"))
  268. gh = CountingGh(149, 150)
  269. monkeypatch.setattr(grm, "_utcnow", clock)
  270. with mock.patch.object(grm, "run_gh", gh), pytest.raises(RuntimeError, match="midnight"):
  271. grm.fetch_snapshot(REPO, star_times=False, baseline=baseline())
  272. def test_a_clean_request_is_made_once(monkeypatch):
  273. clock = Clock(utc(25, "09:59:00"), utc(25, "10:00:00"), utc(25, "10:00:01"))
  274. gh = CountingGh(150)
  275. monkeypatch.setattr(grm, "_utcnow", clock)
  276. with mock.patch.object(grm, "run_gh", gh):
  277. snap = grm.fetch_snapshot(REPO, star_times=False, baseline=baseline())
  278. assert gh.count_calls == 1 and snap["fetched_at"] == "2026-10-25T10:00:01Z"