Coverage for packages/workshop/src/livery/workshop/_publish.py: 74%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, 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_isolated.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/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/conan/tests/test_conan_releases.py ran.

1"""Publish, probe, tag: the release train's receipt-cutting half.
2
3Runs where the release PR's squash landed, discovery reads the ref
4and nothing else: the members and their versions are the release's
5member list as committed at the ref. Names and versions come from the
6same place on purpose: reading names from the commit and versions
7from the working tree would pair this release's members with
8whatever a later release left in the tree, and the ``--ref``
9recovery runs from exactly such a checkout. The squash title is
10presentation, rebuilt from the same list, never parsed.
11
12The wave: a member becomes eligible when every in-set dependency it
13floors on has its receipt tag cut, and every eligible member runs
14its publish, index probe, tag chain concurrently. A failed member
15stops only its dependents; siblings complete and keep their tags,
16and a re-run walks past everything already tagged, the
17duplicate-tolerant publish making that safe.
18"""
19
20from __future__ import annotations
21
22import hashlib
23import json
24import os
25import re
26import subprocess
27import threading
28from collections.abc import Callable
29from concurrent.futures import ThreadPoolExecutor
30from dataclasses import dataclass
31from pathlib import Path
32from typing import TYPE_CHECKING, Any, Protocol
33
34import livery.footman as footman
35from livery import git
36from livery.footman import fail
37from livery.workshop import _lifecycle
38from livery.workshop._packages import Package, discover_packages
39
40if TYPE_CHECKING:
41 from livery.workshop._registries import RegistryTarget
42
43#: The release set's own record, committed on the release branch by
44#: prepare: every member's directory, name and version. Discovery,
45#: the title check and the recovery read it at the squash, so a
46#: recovery re-prepare whose stamps are already on the base (and so
47#: touch nothing else) still names every member.
48MANIFEST = ".release-manifest.json"
49
50
51def read_manifest(text: str) -> tuple[tuple[str, str], ...] | None:
52 """(package dir, version) pairs from manifest *text*, or None.
53
54 None for unreadable content, which the caller refuses: without
55 the list there is no record of what the release contains.
56 """
57 import json
58
59 try:
60 data = json.loads(text)
61 members = data["members"]
62 pairs = tuple((str(m["dir"]), str(m["version"])) for m in members)
63 except (ValueError, KeyError, TypeError):
64 return None
65 return pairs or None
66
67
68#: How long a member waits for the index to serve its version.
69PROBE_TIMEOUT = 300.0
70PROBE_POLL = 5.0
71
72
73class Registry(Protocol):
74 """The one probe the wave needs; livery.forge.SimpleRegistry fits."""
75
76 def versions(self, name: str) -> tuple[str, ...]:
77 """The published versions of *name*."""
78 ...
79
80
81@dataclass(frozen=True)
82class Receipt:
83 """One member's publish outcome."""
84
85 package: Package
86 version: str
87 tag: str
88 published: bool # False when the duplicate tolerance skipped it
89
90
91def discover_release(root: Path, ref: str) -> tuple[tuple[Package, str], ...]:
92 """The members the release squash at *ref* releases, each with its version.
93
94 The members and their versions are the release's member list,
95 ``.release-manifest.json``, as committed at *ref*: the record the
96 release branch writes when it prepares the set. They come in
97 release order, every dependency before its dependents
98 ([livery.workshop.order_topologically][]). A rider file in the
99 squash changes nothing here, which is what makes hand-editing a
100 release branch safe.
101
102 Args:
103 root: The workspace root.
104 ref: The commit whose member list is read, as git names it.
105
106 Returns:
107 Each released member and the version the list states for it.
108
109 Raises:
110 Failed: when the commit carries no readable member list, since
111 it is then no release squash, naming the flag that points
112 the publish at the squash; and when the list names a member
113 the workspace does not hold.
114 """
115 from livery.workshop._graph import order_topologically
116
117 pairs = read_manifest(git.file_at(root, ref, MANIFEST))
118 if pairs is None:
119 fail(
120 f"this commit is not a release squash: it carries no readable"
121 f" {MANIFEST}, the member list a release branch commits. Publish"
122 " runs on the merge commit of a workflow.release PR; pass"
123 " --ref=<squash sha> when HEAD has moved past it."
124 )
125 listed = {p.member: p for p in discover_packages(root)}
126 chosen: list[Package] = []
127 stated: dict[str, str] = {}
128 for name, version in pairs:
129 member = listed.get(name)
130 if member is None:
131 fail(
132 f"the release manifest at {ref[:10]} names"
133 f" packages/{name}, which is not a workspace package"
134 )
135 chosen.append(member)
136 stated[member.path] = version
137 in_order = order_topologically(tuple(chosen))
138 return tuple((member, stated[member.path]) for member in in_order)
139
140
141_MINED_AT_RE = re.compile(r"^Mined-At: ([0-9a-f]{7,40})$", re.M)
142
143
144def mined_at(message: str) -> str:
145 """The mining point a release squash's *message* records, or ``""``.
146
147 The driver writes ``Mined-At: <sha>`` into the pull request body,
148 which becomes the squash's message at the merge. A commit without
149 the line is not a release squash: a branch's own stamp commit, or
150 a squash whose body was rewritten. The wave and the dispatch judge
151 a commit by this one rule.
152 """
153 match = _MINED_AT_RE.search(message)
154 return match.group(1) if match else ""
155
156
157def movement_check(root: Path, package: Package, ref: str) -> None:
158 """Refuse when commits the entry never saw ride in this squash.
159
160 The movement analysis's backstop. The driver records the mining
161 point in the squash body (``Mined-At: <sha>``), so the moved
162 range is exact: commits between the mining point and the squash's
163 parent touching this member's paths are code the stamped entry
164 does not cover. A squash without the line is not the driver's,
165 and publishing it is refused for the same reason.
166 """
167 point = mined_at(git.commit_message(root, ref))
168 if not point:168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true
169 fail(
170 f"{package.name}: the squash at {ref[:10]} carries no Mined-At"
171 " line, so the movement backstop cannot run. Releases publish"
172 " only from workflow.release squashes; re-run the release to"
173 " produce one."
174 )
175 # The squash's first parent, spelled without a caret, which cmd.exe
176 # drops on its way to a git run through a `.cmd` launcher on Windows.
177 span = f"{point}..{ref}~1"
178 moved = git.log_paths(root, span, (f"packages/{package.member}",))
179 if moved:
180 listed = "\n".join(f" {s}" for s in moved)
181 fail(
182 f"{package.name}: commits the stamped entry never saw are in"
183 f" this squash:\n{listed}\n the release went stale after"
184 f" prepare. Re-run `{footman.prog()} workflow.release` to re-derive on the"
185 " moved base; publishing this squash would ship code the"
186 " changelog does not cover."
187 )
188
189
190#: The python registry kind name, kept in one constant so the base
191#: does not scatter registry-kind literals across functions.
192_PYTHON_REGISTRY = "python"
193
194
195def index_target(index_url: str, token: str) -> RegistryTarget:
196 """Make the python registry target an upload index names, *token* its credential.
197
198 The release train's wave hands it to each member that releases
199 python distributions, and the dev act to each member whose
200 distributions are all python's: both read and publish at the one
201 address the caller resolved.
202 """
203 from livery.workshop._registries import RegistryTarget
204
205 return RegistryTarget(
206 kind=_PYTHON_REGISTRY, url=index_url, publish_url=index_url, token=token
207 )
208
209
210def collected(package: Package) -> bool:
211 """Whether *package*'s ``dist/`` holds a file.
212
213 Inside CI a runner's checkout starts with no ``dist/``, so a file
214 there was collected from the artifact of a job that built the
215 member before the wave.
216 """
217 dist = package.directory / "dist"
218 return dist.is_dir() and any(path.is_file() for path in dist.iterdir())
219
220
221def probe_until_served(
222 registry: Registry,
223 name: str,
224 version: str,
225 *,
226 timeout: float = PROBE_TIMEOUT,
227 poll: float = PROBE_POLL,
228) -> None:
229 """Wait until the index serves *version*; the receipt's condition.
230
231 An accepted upload is not a served wheel, and the tag is a
232 receipt, so it waits on the probe, not the exit code.
233 """
234 from livery.workshop._verdict import FollowTimedOut, Pending, follow
235
236 def served() -> bool | Pending:
237 return True if version in registry.versions(name) else Pending()
238
239 try:
240 follow(
241 None,
242 served,
243 subject=f"{name} {version} on the index",
244 interval=poll,
245 timeout=timeout,
246 quiet=None,
247 retried=(),
248 )
249 except FollowTimedOut:
250 fail(
251 f"{name} {version} was uploaded but the index never served"
252 f" it within {timeout:.0f}s; re-run the publish once the"
253 " index settles, everything already tagged is walked past"
254 )
255
256
257def floor_probe(
258 package: Package,
259 by_path: dict[str, Package],
260 registry_for: Callable[[Package], Registry],
261 *,
262 coreleased: frozenset[str] = frozenset(),
263) -> None:
264 """Every declared floor must be servable before anything uploads.
265
266 A floor no index can satisfy strands every consumer at install
267 time, and refusing here is cheap where unpublishing is
268 impossible.
269 """
270 for edge in package.depends:
271 dependency = by_path.get(edge.path)
272 floor = getattr(edge, "floor", "")
273 if dependency is None or not floor:273 ↛ 274line 273 didn't jump to line 274 because the condition on line 273 was never true
274 continue
275 if f"{edge.path}/v{floor}" in coreleased:
276 continue # the wave itself serves this floor, receipts first
277 # The dependency's own registry: a floor across ecosystems (the
278 # extension on the library) lives in the conan target, not the
279 # python index.
280 served = registry_for(dependency).versions(dependency.name)
281 floor_key = tuple(int(x) for x in floor.split("."))
282 satisfied = any(
283 tuple(int(x) for x in v.split(".")) >= floor_key
284 for v in served
285 if v.replace(".", "").isdigit()
286 )
287 if not satisfied:
288 fail(
289 f"{package.name} floors {dependency.name} at {floor}, and"
290 " no served version satisfies it. Release"
291 f" {dependency.name} first (or in the same set), or the"
292 " uploaded wheel strands every consumer at install time."
293 )
294
295
296def cut_tag(root: Path, tag: str, ref: str) -> None:
297 """Cut and push the receipt, annotated, by name, idempotent."""
298 existing = git.tags(root)
299 if tag not in existing:
300 git.run(root, "tag", "-a", tag, ref, "-m", tag)
301 git.run(root, "push", "origin", tag)
302
303
304#: The words PyPI answers a new project's first upload with once one
305#: account has created as many projects as its limit allows for now.
306#: uv relays the server's message as text, and neither its exit code nor
307#: any structured output tells this refusal apart, so this match is the
308#: one place it is read; checked with uv 0.12.5.
309NEW_PROJECT_LIMIT = "Too many new projects created"
310
311
312def publish_release(
313 root: Path,
314 registry_for: Callable[[Package], Registry],
315 *,
316 ref: str = "",
317 index_url: str = "",
318 token: str = "",
319 probe_timeout: float = PROBE_TIMEOUT,
320 probe_poll: float = PROBE_POLL,
321 prebuilt: bool = False,
322) -> tuple[Receipt, ...]:
323 """The wave: verify, then publish, probe, tag per member.
324
325 Eligibility is dependency tags: a member starts when every in-set
326 dependency's receipt exists, independent members run abreast, a
327 failure stops only its dependents. Every read is *ref*-scoped.
328 Each member builds through its lifecycle's build, which judges the
329 tags of the wheels it writes, and publishes to the target of the
330 ecosystem its extensions release it to: the python target the
331 caller resolved, *index_url* with *token*, or the one the registry
332 ladder resolves for any other ecosystem. A member whose extensions
333 answer no registry, or more than one, refuses the wave before
334 anything uploads. With *prebuilt*, a member a job of the run builds
335 before the wave (the workspace's ``job-built-members`` answer) is
336 not built here: the wave publishes what the run collected into its
337 ``dist/``, and refuses one whose ``dist/`` holds nothing, naming
338 the job. Such a member's publish phase gets ``prebuilt`` true.
339 """
340 from livery.workshop._queries import JOB_BUILT_MEMBERS, answer
341 from livery.workshop._release import verify_release
342
343 resolved_ref = ref or git.head_sha(root)
344 discovered = discover_release(root, resolved_ref)
345 ordered = tuple(package for package, _version in discovered)
346 manifest = {package.name: version for package, version in discovered}
347 epoch = int(git.run(root, "log", "-1", "--format=%ct", resolved_ref).strip() or "0")
348 # Each member a job of the run builds before the wave, to the job.
349 built = answer(root, JOB_BUILT_MEMBERS) if prebuilt else {}
350
351 by_path = {p.path: p for p in discover_packages(root)}
352 coreleased = frozenset(f"{p.path}/v{manifest[p.name]}" for p in ordered)
353 from livery.workshop._registries import resolve_registry
354
355 # Each member goes to the target of the ecosystem its extensions
356 # release it to, and each target is resolved once, before anything
357 # uploads: a member with no registry or more than one, and a ladder
358 # that resolves no target, stop the wave while there is still nothing
359 # to undo. The python target is the one the caller resolved. A member
360 # that opts out of publishing needs no target and asks for none.
361 python_target = index_target(index_url, token)
362 targets = {python_target.kind: python_target}
363 releases_to = {p.path: _lifecycle.ecosystem(p) for p in ordered if p.publish}
364 for ecosystem in releases_to.values():
365 if ecosystem not in targets:
366 targets[ecosystem] = resolve_registry(root, ecosystem)
367 for package in ordered:
368 tag = f"{package.path}/v{manifest[package.name]}"
369 verify_release(root, tag, coreleased=coreleased)
370 movement_check(root, package, resolved_ref)
371 floor_probe(package, by_path, registry_for, coreleased=coreleased)
372
373 chosen = {p.path for p in ordered}
374 done: dict[str, threading.Event] = {p.path: threading.Event() for p in ordered}
375 receipts: dict[str, Receipt] = {}
376 failures: dict[str, BaseException] = {}
377 lock = threading.Lock()
378 # A registry may limit how many new projects one account creates in
379 # a period, as PyPI does. The members whose project the registry
380 # does not know yet upload one at a time, so a refusal stops at the
381 # first of them, and the ones after it do not try.
382 new_projects = [
383 p.name for p in ordered if p.publish and not registry_for(p).versions(p.name)
384 ]
385 first_upload = threading.Lock()
386 refused_new: list[str] = []
387
388 def _build_member(package: Package) -> None:
389 """Build the member, or trust what the job that builds it collected."""
390 job = built.get(package.path)
391 if job is None:
392 _lifecycle.build_release(package, root, epoch=epoch)
393 return
394 # The job built this member on each of its legs and the run
395 # collected what every leg made; a build here would replace
396 # that with what this runner's host alone can make.
397 if not collected(package):
398 fail(
399 f"{package.name}: --prebuilt, and dist/ holds nothing the {job}"
400 " job collected; re-run the release so that job builds it before"
401 " the wave"
402 )
403
404 def _first_upload(package: Package, version: str, target: RegistryTarget) -> bool:
405 """Upload a new project's first version, or name the limit that stops it."""
406 if refused_new:
407 raise SystemExit(
408 f"{package.name}: not uploaded: the registry already refused a"
409 f" new project in this wave ({refused_new[0]})"
410 )
411 try:
412 return _lifecycle.publish(
413 package,
414 root,
415 version=version,
416 target=target,
417 prebuilt=package.path in built,
418 )
419 except BaseException as exc:
420 if NEW_PROJECT_LIMIT not in str(exc):
421 raise
422 refused_new.append(package.name)
423 waiting = [name for name in new_projects if name not in receipts_named()]
424 raise SystemExit(
425 f"{package.name}: the registry refuses more new projects for now"
426 f" ({NEW_PROJECT_LIMIT}): it limits how many one account creates"
427 f" in a period. New projects still to create: {', '.join(waiting)}."
428 f" Re-dispatch later with `{footman.prog()} workflow.release.dispatch`;"
429 " the wave walks past what it already published."
430 ) from exc
431
432 def receipts_named() -> set[str]:
433 with lock:
434 return {receipt.package.name for receipt in receipts.values()}
435
436 def _run_member(package: Package) -> None:
437 version = manifest[package.name]
438 tag = f"{package.path}/v{version}"
439 try:
440 for edge in package.depends:
441 if edge.path in chosen:441 ↛ 440line 441 didn't jump to line 440 because the condition on line 441 was always true
442 done[edge.path].wait()
443 if edge.path in failures:
444 raise SystemExit(
445 f"{package.name}: its dependency"
446 f" {edge.path} failed, so this member never"
447 " started"
448 )
449 # A package that opts out of publishing is versioned,
450 # built and tagged by the train and never uploaded: the
451 # registry is neither probed nor written for it, and a
452 # re-run walks past its tag the way it walks past a
453 # served version. Its publish phase never runs.
454 if not package.publish:
455 if tag in git.tags(root):
456 print(
457 f" {package.name} v{version}: already tagged;"
458 " publish = false, done"
459 )
460 else:
461 _build_member(package)
462 cut_tag(root, tag, resolved_ref)
463 print(
464 f" {package.name} v{version}: publish = false; the"
465 " registry upload skips, the tag and the changelog stand"
466 )
467 with lock:
468 receipts[package.path] = Receipt(
469 package, version, tag, published=False
470 )
471 return
472 # A version the target already serves is walked past
473 # before any build or upload: a re-run after a died
474 # receipt, from CI or from a machine without a publish
475 # credential, must reach the tag. The duplicate rejection
476 # at the upload stays as the second net for two waves
477 # racing.
478 served = version in registry_for(package).versions(package.name)
479 if tag in git.tags(root) and served:
480 print(f" {package.name} v{version}: already tagged and served; done")
481 with lock:
482 receipts[package.path] = Receipt(
483 package, version, tag, published=False
484 )
485 return
486 _build_member(package)
487 # The member's publish phase owns the upload; the wave only
488 # hands it the target of the ecosystem it releases to.
489 target = targets[releases_to[package.path]]
490 if served:
491 print(
492 f" {package.name} v{version}: already served; walking"
493 " past the upload"
494 )
495 published = False
496 else:
497 if target.releases and tag not in git.tags(root):
498 # A release is addressed by its tag, so the tag
499 # exists before the assets do. The receipt is
500 # complete only once the probe sees them, which
501 # is why a tag alone no longer ends the member:
502 # a re-run finishes the upload.
503 cut_tag(root, tag, resolved_ref)
504 if package.name in new_projects:
505 with first_upload:
506 published = _first_upload(package, version, target)
507 else:
508 published = _lifecycle.publish(
509 package,
510 root,
511 version=version,
512 target=target,
513 prebuilt=package.path in built,
514 )
515 probe_until_served(
516 registry_for(package),
517 package.name,
518 version,
519 timeout=probe_timeout,
520 poll=probe_poll,
521 )
522 cut_tag(root, tag, resolved_ref)
523 with lock:
524 receipts[package.path] = Receipt(
525 package, version, tag, published=published
526 )
527 print(f" {package.name} v{version}: published, served, tagged")
528 except BaseException as exc:
529 with lock:
530 failures[package.path] = exc
531 raise
532 finally:
533 done[package.path].set()
534
535 with ThreadPoolExecutor(max_workers=max(len(ordered), 1)) as pool:
536 futures = [pool.submit(_run_member, p) for p in ordered]
537 for future in futures:
538 exc = future.exception()
539 if exc is not None and not isinstance(exc, SystemExit):
540 raise exc
541 if failures:
542 detail = "; ".join(f"{path}: {failures[path]}" for path in sorted(failures))
543 tagged = ", ".join(sorted(receipts)) or "none"
544 fail(
545 f"the wave stopped: {detail}\n receipts already cut: {tagged}."
546 " Fix the cause and re-run the publish; everything tagged is"
547 " walked past."
548 )
549 return tuple(receipts[p.path] for p in ordered)
550
551
552#: Relative path under the workspace root where the unprivileged release
553#: ``build`` job records SHA-256 digests of every distribution it built
554#: for the isolated ``publish`` job to verify before uploading.
555DIST_MANIFEST = "packages/.release-dists.json"
556
557#: Duplicate-upload responses tolerated by idempotent ``uv publish``.
558_DUPLICATE_PHRASES = (
559 "already exists",
560 "duplicate",
561 "file name has already been taken",
562)
563
564
565def _sha256_file(path: Path) -> str:
566 """Lowercase hex SHA-256 digest of *path*."""
567 digest = hashlib.sha256()
568 with path.open("rb") as handle:
569 for chunk in iter(lambda: handle.read(65536), b""):
570 digest.update(chunk)
571 return digest.hexdigest()
572
573
574def build_release_dists(root: Path, *, ref: str = "") -> Path:
575 """Build non-job-built release members and record their SHA-256 digests.
576
577 Runs in the unprivileged ``build`` job (no publishing credentials).
578 Members built by another job of the release point (such as native
579 wheel jobs returned by ``job-built-members``) are skipped so their
580 platform artifacts are not overwritten. Writes `DIST_MANIFEST` even
581 when every member is built by another job so the ``dists`` artifact
582 is always present and rooted at ``packages/``.
583 """
584 from livery.workshop._queries import JOB_BUILT_MEMBERS, answer
585
586 resolved_ref = ref or git.head_sha(root)
587 discovered = discover_release(root, resolved_ref)
588 epoch = int(git.run(root, "log", "-1", "--format=%ct", resolved_ref).strip() or "0")
589 job_built = answer(root, JOB_BUILT_MEMBERS)
590 members_data: dict[str, dict[str, Any]] = {}
591 for package, version in discovered:
592 if package.path in job_built:
593 continue
594 _lifecycle.build_release(package, root, epoch=epoch)
595 dist_dir = package.directory / "dist"
596 files: dict[str, str] = {}
597 if dist_dir.is_dir():
598 for artifact in sorted(dist_dir.iterdir()):
599 if artifact.is_file():
600 files[artifact.name] = _sha256_file(artifact)
601 members_data[package.path] = {
602 "name": package.name,
603 "version": version,
604 "files": files,
605 }
606 manifest_path = root / DIST_MANIFEST
607 manifest_path.parent.mkdir(parents=True, exist_ok=True)
608 payload = {"ref": resolved_ref, "members": members_data}
609 manifest_path.write_text(
610 json.dumps(payload, indent=2, sort_keys=True) + "\n",
611 encoding="utf-8",
612 )
613 return manifest_path
614
615
616def verify_release_dists(root: Path, ref: str) -> dict[str, dict[str, Any]]:
617 """Verify `DIST_MANIFEST` matches *ref* and every listed file's SHA-256.
618
619 Refuses a missing manifest, unreadable JSON, a ref mismatch, a
620 missing distribution file, or any digest mismatch before any
621 credential is used to upload.
622 """
623 manifest_path = root / DIST_MANIFEST
624 if not manifest_path.is_file():
625 fail(
626 f"missing {DIST_MANIFEST}: the unprivileged build job must produce"
627 " release distributions and their digest manifest before isolated"
628 " publish runs"
629 )
630 try:
631 data = json.loads(manifest_path.read_text("utf-8"))
632 except (OSError, ValueError) as error:
633 fail(f"unreadable {DIST_MANIFEST}: {error}")
634 if not isinstance(data, dict) or not isinstance(data.get("members"), dict):634 ↛ 635line 634 didn't jump to line 635 because the condition on line 634 was never true
635 fail(f"malformed {DIST_MANIFEST}: expected object with 'ref' and 'members'")
636 expected_ref = str(data.get("ref") or "")
637 if expected_ref != ref:
638 fail(
639 f"{DIST_MANIFEST} was built for {expected_ref[:10]!r}, not"
640 f" {ref[:10]!r}; refusing mismatched artifacts"
641 )
642 members = data["members"]
643 for rel_path, entry in members.items():
644 if not isinstance(entry, dict) or not isinstance(entry.get("files"), dict):644 ↛ 645line 644 didn't jump to line 645 because the condition on line 644 was never true
645 fail(f"malformed {DIST_MANIFEST} entry for {rel_path}")
646 dist_dir = root / rel_path / "dist"
647 for filename, expected_digest in entry["files"].items():
648 file_path = dist_dir / filename
649 if not file_path.is_file():649 ↛ 650line 649 didn't jump to line 650 because the condition on line 649 was never true
650 fail(
651 f"missing built distribution {rel_path}/dist/{filename}"
652 f" listed in {DIST_MANIFEST}"
653 )
654 actual = _sha256_file(file_path)
655 if actual != str(expected_digest):
656 fail(
657 f"digest mismatch for {rel_path}/dist/{filename}:"
658 f" expected {expected_digest}, got {actual}"
659 )
660 return dict(members)
661
662
663def _uv_publish_dists(package: Package, *, index_url: str, token: str) -> bool:
664 """Upload prebuilt ``dist/*`` using ``uv publish`` without workspace code."""
665 if not index_url:
666 fail(
667 f"{package.name}: no publish address resolved; declare"
668 " [registries.python] publish in workshop.toml or set"
669 " PYTHON_PUBLISH_INDEX"
670 )
671 dist_files = sorted(
672 p for p in (package.directory / "dist").iterdir() if p.is_file()
673 )
674 if not dist_files:
675 fail(f"{package.name}: dist/ holds no prebuilt distributions to upload")
676 command = ["uv", "publish", "--publish-url", index_url]
677 if token:
678 command += ["--token", token]
679 command += [str(path) for path in dist_files]
680 # Drop an empty UV_PUBLISH_TOKEN so uv stays on OIDC trusted publishing.
681 env = {k: v for k, v in os.environ.items() if k != "UV_PUBLISH_TOKEN" or v}
682 result = subprocess.run(
683 command,
684 cwd=package.directory,
685 env=env,
686 capture_output=True,
687 text=True,
688 check=False,
689 )
690 if result.returncode == 0:
691 return True
692 output = f"{result.stdout}{result.stderr}"
693 if any(phrase in output.lower() for phrase in _DUPLICATE_PHRASES):
694 print(f" {package.name}: already published; walking past")
695 return False
696 fail(f"uv publish ({package.name}) exited {result.returncode}:\n{output}")
697
698
699def isolated_publish_release(
700 root: Path,
701 *,
702 ref: str = "",
703 index_url: str = "",
704 token: str = "",
705 registry_for: Callable[[Package], Registry] | None = None,
706 uploader: Callable[[Package, str, str], bool] | None = None,
707 probe_timeout: float = PROBE_TIMEOUT,
708 probe_poll: float = PROBE_POLL,
709) -> tuple[Receipt, ...]:
710 """Verify prebuilt distributions and publish the wave in Tier 1 isolation.
711
712 Runs without ``setup.sh``, without mounting workspace extensions,
713 without loading ``tasks.py``, and without folding ``.repo.env``.
714 Verifies `DIST_MANIFEST` SHA-256 digests, checks release movement
715 and dependency floors, uploads prebuilt distributions via
716 ``uv publish``, waits until the index serves each version, and cuts
717 receipt tags in dependency order.
718 """
719 from livery.forge import SimpleRegistry
720 from livery.workshop._registries import resolve_registry
721 from livery.workshop._release import verify_release
722
723 resolved_ref = ref or git.head_sha(root)
724 discovered = discover_release(root, resolved_ref)
725 ordered = tuple(package for package, _version in discovered)
726 manifest = {package.name: version for package, version in discovered}
727 verify_release_dists(root, resolved_ref)
728
729 resolved_publish_url = index_url
730 resolved_token = token
731 resolved_read_url = ""
732 if not resolved_publish_url or registry_for is None:732 ↛ 733line 732 didn't jump to line 733 because the condition on line 732 was never true
733 target = resolve_registry(root, _PYTHON_REGISTRY)
734 if not resolved_publish_url:
735 resolved_publish_url = target.publish_url
736 if not resolved_token:
737 resolved_token = target.token
738 resolved_read_url = target.url
739
740 if not resolved_publish_url and any(p.publish for p in ordered):740 ↛ 741line 740 didn't jump to line 741 because the condition on line 740 was never true
741 fail(
742 "no publish address resolved: declare [registries.python] publish"
743 " in workshop.toml or set PYTHON_PUBLISH_INDEX"
744 )
745
746 if registry_for is None:746 ↛ 747line 746 didn't jump to line 747 because the condition on line 746 was never true
747 simple = SimpleRegistry(resolved_read_url, token=resolved_token)
748
749 def _default_registry(_package: Package) -> Registry:
750 return simple
751
752 probe_for: Callable[[Package], Registry] = _default_registry
753 else:
754 probe_for = registry_for
755
756 upload_fn = uploader or (
757 lambda pkg, url, tok: _uv_publish_dists(pkg, index_url=url, token=tok)
758 )
759
760 by_path = {p.path: p for p in discover_packages(root)}
761 coreleased = frozenset(f"{p.path}/v{manifest[p.name]}" for p in ordered)
762 for package in ordered:
763 tag = f"{package.path}/v{manifest[package.name]}"
764 verify_release(root, tag, coreleased=coreleased)
765 movement_check(root, package, resolved_ref)
766 if package.publish:766 ↛ 762line 766 didn't jump to line 762 because the condition on line 766 was always true
767 floor_probe(package, by_path, probe_for, coreleased=coreleased)
768
769 chosen = {p.path for p in ordered}
770 done: dict[str, threading.Event] = {p.path: threading.Event() for p in ordered}
771 receipts: dict[str, Receipt] = {}
772 failures: dict[str, BaseException] = {}
773 lock = threading.Lock()
774 new_projects = [
775 p.name for p in ordered if p.publish and not probe_for(p).versions(p.name)
776 ]
777 first_upload = threading.Lock()
778 refused_new: list[str] = []
779
780 def _run_member(package: Package) -> None:
781 version = manifest[package.name]
782 tag = f"{package.path}/v{version}"
783 try:
784 for edge in package.depends:784 ↛ 785line 784 didn't jump to line 785 because the loop on line 784 never started
785 if edge.path in chosen:
786 done[edge.path].wait()
787 if edge.path in failures:
788 raise SystemExit(
789 f"{package.name}: its dependency {edge.path} failed,"
790 " so this member never started"
791 )
792 if not package.publish:792 ↛ 793line 792 didn't jump to line 793 because the condition on line 792 was never true
793 if tag not in git.tags(root):
794 cut_tag(root, tag, resolved_ref)
795 with lock:
796 receipts[package.path] = Receipt(
797 package, version, tag, published=False
798 )
799 return
800 served = version in probe_for(package).versions(package.name)
801 if tag in git.tags(root) and served:801 ↛ 802line 801 didn't jump to line 802 because the condition on line 801 was never true
802 with lock:
803 receipts[package.path] = Receipt(
804 package, version, tag, published=False
805 )
806 return
807 if not collected(package):807 ↛ 808line 807 didn't jump to line 808 because the condition on line 807 was never true
808 fail(
809 f"{package.name}: dist/ holds no prebuilt distributions"
810 " collected from build or wheels jobs"
811 )
812 if served:812 ↛ 813line 812 didn't jump to line 813 because the condition on line 812 was never true
813 published = False
814 elif package.name in new_projects:814 ↛ 831line 814 didn't jump to line 831 because the condition on line 814 was always true
815 with first_upload:
816 if refused_new:816 ↛ 817line 816 didn't jump to line 817 because the condition on line 816 was never true
817 raise SystemExit(
818 f"{package.name}: not uploaded: the registry already"
819 f" refused a new project in this wave ({refused_new[0]})"
820 )
821 try:
822 published = upload_fn(
823 package, resolved_publish_url, resolved_token
824 )
825 except BaseException as exc:
826 if NEW_PROJECT_LIMIT not in str(exc):
827 raise
828 refused_new.append(package.name)
829 raise SystemExit(str(exc)) from exc
830 else:
831 published = upload_fn(package, resolved_publish_url, resolved_token)
832 probe_until_served(
833 probe_for(package),
834 package.name,
835 version,
836 timeout=probe_timeout,
837 poll=probe_poll,
838 )
839 cut_tag(root, tag, resolved_ref)
840 with lock:
841 receipts[package.path] = Receipt(
842 package, version, tag, published=published
843 )
844 print(f" {package.name} v{version}: published, served, tagged")
845 except BaseException as exc:
846 with lock:
847 failures[package.path] = exc
848 raise
849 finally:
850 done[package.path].set()
851
852 with ThreadPoolExecutor(max_workers=max(len(ordered), 1)) as pool:
853 futures = [pool.submit(_run_member, p) for p in ordered]
854 for future in futures:
855 exc = future.exception()
856 if exc is not None and not isinstance(exc, SystemExit):856 ↛ 857line 856 didn't jump to line 857 because the condition on line 856 was never true
857 raise exc
858 if failures:858 ↛ 859line 858 didn't jump to line 859 because the condition on line 858 was never true
859 detail = "; ".join(f"{path}: {failures[path]}" for path in sorted(failures))
860 tagged = ", ".join(sorted(receipts)) or "none"
861 fail(
862 f"the wave stopped: {detail}\n receipts already cut: {tagged}."
863 " Fix the cause and re-run the publish; everything tagged is"
864 " walked past."
865 )
866 return tuple(receipts[p.path] for p in ordered)