Coverage for packages/workshop/src/livery/workshop/_release_driver.py: 86%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.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_prose.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/conan/tests/test_cross_kind.py ran.

1"""``workflow.release``: the release train's driver on the engine.
2
3One release shape for a set of N >= 1 packages: derive each member's
4version from its commits and its entry through the release notes'
5provider, bump floors within the set only, stamp, commit per member in
6dependency order, and hand the branch to the shared engine. The branch
7decides the act: main-family (``main`` and the engine's ``workflow/``
8namespace) runs the real train, any other branch is the dev act, a wheel
9straight from the branch. ``--local`` is everything that stays on this
10machine: derive, build, validate, report, then roll the stamps back like
11a failed prepare, leaving ``dist/`` and the report.
12"""
13
14from __future__ import annotations
15
16import contextlib
17import time
18from collections.abc import Callable, Sequence
19from dataclasses import dataclass
20from functools import partial
21from pathlib import Path
22from typing import Annotated
23
24import livery.footman as footman
25from livery import git
26from livery.footman import doc, fail
27from livery.forge import ForgeError, Repository, Run
28from livery.workshop import _lifecycle
29from livery.workshop._graph import order_topologically
30from livery.workshop._packages import Package, discover_packages, receipt_member
31from livery.workshop._release import prepare_release
32from livery.workshop._verdict import (
33 FollowTimedOut,
34 ForgeUnreachable,
35 Pending,
36 Transient,
37 follow,
38)
39from livery.workshop._versions import derive_version, release_pathspecs
40from livery.workshop._workflow_engine import Submission, run_workflow
41from livery.workshop._workflow_state import WorkflowKind
42from livery.workshop._workflow_tasks import workflow
43
44
45def _moved_paths(root: Path, span: str, pathspecs: tuple[str, ...]) -> tuple[str, ...]:
46 """Commit subjects in *span* touching *pathspecs*, honoring ``:(exclude)``."""
47 if not any(spec.startswith(":(exclude)") for spec in pathspecs):47 ↛ 49line 47 didn't jump to line 49 because the condition on line 47 was always true
48 return git.log_paths(root, span, pathspecs)
49 out = git.run(root, "log", "--format=%s", span, "--", *pathspecs)
50 return tuple(line for line in out.splitlines() if line)
51
52
53#: The base gate's patience and cadence.
54BASE_TIMEOUT = 30 * 60
55BASE_POLL = 15
56#: A tip with zero reported contexts this long gets one nudge: run
57#: creation itself failed, and patience cannot fix that.
58SILENT_NUDGE_AFTER = 3 * 60
59
60
61@dataclass(frozen=True)
62class MemberPlan:
63 """One member's derived release: the package and its next version."""
64
65 package: Package
66 version: str
67
68
69#: The longest the members' joined directories may run in a release's
70#: name. The name is a branch, and a checkout keeps a branch as a file
71#: under ``.git/refs/remotes/origin/``: past Windows' path limit there,
72#: a CI checkout fails before anything runs.
73NAME_LIMIT = 64
74
75
76def release_name(members: tuple[str, ...]) -> str:
77 """The workflow name a set earns: its directories, sorted and ``+``-joined.
78
79 A set whose joined directories run past `NAME_LIMIT` is named by
80 its size and a digest of them instead, so the branch stays short
81 and the same set always earns the same name.
82 """
83 joined = "+".join(sorted(members))
84 if len(joined) <= NAME_LIMIT:
85 return f"release/{joined}"
86 import hashlib
87
88 digest = hashlib.sha256(joined.encode("utf-8")).hexdigest()[:12]
89 return f"release/{len(members)}-packages-{digest}"
90
91
92def resolve_set(root: Path, paths: tuple[str, ...]) -> tuple[Package, ...]:
93 """The named packages, in dependency order; every name must exist."""
94 packages = {p.path: p for p in discover_packages(root)}
95 chosen: list[Package] = []
96 for path in paths:
97 package = packages.get(path) or packages.get(f"packages/{path}")
98 if package is None:
99 known = ", ".join(sorted(packages))
100 fail(f"{path} is not a workspace package; members: {known}")
101 chosen.append(package)
102 return order_topologically(tuple(chosen))
103
104
105def derive_plans(root: Path, members: tuple[Package, ...]) -> tuple[MemberPlan, ...]:
106 """Each member's next version, every member refused when unchanged.
107
108 Runs before the branch is cut, from read-only state: a refusal
109 here has nothing to undo. A member whose bump equals its newest
110 released tag has nothing unreleased, and minting a number the
111 index already has is refused with the options. The tag is the
112 judge, never the stamped version: a stamp can land without its
113 release cutting, and judging by it would strand that release
114 (the same rule livery.workshop._release.prepare_release keeps).
115 """
116 from livery.workshop._release import _last_released
117
118 plans: list[MemberPlan] = []
119 unchanged: list[str] = []
120 for package in members:
121 released = _last_released(root, package)
122 derived = derive_version(root, package, released=released)
123 if not derived or derived == released:
124 unchanged.append(package.member)
125 continue
126 plans.append(MemberPlan(package=package, version=derived))
127 if unchanged:
128 names = ", ".join(unchanged)
129 fail(
130 f"nothing unreleased touches: {names}. Options: drop them from"
131 " the set (release the rest now); or, if a hollow re-release is"
132 " truly meant, stamp a version explicitly with"
133 f" `{footman.prog()} release.prepare <path> <version>`."
134 )
135 return tuple(plans)
136
137
138def _write_manifest(
139 root: Path, plans: tuple[MemberPlan, ...], *, mined_at: str
140) -> None:
141 """Write the release set's record for the squash's discovery.
142
143 The publish wave and the title check read it at the ref, so a
144 recovery re-prepare whose stamps already sit on the base still
145 names every member; see [livery.workshop._publish.MANIFEST][].
146 The record carries *mined_at*, which differs for every prepare,
147 so every release squash touches the file: the dispatch finds the
148 squash as the last commit touching it, and a prepare that takes
149 over an abandoned squash at the same versions still has a commit.
150 """
151 import json
152
153 from livery.workshop._publish import MANIFEST
154
155 payload = {
156 "schema": 1,
157 "mined-at": mined_at,
158 "members": [
159 {
160 "dir": plan.package.member,
161 "name": plan.package.name,
162 "version": plan.version,
163 }
164 for plan in plans
165 ],
166 }
167 (root / MANIFEST).write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8")
168
169
170def member_pairs_at(root: Path, ref: str) -> list[tuple[str, str]] | None:
171 """(distribution, version) for each member in the member list at *ref*.
172
173 Each name is read from the member's contract as committed at
174 *ref*, so the answer describes that commit alone. None when *ref*
175 carries no readable list.
176 """
177 import tomllib
178
179 from livery.workshop._publish import MANIFEST, read_manifest
180
181 recorded = read_manifest(git.file_at(root, ref, MANIFEST))
182 if recorded is None:
183 return None
184 pairs: list[tuple[str, str]] = []
185 for directory, version in recorded:
186 try:
187 contract = tomllib.loads(
188 git.file_at(root, ref, f"packages/{directory}/workshop.toml")
189 )
190 name = str(contract.get("name") or directory)
191 except tomllib.TOMLDecodeError:
192 name = directory
193 pairs.append((name, version))
194 return pairs
195
196
197def bump_set_floors(root: Path, plans: tuple[MemberPlan, ...]) -> list[str]:
198 """Raise floors between co-released members through the stamp phase; the files.
199
200 Within the set only (contract: a solo release never moves a
201 floor): each member's stamp phase runs at the version it declares
202 now, with every other member's version as its floors, so the
203 version stays for `prepare_release` to stamp. Each step raises the
204 floors in its own manifests, and the base those of the member's
205 ``[[depends]]`` edges, as `livery.workshop._lifecycle.stamp` says.
206 The files are the ones the phase reported, relative to *root*.
207 """
208 if len(plans) < 2:
209 return []
210 changed: list[str] = []
211 for plan in plans:
212 package = plan.package
213 floors = {
214 other.package.path: other.version
215 for other in plans
216 if other.package.path != package.path
217 }
218 current = _lifecycle.current_version(package)
219 stamped = _lifecycle.stamp(package, root, current, floors=floors)
220 changed += [
221 (package.directory / name).relative_to(root).as_posix() for name in stamped
222 ]
223 return changed
224
225
226def rollback_prepare(
227 root: Path, members: tuple[Package, ...], reported: Sequence[str] = ()
228) -> None:
229 """Restore exactly the files prepare writes; never raises.
230
231 The error being unwound is the one worth seeing, so this raises
232 nothing of its own: each member's changelog, contract and version
233 files return to HEAD, and so do the files the stamp phase
234 *reported* raising floors in (relative to *root*), the set's
235 manifest and the workspace lock the stamp refreshed. One of these
236 files on disk that HEAD lacks is one prepare created, as a first
237 release's changelog and manifest are, and it is removed, so the
238 switch back to the base does not carry it along. Each restore reads
239 HEAD, never the index: a commit that failed (a signing agent that
240 refused) has already staged every change, and a restore from the
241 index would keep them. Each path the rollback could not put back is
242 printed with the reason, and the other paths are put back all the
243 same.
244 """
245 for path, reason in _put_back(root, _prepare_paths(root, members, reported)):
246 print(f" the rollback could not restore {path}: {reason}")
247
248
249def _prepare_paths(
250 root: Path, members: tuple[Package, ...], reported: Sequence[str] = ()
251) -> tuple[str, ...]:
252 """The paths prepare may write for *members*, each once, from *root*.
253
254 The files the stamp phase *reported* raising floors in, then each
255 member's changelog, its contract and the files its set's stamp
256 writes a version into, then the workspace lock and the set's
257 manifest, with forward slashes. The rollback puts back exactly
258 these, and the local act refuses while one of them has changes of
259 its own, so the two read the same list.
260 """
261 from livery.workshop._contract import CONTRACT
262 from livery.workshop._publish import MANIFEST
263
264 paths = [Path(name).as_posix() for name in reported]
265 for package in members:
266 base = package.directory.relative_to(root)
267 paths.extend((base / name).as_posix() for name in ("CHANGELOG.md", CONTRACT))
268 # Every file the set's stamp writes a version into. A set that
269 # cannot name them restores the rest regardless.
270 with contextlib.suppress(Exception):
271 paths.extend(
272 home.relative_to(root).as_posix()
273 for home in _lifecycle.version_files(package)
274 )
275 paths.extend(("uv.lock", MANIFEST))
276 return tuple(dict.fromkeys(paths))
277
278
279def _require_unchanged(root: Path, members: tuple[Package, ...]) -> None:
280 """Refuse while a path prepare may write has changes of its own, naming each.
281
282 The rollback returns each of those paths to HEAD and deletes one
283 HEAD lacks, so an uncommitted edit there, or a file a person made
284 there by hand, would be lost. A change anywhere else in the tree
285 does not refuse.
286
287 Raises:
288 Failed: naming each such path, modified, staged, deleted or
289 untracked, and saying to commit or stash it first.
290 """
291 out = git.run(
292 root,
293 "status",
294 "--porcelain",
295 "-z",
296 "--untracked-files=all",
297 "--",
298 *_prepare_paths(root, members),
299 )
300 fields = out.split("\0")
301 changed: list[str] = []
302 index = 0
303 while index < len(fields):
304 record = fields[index]
305 index += 1
306 if len(record) < 4:
307 continue
308 changed.append(record[3:])
309 if record[0] in "RC":309 ↛ 311line 309 didn't jump to line 311 because the condition on line 309 was never true
310 # A rename or a copy names the path it came from next.
311 index += 1
312 if changed:
313 listed = "".join(f"\n {path}" for path in sorted(set(changed)))
314 fail(
315 "the local act writes these files and then restores them from"
316 f" HEAD, so the changes they have now would be lost:{listed}\n"
317 "Commit or stash them first, then run it again."
318 )
319
320
321def _put_back(root: Path, paths: tuple[str, ...]) -> list[tuple[str, str]]:
322 """Return each of *paths* to HEAD; each path that failed, with the reason.
323
324 A path HEAD has is checked out from HEAD. A path HEAD lacks that
325 is on disk is taken out of the index and deleted. A path in
326 neither is left alone. The paths HEAD has are checked out in one
327 call, and only when git refuses that call is each checked out
328 alone: git refuses the whole call for one bad path, so the one
329 path git refuses never stops the rest.
330 """
331 tracked: list[str] = []
332 failed: list[tuple[str, str]] = []
333 for path in paths:
334 try:
335 if git.tracks(root, f"HEAD:{path}"):
336 tracked.append(path)
337 elif (root / path).is_file():
338 git.unstage(root, path)
339 (root / path).unlink()
340 except (git.GitError, OSError) as error:
341 failed.append((path, str(error)))
342 if tracked and git.restore(root, *tracked):
343 for path in tracked:
344 refused = git.restore(root, path)
345 if refused:
346 failed.append((path, refused))
347 return failed
348
349
350def verify_set(root: Path, plans: tuple[MemberPlan, ...]) -> None:
351 """Run the publish job's own checks over the stamped set, before any leg.
352
353 The wave refuses a member whose version homes disagree with its tag,
354 whose release notes are unsound, or whose floor names an unreleased
355 version, and it refuses only after the release has merged. The same
356 checks on the stamped tree refuse before a release pull request
357 exists. The set's own tags count as released, as the wave counts them.
358
359 Raises:
360 Failed: as the publish job's check refuses, naming the member and
361 each problem.
362 """
363 from livery.workshop._release import verify_release
364
365 coreleased = frozenset(f"{plan.package.path}/v{plan.version}" for plan in plans)
366 for plan in plans:
367 verify_release(
368 root, f"{plan.package.path}/v{plan.version}", coreleased=coreleased
369 )
370
371
372def _wheel_dists(plans: tuple[MemberPlan, ...]) -> tuple[Path, ...]:
373 """The find-links dirs: each member's ``dist/`` that exists, in set order.
374
375 Read after the set's builds. A build that writes nothing there, a
376 conan member's, leaves no directory to name, and a find-links path
377 that does not exist fails the sibling legs outright.
378 """
379 dists = (plan.package.directory / "dist" for plan in plans)
380 return tuple(dist for dist in dists if dist.is_dir())
381
382
383#: The key of `[release]` listing the resolutions a release tests at.
384PROVE = "prove"
385
386#: The resolutions a release may test a member at, in the order the legs
387#: run: the floor first, since a floor lying about compatibility fails
388#: before anything else is spent, then the newest, then the lock's.
389RESOLUTIONS = ("floor", "latest", "head")
390
391#: The resolutions a release tests at when no contract lists any.
392DEFAULT_RESOLUTIONS = ("floor", "latest")
393
394
395def proved_resolutions(root: Path, package: Package) -> tuple[tuple[str, ...], str]:
396 """The resolutions *package*'s release tests at, and the file that listed them.
397
398 The package's own `[release] prove` wins; the workspace's is the
399 default; without either the release tests at
400 [livery.workshop._release_driver.DEFAULT_RESOLUTIONS][], and the
401 file is empty. The contract's judge refuses a word other than the
402 three and a word listed twice, so the list holds each at most
403 once, in the order the legs run.
404 """
405 from livery.workshop._contract import load_contract
406
407 for contract in (package.directory / "workshop.toml", root / "workshop.toml"):
408 if not contract.is_file():408 ↛ 409line 408 didn't jump to line 409 because the condition on line 408 was never true
409 continue
410 release = load_contract(contract).get("release") or {}
411 if PROVE in release:
412 listed = {str(word) for word in release[PROVE]}
413 where = contract.relative_to(root).as_posix()
414 return tuple(word for word in RESOLUTIONS if word in listed), where
415 return DEFAULT_RESOLUTIONS, ""
416
417
418def validate_member(
419 root: Path, plan: MemberPlan, release_dirs: tuple[Path, ...]
420) -> None:
421 """Run the member's test phase isolated once per resolution it proves; report each.
422
423 One leg per resolution
424 ([livery.workshop._release_driver.proved_resolutions][]), in the
425 order of [livery.workshop._release_driver.RESOLUTIONS][], so the
426 floor leg runs before the latest leg; a list from a contract is
427 named with its file. The report names what each leg resolved per
428 co-member and sibling: every workspace member but the one under
429 test. The caller builds every set member's wheel first: the legs'
430 find-links name each sibling's ``dist/``, so a later member's
431 wheel must exist before an earlier member's floor leg resolves.
432
433 A member whose extensions add no isolated test, as a conan
434 package's do, has no venv to isolate: its own gate already built
435 and ran ctest, so the legs skip saying why.
436 """
437 if not _lifecycle.has_isolated_test(plan.package):
438 print(
439 f" {plan.package.name}: isolated legs skip (its extensions add no"
440 " isolated test, since it publishes no wheel; its own gate builds"
441 " and tests)"
442 )
443 return
444 legs, where = proved_resolutions(root, plan.package)
445 if where:
446 listed = ", ".join(legs) or "nothing, so no leg runs"
447 print(f" {plan.package.name}: [release] {PROVE} in {where} lists {listed}")
448 members = {_normalised(package.name) for package in discover_packages(root)}
449 own = _normalised(plan.package.name)
450 for leg in legs:
451 resolved = _lifecycle.isolated_test(
452 plan.package, root, resolution=leg, release_dirs=release_dirs
453 )
454 siblings = {
455 name: version
456 for name, version in sorted(resolved.items())
457 if _normalised(name) in members and _normalised(name) != own
458 }
459 listed = ", ".join(f"{n} {v}" for n, v in siblings.items()) or "no siblings"
460 print(f" {plan.package.name} {leg} leg: {listed}")
461
462
463def _normalised(name: str) -> str:
464 """A distribution's name as an index compares it: lower case, hyphens."""
465 return name.lower().replace("_", "-").replace(".", "-")
466
467
468def _base_tree_verified(root: Path, base: str) -> bool:
469 """Whether the proved record already vouches for *base*'s tip on every check leg."""
470 from livery.workshop import _proved
471
472 try:
473 git.fetch(root)
474 proved, why = _proved.base_proved(root, base)
475 except Exception as error:
476 print(
477 f" {base}: its tip cannot be read for the proved record: {error};"
478 " waiting for the tip's own run"
479 )
480 return False
481 if why:481 ↛ 482line 481 didn't jump to line 482 because the condition on line 481 was never true
482 print(f" {base}: {why}; waiting for the tip's own run")
483 return False
484 if proved:
485 print(f" {base} verified: proved green on every leg; the release starts now")
486 return True
487 return False
488
489
490def require_verified_base(
491 repo: Repository,
492 root: Path,
493 base: str,
494 *,
495 force: bool = False,
496 timeout: float = BASE_TIMEOUT,
497 poll: float = BASE_POLL,
498) -> None:
499 """Wait for the base's own push CI to be green; stop on red or skip.
500
501 Branch protection only ever judged PR heads, and a release
502 publishes the base's tree, so the base's push run is the only
503 vouching there is. Green, not merely not-red; red is a verdict
504 waiting cannot improve; a skip-ci tip will never get a run; an
505 unreachable forge fails open, the engine's UNKNOWN story says it
506 better.
507
508 Zero reported contexts after minutes means run creation itself
509 failed, and every forge can do it: Gitea's actions queue could
510 wedge before 1.27.3, GitHub silently drops a push's workflow-run
511 creation under load, and GitLab can never mint the pipeline (a
512 job-queue backlog, or workflow rules evaluating to nothing). The
513 combined-status read
514 reports all three identically, so detection is uniform; the safe
515 remedy is not (whether a tool may push to the base varies per
516 forge and protection), so the silent tip gets a printed teaching
517 naming the fresh-push-event remedy, never an automatic push. The
518 timeout tells the two conditions apart: a run that reported and
519 hung sends the reader to the runners, a tip that never got a run
520 names run creation.
521 """
522 if force:
523 print(" base verification skipped (--force-unverified-base)")
524 return
525 if _base_tree_verified(root, base):
526 return
527 announced = False
528 silent_since: float | None = None
529 nudged = False
530 ever_reported = False
531
532 def read() -> bool | Pending:
533 nonlocal announced, silent_since, nudged, ever_reported
534 try:
535 git.fetch(root)
536 sha = git.remote_head(root, base)
537 status = repo.checks.status(sha) if sha else None
538 except ForgeError:
539 raise
540 except Exception as error:
541 # The base gate fails open: a tree nobody can vouch for
542 # releases, and the reason is said rather than swallowed.
543 print(f" {base}'s CI could not be read ({error}); releasing unverified")
544 return True
545 if status is None or status.state == "success":
546 return True
547 if status.state == "failure":
548 fail(
549 f"{base}'s own CI is red, and a release publishes that tree."
550 f" Fix {base} first (`{footman.prog()} ci.logs` on it names"
551 " the job), or"
552 " release with --force-unverified-base if you accept an"
553 " unvouched tree."
554 )
555 if "[skip ci]" in git.commit_message(root, sha):555 ↛ 556line 555 didn't jump to line 556 because the condition on line 555 was never true
556 fail(
557 f"{base}'s tip carries a skip-ci marker, so CI will never"
558 " report on it. Push a commit CI can run, or"
559 " --force-unverified-base to accept it unverified."
560 )
561 now = time.monotonic()
562 if status.contexts:
563 ever_reported = True
564 silent_since = None
565 elif silent_since is None:
566 silent_since = now
567 elif not nudged and now - silent_since >= SILENT_NUDGE_AFTER:567 ↛ 568line 567 didn't jump to line 568 because the condition on line 567 was never true
568 nudged = True
569 print(
570 f" {base}'s tip has had no CI run for"
571 f" {SILENT_NUDGE_AFTER // 60} min; a fresh push event may be"
572 " needed (an empty commit mints one)."
573 )
574 if not announced:
575 announced = True
576 print(
577 f" waiting for {base}'s own CI before releasing (up to"
578 f" {BASE_TIMEOUT // 60} min)"
579 )
580 return Pending()
581
582 try:
583 follow(
584 repo,
585 read,
586 subject=f"{base}'s own CI",
587 interval=poll,
588 timeout=timeout,
589 quiet=None,
590 )
591 except ForgeUnreachable as exc:
592 print(exc.line)
593 print(f" releasing unverified: {base}'s CI could not be read")
594 except FollowTimedOut:
595 # Not started and hanging are different problems with
596 # different remedies, so the timeout names the one that
597 # actually happened.
598 if ever_reported:
599 fail(
600 f"{base} reported a run but never went green within"
601 f" {timeout / 60:.0f} minutes. Check the runners"
602 f" (`{footman.prog()} status --watch` on a branch follows"
603 " a run), or"
604 " --force-unverified-base."
605 )
606 fail(
607 f"{base}'s tip never got a CI run in {timeout / 60:.0f}"
608 " minutes: run creation itself failed, and waiting cannot"
609 " fix that. A fresh push event mints a run (an empty"
610 " commit, or its PR merged), or --force-unverified-base."
611 )
612
613
614class ReleaseDriver:
615 """The release kind's driver for the shared engine."""
616
617 kind = WorkflowKind.RELEASE
618
619 def __init__(
620 self,
621 root: Path,
622 repo: Repository,
623 members: tuple[Package, ...],
624 *,
625 armed: bool,
626 force_unverified_base: bool = False,
627 wave_timeout: float = 1800.0,
628 ) -> None:
629 self._root = root
630 self._repo = repo
631 self._members = members
632 self.members = tuple(p.member for p in members)
633 self.name = release_name(self.members)
634 self.armed = armed
635 self._force = force_unverified_base
636 self._wave_timeout = wave_timeout
637 # An armed release follows its pull request for as long as it
638 # would wait for the wave; the engine's own tests pass zero.
639 self.watch = wave_timeout
640 # Set by `discard`: the next prepare starts from the base, and
641 # the given-up branch's manifest says which members' legs
642 # still hold.
643 self._fresh = False
644 self._previous: tuple[str, tuple[tuple[str, str], ...]] | None = None
645
646 @property
647 def branch(self) -> str:
648 return f"workflow/{self.name}"
649
650 @property
651 def base(self) -> str:
652 return "main"
653
654 def discard(self) -> None:
655 """Give up the prepared branch: the base moved in the set's paths.
656
657 The next prepare derives the set again from the base and
658 force-pushes the branch, so the open pull request carries the
659 new stamps, entries and ``Mined-At``. The given-up branch's
660 manifest is kept: a member whose directory the base did not
661 move since that prepare, at the same versions for the whole
662 set, keeps its legs' verdict instead of running them again.
663 """
664 import json
665
666 from livery.workshop._publish import MANIFEST, read_manifest
667
668 root = self._root
669 git.fetch(root)
670 text = git.file_at(root, f"origin/{self.branch}", MANIFEST)
671 pairs = read_manifest(text) if text else None
672 mined = ""
673 if pairs:673 ↛ 676line 673 didn't jump to line 676 because the condition on line 673 was always true
674 with contextlib.suppress(ValueError, TypeError, AttributeError):
675 mined = str(json.loads(text).get("mined-at") or "")
676 self._previous = (mined, pairs) if pairs and mined else None
677 if git.current_branch(root) == self.branch:677 ↛ 679line 677 didn't jump to line 679 because the condition on line 677 was always true
678 git.switch(root, self.base)
679 if git.local_branch_exists(root, self.branch):679 ↛ 681line 679 didn't jump to line 681 because the condition on line 679 was always true
680 git.delete_branch(root, self.branch)
681 self._fresh = True
682
683 def legs_kept(self, plans: tuple[MemberPlan, ...], mined_at: str) -> set[str]:
684 """The members whose legs from the discarded prepare still hold.
685
686 Only when the whole set keeps its versions (a co-member's new
687 version moves the floors every other member is tested at), and
688 then each member the base did not touch between the two mining
689 points.
690 """
691 if self._previous is None:
692 return set()
693 previous_mined, previous_pairs = self._previous
694 now = tuple((plan.package.member, plan.version) for plan in plans)
695 if tuple(sorted(previous_pairs)) != tuple(sorted(now)):
696 return set()
697 kept: set[str] = set()
698 for plan in plans:
699 try:
700 moved = _moved_paths(
701 self._root,
702 f"{previous_mined}..{mined_at}",
703 release_pathspecs(plan.package),
704 )
705 except git.GitError:
706 continue # an unreadable span proves nothing: run the legs
707 if not moved:
708 kept.add(plan.package.member)
709 return kept
710
711 def prepare(self) -> Submission | None:
712 """Derive, stamp, and commit the set; recover an existing branch.
713
714 A branch already alive locally or on the remote is recovery:
715 nothing is rebuilt, the engine re-submits what the branch
716 holds, and titles come from the ref, never the working tree.
717 """
718 root = self._root
719 if not self._fresh and (
720 git.local_branch_exists(root, self.branch)
721 or self._repo.branch_exists(self.branch)
722 ):
723 if git.current_branch(root) != self.branch:723 ↛ 724line 723 didn't jump to line 724 because the condition on line 723 was never true
724 if not git.local_branch_exists(root, self.branch):
725 git.fetch(root)
726 git.run(
727 root, "checkout", "-b", self.branch, f"origin/{self.branch}"
728 )
729 else:
730 git.switch(root, self.branch)
731 print(f" recovering the prepared {self.name} from its branch")
732 self._require_fresh_base()
733 return self._submission_from_ref()
734
735 require_verified_base(self._repo, root, self.base, force=self._force)
736 plans = derive_plans(self._root, self._members)
737 mined_at = git.head_sha(root)
738 kept = self.legs_kept(plans, mined_at)
739 git.create_branch(root, self.branch)
740 prepared = False
741 floor_changes: list[str] = []
742 try:
743 floor_changes = bump_set_floors(self._root, plans)
744 if floor_changes:
745 print(f" floors raised within the set: {', '.join(floor_changes)}")
746 _write_manifest(self._root, plans, mined_at=mined_at)
747 for plan in plans:
748 prepare_release(self._root, plan.package.path, plan.version)
749 _lifecycle.build_release(plan.package, self._root)
750 if git.is_clean(root):750 ↛ 755line 750 didn't jump to line 755 because the condition on line 750 was never true
751 # Already stamped: a release squash-merged but never
752 # published leaves main carrying exactly these
753 # entries and versions, and re-preparing is the
754 # recovery. A clean tree is that state, not a fault.
755 print(
756 f" {plan.package.name} v{plan.version}:"
757 " already stamped on the base; nothing to commit"
758 )
759 continue
760 git.commit_all(
761 root, f"chore(release): {plan.package.name} v{plan.version}"
762 )
763 if not git.is_clean(root):763 ↛ 768line 763 didn't jump to line 768 because the condition on line 763 was never true
764 # Only the manifest changed: every member was already
765 # stamped on the base (a merged release whose publish
766 # failed), and the manifest alone is what lets the
767 # squash's discovery still name the whole set.
768 git.commit_all(root, "chore(release): the set manifest")
769 verify_set(self._root, plans)
770 # Every member's wheel exists before any leg runs; a
771 # failed leg still tears the whole branch down, commits
772 # included, so nothing unvalidated survives.
773 release_dirs = _wheel_dists(plans)
774 for plan in plans:
775 if plan.package.member in kept:775 ↛ 776line 775 didn't jump to line 776 because the condition on line 775 was never true
776 print(
777 f" {plan.package.name} v{plan.version}: legs kept from the"
778 " discarded prepare; the base did not move its directory"
779 )
780 continue
781 validate_member(self._root, plan, release_dirs)
782 prepared = True
783 finally:
784 if not prepared:
785 rollback_prepare(self._root, self._members, floor_changes)
786 git.switch(root, self.base)
787 git.delete_branch(root, self.branch)
788 title = release_title([(plan.package.name, plan.version) for plan in plans])
789 body = (
790 "## Release summary\n"
791 + "\n".join(f"- **{plan.package.name}** v{plan.version}" for plan in plans)
792 + f"\n\nMined-At: {mined_at}"
793 )
794 return Submission(title=title, body=body)
795
796 def _require_fresh_base(self) -> None:
797 """Refuse a prepared branch whose base moved under it.
798
799 hse merges the default branch into a stale release branch and
800 re-verifies; livery's entries carry a mining point instead,
801 and commits merged in beneath it would ship under-documented,
802 so the stale branch is refused outright: abandon and re-run,
803 and the fresh prepare mines everything. Deviation from hse
804 ruled 2026-09-04 with issue #161.
805 """
806 root = self._root
807 git.fetch(root)
808 base_sha = git.run(root, "rev-parse", f"origin/{self.base}").strip()
809 if git.is_ancestor(root, base_sha, "HEAD"):
810 return
811 fail(
812 f"{self.base} has moved past this prepared release: commits"
813 " it gained are not mined into the branch's entries, and"
814 " releasing them under-documented is worse than re-preparing."
815 f"\n Run `{footman.prog()} abandon` on the branch, then"
816 f" `{footman.prog()} workflow.release` again."
817 )
818
819 def _submission_from_ref(self) -> Submission:
820 """The title and body the branch's member list states.
821
822 Recovery reads the branch's committed member list, never the
823 working tree and never commit subjects: a checkout standing
824 elsewhere holds a different tree, and a rider commit is not
825 part of what was prepared, so the rebuilt title stays
826 consistent with the content the squash will carry.
827 """
828 root = self._root
829 mined_at = git.run(root, "merge-base", "HEAD", f"origin/{self.base}").strip()
830 pairs = member_pairs_at(root, "HEAD") or []
831 body = (
832 "## Release summary\n"
833 + "\n".join(f"- **{name}** v{version}" for name, version in pairs)
834 + f"\n\nMined-At: {mined_at}"
835 )
836 return Submission(title=release_title(pairs), body=body)
837
838 def on_merged(self) -> None:
839 """The merge point dispatches the wave; follow it to its verdict.
840
841 The wave's run is awaited by its id, then followed the way
842 ``ci.status --point=release --wait`` follows it, so the act
843 ends with the wave's own verdict and exit; the receipt tags
844 say when each member is done. A wave timeout of zero reports
845 the merge and names the dispatch verb as the confirmation
846 instead of waiting: the engine's own tests run against a
847 forge with no merge point.
848 """
849 if self._wave_timeout <= 0:
850 print(
851 " merged; the merge point dispatches the wave, confirm it with"
852 f" `{footman.prog()} workflow.release.dispatch`"
853 )
854 return
855 transient = Transient(interval=_WAVE_POLL)
856 before = {run.id for run in _wave_runs_answered(self._repo, transient)}
857 run_id = await_wave(
858 self._repo,
859 before=before,
860 timeout=self._wave_timeout,
861 transient=transient,
862 )
863 if run_id is None:863 ↛ 864line 863 didn't jump to line 864 because the condition on line 863 was never true
864 fail(
865 "merged, but no release wave appeared within"
866 f" {self._wave_timeout:.0f}s: the merge point's dispatch job"
867 " runs after main's own verdict, so a red main or a slow"
868 " queue is the usual cause. The recovery is"
869 f" `{footman.prog()} workflow.release.dispatch` from any"
870 " checkout, which answers green once the wave is up."
871 )
872 print(
873 f" merged; the merge point dispatched the wave, run {run_id}; the"
874 " receipt tags say when each member is done"
875 )
876 run = next(
877 (r for r in _wave_runs_answered(self._repo, transient) if r.id == run_id),
878 None,
879 )
880 if run is None:880 ↛ 881line 880 didn't jump to line 881 because the condition on line 880 was never true
881 return
882 from livery.workshop._ci_tasks import follow_run
883
884 code = follow_run(self._repo, "release", run, timeout=self._wave_timeout)
885 self._trace_the_chain()
886 if code:
887 raise SystemExit(code)
888
889 def _trace_the_chain(self) -> None:
890 """Fold everything this release caused into the command's own trace.
891
892 A release is two commits and one hop. The branch commit carries
893 the pull request's run, and the commit its merge made carries
894 the base's own run and the wave dispatched at it. One walk from
895 the branch holds the whole story, and a red wave's is the one
896 most worth having, so this runs before the exit code does.
897
898 The branch is already gone from a checkout that recovered a
899 release it did not prepare, and then the release squash on the
900 base is where the walk starts instead.
901 """
902 from livery.workshop._traces import drop_chain
903
904 root = self._root
905 at = git.sha_of(root, self.branch)
906 if not at:906 ↛ 908line 906 didn't jump to line 908 because the condition on line 906 was always true
907 at, _subject = newest_release_squash(root, self.base)
908 if line := drop_chain(self._repo, root, commit=at):
909 print(f" {line}")
910
911
912#: The longest release title. GitHub's auto-merge refuses a squash
913#: headline it judges too long, and its refusal names 80 characters.
914TITLE_LIMIT = 80
915
916
917def release_title(pairs: Sequence[tuple[str, str]]) -> str:
918 """The release pull request's title: each member with its version, or a count.
919
920 The title is the squash commit's headline, and arming hands it to
921 GitHub's auto-merge, which refuses a long one. A set whose title
922 would pass `TITLE_LIMIT` characters is counted instead; the pull
923 request's body and the commit's body list every member.
924 """
925 listed = ", ".join(f"{name} v{version}" for name, version in pairs)
926 title = f"chore(release): released {listed}"
927 if len(title) <= TITLE_LIMIT:
928 return title
929 counted = "1 package" if len(pairs) == 1 else f"{len(pairs)} packages"
930 return f"chore(release): released {counted}"
931
932
933def runs_the_train(branch: str) -> bool:
934 """Whether `workflow.release` on *branch* is the release train, not the dev act.
935
936 ``main`` and the engine's reserved ``workflow/`` branches release;
937 any other branch builds a dev wheel straight from its commit.
938 """
939 return branch == "main" or branch.startswith("workflow/")
940
941
942def fresh_receipts(root: Path) -> None:
943 """Fetch origin's tags, so a derivation reads every receipt a wave cut.
944
945 A release wave tags its receipts on the remote, and this checkout
946 holds them only after a fetch: a derivation from stale tags names
947 versions the index already has. A checkout with no origin has only
948 its own tags to read; one that cannot reach origin derives from its
949 own and says so.
950 """
951 if not git.has_remote(root, "origin"):951 ↛ 952line 951 didn't jump to line 952 because the condition on line 951 was never true
952 return
953 try:
954 git.fetch_tags(root)
955 except git.GitError as error:
956 print(
957 " origin could not be fetched, so the versions come from this"
958 f" checkout's own tags: {error}"
959 )
960
961
962def local_release(root: Path, members: tuple[Package, ...]) -> None:
963 """Everything that stays on this machine, then the stamps roll back.
964
965 Derive, stamp (so the built wheels carry the would-be versions),
966 build, run the isolated legs, print the would-be release, restore
967 the tree; ``dist/`` and the report remain. Publishing consent is
968 never asked because nothing leaves the machine. The derivation
969 reads origin's receipts, fetched first, so it names the versions
970 the armed act would ([livery.workshop._release_driver.fresh_receipts][]).
971 Before any of it, the act refuses while a file it would write has
972 changes of its own, since the restore would discard them; a change
973 anywhere else in the tree is left alone.
974 """
975 _require_unchanged(root, members)
976 fresh_receipts(root)
977 plans = derive_plans(root, members)
978 print(" act: local; nothing leaves this machine")
979 floor_changes: list[str] = []
980 try:
981 floor_changes = bump_set_floors(root, plans)
982 for plan in plans:
983 prepare_release(root, plan.package.path, plan.version)
984 _lifecycle.build_release(plan.package, root)
985 verify_set(root, plans)
986 release_dirs = _wheel_dists(plans)
987 for plan in plans:
988 validate_member(root, plan, release_dirs)
989 listed = ", ".join(f"{plan.package.name} v{plan.version}" for plan in plans)
990 print(f" would release: {listed}")
991 print(" wheels in each member's dist/; the tree is restored")
992 finally:
993 rollback_prepare(root, members, floor_changes)
994
995
996#: The release workflow, as the forges address one for a dispatch and
997#: name one on a run (GitHub lists the path, Gitea the file; the
998#: basename is the comparison).
999RELEASE_WORKFLOW = "release.yml"
1000
1001
1002def _wave_runs(repo: Repository) -> tuple[Run, ...]:
1003 """The release workflow's newest dispatched runs, newest first.
1004
1005 Asked of the workflow's own listing, so every poll of a wave reads
1006 one page whatever else was dispatched.
1007 """
1008 from livery.workshop._ci_tasks import RECENT_RUNS
1009
1010 return tuple(
1011 run
1012 for run in repo.checks.runs(
1013 event="workflow_dispatch", workflow=RELEASE_WORKFLOW, limit=RECENT_RUNS
1014 )
1015 if run.workflow.rsplit("/", 1)[-1] == RELEASE_WORKFLOW
1016 )
1017
1018
1019#: Seconds between the train's polls of the wave's runs.
1020_WAVE_POLL = 5.0
1021
1022
1023def _wave_runs_answered(
1024 repo: Repository, transient: Transient, *, interval: float = _WAVE_POLL
1025) -> tuple[Run, ...]:
1026 """The wave's runs, asked again while the forge does not answer.
1027
1028 An unreadable poll is a retry, as ``fm ci.status --wait`` treats it:
1029 *transient* counts the run of them, and a spent budget ends the train
1030 with the forge's words and the command that follows the wave, which
1031 runs on in CI whatever happens here.
1032 """
1033 try:
1034 return follow(
1035 repo,
1036 lambda: _wave_runs(repo),
1037 subject=_WAVE_SUBJECT,
1038 interval=interval,
1039 timeout=None,
1040 quiet=None,
1041 transient=transient,
1042 )
1043 except ForgeUnreachable as exc:
1044 fail(exc.line.strip())
1045
1046
1047def _wave_subject() -> str:
1048 """What a spent budget names: the wave runs on, and the verb that follows it."""
1049 return (
1050 "the wave runs on in CI; follow it with"
1051 f" `{footman.prog()} ci.status --point=release --wait`"
1052 )
1053
1054
1055_WAVE_SUBJECT = _wave_subject
1056
1057
1058def await_wave(
1059 repo: Repository,
1060 *,
1061 before: set[int],
1062 timeout: float = 1800.0,
1063 interval: float = _WAVE_POLL,
1064 transient: Transient | None = None,
1065) -> int | None:
1066 """The id of the newest wave run not in *before*, or ``None`` when none appears.
1067
1068 Any state counts: a wave that already finished by the time the
1069 poll saw it is still the wave that ran, and a confirmation that
1070 demanded a live run would miss a fast forge. An unreadable poll is
1071 retried within *transient*'s budget.
1072 """
1073
1074 def new_run() -> int | Pending:
1075 new = [run for run in _wave_runs(repo) if run.id not in before]
1076 return new[0].id if new else Pending()
1077
1078 try:
1079 return follow(
1080 repo,
1081 new_run,
1082 subject=_WAVE_SUBJECT,
1083 interval=interval,
1084 timeout=timeout,
1085 quiet=None,
1086 transient=transient,
1087 )
1088 except ForgeUnreachable as exc:
1089 fail(exc.line.strip())
1090 except FollowTimedOut:
1091 return None
1092
1093
1094def dispatch_flow(
1095 root: Path,
1096 repo: Repository,
1097 *,
1098 base: str = "main",
1099 at: str = "",
1100 workshop: str = "",
1101 again: bool = False,
1102 timeout: float = 60.0,
1103 interval: float = 2.0,
1104) -> list[str]:
1105 """Dispatch the wave for a merged, unpublished release, or say why not.
1106
1107 Reads the manifest on ``origin/<base>`` after a fetch, whatever
1108 commit this checkout stands on, or at *at*, an older release squash
1109 a later release has moved past. A checkout behind the base would
1110 otherwise send the wave to the squash a later release took over.
1111 *workshop* names a released driver for the wave instead of the
1112 squash's own, the recovery for a wave whose workshop was the fault;
1113 empty runs the squash's. Green when there is none, or when
1114 every member's receipt tag is already on the remote: the
1115 manifest is permanent residue of the last release, so presence
1116 is not the signal, missing receipts are. A wave already in
1117 flight is reported green with its run id. A wave that already ran
1118 at the squash with the squash's own driver and ended failure is
1119 reported green too, with its run and the recoveries, and nothing
1120 is dispatched: the same wave fails the same way, and every merge
1121 would otherwise start one more copy of it. *again* dispatches it
1122 anyway, the gesture by hand once the cause is gone, and a named
1123 *workshop* is another wave. Otherwise the wave is dispatched on
1124 *base* with the commit that stamped the manifest as its ``ref``
1125 input, never this run's own sha, so an unrelated merge landing
1126 first cannot move the wave onto another tree; the dispatch is
1127 confirmed by the run id that appears, or refused with the reason.
1128 Remote state only, receipts by ``ls-remote`` and runs by the
1129 forge, so any checkout answers the same as CI.
1130 """
1131 from livery.workshop._publish import MANIFEST, read_manifest
1132
1133 where = at or _base_ref(root, base)
1134 text = git.file_at(root, where, MANIFEST)
1135 recorded = read_manifest(text) if text else None
1136 if not recorded:
1137 return [f" no release manifest at {where}: nothing to dispatch"]
1138 cut = set(git.remote_tags(root))
1139 receipts = [f"packages/{directory}/v{version}" for directory, version in recorded]
1140 missing = [tag for tag in receipts if tag not in cut]
1141 if not missing:
1142 return [f" every receipt is cut ({', '.join(receipts)}): nothing to dispatch"]
1143 live = [run for run in _wave_runs(repo) if run.status != "completed"]
1144 if live:
1145 return [
1146 f" the wave is already in flight: run {live[0].id};"
1147 f" uncut so far: {', '.join(missing)}"
1148 ]
1149 stamping = at or git.last_commit_touching(root, MANIFEST, ref=where)
1150 if not stamping:1150 ↛ 1151line 1150 didn't jump to line 1151 because the condition on line 1150 was never true
1151 return [
1152 f" {MANIFEST} is at {where} but no commit touches it: nothing to dispatch"
1153 ]
1154 _require_release_squash(root, stamping, base)
1155 if not workshop and not again:
1156 failed = _failed_wave_at(root, repo, stamping)
1157 if failed is not None:
1158 prog = footman.prog()
1159 return [
1160 f" a wave already ran at {stamping[:12]} and ended failure: run"
1161 f" {failed.id} ({repo.web_url()}/actions/runs/{failed.id}); the same"
1162 f" wave fails the same way, so none is dispatched. Uncut:"
1163 f" {', '.join(missing)}",
1164 f" to run it again once the cause is gone: `{prog}"
1165 " workflow.release.dispatch --again`; with a released driver:"
1166 f" `--workshop=<version>`; to give the release up: `{prog}"
1167 " workflow.release --abandon`",
1168 ]
1169 seen = {run.id for run in _wave_runs(repo)}
1170 inputs = {"ref": stamping}
1171 if workshop:
1172 inputs["workshop"] = workshop
1173 try:
1174 repo.checks.dispatch(RELEASE_WORKFLOW, ref=base, inputs=inputs)
1175 except ForgeError as error:
1176 # Red, never a printed line: the merge point's verdict is the
1177 # exit code, and a wave that did not start leaves the release
1178 # uncut until someone reads the log.
1179 fail(
1180 f"the forge refused the dispatch: {error}; uncut:"
1181 f" {', '.join(missing)}. Nothing started; on GitHub the job"
1182 " needs the actions: write grant, and the recovery by hand"
1183 f" is `{footman.prog()} workflow.release.dispatch`"
1184 )
1185 import time
1186
1187 deadline = time.monotonic() + timeout
1188 while time.monotonic() < deadline:
1189 new = [run for run in _wave_runs(repo) if run.id not in seen]
1190 if new:
1191 driver = f" driven by {workshop}" if workshop else ""
1192 return [
1193 f" dispatched the wave at {stamping[:12]}{driver}: run {new[0].id};"
1194 f" uncut: {', '.join(missing)}"
1195 ]
1196 time.sleep(interval)
1197 return [
1198 " the dispatch was accepted but no wave run appeared within"
1199 f" {timeout:.0f}s; re-run `{footman.prog()} workflow.release.dispatch`,"
1200 " which reports a wave that has since appeared"
1201 ]
1202
1203
1204def _failed_wave_at(root: Path, repo: Repository, squash: str) -> Run | None:
1205 """The newest dispatched wave about *squash* that ended failure, or None.
1206
1207 The runs about the squash are the forge's listing for it and the
1208 runs that recorded themselves as its (`runs_about`), since a wave
1209 the forge filed under a tip that moved on is still the squash's.
1210 A cancelled wave, or one that never ran, is not a failure here:
1211 the next merge dispatches again for those, as for a died merge
1212 run.
1213 """
1214 from livery.workshop._traces import runs_about
1215
1216 caused, _lines = runs_about(root, repo, squash)
1217 ids = {item.run_id for item in caused if item.event == "workflow_dispatch"}
1218 failed = [
1219 run
1220 for run in _wave_runs(repo)
1221 if str(run.id) in ids
1222 and run.status == "completed"
1223 and run.conclusion == "failure"
1224 ]
1225 return max(failed, key=lambda run: run.id) if failed else None
1226
1227
1228def _require_release_squash(root: Path, stamping: str, base: str) -> None:
1229 """Refuse to send the wave to a commit the wave itself would refuse.
1230
1231 The wave publishes only from a release squash, recognised by the
1232 ``Mined-At`` line the pull request body becomes at the merge. The
1233 last commit touching the manifest on a release branch is the
1234 branch's own stamp commit, which carries no such line, so a
1235 dispatch from a checkout left on that branch would send a wave
1236 that refuses. The refusal names the squash on the base instead.
1237 """
1238 from livery.workshop._publish import mined_at
1239
1240 if mined_at(git.commit_message(root, stamping)):
1241 return
1242 squash, subject = newest_release_squash(root, base)
1243 prog = footman.prog()
1244 if squash:1244 ↛ 1245line 1244 didn't jump to line 1245 because the condition on line 1244 was never true
1245 where = (
1246 f"the newest release squash on origin/{base} is {squash[:12]}"
1247 f" ({subject}); run `{prog} workflow.release.dispatch` from {base},"
1248 f" or `{prog} workflow.release.dispatch --at={squash[:12]}` here"
1249 )
1250 else:
1251 where = f"origin/{base} holds no release squash in its recent history"
1252 fail(
1253 f"{stamping[:12]} carries no Mined-At line: it is a branch's stamp"
1254 " commit, not a release squash, and the wave would refuse it."
1255 f" {where}"
1256 )
1257
1258
1259def newest_release_squash(root: Path, base: str = "main") -> tuple[str, str]:
1260 """The newest release squash on the base, as (sha, subject); ("", "") when none."""
1261 from livery.workshop._publish import mined_at
1262
1263 for sha, subject in git.recent_commits(root, 50, ref=_base_ref(root, base)):
1264 if subject.startswith("chore(release): released") and mined_at(1264 ↛ 1267line 1264 didn't jump to line 1267 because the condition on line 1264 was never true
1265 git.commit_message(root, sha)
1266 ):
1267 return sha, subject
1268 return "", ""
1269
1270
1271def _base_ref(root: Path, base: str) -> str:
1272 """``origin/<base>`` after a fetch when the clone knows it, else HEAD.
1273
1274 The release squashes live on the base. HEAD equals the base on the
1275 merge point and on a person's main, and differs on a release
1276 branch, whose history lacks the squash it was merged as; a clone
1277 without the remote (a rig) has only HEAD.
1278 """
1279 with contextlib.suppress(git.GitError):
1280 git.fetch(root)
1281 try:
1282 git.object_id(root, f"origin/{base}")
1283 except git.GitError:
1284 return "HEAD"
1285 return f"origin/{base}"
1286
1287
1288def pending_release_waves(
1289 root: Path, base: str = "main"
1290) -> tuple[tuple[str, tuple[str, ...]], ...]:
1291 """Every recent release squash whose receipts are not all cut, oldest first.
1292
1293 A merged release whose wave died leaves the squash on the base
1294 with the stamps and changelogs landed and receipt tags missing.
1295 Re-preparing from that state derives an empty release (measured:
1296 an empty pull request the forge never agrees to merge), so the
1297 recovery is the wave at the squash, never a new pull request.
1298 Every release squash in the base's recent history is consulted, so
1299 a later release never strands an earlier died wave, and a checkout
1300 standing on a release branch still finds the squash it was merged
1301 as. A later release squash naming a package takes over that
1302 package's uncut receipt, so a squash abandoned for a new release
1303 (`fm workflow.release --abandon`) is never offered again. Each
1304 entry is the squash sha and its missing receipt tags.
1305 """
1306 from livery.workshop._publish import discover_release
1307
1308 cut = set(git.remote_tags(root))
1309 pending: list[tuple[str, tuple[str, ...]]] = []
1310 # Newest first: the packages a later release squash names.
1311 taken: set[str] = set()
1312 for sha, subject in git.recent_commits(root, 50, ref=_base_ref(root, base)):
1313 if not subject.startswith("chore(release): released"):
1314 continue
1315 released = discover_release(root, sha)
1316 missing = tuple(
1317 f"{package.path}/v{version}"
1318 for package, version in released
1319 if f"{package.path}/v{version}" not in cut and package.path not in taken
1320 )
1321 taken.update(package.path for package, _version in released)
1322 if missing:
1323 pending.append((sha, missing))
1324 pending.reverse()
1325 return tuple(pending)
1326
1327
1328def pending_release_wave(root: Path) -> tuple[str, tuple[str, ...]] | None:
1329 """The oldest release squash with an uncut receipt, or None.
1330
1331 The set-blind selection, for a dispatch with no set named:
1332 recoveries run in order, oldest first.
1333 """
1334 waves = pending_release_waves(root)
1335 return waves[0] if waves else None
1336
1337
1338def pending_release_wave_for(
1339 root: Path, members: tuple[Package, ...]
1340) -> tuple[str, tuple[str, ...]] | None:
1341 """The oldest uncut squash whose receipts touch *members*, or None.
1342
1343 A release of one set must find its own died wave even when an
1344 older squash of another set is uncut too: that squash is the
1345 other set's recovery, named by the caller, never a reason to
1346 prepare this set again from a tree already stamped.
1347 """
1348 for sha, missing in pending_release_waves(root):
1349 if uncut_in_set(missing, members):
1350 return (sha, missing)
1351 return None
1352
1353
1354def uncut_in_set(
1355 missing: tuple[str, ...], members: tuple[Package, ...]
1356) -> tuple[str, ...]:
1357 """The uncut receipts, `packages/<member>/v<x>`, that belong to *members*."""
1358 names = {member.member for member in members}
1359 return tuple(tag for tag in missing if receipt_member(tag) in names)
1360
1361
1362release_group = workflow.group("release", help="The release train")
1363
1364
1365@release_group.default(interactive=True)
1366def workflow_release(
1367 *paths: str,
1368 armed: Annotated[bool, doc("arm the release PR to merge on green")] = False,
1369 local: Annotated[
1370 bool, doc("derive, build, validate, report; nothing leaves the machine")
1371 ] = False,
1372 force_unverified_base: Annotated[
1373 bool, doc("release without waiting for the base's own CI")
1374 ] = False,
1375 workshop: Annotated[
1376 str, doc("a released livery-workshop version to drive a re-dispatched wave")
1377 ] = "",
1378 abandon: Annotated[
1379 bool,
1380 doc(
1381 "prepare a new release over a died wave of this set instead of"
1382 " re-dispatching it"
1383 ),
1384 ] = False,
1385) -> None:
1386 """Release a set of packages: the branch decides the act.
1387
1388 Names the set positionally (``packages/forge`` or just ``forge``).
1389 On a main-family branch this is the release train: one PR,
1390 receipts per member, re-running the recovery at every step;
1391 ``--armed`` follows the pull request to its squash and the wave
1392 to its verdict, from main, the way ``submit --armed`` follows a
1393 feature pull request, and an unarmed run returns at once. On
1394 any other branch it is the dev act: a wheel straight from the
1395 branch at a dev version, published only to the configured custom
1396 index after a confirmation, no reserved branch, no PR, no tags.
1397 ``--local`` is everything that stays on this machine, on either
1398 branch mode. ``--workshop`` applies only to the recovery of a
1399 died wave: the named release drives the wave in place of the
1400 squash's own workshop. ``--abandon`` gives up that recovery: when
1401 no released workshop can drive the died wave, a new release of
1402 the set takes its uncut receipts over.
1403 """
1404 from livery.workshop._dev_release import dev_release
1405 from livery.workshop._extensions import workspace_root
1406 from livery.workshop._forge_lane import this_repository
1407
1408 root = workspace_root()
1409 if root is None:1409 ↛ 1410line 1409 didn't jump to line 1410 because the condition on line 1409 was never true
1410 fail("no workspace: no workshop.toml above the working directory")
1411 if not paths:1411 ↛ 1412line 1411 didn't jump to line 1412 because the condition on line 1411 was never true
1412 fail(
1413 f"name the set: `{footman.prog()} workflow.release forge` (one package) or"
1414 f" `{footman.prog()} workflow.release forge workshop` (an atomic set)"
1415 )
1416 members = resolve_set(root, tuple(paths))
1417 branch = git.current_branch(root)
1418 if not branch:
1419 fail(
1420 "HEAD is detached, and the branch decides the act. Check out a"
1421 " branch (main for the release train, any feature branch for a"
1422 " dev build), then run this again."
1423 )
1424 if not runs_the_train(branch):
1425 dev_release(root, members, local=local)
1426 return
1427 if local:
1428 local_release(root, members)
1429 return
1430 print(f" act: release train, from '{branch}'")
1431 pending = pending_release_wave_for(root, members)
1432 repo = this_repository(root)
1433 if abandon:1433 ↛ 1446line 1433 didn't jump to line 1446 because the condition on line 1433 was always true
1434 if pending is None:
1435 fail(
1436 "--abandon gives up a died wave of this set, and no release"
1437 " squash has an uncut receipt in it; drop the flag to prepare"
1438 " a release"
1439 )
1440 squash, missing = pending
1441 print(
1442 f" release squash {squash[:12]} abandoned; this release takes over"
1443 f" its uncut receipts: {', '.join(uncut_in_set(missing, members))}"
1444 )
1445 pending = None
1446 if pending is not None:1446 ↛ 1447line 1446 didn't jump to line 1447 because the condition on line 1446 was never true
1447 squash, missing = pending
1448 print(f" release squash {squash[:12]} has uncut receipts:")
1449 for name in missing:
1450 print(f" {name}")
1451 # CI publishes, never this machine: the wave is dispatched
1452 # at the squash, the duplicate-tolerant wave walks past what
1453 # an earlier attempt already did, and nothing new prepares.
1454 print(" dispatching the wave at the squash; nothing new prepares")
1455 for line in dispatch_flow(root, repo, at=squash, workshop=workshop):
1456 print(line)
1457 print(" re-run to release work newer than the squash")
1458 return
1459 for squash, missing in pending_release_waves(root):
1460 # An uncut receipt outside this set is that set's recovery,
1461 # named so a person can run it; this release goes ahead.
1462 inside = uncut_in_set(missing, members)
1463 missing = tuple(tag for tag in missing if tag not in inside)
1464 if not missing:1464 ↛ 1466line 1464 didn't jump to line 1466 because the condition on line 1464 was always true
1465 continue
1466 others = " ".join(sorted({receipt_member(tag) for tag in missing}))
1467 print(
1468 f" release squash {squash[:12]} has uncut receipts outside this"
1469 f" set: {', '.join(missing)}; `{footman.prog()} workflow.release"
1470 f" {others}` re-dispatches its wave"
1471 )
1472 if workshop:1472 ↛ 1473line 1472 didn't jump to line 1473 because the condition on line 1472 was never true
1473 fail(
1474 "--workshop pins the driver of a re-dispatched wave, and no"
1475 " release squash has an uncut receipt; drop the flag to prepare"
1476 " a release"
1477 )
1478 run_release(
1479 partial(
1480 ReleaseDriver,
1481 root,
1482 repo,
1483 members,
1484 armed=armed,
1485 force_unverified_base=force_unverified_base,
1486 ),
1487 repo,
1488 root,
1489 armed=armed,
1490 )
1491
1492
1493def run_release(
1494 make_driver: Callable[[], ReleaseDriver],
1495 repo: Repository,
1496 root: Path,
1497 *,
1498 armed: bool,
1499) -> None:
1500 """Drive a release through the engine; an armed one re-derives a stale set.
1501
1502 An armed release whose follow ends red because the base moved
1503 under its set prepares again on the moved base and follows again,
1504 up to [livery.workshop._release_driver.REDERIVE_LIMIT] prepares
1505 in all; any other red is the release's verdict and exits with it.
1506 """
1507 for attempt in range(1, REDERIVE_LIMIT + 1):1507 ↛ exitline 1507 didn't return from function 'run_release' because the loop on line 1507 didn't complete
1508 driver = make_driver()
1509 try:
1510 run_workflow(driver, repo, root)
1511 return
1512 except SystemExit:
1513 if (
1514 not armed
1515 or attempt == REDERIVE_LIMIT
1516 or not set_moved(repo, root, driver.name)
1517 ):
1518 raise
1519 print(
1520 f" {driver.branch}: the base moved under the set while its pull"
1521 f" request waited; re-deriving ({attempt} of"
1522 f" {REDERIVE_LIMIT - 1} re-derives)"
1523 )
1524
1525
1526#: How many times an armed release prepares in all: the first prepare
1527#: and its re-derives on a base that keeps moving under the set. A
1528#: base that moves faster than a release can prepare is a repository
1529#: where releases need merges held, and saying so beats looping.
1530REDERIVE_LIMIT = 3
1531
1532
1533def set_moved(repo: Repository, root: Path, name: str) -> bool:
1534 """Whether release *name*'s open pull request is stale in its set's paths."""
1535 from livery.workshop._workflow_state import workflow_states
1536
1537 git.fetch(root)
1538 return any(
1539 wf.name == name and wf.blocker.name == "STALE_SET"
1540 for wf in workflow_states(repo, root)
1541 )
1542
1543
1544@release_group.task(name="dispatch")
1545def workflow_release_dispatch(
1546 at: Annotated[
1547 str, doc("an older release squash to dispatch instead of HEAD's")
1548 ] = "",
1549 workshop: Annotated[
1550 str, doc("a released livery-workshop version to drive the wave")
1551 ] = "",
1552 again: Annotated[
1553 bool, doc("dispatch although a wave already failed at the squash")
1554 ] = False,
1555) -> None:
1556 """Dispatch the release wave for a merged, unpublished release; green otherwise.
1557
1558 The merge point's last task, and the recovery gesture by hand:
1559 it reads the manifest at HEAD and the receipts on the remote, so
1560 on a normal day it prints green, after a died merge run it
1561 dispatches, a wave in flight is reported with its run id, and a
1562 wave that already failed at the squash is reported with its run
1563 and dispatched again only on ``--again``. ``--at`` names an older
1564 release squash a later release has moved past; ``--workshop``
1565 names a released driver for a wave whose own workshop was the
1566 fault.
1567 """
1568 from livery.workshop._extensions import workspace_root
1569 from livery.workshop._forge_lane import this_repository
1570
1571 root = workspace_root()
1572 if root is None:
1573 fail("no workspace: no workshop.toml above the working directory")
1574 for line in dispatch_flow(
1575 root, this_repository(root), at=at, workshop=workshop, again=again
1576 ):
1577 print(line)
1578
1579
1580@release_group.task(name="check-title", hidden=True)
1581def workflow_release_check_title(
1582 title: Annotated[str, doc("the PR title CI observed")] = "",
1583) -> None:
1584 """Verify a release PR's title against the release's member list.
1585
1586 The publish wave discovers a release from the squash's member
1587 list; the title is presentation. This job keeps the two
1588 consistent: the gate job runs this first, so a title that no
1589 longer names what the list prepared is refused before the
1590 union and the verdict, and the merge waits for a person to fix
1591 the title. Without ``--title`` the title
1592 comes from the runner's event payload; a run that is not a pull
1593 request, or a pull request off a release branch, is green here
1594 and says so.
1595 """
1596 from livery.workshop._extensions import workspace_root
1597
1598 root = workspace_root()
1599 if root is None:1599 ↛ 1600line 1599 didn't jump to line 1600 because the condition on line 1599 was never true
1600 fail("no workspace: no workshop.toml above the working directory")
1601 if not title:
1602 # The shell passes no title: the event payload names it, and
1603 # names the head branch too. An explicit --title is always
1604 # checked, whatever branch the runner is on.
1605 from livery.workshop._ci_context import event_payload
1606
1607 pull = (event_payload() or {}).get("pull_request") or {}
1608 title = str(pull.get("title") or "")
1609 if not title:
1610 print(" not a pull request: no title to check")
1611 return
1612 head_ref = str((pull.get("head") or {}).get("ref") or "")
1613 if head_ref and not head_ref.startswith("workflow/release/"):1613 ↛ 1616line 1613 didn't jump to line 1616 because the condition on line 1613 was always true
1614 print(f" {head_ref} is not a release branch: nothing to check")
1615 return
1616 branch = git.current_branch(root)
1617 recorded = member_pairs_at(root, "HEAD")
1618 if not recorded:1618 ↛ 1619line 1618 didn't jump to line 1619 because the condition on line 1618 was never true
1619 print(f" {branch}: no release member list; nothing to check")
1620 return
1621 expected = release_title(recorded)
1622 if title and title != expected:
1623 fail(
1624 f"the PR title does not match what the member list prepared:\n"
1625 f" title: {title}\n prepared: {expected}\n"
1626 " The title is presentation rebuilt from the branch's"
1627 " member list; restore it or re-run workflow.release."
1628 )
1629 print(f" title matches the prepared release: {expected}")
1630
1631
1632@release_group.task(name="check-fresh", hidden=True)
1633def workflow_release_check_fresh(
1634 head: Annotated[str, doc("the pull request's head branch")] = "",
1635 base: Annotated[str, doc("the branch it merges into")] = "",
1636) -> None:
1637 """Refuse a release pull request whose base moved in its set's paths.
1638
1639 The gate job runs this last, so the time between the check and
1640 the merge it allows is as short as the forge makes it. The
1641 release's manifest names its members and the commit the prepare
1642 mined at; a commit the base gained since then under a member's
1643 directory is code the stamped changelog does not cover, and the
1644 squash's publish would refuse it after the merge, where nothing
1645 can fix the squash. Refused here, the pull request waits while
1646 `workflow.release` re-derives it in place. Without ``--head`` the
1647 branches come from the runner's event payload; a run that is not
1648 a pull request, or one off a release branch, is green and says so.
1649 """
1650 import json
1651
1652 from livery.workshop._extensions import workspace_root
1653 from livery.workshop._publish import MANIFEST, read_manifest
1654
1655 root = workspace_root()
1656 if root is None:1656 ↛ 1657line 1656 didn't jump to line 1657 because the condition on line 1656 was never true
1657 fail("no workspace: no workshop.toml above the working directory")
1658 if not head:1658 ↛ 1659line 1658 didn't jump to line 1659 because the condition on line 1658 was never true
1659 from livery.workshop._ci_context import event_payload
1660
1661 pull = (event_payload() or {}).get("pull_request") or {}
1662 if not pull:
1663 print(" not a pull request: nothing to check")
1664 return
1665 head = str((pull.get("head") or {}).get("ref") or "")
1666 base = base or str((pull.get("base") or {}).get("ref") or "")
1667 if not head.startswith("workflow/release/"):
1668 print(f" {head or 'this branch'} is not a release branch: nothing to check")
1669 return
1670 base = base or "main"
1671 text = git.file_at(root, "HEAD", MANIFEST)
1672 pairs = read_manifest(text) if text else None
1673 mined = ""
1674 if pairs:1674 ↛ 1677line 1674 didn't jump to line 1677 because the condition on line 1674 was always true
1675 with contextlib.suppress(ValueError, TypeError, AttributeError):
1676 mined = str(json.loads(text).get("mined-at") or "")
1677 if not pairs or not mined:
1678 print(f" {MANIFEST} records no mining point: nothing to check")
1679 return
1680 git.fetch(root)
1681 by_member = {pkg.member: pkg for pkg in discover_packages(root)}
1682 pathspecs = tuple(
1683 spec
1684 for directory, _ in pairs
1685 for spec in (
1686 release_pathspecs(by_member[directory])
1687 if directory in by_member
1688 else (f"packages/{directory}",)
1689 )
1690 )
1691 paths = tuple(f"packages/{directory}" for directory, _ in pairs)
1692 moved = _moved_paths(root, f"{mined}..origin/{base}", pathspecs)
1693 if moved:
1694 listed = "\n".join(f" {subject}" for subject in moved)
1695 members = " ".join(directory for directory, _ in pairs)
1696 fail(
1697 f"{base} moved under this release since its prepare at"
1698 f" {mined[:12]}:\n{listed}\n Merged, the squash would ship code"
1699 " its changelog does not cover. `"
1700 f"{footman.prog()} workflow.release {members}` re-derives it in"
1701 " place; an armed release does that itself."
1702 )
1703 print(f" fresh: {base} has not moved under {', '.join(paths)} since {mined[:12]}")
1704
1705
1706@release_group.task(name="build", hidden=True)
1707def workflow_release_build(
1708 ref: Annotated[str, doc("the release squash; empty means HEAD")] = "",
1709) -> None:
1710 """Build non-job-built release members and record their SHA-256 digests."""
1711 from livery.workshop._extensions import workspace_root
1712 from livery.workshop._publish import build_release_dists
1713
1714 root = workspace_root()
1715 if root is None:
1716 fail("no workspace: no workshop.toml above the working directory")
1717 manifest = build_release_dists(root, ref=ref)
1718 print(f" built release distributions and wrote {manifest.relative_to(root)}")
1719
1720
1721@release_group.task(name="publish", hidden=True)
1722def workflow_release_publish(
1723 ref: Annotated[str, doc("the release squash; empty means HEAD")] = "",
1724 prebuilt: Annotated[
1725 bool, doc("trust the dist/ the run collected for each member a job builds")
1726 ] = False,
1727) -> None:
1728 """Publish the squash at --ref: the wave, receipts cut per member.
1729
1730 The CI entry point after a release PR merges, and the recovery
1731 entry when a publish died mid-wave: everything already tagged is
1732 walked past. ``--ref`` exists because HEAD usually moves past the
1733 squash before a recovery runs. Each member publishes to the
1734 registry of the ecosystem its extensions release it to, and the
1735 wave reads what that registry serves through the probe they answer:
1736 the resolved index for a python package, the resolved conan target
1737 for a conan recipe that names a reference.
1738 ``--prebuilt`` says the jobs of the run already built the members
1739 they build before the wave, the workspace's ``job-built-members``
1740 answer: a platform-wheel member's dist/ holds the wheels collected
1741 from every platform, a conan member's the caches saved on every
1742 host, and the wave publishes them instead of building on this
1743 runner alone. Inside CI the wave decides that for itself: such a
1744 member whose dist/ already holds a file was fed by the run, since
1745 a runner's checkout starts with none.
1746 """
1747 import os
1748
1749 from livery.workshop._extensions import workspace_root
1750 from livery.workshop._publish import Registry, publish_release
1751 from livery.workshop._registries import resolve_registry
1752
1753 root = workspace_root()
1754 if root is None:1754 ↛ 1755line 1754 didn't jump to line 1755 because the condition on line 1754 was never true
1755 fail("no workspace: no workshop.toml above the working directory")
1756 target = resolve_registry(root, "python")
1757 if not target.publish_url:1757 ↛ 1758line 1757 didn't jump to line 1758 because the condition on line 1757 was never true
1758 from livery.workshop._dev_release import INDEX_VAR
1759
1760 fail(
1761 "no publish address resolved for python: the declaration"
1762 " names only a read index, and an upload endpoint is"
1763 " never defaulted. Declare [registries.python] publish in"
1764 f" workshop.toml, or set {INDEX_VAR}."
1765 )
1766 if not prebuilt:1766 ↛ 1767line 1766 didn't jump to line 1767 because the condition on line 1766 was never true
1767 prebuilt = collected_wheels(root, ref)
1768 # Each member's probe is its extensions' answer, asked once and
1769 # polled through the wave's whole wait.
1770 probes: dict[str, Registry] = {}
1771
1772 def registry_for(package: Package) -> Registry:
1773 probe = probes.get(package.path)
1774 if probe is None:
1775 probe = probes[package.path] = _lifecycle.registry(package)
1776 return probe
1777
1778 receipts = publish_release(
1779 root,
1780 registry_for,
1781 ref=ref,
1782 index_url=target.publish_url,
1783 # UV_PUBLISH_TOKEN is the explicit override; the resolved
1784 # target's credential is the same seam the probe reads, so a
1785 # forge registry publishes with the lane token unprompted.
1786 token=os.environ.get("UV_PUBLISH_TOKEN", "") or target.token,
1787 prebuilt=prebuilt,
1788 )
1789 print(f" wave: {len(receipts)} member(s) published")
1790
1791
1792def collected_wheels(root: Path, ref: str) -> bool:
1793 """Whether the run collected what a job built for this wave, judged inside CI alone.
1794
1795 The members a job builds before the wave are the workspace's
1796 ``job-built-members`` answer. A runner's checkout starts with no
1797 dist/, so a file in such a member's dist/ was collected from that
1798 job's artifact, and the wave trusts the collection; each member it
1799 trusts is printed with its job. Outside CI a dist/ may hold a stale
1800 local build, and the wave builds as asked.
1801 """
1802 from livery.workshop._ci_context import run_context
1803 from livery.workshop._publish import collected, discover_release
1804 from livery.workshop._queries import JOB_BUILT_MEMBERS, answer
1805
1806 if run_context() is None:
1807 return False
1808 built = answer(root, JOB_BUILT_MEMBERS)
1809 fed = False
1810 for package, _version in discover_release(root, ref or git.head_sha(root)):
1811 job = built.get(package.path)
1812 if job is not None and collected(package):
1813 print(
1814 f" prebuilt: {package.name}: the run collected what the {job} job"
1815 " built"
1816 )
1817 fed = True
1818 return fed