test_ci_cost_gate.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. """scripts/ci_cost_gate.sh and the round-two hardening of the phase lifecycle."""
  2. import json
  3. import os
  4. import shutil
  5. import subprocess
  6. import sys
  7. from pathlib import Path
  8. import pytest
  9. sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
  10. import cost_check
  11. import cost_raise
  12. ROOT = Path(__file__).resolve().parents[1]
  13. # Tests that need a known lifecycle state (stage-1 current, stage-2 planned) use a frozen
  14. # copy of approved.json, so advancing the real file's current phase does not break them.
  15. FIXTURE_STAGE1 = ROOT / "tests/fixtures/approved_stage1_current.json"
  16. GIT_ENV = {
  17. "GIT_AUTHOR_NAME": "t",
  18. "GIT_AUTHOR_EMAIL": "t@example.invalid",
  19. "GIT_COMMITTER_NAME": "t",
  20. "GIT_COMMITTER_EMAIL": "t@example.invalid",
  21. }
  22. def copy_repo(dest):
  23. for rel in ("docs/stages/approved.json", "docs/cost-prices.json", "docs/cost-prices"):
  24. src, dst = ROOT / rel, dest / rel
  25. dst.parent.mkdir(parents=True, exist_ok=True)
  26. if src.is_dir():
  27. shutil.copytree(src, dst)
  28. else:
  29. shutil.copy(src, dst)
  30. shutil.copy(FIXTURE_STAGE1, dest / "docs/stages/approved.json")
  31. for rel in ("stacks", "modules", ".spacelift"):
  32. if (ROOT / rel).exists():
  33. shutil.copytree(
  34. ROOT / rel, dest / rel, ignore=shutil.ignore_patterns(".terraform")
  35. )
  36. (dest / "scripts").mkdir(exist_ok=True)
  37. for name in ("cost_check.py", "ci_cost_gate.sh"):
  38. shutil.copy(ROOT / "scripts" / name, dest / "scripts" / name)
  39. def sh(*cmd, cwd, env=None, check=True):
  40. full = {**os.environ, **GIT_ENV, **(env or {})}
  41. return subprocess.run(cmd, cwd=cwd, env=full, capture_output=True, text=True, check=check)
  42. @pytest.fixture
  43. def clones(tmp_path):
  44. """(base repo = the remote, pr = a clone of it)."""
  45. base = tmp_path / "base"
  46. base.mkdir()
  47. copy_repo(base)
  48. sh("git", "init", "-q", "-b", "main", cwd=base)
  49. sh("git", "add", "-A", cwd=base)
  50. sh("git", "commit", "-q", "-m", "base", cwd=base)
  51. pr = tmp_path / "pr"
  52. sh("git", "clone", "-q", "--depth=1", f"file://{base}", str(pr), cwd=tmp_path)
  53. return base, pr
  54. def run_gate(pr, **env):
  55. full = {"PYTHON": sys.executable, "GITHUB_EVENT_NAME": "pull_request", "GITHUB_BASE_REF": "main"}
  56. full.update(env)
  57. return sh("bash", "scripts/ci_cost_gate.sh", cwd=pr, env=full, check=False)
  58. def edit_approved(pr, mutate):
  59. path = pr / "docs/stages/approved.json"
  60. data = json.loads(path.read_text())
  61. mutate(data)
  62. path.write_text(json.dumps(data, indent=2) + "\n")
  63. def test_an_unchanged_pull_request_passes_and_names_the_base(clones):
  64. _, pr = clones
  65. out = run_gate(pr)
  66. assert out.returncode == 0, out.stderr
  67. assert "comparing with main" in out.stdout
  68. def test_a_pull_request_that_raises_the_effective_ceiling_is_flagged(clones):
  69. _, pr = clones
  70. def mutate(d):
  71. d["phases"]["stage-2"]["status"] = "current"
  72. d["phases"]["stage-1"]["status"] = "done"
  73. d["current_phase"] = "stage-2"
  74. d["phases"]["stage-2"]["ceiling"] = 36.0
  75. for later in ("stage-3", "stage-4", "aws-twin", "edge", "second-site", "learner-soc"):
  76. d["phases"][later]["ceiling"] = max(d["phases"][later]["ceiling"], 36.0)
  77. edit_approved(pr, mutate)
  78. out = run_gate(pr)
  79. assert out.returncode == 0, out.stderr
  80. assert "EFFECTIVE CEILING CHANGED: phase stage-1 $30.00 -> phase stage-2 $36.00" in out.stdout
  81. def test_deleting_the_current_phase_while_raising_later_ones_fails(clones):
  82. _, pr = clones
  83. def mutate(d):
  84. del d["phases"]["stage-1"]
  85. d["phases"]["stage-2"]["status"] = "current"
  86. d["current_phase"] = "stage-2"
  87. for key in ("stage-2", "stage-3", "stage-4", "aws-twin", "edge", "second-site"):
  88. d["phases"][key]["ceiling"] = 60.0
  89. edit_approved(pr, mutate)
  90. out = run_gate(pr)
  91. assert out.returncode == 1
  92. assert "stage-1 (current) may not be removed" in out.stderr
  93. assert "EFFECTIVE CEILING CHANGED: phase stage-1 $30.00 -> phase stage-2 $60.00" in out.stdout
  94. def test_a_planted_done_phase_fails_with_and_without_a_base(clones):
  95. _, pr = clones
  96. def mutate(d):
  97. phases = {}
  98. for key, value in d["phases"].items():
  99. if key == "stage-1":
  100. phases["reserve"] = {
  101. "ceiling": 60.0, "reason": "reserve", "decided": "2026-10-10", "status": "done",
  102. } # fmt: skip
  103. value["lowers"] = True
  104. phases[key] = value
  105. d["phases"] = phases
  106. edit_approved(pr, mutate)
  107. data = json.loads((pr / "docs/stages/approved.json").read_text())
  108. assert any("above the current ceiling" in p for p in cost_check.phase_problems(data))
  109. out = run_gate(pr)
  110. assert out.returncode == 1
  111. def test_a_fetch_failure_fails_closed(clones):
  112. _, pr = clones
  113. out = run_gate(pr, CAH_BASE_REMOTE="no-such-remote")
  114. assert out.returncode == 1 and "FAIL: could not fetch" in out.stderr
  115. def test_a_pull_request_without_a_base_ref_fails_closed(clones):
  116. _, pr = clones
  117. out = run_gate(pr, GITHUB_BASE_REF="")
  118. assert out.returncode == 1 and "GITHUB_BASE_REF" in out.stderr
  119. def test_a_base_without_the_file_fails_closed(clones):
  120. base, pr = clones
  121. sh("git", "rm", "-q", "docs/stages/approved.json", cwd=base)
  122. sh("git", "commit", "-q", "-m", "drop", cwd=base)
  123. out = run_gate(pr)
  124. assert out.returncode == 1 and "has no docs/stages/approved.json" in out.stderr
  125. def test_other_events_run_the_plain_gate_and_say_why(clones):
  126. _, pr = clones
  127. out = run_gate(pr, GITHUB_EVENT_NAME="push", GITHUB_BASE_REF="")
  128. assert out.returncode == 0, out.stderr
  129. assert "lifecycle check skipped" in out.stdout
  130. def test_other_events_still_fail_a_bad_file(clones):
  131. _, pr = clones
  132. edit_approved(pr, lambda d: d.update(current_phase="gone"))
  133. assert run_gate(pr, GITHUB_EVENT_NAME="push").returncode == 1
  134. def test_ci_runs_this_script_not_the_bare_gate():
  135. text = (ROOT / ".github/workflows/ci.yml").read_text()
  136. line = next(x for x in text.splitlines() if "test-command:" in x)
  137. assert "bash scripts/ci_cost_gate.sh" in line
  138. assert "scripts/cost_check.py" not in line
  139. # --- the base-aware rules, in process ---------------------------------------------
  140. def real():
  141. return json.loads(FIXTURE_STAGE1.read_text())
  142. @pytest.mark.parametrize("key", ["stage-0", "stage-1", "stage-2", "learner-soc"])
  143. def test_no_base_phase_of_any_status_may_be_removed(key):
  144. new = real()
  145. del new["phases"][key]
  146. assert any(f"phase {key}" in p and "may not be removed" in p for p in cost_check.transition_problems(real(), new))
  147. def test_the_base_current_phase_may_only_stay_current_or_become_done():
  148. for bad in ("planned",):
  149. new = real()
  150. new["phases"]["stage-1"]["status"] = bad
  151. assert cost_check.transition_problems(real(), new)
  152. new = real()
  153. new["phases"]["stage-1"]["status"] = "done"
  154. new["phases"]["stage-2"]["status"] = "current"
  155. new["current_phase"] = "stage-2"
  156. assert cost_check.transition_problems(real(), new) == []
  157. def test_a_done_phase_above_the_live_ceiling_fails_on_one_file():
  158. d = real()
  159. d["phases"]["stage-0"]["ceiling"] = 31.0
  160. assert any("stage-0: done at $31.00" in p for p in cost_check.phase_problems(d))
  161. def test_a_done_phase_at_or_below_the_live_ceiling_is_fine():
  162. assert cost_check.phase_problems(real()) == []
  163. # --- huge integers ----------------------------------------------------------------
  164. @pytest.mark.parametrize("bad", [10**400, -(10**400)])
  165. def test_a_huge_integer_is_a_controlled_rejection(bad):
  166. with pytest.raises(ValueError):
  167. cost_check.money(bad, "x")
  168. with pytest.raises(ValueError):
  169. cost_check.num(bad, "x")
  170. d = real()
  171. d["phases"]["stage-3"]["ceiling"] = bad
  172. assert any("stage-3" in p for p in cost_check.phase_problems(d))
  173. assert any("hard_max" in p for p in cost_check.phase_problems({**real(), "hard_max": bad}))
  174. def test_a_huge_integer_approval_fails_the_gate_without_a_traceback(tmp_path, capsys):
  175. copy_repo(tmp_path)
  176. path = tmp_path / "docs/stages/approved.json"
  177. text = path.read_text().replace('"approved_monthly_total": 12.0', '"approved_monthly_total": 1' + "0" * 400)
  178. path.write_text(text)
  179. code = cost_check.main(["--root", str(tmp_path)])
  180. assert code == 1
  181. assert "Traceback" not in capsys.readouterr().err
  182. def test_cost_raise_survives_a_huge_integer_in_the_file(tmp_path, capsys):
  183. copy_repo(tmp_path)
  184. path = tmp_path / "docs/stages/approved.json"
  185. path.write_text(path.read_text().replace('"approved_monthly_total": 12.0', '"approved_monthly_total": 1' + "0" * 400))
  186. args = [
  187. "--root", str(tmp_path), "--phase", "stage-3", "--ceiling", "36", "--reason", "r",
  188. "--decided", "2026-10-17", "--cascade", "--write",
  189. ] # fmt: skip
  190. assert cost_raise.main(args) == 1
  191. # --- cost_raise holds the lock across validation and rechecks every input ----------------
  192. def args_for(root):
  193. return [
  194. "--root", str(root), "--phase", "stage-3", "--ceiling", "36", "--reason", "r",
  195. "--decided", "2026-10-17", "--cascade", "--write",
  196. ] # fmt: skip
  197. @pytest.mark.parametrize(
  198. "rel,payload",
  199. [
  200. ("stacks/10-access/cost.json", None),
  201. ("docs/cost-prices.json", None),
  202. ("stacks/10-access/zz.tf", "# new\n"),
  203. (".spacelift/config.yml", None),
  204. ],
  205. )
  206. def test_a_gate_input_changed_during_validation_blocks_the_write(
  207. tmp_path, capsys, monkeypatch, rel, payload
  208. ):
  209. copy_repo(tmp_path)
  210. approved = tmp_path / "docs/stages/approved.json"
  211. before = approved.read_text()
  212. real_gate = cost_raise.gate_problems
  213. def touch_while_validating(gate, root, doc):
  214. out = real_gate(gate, root, doc)
  215. target = root / rel
  216. if payload is None:
  217. target.write_text(target.read_text() + "\n")
  218. else:
  219. target.write_text(payload)
  220. return out
  221. monkeypatch.setattr(cost_raise, "gate_problems", touch_while_validating)
  222. assert cost_raise.main(args_for(tmp_path)) == 1
  223. assert "changed while the change was being checked" in capsys.readouterr().err
  224. assert approved.read_text() == before
  225. def test_the_directory_lock_is_held_during_validation(tmp_path, monkeypatch):
  226. import fcntl
  227. copy_repo(tmp_path)
  228. real_gate = cost_raise.gate_problems
  229. seen = {}
  230. def probe(gate, root, doc):
  231. fd = os.open(root / "docs/stages", os.O_RDONLY)
  232. try:
  233. try:
  234. fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  235. seen["held"] = False
  236. except BlockingIOError:
  237. seen["held"] = True
  238. finally:
  239. os.close(fd)
  240. return real_gate(gate, root, doc)
  241. monkeypatch.setattr(cost_raise, "gate_problems", probe)
  242. assert cost_raise.main(args_for(tmp_path)) == 0
  243. assert seen == {"held": True}
  244. def test_a_dry_run_does_not_take_the_lock(tmp_path, monkeypatch):
  245. copy_repo(tmp_path)
  246. monkeypatch.setattr(
  247. cost_raise, "locked", lambda d: (_ for _ in ()).throw(AssertionError("locked"))
  248. )
  249. args = args_for(tmp_path)
  250. args.remove("--write")
  251. assert cost_raise.main(args) == 0
  252. def test_inputs_digest_changes_with_any_gate_input(tmp_path):
  253. copy_repo(tmp_path)
  254. first = cost_raise.inputs_digest(tmp_path)
  255. assert cost_raise.inputs_digest(tmp_path) == first
  256. (tmp_path / "modules/zz.tf").write_text("x\n")
  257. assert cost_raise.inputs_digest(tmp_path) != first