Coverage for packages/workshop/src/livery/workshop/_verdict.py: 94%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_release_point.py, packages/workshop/tests/test_workshop_release_fresh.py, packages/workshop/tests/test_workshop_release_driver.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_balance.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_cross_kind.py ran.

1"""Where a branch's pull request stands, as one plain answer.
2
3One read of the forge plus two local git probes, folded into a
4livery.workshop._verdict.Verdict that names the state and the exit
5code a caller branches on. The codes are stable interface: skills,
6hooks, and humans read them, so a new state gets a new code, never a
7reused one.
8
9Exit codes:
10 10: the merge would conflict; integrate the base and re-submit.
11 11: nothing will merge it; the pull request is not armed.
12 12: the pull request is closed unmerged.
13 13: CI is red; the message names the failing job.
14 14: still in flight when the watch deadline passed.
15 15: the forge was unreachable past the transient budget.
16 16: green and armed with no merge; the server lost the evaluation.
17 17: the head is behind the base; integrate and re-submit.
18
19A required-review blocker is not an error: readable protection with
20approvals outstanding reads as ``awaiting-approvals``, exit 0, and
21the message names the missing count and the eligible reviewers.
22Protection the token cannot read is never asserted as a blocker; the
23pull request reads as 16 and the message says what to check.
24"""
25
26from __future__ import annotations
27
28import time
29from collections.abc import Callable
30from dataclasses import dataclass
31from pathlib import Path
32from typing import TypeVar
33
34import livery.footman as footman
35from livery import git
36from livery.forge import (
37 CombinedStatus,
38 ForgeError,
39 Job,
40 PullRequest,
41 RateBudget,
42 RateLimited,
43 Repository,
44 Run,
45 classify_merge_refusal,
46)
47
48EXIT_CONFLICTS = 10
49EXIT_DISARMED = 11
50EXIT_CLOSED = 12
51EXIT_CI_FAILED = 13
52EXIT_TIMEOUT = 14
53EXIT_UNREACHABLE = 15
54EXIT_STALLED = 16
55EXIT_BEHIND = 17
56#: ``ci.status``'s exit while the head's runs are still moving, or
57#: none has started: the state a script waits on.
58EXIT_PENDING = 18
59
60#: Consecutive unreadable polls before a watch gives up with 15.
61_UNREACHABLE_BUDGET = 5
62
63
64#: The share of the forge's API budget below which a watch slows its
65#: polling, so one long watch never spends what every other caller needs.
66LOW_BUDGET = 0.2
67
68#: About how many requests one poll of a watch makes: the pull request,
69#: its checks and their jobs.
70REQUESTS_PER_POLL = 10
71
72#: How long a watch waits when the forge refuses with no reset time.
73UNSAID_RESET = 60.0
74
75
76def paced(interval: float, budget: RateBudget | None, *, now: float) -> float:
77 """The seconds to wait before the next poll, given what is left of the budget.
78
79 *interval* while the budget is ample or unknown. Below
80 [livery.workshop._verdict.LOW_BUDGET] of it, the polls left are
81 spread over the time until it renews, so the watch never spends it.
82 """
83 if budget is None or budget.limit <= 0 or budget.reset_at is None:
84 return interval
85 if budget.remaining >= budget.limit * LOW_BUDGET:
86 return interval
87 polls = max(budget.remaining // REQUESTS_PER_POLL, 1)
88 return max(interval, (budget.reset_at - now) / polls)
89
90
91def _duration(seconds: float) -> str:
92 """*seconds* as a person reads a wait: seconds under two minutes, minutes above."""
93 if seconds < 120:
94 return f"{seconds:.0f}s"
95 return f"{seconds / 60:.0f} min"
96
97
98def wait_for_reset(error: RateLimited, *, now: float) -> float:
99 """The seconds a watch waits for a spent budget: until it returns, and a margin."""
100 if error.reset_at is None:
101 return UNSAID_RESET
102 return max(error.reset_at - now, 0.0) + 5.0
103
104
105class Pace:
106 """A watch's waits between polls of the forge.
107
108 The interval while the API budget is ample; slower while it is low
109 ([livery.workshop._verdict.paced][]), said once; and a spent budget
110 waited out until it returns, said with the forge's own refusal.
111 """
112
113 def __init__(
114 self, interval: float, *, sleep: Callable[[float], None] | None = None
115 ) -> None:
116 """Pace polls *interval* seconds apart while the budget allows.
117
118 Args:
119 interval: Seconds between polls while the budget is ample.
120 sleep: What waits; `time.sleep` when None, looked up at
121 each wait.
122 """
123 self.interval = interval
124 self._sleep = sleep
125 self._slowed = False
126
127 def _wait(self, seconds: float) -> None:
128 """Wait *seconds* with the sleep this pace was given."""
129 (time.sleep if self._sleep is None else self._sleep)(seconds)
130
131 def rest(self, repo: Repository) -> None:
132 """Sleep until the next poll, slowed while *repo*'s forge budget is low."""
133 wait = paced(self.interval, repo.rate_budget(), now=time.time())
134 slowed = wait > self.interval
135 if slowed and not self._slowed:135 ↛ 136line 135 didn't jump to line 136 because the condition on line 135 was never true
136 print(
137 f" the forge's API budget is low; polling every {wait:.0f}s"
138 " until it renews"
139 )
140 self._slowed = slowed
141 self._wait(wait)
142
143 def wait_out(self, error: RateLimited) -> float:
144 """Sleep until a spent budget returns; the seconds waited.
145
146 A caller with a deadline moves it by the wait: the forge's
147 budget, not the work being watched, took the time.
148 """
149 wait = wait_for_reset(error, now=time.time())
150 print(f" {error}; waiting {_duration(wait)}, then watching again")
151 self._wait(wait)
152 return wait
153
154
155class Transient:
156 """A bounded run of unreadable polls: each printed once, the budget ends it.
157
158 A transport error during a poll is a retry, not a verdict: the
159 server dropped a connection, answered 5xx, or timed out, and the
160 next poll may answer. `note` prints the error with its place in
161 the run and returns True when the run has reached the budget;
162 `reset` is the answered poll that ends the run. `giving_up` is
163 the last line a watcher prints before exiting 15.
164
165 Attributes:
166 budget: The consecutive failures the watcher tolerates.
167 interval: The seconds between polls, for the line that says
168 how long the forge was unreachable.
169 count: The failures in the current run.
170 last: The last error's words.
171 """
172
173 def __init__(self, *, budget: int = _UNREACHABLE_BUDGET, interval: float = 15):
174 self.budget = budget
175 self.interval = interval
176 self.count = 0
177 self.last = ""
178
179 def note(self, error: Exception) -> bool:
180 """Print *error* as one failure of the run; True when the run is spent."""
181 self.count += 1
182 self.last = str(error)
183 print(f" forge unreachable ({self.count}/{self.budget}): {error}")
184 return self.count >= self.budget
185
186 def reset(self) -> None:
187 """An answered poll ends the run."""
188 self.count = 0
189
190 def giving_up(self, subject: str) -> str:
191 """The line for a spent budget: how long, the last error, and *subject*."""
192 seconds = self.budget * self.interval
193 return (
194 f" giving up: the forge was unreachable for {self.budget} consecutive"
195 f" polls ({seconds:.0f}s at {self.interval:.0f}s); last error:"
196 f" {self.last}; {subject}"
197 )
198
199
200@dataclass(frozen=True)
201class Pending:
202 """What one poll answers while the thing followed is not there yet.
203
204 Attributes:
205 line: The line the follow prints when the state changes, and
206 again at its quiet cadence while the state holds; empty
207 prints nothing.
208 key: What tells one pending state from another; the line
209 when empty.
210 """
211
212 line: str = ""
213 key: str = ""
214
215 @property
216 def state(self) -> str:
217 """The key, or the line when no key was given."""
218 return self.key or self.line
219
220
221class FollowTimedOut(Exception):
222 """A follow reached its deadline with the thing followed still pending.
223
224 Attributes:
225 subject: What was followed, in the caller's words.
226 timeout: The seconds the follow waited.
227 last: The last pending answer, for the caller's own line.
228 """
229
230 def __init__(self, subject: str, timeout: float, last: Pending) -> None:
231 super().__init__(f"{subject}: still pending after {timeout:.0f}s")
232 self.subject = subject
233 self.timeout = timeout
234 self.last = last
235
236
237class ForgeUnreachable(Exception):
238 """A follow spent its transient budget on unreadable polls.
239
240 Attributes:
241 line: The giving-up line, how long and the last error, for the
242 caller to print before it exits 15 or fails.
243 error: The last error.
244 """
245
246 def __init__(self, line: str, error: Exception) -> None:
247 super().__init__(line.strip())
248 self.line = line
249 self.error = error
250
251
252_T = TypeVar("_T")
253
254
255def follow(
256 repo: Repository | None,
257 read: Callable[[], _T | Pending],
258 *,
259 subject: str | Callable[[], str],
260 interval: float = 15,
261 timeout: float | None = 1800,
262 quiet: float | None = 60,
263 transient: Transient | None = None,
264 retried: tuple[type[Exception], ...] = (ForgeError,),
265 clock: Callable[[], float] | None = None,
266 sleep: Callable[[float], None] | None = None,
267) -> _T:
268 """Poll *read* until it answers: the one wait on the forge.
269
270 *read* returns the answer, or a [livery.workshop._verdict.Pending][]
271 while there is none yet. The follow prints a pending line when its
272 state changes and again every *quiet* seconds while it holds
273 (``None`` prints on change alone), rests *interval* seconds between
274 polls, slower while *repo*'s API budget is low, and waits out a
275 spent budget, moving the deadline by the wait. An error of a
276 *retried* type is a retry within *transient*'s budget; a run of
277 them that spends it raises
278 [livery.workshop._verdict.ForgeUnreachable][] with the giving-up
279 line. The deadline, *timeout* seconds from the start, raises
280 [livery.workshop._verdict.FollowTimedOut][]; ``None`` waits as long
281 as the caller's own timeout allows. Without a *repo* the rests are
282 plain sleeps. The deadline and the quiet cadence read *clock*, and
283 every wait goes through *sleep*, so a caller that passes both
284 decides how much time each poll takes.
285
286 Args:
287 repo: The repository polled, for its rate budget; None for a
288 wait on something that is not a forge.
289 read: One poll: the answer, or a pending state.
290 subject: What is followed, for the giving-up and timeout
291 lines; a callable is asked only when a line needs it.
292 interval: Seconds between polls.
293 timeout: Seconds until the follow gives up, or None for none.
294 quiet: Seconds after which a held pending line prints again.
295 transient: The budget for unreadable polls; a fresh one at
296 *interval* when None, shared across calls when given.
297 retried: The exception types a poll may raise and be retried.
298 clock: Seconds from a fixed start; `time.monotonic` when None.
299 sleep: What waits between polls; `time.sleep` when None.
300
301 Returns:
302 What *read* answered.
303
304 Raises:
305 FollowTimedOut: The deadline passed with *read* still pending.
306 ForgeUnreachable: *read* raised a retried error past the budget.
307 """
308 now_of = time.monotonic if clock is None else clock
309 pause = time.sleep if sleep is None else sleep
310 started = now_of()
311 deadline = None if timeout is None else started + timeout
312 if transient is None:
313 transient = Transient(interval=interval)
314 pace = Pace(interval, sleep=pause)
315 last = Pending()
316 printed_at: float | None = None
317 while True:
318 try:
319 answer = read()
320 except RateLimited as exc:
321 waited = pace.wait_out(exc)
322 if deadline is not None:322 ↛ 324line 322 didn't jump to line 324 because the condition on line 322 was always true
323 deadline += waited
324 continue
325 except retried as exc:
326 if transient.note(exc):
327 words = subject if isinstance(subject, str) else subject()
328 raise ForgeUnreachable(transient.giving_up(words), exc) from exc
329 pause(interval)
330 continue
331 transient.reset()
332 if not isinstance(answer, Pending):
333 return answer
334 now = now_of()
335 held = (
336 quiet is not None and printed_at is not None and now - printed_at >= quiet
337 )
338 if answer.line and (printed_at is None or answer.state != last.state or held):
339 print(answer.line)
340 printed_at = now
341 last = answer
342 if deadline is not None and now >= deadline:
343 words = subject if isinstance(subject, str) else subject()
344 raise FollowTimedOut(words, timeout or 0.0, answer)
345 if repo is not None:
346 pace.rest(repo)
347 else:
348 pause(interval)
349
350
351#: Green-and-armed polls the watch grants the server to merge before
352#: probing for behind/conflicts and calling the evaluation lost.
353#: Forge evidence (livery PR #35): github.com's auto-merge can take
354#: over a minute after green, and three 15s polls declared it stalled
355#: 25 seconds before the merge landed.
356_MERGE_GRACE_POLLS = 8
357
358#: A blocker ends the watch only after holding this many
359#: consecutive polls (closed excepted): one-poll blips are races,
360#: not verdicts.
361_CONFIRM_POLLS = 2
362
363
364@dataclass(frozen=True)
365class Verdict:
366 """One reading of where a branch's pull request stands.
367
368 Attributes:
369 state: A short name: ``merged``, ``in-flight``, ``conflicts``,
370 ``disarmed``, ``closed``, ``ci-failed``, ``stalled``,
371 ``behind``, ``awaiting-approvals``, ``no-pr``.
372 exit_code: The stable code for the state; 0 when nothing is
373 wrong (``merged``, ``in-flight``, ``awaiting-approvals``,
374 ``no-pr``).
375 detail: One sentence for a person, naming the evidence.
376 pr_number: The pull request, when one exists.
377 """
378
379 state: str
380 exit_code: int
381 detail: str
382 pr_number: int = 0
383
384
385def _deciding_runs(runs: tuple[Run, ...]) -> tuple[Run, ...]:
386 """The runs that decide a commit: the newest run of each workflow at it.
387
388 A workflow that ran again at the same commit superseded its earlier
389 run, so a rehearsal dispatched by hand that failed and then passed,
390 or a red run re-run green, no longer counts against the commit.
391 """
392 newest: dict[str, Run] = {}
393 for run in runs:
394 held = newest.get(run.workflow)
395 if held is None or run.id > held.id:
396 newest[run.workflow] = run
397 return tuple(newest.values())
398
399
400def _failing_job(repo: Repository, head_sha: str) -> tuple[str, tuple[Run, ...]]:
401 """The first failing job among the runs that decide *head_sha*, and those runs.
402
403 A job carries its own conclusion while its run continues, so a red
404 leg is named the moment it ends, not when the last leg does. The
405 name is empty when no deciding run has failed: the red the forge
406 aggregates then belongs to a superseded run.
407 """
408 deciding = _deciding_runs(repo.checks.runs(head_sha=head_sha))
409 for run in deciding:
410 for job in repo.checks.jobs(run.id):
411 if job.conclusion in ("failure", "cancelled"):
412 tail = "" if run.conclusion else "; the run continues"
413 return f"{run.workflow}: {job.name} ({job.conclusion}){tail}", deciding
414 if run.conclusion in ("failure", "cancelled"):414 ↛ 415line 414 didn't jump to line 415 because the condition on line 414 was never true
415 return f"{run.workflow} ({run.conclusion})", deciding
416 return "", deciding
417
418
419def _published_conflict(
420 repo: Repository, root: Path, pr: PullRequest, status: CombinedStatus
421) -> str:
422 """The forge's own words for a pull request it cannot merge, or empty.
423
424 GitHub and GitLab publish a mergeability state beside the pull
425 request and start no run for one in conflict, so its combined
426 status stays ``none`` for as long as anyone waits. The local probe
427 can miss the conflict (a merge driver the forge ignores resolves it
428 here), so the forge's answer decides. Gitea publishes none.
429 """
430 from livery.workshop import _forge_lane
431
432 kind = _forge_lane.forge_kind(root)
433 if kind not in ("github", "gitlab"):
434 return ""
435 hold = repo.pr.merge_hold(pr.number)
436 if hold in ("", "clean", "mergeable"):436 ↛ 437line 436 didn't jump to line 437 because the condition on line 436 was never true
437 return ""
438 classified = classify_merge_refusal(
439 kind, "", combined=status, item_state=pr.state, merged=pr.merged, hold=hold
440 )
441 if classified.state != "conflict":441 ↛ 442line 441 didn't jump to line 442 because the condition on line 441 was never true
442 return ""
443 return f"{classified.message} (the forge reports {hold})"
444
445
446_GREEN_CONCLUSIONS = ("", "success", "skipped", "neutral")
447
448
449def elapsed_label(seconds: float) -> str:
450 """*seconds* as a person reads a wait: `37s`, `4m12s`, `1h02m`."""
451 whole = int(seconds)
452 if whole < 60:
453 return f"{whole}s"
454 if whole < 3600:
455 return f"{whole // 60}m{whole % 60:02d}s"
456 return f"{whole // 3600}h{whole % 3600 // 60:02d}m"
457
458
459class JobWatch:
460 """The jobs of a head's runs, reported as they move, each line stamped.
461
462 Each report reads every run for the head and the jobs of each,
463 prints one line per job whose status or conclusion changed since
464 the last report, and under a job that just failed the log's
465 failure lines, when the forge already has the log. A report that
466 finds nothing moved prints nothing. Every line opens with the time
467 since the watch began, so a log read later shows where the minutes
468 went; *clock* is the seam a test hands a clock of its own to.
469 """
470
471 def __init__(self, clock: Callable[[], float] = time.monotonic) -> None:
472 self.seen: dict[tuple[str, str], str] = {}
473 self._clock = clock
474 self._started = clock()
475
476 def stamp(self) -> str:
477 """The elapsed time since the watch began, padded for a line's head."""
478 return f" {elapsed_label(self._clock() - self._started):>6} "
479
480 def report(self, repo: Repository, head_sha: str) -> list[str]:
481 """Print and return the lines for what moved since the last report."""
482 lines: list[str] = []
483 if not head_sha:
484 return lines
485 for run in repo.checks.runs(head_sha=head_sha):
486 for job in repo.checks.jobs(run.id):
487 state = job.conclusion or job.status
488 key = (run.workflow, job.name)
489 if self.seen.get(key) == state:
490 continue
491 self.seen[key] = state
492 word = {"failure": "failed", "in_progress": "running"}.get(state, state)
493 stamp = self.stamp()
494 workflow = run.workflow.rsplit("/", 1)[-1]
495 lines.append(f"{stamp}{workflow} / {job.name}: {word}")
496 if job.conclusion not in _GREEN_CONCLUSIONS:
497 pad = " " * len(stamp)
498 lines += [pad + line for line in _failure_excerpt(repo, job)]
499 for line in lines:
500 print(line)
501 return lines
502
503
504def _failure_excerpt(repo: Repository, job: Job, *, limit: int = 12) -> list[str]:
505 """The failure lines of a job's log, falling back to structured diagnostics.
506
507 When the log is unavailable (a cancelled job that never acquired a
508 runner) or carries no failure marks, ``job.failure_reason`` and
509 check-run annotations (where supported) surface instead so a watch
510 explains the red or cancelled leg inline.
511 """
512 from livery.workshop._ci_tasks import (
513 _format_annotation,
514 _read_annotations,
515 failure_lines,
516 )
517
518 try:
519 log = repo.checks.job_log(job.id)
520 except ForgeError:
521 log = ""
522 lines = failure_lines(log, limit=limit) if log else []
523 if lines:
524 return lines
525 fallback: list[str] = []
526 if job.failure_reason:
527 fallback.append(f"failure reason: {job.failure_reason}")
528 for annotation in _read_annotations(repo, job.id):
529 fallback.extend(_format_annotation(annotation, indent=""))
530 return fallback[:limit]
531
532
533def _head_of(repo: Repository, branch: str, *, pr_number: int = 0) -> str:
534 """The pull request's head for *branch* (or *pr_number*), or empty without one."""
535 pr = repo.pr.get(pr_number) if pr_number else repo.pr.find_by_head(branch)
536 return pr.head_sha if pr is not None else ""
537
538
539def _probe_head(root: Path, pr: PullRequest, *, own: bool) -> str:
540 """The git ref local probes check against ``origin/<base>``, or empty.
541
542 On the pull request's own branch, HEAD is ground truth; from
543 another branch, the pull request's head commit is probed when the
544 clone holds it, and skipped when it does not (e.g. a fork branch).
545 """
546 if own:
547 return "HEAD"
548 return git.sha_of(root, pr.head_sha) or git.sha_of(root, f"origin/{pr.head_branch}")
549
550
551def classify(
552 repo: Repository,
553 branch: str,
554 root: Path,
555 *,
556 grace_spent: bool = False,
557 pr: PullRequest | None = None,
558) -> Verdict:
559 """One reading of the branch (or an explicit *pr*), named and coded.
560
561 *grace_spent* is the watcher's signal that a green-and-armed pull
562 request has already been given time to merge, so the local probes
563 (behind, conflicts) may now decide between 10, 16, and 17. A
564 single un-watched read never reports 16: the server may simply not
565 have evaluated yet.
566 """
567 from livery.workshop._forge_lane import pull_request_for
568
569 if pr is None:
570 pr = pull_request_for(repo, root, branch)
571 if pr is None:
572 return Verdict("no-pr", 0, f"no pull request for {branch}")
573 if pr.merged:
574 return Verdict("merged", 0, f"PR #{pr.number} merged", pr.number)
575 if pr.state == "closed":
576 return Verdict(
577 "closed",
578 EXIT_CLOSED,
579 f"PR #{pr.number} is closed unmerged; `{footman.prog()} submit`"
580 " after reopening,"
581 " or start over",
582 pr.number,
583 )
584 # The local head is ground truth for a verdict: right after a
585 # push the forge's pull request read can lag and still report
586 # the previous head, and a verdict on that head judges the
587 # commit the push replaced. In-flight until the forge catches
588 # up; a branch checked out elsewhere (submit.merge or a numbered
589 # status from another tree) matches by construction.
590 standing, head = git.position(root)
591 own = standing == branch
592 local_head = head if own else ""
593 if local_head and pr.head_sha != local_head:
594 return Verdict(
595 "in-flight",
596 0,
597 f"the forge still reports {pr.head_sha[:10]}; the local head"
598 f" is {local_head[:10]}",
599 pr.number,
600 )
601 status = repo.checks.status(pr.head_sha)
602 state = status.state
603 if state == "failure":
604 failing, deciding = _failing_job(repo, pr.head_sha)
605 if failing or not deciding:
606 return Verdict(
607 "ci-failed", EXIT_CI_FAILED, failing or "CI is red", pr.number
608 )
609 # The red the forge aggregates belongs to a superseded run: a
610 # workflow that ran again at this commit. The runs that decide
611 # are green or still moving, so they judge the commit.
612 moving = any(run.status != "completed" for run in deciding)
613 state = "pending" if moving else "success"
614 if state == "none":
615 # A pull request whose merge ref the forge cannot build gets no
616 # run at all, so its status stays none for as long as anyone
617 # waits. The conflict probe decides at once instead: exit 10,
618 # and the self-heal integrates and re-submits. The forge's
619 # published state decides where the local probe cannot see the
620 # conflict.
621 git.fetch(root)
622 probe = _probe_head(root, pr, own=own)
623 if probe and git.conflicts_with_base(root, pr.base_branch, head=probe):
624 return Verdict(
625 "conflicts",
626 EXIT_CONFLICTS,
627 f"PR #{pr.number} conflicts with {pr.base_branch}, so the forge"
628 " runs nothing for it",
629 pr.number,
630 )
631 published = _published_conflict(repo, root, pr, status)
632 if published:
633 return Verdict(
634 "conflicts",
635 EXIT_CONFLICTS,
636 f"PR #{pr.number} cannot merge into {pr.base_branch}, so the"
637 f" forge runs nothing for it: {published}",
638 pr.number,
639 )
640 if state in ("pending", "none"):
641 return Verdict("in-flight", 0, f"CI {state} for {pr.head_sha[:10]}", pr.number)
642 # Green. A conflict blocks the merge whatever the arming state, so
643 # it is classified first; behind matters only once an armed pull
644 # request has been given time, because without strict protection an
645 # armed behind head still merges.
646 git.fetch(root)
647 probe = _probe_head(root, pr, own=own)
648 if probe and git.conflicts_with_base(root, pr.base_branch, head=probe):
649 return Verdict(
650 "conflicts",
651 EXIT_CONFLICTS,
652 f"PR #{pr.number} conflicts with {pr.base_branch}",
653 pr.number,
654 )
655 if not repo.pr.is_armed(pr.number):
656 # Forge evidence (livery PR #21): a merge in flight consumes the
657 # schedule between the open-PR read and this one, so an armed
658 # merge can read as "green and not armed". Re-read before
659 # reporting: merged wins over any blocker derived from stale
660 # reads.
661 current = repo.pr.get(pr.number)
662 if current is not None and current.merged:
663 return Verdict("merged", 0, f"PR #{pr.number} merged", pr.number)
664 behind = git.behind_base(root, pr.base_branch, head=probe) if probe else 0
665 if behind:
666 # Without this, the parked answer says "merge it" while
667 # the merge verb refuses behindness, and the two point at
668 # each other with no exit.
669 return Verdict(
670 "disarmed",
671 EXIT_DISARMED,
672 f"PR #{pr.number} is green, parked unarmed, and {behind}"
673 f" commit(s) behind {pr.base_branch}:"
674 f" `{footman.prog()} integrate`, then"
675 f" `{footman.prog()} submit`, then merge",
676 pr.number,
677 )
678 return Verdict(
679 "disarmed",
680 EXIT_DISARMED,
681 f"PR #{pr.number} is green and parked unarmed; arm it with"
682 f" `{footman.prog()} submit --armed`, or merge it with"
683 f" `{footman.prog()} submit.merge`",
684 pr.number,
685 )
686 if not grace_spent:686 ↛ 687line 686 didn't jump to line 687 because the condition on line 686 was never true
687 return Verdict("in-flight", 0, "green and armed; awaiting the merge", pr.number)
688 if probe and git.behind_base(root, pr.base_branch, head=probe) > 0:
689 return Verdict(
690 "behind",
691 EXIT_BEHIND,
692 f"PR #{pr.number} is behind {pr.base_branch}, and protection"
693 " blocks outdated branches",
694 pr.number,
695 )
696 current = repo.pr.get(pr.number)
697 if current is not None and current.merged:697 ↛ 698line 697 didn't jump to line 698 because the condition on line 697 was never true
698 return Verdict("merged", 0, f"PR #{pr.number} merged", pr.number)
699 outstanding = _approvals_outstanding(
700 repo, pr.number, pr.base_branch, root, head=probe
701 )
702 if outstanding is not None:
703 return Verdict("awaiting-approvals", 0, outstanding, pr.number)
704 return Verdict(
705 "stalled",
706 EXIT_STALLED,
707 f"PR #{pr.number} is green and armed with no merge: the server lost"
708 " the evaluation (or a required review is missing)",
709 pr.number,
710 )
711
712
713def _approvals_outstanding(
714 repo: Repository,
715 number: int,
716 base: str,
717 root: Path,
718 *,
719 head: str = "HEAD",
720) -> str | None:
721 """The awaiting-approvals message, or None when reviews are not it.
722
723 Green and armed with reviews missing is nobody's error: the arm
724 survives, and the last approval merges it with nothing to
725 re-run. Answered only when protection is readable and actually
726 requires approvals the pull request does not have; an unreadable
727 protection stays with the stalled verdict's softer wording,
728 because a blocker must never be asserted from a state that could
729 not be read.
730 """
731 try:
732 protection = repo.protection(base)
733 except ForgeError:
734 return None
735 if protection is None or protection.required_approvals <= 0:
736 return None
737 try:
738 reviews = repo.pr.reviews(number)
739 details = repo.pr.get(number)
740 except ForgeError:
741 return None
742 approved = {r.author for r in reviews if r.state == "approved"}
743 needed = protection.required_approvals - len(approved)
744 if needed <= 0:744 ↛ 745line 744 didn't jump to line 745 because the condition on line 744 was never true
745 return None
746 author = details.author if details is not None else ""
747 eligible = _eligible_reviewers(root, base, head=head) - approved - {author}
748 who = ", ".join(sorted(eligible)) if eligible else "the declared owners"
749 plural = "approval" if needed == 1 else "approvals"
750 return (
751 f"green and armed, awaiting {needed} {plural}: {who} can give"
752 " them. The arm survives, so the last approval merges it with"
753 " nothing to re-run."
754 )
755
756
757def _eligible_reviewers(root: Path, base: str, *, head: str = "HEAD") -> set[str]:
758 """Owners of the touched paths, from the package declarations.
759
760 Best effort: an unreadable workspace answers empty and the
761 message falls back to naming the declared owners collectively.
762 """
763 if not head:763 ↛ 764line 763 didn't jump to line 764 because the condition on line 763 was never true
764 return set()
765 try:
766 from livery.workshop._governance import governance_entries
767
768 touched = git.run(
769 root, "diff", "--name-only", f"origin/{base}...{head}"
770 ).splitlines()
771 owners: set[str] = set()
772 for entry in governance_entries(root):
773 prefix = entry.path.strip("/")
774 if any(name.startswith(prefix) for name in touched if name):
775 owners.update(owner for owner in entry.owners if "/" not in owner)
776 return owners
777 except Exception:
778 return set()
779
780
781def follow_pull_request(
782 repo: Repository,
783 branch: str,
784 root: Path,
785 *,
786 pr_number: int = 0,
787 interval: float = 15,
788 timeout: float = 1800,
789 clock: Callable[[], float] | None = None,
790 sleep: Callable[[float], None] | None = None,
791) -> Verdict:
792 """Watch until a terminal verdict, or raise SystemExit with its code.
793
794 Returns the ``merged`` verdict on success, or ``awaiting-approvals``
795 once the arm holds and a review is what happens next. Every job's
796 status change prints as a line of its own as it happens
797 ([livery.workshop._verdict.JobWatch][]), and a job that fails
798 prints its failure lines under its name. Every terminal blocker
799 (10-13, 16, 17) raises SystemExit carrying its code, after printing
800 the detail; the deadline raises 14; a forge unreachable past the
801 transient budget raises 15, naming the last error and the pull
802 request. The polls, the transient budget, the API budget, and the
803 *clock* and *sleep* the deadline and the waits use are
804 [livery.workshop._verdict.follow][]'s.
805 """
806 green_polls = 0
807 confirm_streak = 0
808 last_state = ""
809 last_verdict: Verdict | None = None
810 jobs = JobWatch()
811
812 def read() -> Verdict | Pending:
813 nonlocal green_polls, confirm_streak, last_state, last_verdict
814 grace_spent = green_polls >= _MERGE_GRACE_POLLS
815 current_pr = repo.pr.get(pr_number) if pr_number else None
816 active_branch = current_pr.head_branch if current_pr is not None else branch
817 verdict = classify(
818 repo, active_branch, root, grace_spent=grace_spent, pr=current_pr
819 )
820 # Every job's move prints as it happens, before the verdict
821 # line it may lead to: a red leg is named while the others
822 # run, with its failure lines, so the fix starts at once.
823 head_sha = (
824 current_pr.head_sha
825 if current_pr is not None
826 else _head_of(repo, active_branch, pr_number=pr_number)
827 )
828 jobs.report(repo, head_sha)
829 last_verdict = verdict
830 changed = verdict.state != last_state
831 last_state = verdict.state
832 if changed:
833 confirm_streak = 0
834 line = f"{jobs.stamp()}{verdict.state}: {verdict.detail}"
835 if verdict.state in ("merged", "awaiting-approvals"):
836 if changed:836 ↛ 838line 836 didn't jump to line 838 because the condition on line 836 was always true
837 print(line)
838 return verdict
839 if verdict.exit_code:
840 # A blocker must hold for two consecutive polls before it
841 # ends the watch: the submit-then-arm race, an async
842 # mergeability recompute, and a close-supersede all read
843 # as a blocker for one poll and clear on the next. CLOSED
844 # is the exception, definitive on a single read: a closed
845 # pull request does not reopen itself.
846 confirm_streak += 1
847 if verdict.state == "closed" or confirm_streak >= _CONFIRM_POLLS:
848 if changed:
849 print(line)
850 return verdict
851 return Pending(line, key=verdict.state)
852 if verdict.state == "in-flight" and verdict.detail.startswith("green"):852 ↛ 853line 852 didn't jump to line 853 because the condition on line 852 was never true
853 green_polls += 1
854 else:
855 green_polls = 0
856 return Pending(line, key=verdict.state)
857
858 try:
859 verdict = follow(
860 repo,
861 read,
862 subject=lambda: _pull_request_words(repo, branch, pr_number=pr_number),
863 interval=interval,
864 timeout=timeout,
865 quiet=None,
866 clock=clock,
867 sleep=sleep,
868 )
869 except ForgeUnreachable as exc:
870 print(exc.line)
871 raise SystemExit(EXIT_UNREACHABLE) from None
872 except FollowTimedOut:
873 print(f" still in flight after {timeout:.0f}s")
874 if last_verdict is not None:874 ↛ 876line 874 didn't jump to line 876 because the condition on line 874 was always true
875 _record_ending(repo, last_verdict, branch, root)
876 raise SystemExit(EXIT_TIMEOUT) from None
877 if verdict.exit_code:
878 _record_ending(repo, verdict, branch, root)
879 raise SystemExit(verdict.exit_code)
880 return verdict
881
882
883def _pull_request_words(repo: Repository, branch: str, *, pr_number: int = 0) -> str:
884 """The pull request to look at, or the branch when the forge cannot say."""
885 try:
886 pr = (
887 repo.pr.get(pr_number)
888 if pr_number
889 else repo.pr.find_by_head(branch, state="all")
890 )
891 except ForgeError:
892 pr = None
893 if pr is None:893 ↛ 894line 893 didn't jump to line 894 because the condition on line 893 was never true
894 what = f"PR #{pr_number}" if pr_number else f"the pull request for {branch}"
895 return f"{what} could not be read"
896 return f"the pull request: PR #{pr.number} {pr.url}"
897
898
899def _record_ending(repo: Repository, verdict: Verdict, branch: str, root: Path) -> None:
900 """Write the diagnostic bundle for a non-merged ending; best effort."""
901 from livery.workshop._diagnostics import SERIES, record
902
903 name, why = record(root, repo, verdict, branch=branch)
904 if name:904 ↛ 910line 904 didn't jump to line 910 because the condition on line 904 was always true
905 print(
906 f" diagnostics: {name} on {SERIES.ref}"
907 f" (`{footman.prog()} store.show {SERIES.name} --row={name}`)"
908 )
909 else:
910 print(f" diagnostics: not recorded ({why})")