Coverage for src/keel/finish.py: 100%

91 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-10-20 19:17 +0000

1"""``keel finish`` decision logic — pure. 

2 

3``keel finish`` chains steps keel already has (``review``, the CI wait, ``ship`` and 

4``merge``); it adds no new refusal and removes none. This module holds only the part that is 

5a *decision* — which steps run, what a CI snapshot means for the wait, how the timeout is 

6accounted — so it can be tested without a clock, a network or a subprocess. The I/O (the 

7polling loop, the ``gh`` calls, the sub-command invocations) is in :mod:`keel.cli`. 

8 

9Two properties are deliberate: 

10 

11* **A timeout is a timeout.** :func:`ci_decision` answers ``timeout`` once the elapsed time 

12 reaches the budget while checks are still pending; nothing here turns it into ``proceed``. 

13* **No bypass.** The argv builders never emit ``--hotfix``, ``--no-checkpoint-gate`` or 

14 ``--operator-override``; the steps run with exactly the refusals they have on their own. 

15""" 

16 

17from __future__ import annotations 

18 

19import math 

20from collections.abc import Sequence 

21 

22SCHEMA_VERSION = "keel.finish.v1" 

23 

24STEP_REVIEW = "review" 

25STEP_CI = "ci" 

26STEP_WINDOW = "window" 

27STEP_SHIP = "ship" 

28STEP_MERGE = "merge" 

29 

30ACTION_PROCEED = "proceed" 

31ACTION_WAIT = "wait" 

32ACTION_RERUN = "rerun" 

33ACTION_FAILED = "failed" 

34ACTION_TIMEOUT = "timeout" 

35 

36#: Consecutive unreadable CI snapshots tolerated before the wait gives up. One dropped 

37#: request during a thirty-minute wait must not end it; a host that cannot be read at all 

38#: must not be waited on for the whole budget either. 

39MAX_READ_FAILURES = 3 

40 

41_STEP_DESCRIPTIONS = { 

42 STEP_REVIEW: "post the supplied review verdicts (keel review --live)", 

43 STEP_CI: "wait for CI on the head, bounded by --ci-timeout", 

44 STEP_WINDOW: "stop if the merge window is closed (no bypass)", 

45 STEP_SHIP: "record the gates-pass ledger entry (keel ship --live --append-ledger)", 

46 STEP_MERGE: "merge through the evidence gate (keel merge)", 

47} 

48 

49 

50def plan_steps(*, reviews: bool, rerun: Sequence[str] = ()) -> list[dict[str, object]]: 

51 """The ordered steps of one finish, each ``{name, description}``. 

52 

53 ``review`` is present only when reviews were supplied. Reviews go first so they are 

54 posted while CI is still running rather than after it. 

55 """ 

56 names = [STEP_REVIEW] if reviews else [] 

57 names += [STEP_CI, STEP_WINDOW, STEP_SHIP, STEP_MERGE] 

58 steps: list[dict[str, object]] = [] 

59 for name in names: 

60 step: dict[str, object] = { 

61 "name": name, 

62 "step": name, 

63 "description": _STEP_DESCRIPTIONS[name], 

64 } 

65 if name == STEP_CI and rerun: 

66 step["rerun_flaky"] = list(rerun) 

67 steps.append(step) 

68 return steps 

69 

70 

71def next_sleep(interval: float, timeout: float, elapsed: float) -> float: 

72 """How long to sleep before the next poll: the interval, never past the deadline.""" 

73 return max(0.0, min(interval, timeout - elapsed)) 

74 

75 

76def poll_cap(timeout: float, interval: float) -> int: 

77 """An upper bound on polls, independent of the clock. 

78 

79 The wait loop is bounded by elapsed time, and *also* by this count, so a clock that 

80 does not advance (a stubbed one, a suspended machine) cannot make it spin forever. 

81 """ 

82 return math.ceil(timeout / interval) + 3 

83 

84 

85def read_failures_exhausted(consecutive: int) -> bool: 

86 return consecutive >= MAX_READ_FAILURES 

87 

88 

89def _names(value: object) -> list[str]: 

90 return [str(n) for n in value] if isinstance(value, list) else [] 

91 

92 

93def ci_decision( 

94 ci: object, 

95 *, 

96 elapsed: float, 

97 timeout: float, 

98 rerun: Sequence[str] = (), 

99 reran: Sequence[str] = (), 

100 settling: Sequence[str] = (), 

101 settle: float = 0, 

102) -> dict[str, object]: 

103 """What one CI snapshot means for the wait: ``{action, names}``. 

104 

105 ``ci`` is the rollup state :func:`keel.cli._ci_rollup_state` returns. ``rerun`` names the 

106 checks the operator allowed to be rerun once, ``reran`` those already rerun, and 

107 ``settling`` those rerun within the settle window: GitHub can keep showing the old 

108 failure for a while after a rerun is requested, and that stale failure must be waited out 

109 rather than read as the rerun failing. ``settle`` is the grace, in seconds, an empty 

110 rollup is waited on before it is accepted as "no checks". 

111 """ 

