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