test_metrics_chain.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The chain of trust around the metrics branch (issue #296, review of PR 298).
  3. The `metrics` branch is mutable, so it is never authoritative:
  4. - the committed baseline holds the star history and NO ledger; the carried snapshot
  5. must match its identity fields exactly and must hold a ledger;
  6. - a carried ledger is kept as an exact prefix: only today's point may be added or
  7. replaced; a missing, changed, reordered or extra earlier point fails closed;
  8. - a carried snapshot older than MAX_CARRY_AGE_DAYS is refused;
  9. - the carry script checks the blob size before writing anything into carried/.
  10. """
  11. import copy
  12. import datetime
  13. import json
  14. import os
  15. import subprocess
  16. import sys
  17. from pathlib import Path
  18. import pytest
  19. from test_growth_bundle import REPO, git, make_bundle
  20. from test_star_ledger import baseline, with_ledger
  21. ROOT = Path(__file__).resolve().parent.parent
  22. sys.path.insert(0, str(ROOT / "scripts"))
  23. import gen_repo_metrics as grm
  24. CARRY = ROOT / "scripts" / "carry_metrics_snapshot.sh"
  25. REF = datetime.datetime(2026, 10, 25, 6, 0, 0, tzinfo=datetime.UTC)
  26. @pytest.fixture(autouse=True)
  27. def _not_in_actions(monkeypatch):
  28. monkeypatch.delenv("GITHUB_ACTIONS", raising=False)
  29. def hashed(snap):
  30. snap = copy.deepcopy(snap)
  31. snap["source_sha256"] = grm.source_digest(snap)
  32. snap["png_sha256"] = "1" * 64
  33. return snap
  34. def write(path, snap):
  35. path.write_text(json.dumps(hashed(snap)))
  36. return path
  37. # -- roles: baseline and carried ---------------------------------------------------------
  38. def test_a_good_baseline_loads(tmp_path):
  39. assert grm.load_baseline(write(tmp_path / "b.json", baseline()), REPO)["stars_as_of"] == "2026-10-20"
  40. def test_a_valid_hashed_baseline_that_contains_a_ledger_is_rejected(tmp_path):
  41. path = write(tmp_path / "b.json", with_ledger())
  42. assert grm.validate_snapshot(json.loads(path.read_text())) == [] # valid in itself
  43. with pytest.raises(RuntimeError, match="must not contain a star_ledger"):
  44. grm.load_baseline(path, REPO)
  45. def test_a_baseline_without_stars_as_of_is_rejected(tmp_path):
  46. snap = baseline()
  47. del snap["stars_as_of"]
  48. with pytest.raises(RuntimeError, match="stars_as_of"):
  49. grm.load_baseline(write(tmp_path / "b.json", snap), REPO)
  50. def test_a_baseline_for_another_repository_is_rejected(tmp_path):
  51. with pytest.raises(RuntimeError, match="not Other/Thing"):
  52. grm.load_baseline(write(tmp_path / "b.json", baseline()), "Other/Thing")
  53. def carried_for(tmp_path, **changes):
  54. snap = with_ledger({"2026-10-21": 104, "2026-10-23": 140})
  55. snap["repo"] = REPO
  56. snap.update(changes)
  57. return write(tmp_path / "c.json", snap)
  58. def test_a_good_carried_snapshot_loads(tmp_path):
  59. base = baseline()
  60. assert grm.load_carried(carried_for(tmp_path), REPO, base, REF)["star_ledger"]["2026-10-23"] == 140
  61. @pytest.mark.parametrize(
  62. "change",
  63. [
  64. {"created_on": "2026-10-09"},
  65. {"stars": {"2026-10-10": 20, "2026-10-12": 50, "2026-10-19": 31}},
  66. {"stars_as_of": "2026-10-19"},
  67. ],
  68. )
  69. def test_a_carried_snapshot_must_equal_the_baseline_identity(tmp_path, change):
  70. with pytest.raises(RuntimeError, match="differs from the baseline"):
  71. grm.load_carried(carried_for(tmp_path, **change), REPO, baseline(), REF)
  72. def test_a_carried_snapshot_without_a_ledger_is_rejected(tmp_path):
  73. snap = with_ledger({})
  74. del snap["star_ledger"]
  75. snap["repo"] = REPO
  76. with pytest.raises(RuntimeError, match="no star_ledger"):
  77. grm.load_carried(write(tmp_path / "c.json", snap), REPO, baseline(), REF)
  78. def test_the_one_ledgerless_case_is_a_snapshot_taken_on_the_baseline_day(tmp_path):
  79. snap = with_ledger({}, fetched="2026-10-20T08:00:00Z")
  80. del snap["star_ledger"]
  81. snap["repo"] = REPO
  82. snap["closed_issues"], snap["merged_prs"], snap["forks"] = {"2026-10-13": 1}, {"2026-10-11": 3}, {"2026-10-13": 1}
  83. assert grm.load_carried(write(tmp_path / "c.json", snap), REPO, baseline(), REF)
  84. def test_a_stale_carried_snapshot_is_rejected(tmp_path):
  85. later = REF + datetime.timedelta(days=grm.MAX_CARRY_AGE_DAYS + 1)
  86. with pytest.raises(RuntimeError, match="days old"):
  87. grm.load_carried(carried_for(tmp_path), REPO, baseline(), later)
  88. edge = datetime.datetime(2026, 10, 23, tzinfo=datetime.UTC) + datetime.timedelta(days=grm.MAX_CARRY_AGE_DAYS)
  89. assert grm.load_carried(carried_for(tmp_path), REPO, baseline(), edge)
  90. def test_the_staleness_bound_is_a_named_constant():
  91. assert grm.MAX_CARRY_AGE_DAYS == 14
  92. # -- the prefix rule -----------------------------------------------------------------------
  93. OLD = {"2026-10-21": 104, "2026-10-22": 110, "2026-10-23": 140}
  94. @pytest.mark.parametrize(
  95. "new, today, ok",
  96. [
  97. (OLD, "2026-10-23", True),
  98. ({**OLD, "2026-10-24": 150}, "2026-10-24", True), # today appended
  99. ({"2026-10-21": 104, "2026-10-22": 110, "2026-10-23": 141}, "2026-10-23", True), # today replaced
  100. ({**OLD, "2026-10-24": 150}, "2026-10-25", False), # an extra point that is not today
  101. ({"2026-10-22": 110, "2026-10-23": 140}, "2026-10-24", False), # first point dropped
  102. ({"2026-10-21": 104, "2026-10-23": 140}, "2026-10-24", False), # middle point dropped
  103. ({"2026-10-21": 105, "2026-10-22": 110, "2026-10-23": 140}, "2026-10-24", False), # earlier point changed
  104. ({"2026-10-22": 110, "2026-10-21": 104, "2026-10-23": 140}, "2026-10-24", False), # reordered
  105. ({"2026-10-20": 90, **OLD}, "2026-10-24", False), # a point inserted before
  106. ({}, "2026-10-24", False), # emptied
  107. ],
  108. )
  109. def test_the_prefix_rule(new, today, ok):
  110. assert (grm.ledger_extension_problems(OLD, new, today) == []) is ok
  111. def test_an_insertion_in_the_middle_that_is_not_today_fails():
  112. new = {"2026-10-21": 104, "2026-10-22": 110, "2026-10-22x": 0}
  113. assert grm.ledger_extension_problems({"2026-10-21": 104}, {"2026-10-21": 104, "2026-10-22": 110, "2026-10-23": 140}, "2026-10-23")
  114. assert grm.ledger_extension_problems({"2026-10-21": 104}, new, "2026-10-23")
  115. def test_a_first_run_may_start_a_ledger_with_today_only():
  116. assert grm.ledger_extension_problems(None, {"2026-10-24": 150}, "2026-10-24") == []
  117. assert grm.ledger_extension_problems(None, {"2026-10-20": 150}, "2026-10-24")
  118. def test_the_refresh_fails_closed_when_the_carried_snapshot_is_not_the_baselines(tmp_path, monkeypatch, capsys):
  119. from test_star_ledger import CiGh
  120. base = write(tmp_path / "base.json", baseline())
  121. carried = carried_for(tmp_path, stars_as_of="2026-10-19")
  122. monkeypatch.setattr(grm, "run_gh", CiGh())
  123. 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(carried)])
  124. assert code == 1 and "differs from the baseline" in capsys.readouterr().err
  125. assert not (tmp_path / "out").exists()
  126. # -- verify-bundle descends from the baseline and the previous snapshot --------------------
  127. def bundle_with(tmp_path, ledger, **changes):
  128. snap = with_ledger(ledger)
  129. snap["repo"] = REPO
  130. snap["fetched_at"] = "2026-10-25T05:30:00Z"
  131. snap.update(changes)
  132. return make_bundle(tmp_path / "bundle", snap=snap)
  133. def baseline_for(tmp_path):
  134. """A committed baseline that matches what make_bundle writes (same star history and dates)."""
  135. snap = {**baseline(), "created_on": "2026-10-10", "stars": {"2026-10-10": 2, "2026-10-12": 5}, "stars_as_of": "2026-10-20"}
  136. return write(tmp_path / "base.json", snap)
  137. def prev_for(tmp_path, ledger):
  138. snap = {**with_ledger(ledger), "repo": REPO, "stars": {"2026-10-10": 2, "2026-10-12": 5}}
  139. return write(tmp_path / "prev.json", snap)
  140. def verify(bundle, base, previous=None):
  141. return grm.verify_bundle(bundle, REPO, None, REF, baseline=base, previous=previous)
  142. def test_a_descendant_bundle_passes(tmp_path):
  143. base = baseline_for(tmp_path)
  144. prev = prev_for(tmp_path, {"2026-10-21": 104, "2026-10-23": 140})
  145. b = bundle_with(tmp_path, {"2026-10-21": 104, "2026-10-23": 140, "2026-10-25": 150})
  146. assert verify(b, base, prev) == []
  147. @pytest.mark.parametrize(
  148. "ledger",
  149. [
  150. {"2026-10-23": 140, "2026-10-25": 150}, # first point dropped
  151. {"2026-10-21": 104, "2026-10-25": 150}, # point dropped
  152. {"2026-10-21": 105, "2026-10-23": 140, "2026-10-25": 150}, # point changed
  153. {"2026-10-21": 104, "2026-10-24": 141, "2026-10-25": 150}, # extra non-today point
  154. ],
  155. )
  156. def test_a_bundle_that_loses_or_rewrites_history_fails(tmp_path, ledger):
  157. base = baseline_for(tmp_path)
  158. prev = prev_for(tmp_path, {"2026-10-21": 104, "2026-10-23": 140})
  159. assert verify(bundle_with(tmp_path, ledger), base, prev)
  160. def test_a_bundle_with_another_baseline_fails(tmp_path):
  161. assert verify(bundle_with(tmp_path, {"2026-10-25": 150}, stars_as_of="2026-10-19"), baseline_for(tmp_path))
  162. def test_a_baseline_with_a_ledger_fails_the_bundle_check(tmp_path):
  163. base = write(tmp_path / "base.json", with_ledger())
  164. assert any("star_ledger" in p for p in verify(bundle_with(tmp_path, {"2026-10-25": 150}), base))
  165. def test_previous_without_a_baseline_is_refused(tmp_path):
  166. prev = prev_for(tmp_path, {"2026-10-21": 104})
  167. assert grm.verify_bundle(bundle_with(tmp_path, {"2026-10-25": 150}), REPO, None, REF, previous=prev)
  168. # -- the carry script ----------------------------------------------------------------------
  169. @pytest.fixture
  170. def remote(tmp_path):
  171. r = tmp_path / "remote.git"
  172. git("init", "-q", "--bare", "-b", "main", str(r))
  173. return r
  174. def push_branch(tmp_path, remote, files, mode=None):
  175. work = tmp_path / "pusher"
  176. git("init", "-q", "-b", "metrics", str(work))
  177. for name, data in files.items():
  178. (work / name).write_bytes(data)
  179. git("-C", str(work), "add", "-A")
  180. git("-C", str(work), "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "x")
  181. git("-C", str(work), "push", "-q", str(remote), "HEAD:refs/heads/metrics")
  182. return git("rev-parse", "HEAD", cwd=work).stdout.strip()
  183. def carry(remote, dest):
  184. env = {**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}
  185. return subprocess.run(["bash", str(CARRY), str(remote), str(dest)], check=False, capture_output=True, text=True, env=env)
  186. def test_no_branch_means_a_first_run_with_an_empty_tip(tmp_path, remote):
  187. dest = tmp_path / "carried"
  188. out = carry(remote, dest)
  189. assert out.returncode == 0, out.stderr
  190. assert out.stdout.strip() == "tip="
  191. assert not any(dest.iterdir())
  192. def test_an_existing_branch_is_carried_with_its_tip(tmp_path, remote):
  193. snap = json.dumps(hashed({**with_ledger(), "repo": REPO}))
  194. tip = push_branch(tmp_path, remote, {"metrics-snapshot.json": snap.encode()})
  195. dest = tmp_path / "carried"
  196. out = carry(remote, dest)
  197. assert out.returncode == 0, out.stderr
  198. assert out.stdout.strip() == f"tip={tip}"
  199. assert (dest / "metrics-snapshot.json").read_text() == snap
  200. assert sorted(p.name for p in dest.iterdir()) == ["metrics-snapshot.json"]
  201. def test_an_oversized_blob_is_rejected_before_any_file_exists(tmp_path, remote):
  202. push_branch(tmp_path, remote, {"metrics-snapshot.json": b"x" * (grm.MAX_SNAPSHOT_BYTES + 1)})
  203. dest = tmp_path / "carried"
  204. out = carry(remote, dest)
  205. assert out.returncode != 0 and "larger than" in out.stderr
  206. assert list(dest.iterdir()) == []
  207. assert not [p for p in tmp_path.rglob("*") if p.is_file() and p.stat().st_size > grm.MAX_SNAPSHOT_BYTES and "pusher" not in p.parts and "remote.git" not in p.parts]
  208. def test_a_blob_exactly_at_the_cap_is_accepted_and_one_over_is_not(tmp_path, remote):
  209. push_branch(tmp_path, remote, {"metrics-snapshot.json": b"x" * grm.MAX_SNAPSHOT_BYTES})
  210. assert carry(remote, tmp_path / "ok").returncode == 0
  211. def test_a_branch_without_the_snapshot_is_rejected(tmp_path, remote):
  212. push_branch(tmp_path, remote, {"other.txt": b"hi"})
  213. out = carry(remote, tmp_path / "carried")
  214. assert out.returncode != 0 and "metrics-snapshot.json" in out.stderr
  215. assert list((tmp_path / "carried").iterdir()) == []
  216. def test_a_symlink_snapshot_is_rejected(tmp_path, remote):
  217. work = tmp_path / "pusher"
  218. git("init", "-q", "-b", "metrics", str(work))
  219. os.symlink("/etc/passwd", work / "metrics-snapshot.json")
  220. git("-C", str(work), "add", "-A")
  221. git("-C", str(work), "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "x")
  222. git("-C", str(work), "push", "-q", str(remote), "HEAD:refs/heads/metrics")
  223. out = carry(remote, tmp_path / "carried")
  224. assert out.returncode != 0 and "regular file" in out.stderr
  225. assert list((tmp_path / "carried").iterdir()) == []
  226. def test_an_unreachable_remote_fails_instead_of_looking_like_a_first_run(tmp_path):
  227. out = carry(tmp_path / "does-not-exist.git", tmp_path / "carried")
  228. assert out.returncode != 0
  229. assert "tip=" not in out.stdout
  230. def test_the_carry_script_never_writes_outside_the_destination_or_forces():
  231. text = CARRY.read_text()
  232. assert "--force" not in text and "head -c" in text and "cat-file -s" in text
  233. def test_the_committed_snapshot_is_a_valid_baseline():
  234. base = grm.load_baseline(ROOT / grm.SNAPSHOT)
  235. assert "star_ledger" not in base and base["stars_as_of"] == base["fetched_at"][:10]
  236. def test_the_page_documents_history_the_prefix_rule_and_the_reset():
  237. page = (ROOT / "docs" / "wiki" / "Repository-Growth.md").read_text()
  238. for needle in ("fast-forward", "compare-and-swap", "at most one small commit per run", "14 days", "delete the `metrics` branch", "reviewed"):
  239. assert needle in page, needle