Coverage for packages/workshop/src/livery/workshop/_workflow_state.py: 98%

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 each reserved-branch workflow sits in its lifecycle.
2
3A workflow lives on a reserved branch whose name is its identity:
4``workflow/release/<members>`` (the set's directory names, sorted,
5joined with ``+``, or their count and a digest when that runs long) or
6``workflow/update/<slug>``. Different names
7coexist; this reader tells the truth per branch and never arbitrates
8between them, which is the decision extension's job
9(livery.workshop._workflow_decision.workflow_decision).
10
11Classification is a pure function (``classify``) of gathered
12signals, so every mapping is testable with no I/O; the gathering
13(``gather``) isolates the network and answers None when the
14forge cannot be read. UNKNOWN is a first-class state, not an error:
15a blip must never read as "nothing running", so everything that
16mutates refuses on it.
17"""
18
19from __future__ import annotations(empty)
20
21from dataclasses import dataclass(empty)
22from enum import Enum(empty)
23from pathlib import Path(empty)
24
25from livery import git(empty)
26from livery.forge import ForgeError, Repository, Unsupported(empty)
27
28#: Reserved workflow branches live under this prefix.
29WORKFLOW_PREFIX = "workflow/"(empty)
30
31
32class WorkflowKind(Enum):(empty)
33 """Which reserved-branch workflow a branch names."""
34
35 RELEASE = "release"(empty)
36 UPDATE = "update"(empty)
37
38
39class WorkflowState(Enum):(empty)
40 """Where a workflow sits in its lifecycle.
41
42 UNKNOWN means the forge could not be read: callers that mutate
43 treat it like a live state and refuse, never assuming "nothing
44 running" from a blip.
45 """
46
47 NONE = "none"(empty)
48 PREPARING = "preparing" # local branch, never submitted(empty)
49 IN_PROGRESS = "in_progress" # armed PR, or publish still running(empty)
50 AWAITING_REVIEW = "awaiting_review" # unarmed PR: waits for a person(empty)
51 FAILED = "failed" # CI red, or closed unmerged(empty)
52 SUCCEEDED = "succeeded" # merged (and, for a release, tagged)(empty)
53 UNKNOWN = "unknown"(empty)
54
55
56class Blocker(Enum):(empty)
57 """Why a workflow will not land by itself, data beside the state."""
58
59 NONE = "none"(empty)
60 CONFLICTS = "conflicts"(empty)
61 CI_FAILING = "ci_failing"(empty)
62 DISARMED = "disarmed"(empty)
63 CLOSED = "closed"(empty)
64 BEHIND_BASE = "behind_base"(empty)
65 REVIEW_REQUIRED = "review_required"(empty)
66 STALE_SET = "stale_set" # the base moved in the release set's paths(empty)
67
68
69#: States ``workflow.abort`` tears down without --force: nothing is
70#: running or can complete on its own. IN_PROGRESS and AWAITING_REVIEW
71#: need force; UNKNOWN always refuses (never tear down on a blip).
72TEARDOWN_SAFE = frozenset((empty)
73 {
74 WorkflowState.NONE,
75 WorkflowState.PREPARING,
76 WorkflowState.FAILED,
77 WorkflowState.SUCCEEDED,
78 }
79)
80
81
82@dataclass(frozen=True)(empty)
83class WorkflowStatus:(empty)
84 """The detector's verdict for one workflow.
85
86 Attributes:
87 kind: Release or update; None on the NONE placeholder.
88 state: The lifecycle state.
89 name: The workflow name, the branch without its prefix
90 (``release/forge+workshop``).
91 branch: The reserved branch (``workflow/<name>``).
92 members: A release's package directory names; empty for an
93 update.
94 detail: A short hint (the failing leg, an unreadable-arm
95 note).
96 reopenable: FAILED from a closed-unmerged PR; reopening is an
97 option.
98 author: Who opened the PR, the forge's login namespace.
99 armed: True = a schedule is live; False = confirmed unarmed;
100 None = unreadable, which watches like armed (a false
101 "disarmed" is the proven wrong exit).
102 blocker: Why it will not land by itself.
103 pr_number: The workflow's PR, when one exists.
104 head_sha: The commit whose CI matters.
105 ci_state: The combined CI verdict for that commit.
106 tagged: A release's members whose receipt tag is already cut.
107 """
108
109 kind: WorkflowKind | None(empty)
110 state: WorkflowState(empty)
111 name: str = ""(empty)
112 branch: str = ""(empty)
113 members: tuple[str, ...] = ()(empty)
114 detail: str = ""(empty)
115 reopenable: bool = False(empty)
116 author: str = ""(empty)
117 armed: bool | None = False(empty)
118 blocker: Blocker = Blocker.NONE(empty)
119 pr_number: int = 0(empty)
120 head_sha: str = ""(empty)
121 ci_state: str = ""(empty)
122 tagged: tuple[str, ...] = ()(empty)
123
124
125def kind_of(name: str) -> WorkflowKind:(empty)
126 """The kind a workflow *name* declares by its first segment."""
127 return (
128 WorkflowKind.RELEASE
129 if name.split("/", 1)[0] == "release"
130 else WorkflowKind.UPDATE
131 )
132
133
134def members_of(name: str) -> tuple[str, ...]:(empty)
135 """A release name's package directories; empty for an update."""
136 if kind_of(name) is not WorkflowKind.RELEASE:
137 return ()
138 _, _, joined = name.partition("/")
139 return tuple(part for part in joined.split("+") if part)
140
141
142@dataclass(frozen=True)(empty)
143class Signals:(empty)
144 """The gathered inputs ``classify`` maps to a state."""
145
146 kind: WorkflowKind(empty)
147 remote_branch: bool(empty)
148 pr_state: str # "none" | "open" | "closed" | "merged"(empty)
149 ci_state: str # "success" | "pending" | "failure" | "none" | ""(empty)
150 tagged: tuple[str, ...] = () # release members with a receipt tag(empty)
151 members: tuple[str, ...] = ()(empty)
152 armed: bool | None = False(empty)
153 mergeable: bool | None = None(empty)
154 detail: str = ""(empty)
155 author: str = ""(empty)
156 pr_number: int = 0(empty)
157 head_sha: str = ""(empty)
158 stale_set: bool = False # base moved in the set's paths(empty)
159
160
161def classify(sig: Signals) -> WorkflowState:(empty)
162 """Map gathered *sig* to a lifecycle state. Pure, no I/O."""
163 if sig.pr_state == "none":
164 return (
165 WorkflowState.IN_PROGRESS if sig.remote_branch else WorkflowState.PREPARING
166 )
167 if sig.pr_state == "open":
168 if sig.ci_state == "failure":
169 return WorkflowState.FAILED
170 # An unreadable arm (None) watches like armed: reporting a
171 # live arm as absent is the proven wrong verdict.
172 return (
173 WorkflowState.AWAITING_REVIEW
174 if sig.armed is False
175 else WorkflowState.IN_PROGRESS
176 )
177 if sig.pr_state == "closed":
178 return WorkflowState.FAILED
179 # merged
180 if sig.kind is WorkflowKind.UPDATE:
181 return WorkflowState.SUCCEEDED
182 # A release is done when every member's receipt tag is cut; the
183 # tags are the ledger, so partial success reads IN_PROGRESS with
184 # the cut members listed, and a red publish run reads FAILED.
185 if sig.members and set(sig.tagged) >= set(sig.members):
186 return WorkflowState.SUCCEEDED
187 if sig.ci_state == "failure":
188 return WorkflowState.FAILED
189 return WorkflowState.IN_PROGRESS
190
191
192def blocker(sig: Signals) -> Blocker:(empty)
193 """Why the workflow will not land by itself. Pure, no I/O.
194
195 CONFLICTS first (fixing them re-triggers CI anyway), then CI red,
196 then the stale set (re-preparing also re-runs CI, so it outranks
197 the arm question), then unarmed.
198 """
199 if sig.pr_state == "closed":
200 return Blocker.CLOSED
201 if sig.pr_state != "open":
202 return Blocker.NONE
203 if sig.mergeable is False:
204 return Blocker.CONFLICTS
205 if sig.ci_state == "failure":
206 return Blocker.CI_FAILING
207 if sig.stale_set:
208 return Blocker.STALE_SET
209 if sig.armed is False:
210 return Blocker.DISARMED
211 return Blocker.NONE
212
213
214def base_moved_in_paths((empty)
215 root: Path, base: str, paths: tuple[str, ...], *, head: str = "HEAD"
216) -> bool:
217 """Whether ``origin/<base>`` carries commits *head* lacks touching *paths*.
218
219 The staleness probe for a release set: pure local git, empty
220 *paths* is never stale. Movement outside the set's paths is
221 harmless by construction and reads False. *head* is the release
222 branch's tip; the checkout the act runs from is usually the base
223 itself, so its own HEAD says nothing about the branch. A tip this
224 clone does not hold reads False: the release pull request's own
225 freshness check is the guard that never guesses.
226 """
227 if not paths:227 ↛ 228line 227 didn't jump to line 228 because the condition on line 227 was never true
228 return False
229 try:
230 out = git.log_paths(root, f"{head}..origin/{base}", paths)
231 except git.GitError:
232 return False
233 return bool(out)
234
235
236def gather((empty)
237 repo: Repository,
238 root: Path,
239 name: str,
240 *,
241 base: str = "main",
242) -> Signals | None:
243 """Gather one workflow's signals, or None when the forge is unreadable."""
244 branch = f"{WORKFLOW_PREFIX}{name}"
245 kind = kind_of(name)
246 members = members_of(name)
247 try:
248 pr = repo.pr.find_by_head(branch, state="all")
249 if pr is None:
250 head = git.any_head(root, branch)
251 if head:251 ↛ 253line 251 didn't jump to line 253 because the condition on line 251 was always true
252 pr = repo.pr.find_by_head_sha(head)
253 remote_branch = repo.branch_exists(branch)
254 except (ForgeError, Unsupported, OSError):
255 return None
256
257 if pr is None:
258 return Signals(
259 kind=kind,
260 remote_branch=remote_branch,
261 pr_state="none",
262 ci_state="",
263 members=members,
264 )
265
266 if pr.merged:
267 pr_state = "merged"
268 elif pr.state == "closed":
269 pr_state = "closed"
270 else:
271 pr_state = "open"
272
273 armed: bool | None = False
274 mergeable: bool | None = None
275 ci_state = ""
276 detail = ""
277 head_sha = pr.head_sha
278 tagged: tuple[str, ...] = ()
279 stale = False
280
281 try:
282 if pr_state == "open":
283 try:
284 armed = repo.pr.is_armed(pr.number)
285 except (ForgeError, Unsupported):
286 armed = None
287 detail = "arming state unreadable"
288 status = repo.checks.status(pr.head_sha)
289 ci_state = status.state
290 if kind is WorkflowKind.RELEASE:
291 stale = base_moved_in_paths(
292 root,
293 base,
294 tuple(f"packages/{m}" for m in members),
295 head=pr.head_sha or "HEAD",
296 )
297 elif pr_state == "merged" and kind is WorkflowKind.RELEASE:
298 tags = set(repo.tags(prefix="packages/"))
299 # The receipt: each member's tag, whatever version it
300 # carries, present on the repository after this merge.
301 tagged = tuple(
302 m for m in members if any(t.startswith(f"packages/{m}/v") for t in tags)
303 )
304 if set(tagged) < set(members):
305 status = repo.checks.status(pr.head_sha)
306 ci_state = status.state
307 except (ForgeError, Unsupported, OSError):
308 return None
309
310 return Signals(
311 kind=kind,
312 remote_branch=remote_branch,
313 pr_state=pr_state,
314 ci_state=ci_state,
315 tagged=tagged,
316 members=members,
317 armed=armed,
318 mergeable=mergeable,
319 detail=detail,
320 author=pr.author,
321 pr_number=pr.number,
322 head_sha=head_sha,
323 stale_set=stale,
324 )
325
326
327def status_of(sig: Signals | None, name: str) -> WorkflowStatus:(empty)
328 """One workflow's ``WorkflowStatus`` from its gathered signals."""
329 kind = kind_of(name)
330 branch = f"{WORKFLOW_PREFIX}{name}"
331 if sig is None:
332 return WorkflowStatus(
333 kind=kind, state=WorkflowState.UNKNOWN, name=name, branch=branch
334 )
335 return WorkflowStatus(
336 kind=kind,
337 state=classify(sig),
338 name=name,
339 branch=branch,
340 members=sig.members,
341 detail=sig.detail,
342 reopenable=(sig.pr_state == "closed"),
343 author=sig.author,
344 armed=sig.armed,
345 blocker=blocker(sig),
346 pr_number=sig.pr_number,
347 head_sha=sig.head_sha,
348 ci_state=sig.ci_state,
349 tagged=sig.tagged,
350 )
351
352
353def active_workflow_names(repo: Repository, root: Path) -> tuple[str, ...]:(empty)
354 """The distinct workflow names in play, local and remote united.
355
356 The union, never local-else-remote: a colleague's live release
357 exists only on the remote, and a local leftover of your own would
358 hide it. The remote probe degrades to the local list when the
359 forge is unreachable.
360 """
361 local = set(git.local_branches(root, WORKFLOW_PREFIX))
362 try:
363 remote = set(git.remote_branches(root, WORKFLOW_PREFIX))
364 except Exception:
365 remote = set()
366 return tuple(sorted(b.removeprefix(WORKFLOW_PREFIX) for b in local | remote))
367
368
369def workflow_states((empty)
370 repo: Repository, root: Path, *, base: str = "main"
371) -> tuple[WorkflowStatus, ...]:
372 """Every active workflow, each classified on its own signals.
373
374 Coexistence is legitimate; multiple names are states to report,
375 not a broken invariant. Releases sort first, then by name.
376 """
377 states = [
378 status_of(gather(repo, root, name, base=base), name)
379 for name in active_workflow_names(repo, root)
380 ]
381 states.sort(key=lambda wf: (wf.kind is not WorkflowKind.RELEASE, wf.name))
382 return tuple(states)