112 ci = ci if isinstance(ci, dict) else {} 

113 state = ci.get("state") 

114 if state == "pass": 

115 return {"action": ACTION_PROCEED, "names": []} 

116 if state == "no-checks": 

117 # Right after a push the rollup is empty until the workflows register, which is when 

118 # finish is usually run. An empty set is waited on for `settle` seconds (never past 

119 # the timeout) before it is taken as a genuinely check-less pull request; whether 

120 # that is acceptable (docs-only) is then the merge gate's call, not the wait's. 

121 if elapsed < settle and elapsed < timeout: 

122 return {"action": ACTION_WAIT, "names": []} 

123 return {"action": ACTION_PROCEED, "names": []} 

124 if state == "fail": 

125 failing = _names(ci.get("failing_checks")) 

126 if not failing: 

127 # A failing state that names nothing is still a failure, not a wait. 

128 return {"action": ACTION_FAILED, "names": []} 

129 real = [n for n in failing if n not in settling] 

130 if not real: 

131 return _wait_or_timeout(failing, elapsed, timeout) 

132 allowed = [n for n in real if n in rerun and n not in reran] 

133 if len(allowed) == len(real): 

134 pending = _names(ci.get("pending_checks")) 

135 if pending: 

136 # `gh run rerun --failed` is refused while the run still has jobs in 

137 # flight, and the snapshot does not say which run a pending check is in. 

138 # So the rerun waits until nothing is pending (within the budget). 

139 return _wait_or_timeout(pending, elapsed, timeout) 

140 return {"action": ACTION_RERUN, "names": allowed} 

141 return {"action": ACTION_FAILED, "names": real} 

142 return _wait_or_timeout(_names(ci.get("pending_checks")), elapsed, timeout) 

143 

144 

145def _wait_or_timeout(names: list[str], elapsed: float, timeout: float) -> dict[str, object]: 

146 if elapsed >= timeout: 

147 return {"action": ACTION_TIMEOUT, "names": names} 

148 return {"action": ACTION_WAIT, "names": names} 

149 

150 

151def consent_argv( 

152 approve_scope: Sequence[str], operator: str | None, consent_mode: str | None 

153) -> list[str]: 

154 """The consent flags every step is given, so one approval covers the whole finish.""" 

155 argv: list[str] = [] 

156 for scope in approve_scope: 

157 argv += ["--approve-scope", scope] 

158 if operator: 

159 argv += ["--operator", operator] 

160 if consent_mode: 

161 argv += ["--consent-mode", consent_mode] 

162 return argv 

163 

164 

165def review_argv( 

166 *, 

167 path: str, 

168 root: str, 

169 pr: int, 

170 issue: int | None, 

171 reviews: str, 

172 closure: str | None, 

173 consent: Sequence[str], 

174) -> list[str]: 

175 argv = ["review", path, "--root", root, "--pr", str(pr), "--reviews", reviews, "--live"] 

176 if issue is not None: 

177 argv += ["--issue", str(issue)] 

178 if closure: 

179 argv += ["--closure", closure] 

180 return argv + list(consent) 

181 

182 

183def ship_argv( 

184 *, 

185 path: str, 

186 root: str, 

187 pr: int, 

188 issue: int, 

189 branch: str | None = None, 

190 head_sha: str | None = None, 

191 run_id: str | None, 

192 capture_status: str | None, 

193 capture_reason: str | None, 

194 capture_artifact: str | None, 

195 implementer: str | None, 

196 consent: Sequence[str], 

197) -> list[str]: 

198 argv = ["ship", path, "--root", root, "--pr", str(pr), "--issue", str(issue)] 

199 argv += ["--live", "--append-ledger"] 

200 for flag, value in ( 

201 ("--branch", branch), 

202 ("--head-sha", head_sha), 

203 ("--run-id", run_id), 

204 ("--capture-status", capture_status), 

205 ("--capture-reason", capture_reason), 

206 ("--capture-artifact", capture_artifact), 

207 ("--implementer", implementer), 

208 ): 

209 if value: 

210 argv += [flag, value] 

211 return argv + list(consent) 

212 

213 

214def merge_argv( 

215 *, 

216 path: str, 

217 root: str, 

218 pr: int, 

219 issue: int, 

220 method: str, 

221 transport: str, 

222 run_id: str | None, 

223 consent: Sequence[str], 

224) -> list[str]: 

225 argv = ["merge", path, "--root", root, "--pr", str(pr), "--issue", str(issue)] 

226 argv += ["--method", method, "--transport", transport] 

227 if run_id: 

228 argv += ["--run-id", run_id] 

229 return argv + list(consent)