Coverage for packages/workshop/src/livery/workshop/_points.py: 95%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_words.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_versions.py, packages/workshop/tests/test_workshop_variables.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_traces.py, packages/workshop/tests/test_workshop_test_reads.py, packages/workshop/tests/test_workshop_test_guard.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync_locked.py, packages/workshop/tests/test_workshop_sync_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_sweep.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_store_tasks.py, packages/workshop/tests/test_workshop_steps.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_shard.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_schema.py, packages/workshop/tests/test_workshop_scale.py, packages/workshop/tests/test_workshop_runtime_language.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.py, packages/workshop/tests/test_workshop_repair.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.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_release.py, packages/workshop/tests/test_workshop_registries.py, packages/workshop/tests/test_workshop_regions.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_provenance.py, packages/workshop/tests/test_workshop_proved_trees.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved_decide.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_proof_pins.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_plugin_tools.py, packages/workshop/tests/test_workshop_phases.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_package_level_fragments.py, packages/workshop/tests/test_workshop_package.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_metrics.py, packages/workshop/tests/test_workshop_lifecycle.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_issue.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_invoke.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.py, packages/workshop/tests/test_workshop_identity.py, packages/workshop/tests/test_workshop_groups.py, packages/workshop/tests/test_workshop_graph.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_fragments.py, packages/workshop/tests/test_workshop_footprint.py, packages/workshop/tests/test_workshop_fold.py, packages/workshop/tests/test_workshop_fallbacks.py, packages/workshop/tests/test_workshop_extensions.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_e2e_rows.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_due.py, packages/workshop/tests/test_workshop_doctor_unlisted.py, packages/workshop/tests/test_workshop_doctor.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/workshop/tests/test_workshop_declaration.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/workshop/tests/test_workshop_cpp_kind.py, packages/workshop/tests/test_workshop_contributed_jobs.py, packages/workshop/tests/test_workshop_contract_file.py, packages/workshop/tests/test_workshop_contract.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_composition.py, packages/workshop/tests/test_workshop_commit.py, packages/workshop/tests/test_workshop_claims.py, packages/workshop/tests/test_workshop_ci_context.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/workshop/tests/test_workshop_balance.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/workshop/tests/test_tools_restub.py, packages/workshop/tests/test_tools_materialise.py, packages/workshop/tests/test_kind_tools.py, packages/extensions/ty/tests/test_ty.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_runner_terminal.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_quality.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/python/tests/test_python_layering.py, packages/extensions/python/tests/test_private_reaches.py, packages/extensions/python/tests/test_plugin_reaches.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/python/tests/test_examples.py, packages/extensions/python/tests/test_declared_imports.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/pytest/tests/test_pytest_coverage.py, packages/extensions/pytest/tests/test_pytest_c6_selection.py, packages/extensions/pytest/tests/test_pytest_c5_repeats.py, packages/extensions/pytest/tests/test_pytest_c4_reads.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/pyrefly/tests/test_pyrefly.py, packages/extensions/nanobind/tests/test_nanobind_kind.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mypy/tests/test_mypy.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_refs.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_docstrings.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings_digests.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_taskref.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_llms.py, packages/extensions/docs/tests/test_influence.py, packages/extensions/docs/tests/test_groups.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/docs/tests/test_docs_verbs.py, packages/extensions/docs/tests/test_docs_site.py, packages/extensions/docs/tests/test_docs_phase.py, packages/extensions/docs/tests/test_docs_contract.py, packages/extensions/docs/tests/test_docs.py, packages/extensions/docs/tests/test_doc_steps.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_parts.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_union_pins.py, packages/extensions/coverage/tests/test_coverage_store.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_coverage_pages.py, packages/extensions/coverage/tests/test_coverage_accept.py, packages/extensions/coverage/tests/test_coverage.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_layering.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/conan/tests/test_cross_kind.py, packages/extensions/conan/tests/test_conan_releases.py, packages/extensions/conan/tests/test_conan_publish.py, packages/extensions/conan/tests/test_conan_kind.py, packages/extensions/cmake/tests/test_measured_run.py, packages/extensions/cmake/tests/test_cpp_kind.py, packages/extensions/cmake/tests/test_coverage_parts.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/clang-tidy/tests/test_clang_tidy.py, packages/extensions/clang-format/tests/test_clang_format.py, packages/extensions/changelog/tests/test_changelog.py, packages/extensions/basedpyright/tests/test_basedpyright.py, packages/extensions/agents/tests/test_agents.py ran.

1"""CI as points: what each point is, what it runs, and the verb that runs it.
2
3A consumer never thinks about CI. They reason about a named point in
4the process and attach a task to it. The four points are ``gate``
5(a pull request, or a dispatch by hand), ``merge`` (main after a
6merge), ``nightly`` (the clock), and ``release`` (dispatched by the
7merge point). A point is a declaration, [livery.workshop._points.Point][]:
8its workflow file, its events, and its jobs, each job stating what it
9needs in the workshop's words ([livery.workshop._points.Job][]); each
10forge's renderer says those in its own. The emitted workflow is a
11static shell, one ``fm ci.run --point=<p> --job=<j>`` per job, with
12``--shard=<i>of<n>`` on a check leg the contract splits, and what a
13job does is data: the builtin schedule below, plus the
14``[[ci.schedule]]`` entries a workspace declares in ``workshop.toml``.
15The matrix shape belongs to a point's job, never to a task.
16
17Reach for [livery.workshop._points.run_point][] to run a job's
18entries, and `schedule` to see them. Every entry runs as a child of
19the runner's own command, so a scheduled task is any task the
20workspace mounts, and the child's exit is the entry's.
21
22The merge point inherits the gate's jobs: a push to main runs the
23same checks, plus the jobs only a merge has (the docs deploy, the
24governance reconcile). A shell spells ``--point=gate`` on the shared
25jobs and the verb promotes the point on a push, so the YAML carries
26no decision.
27
28A package contributes a point of its own through ``[[ci.point]]`` in
29its ``workshop.toml``: a scheduled point with a dispatch entry, one
30job on the runners and Pythons it names, running the task it names
31with the job token and nothing more. `points` is every point a
32workspace has, the builtin four first; every reader takes that set.
33"""
34
35from __future__ import annotations
36
37import contextlib
38import os
39import re
40from collections.abc import Callable, Mapping, Sequence
41from contextlib import AbstractContextManager
42from dataclasses import dataclass, replace
43from datetime import date, timedelta
44from pathlib import Path
45from typing import TYPE_CHECKING, Any
46
47import livery.footman as footman
48from livery.footman import Tasks, fail
49from livery.workshop._ci_context import (
50 LEG_VARIABLE,
51 POINT_VARIABLE,
52 run_context,
53 state_store,
54)
55from livery.workshop._contract import load_contract
56from livery.workshop._shard import ONE, Shard, platform_leg, shard_of
57
58if TYPE_CHECKING:
59 from livery.git import Row
60 from livery.workshop._ci_context import RunContext
61 from livery.workshop._influence import Inputs
62
63#: The events a point may run on, in the forges' words.
64EVENT_NAMES = ("pull_request", "push", "schedule", "workflow_dispatch")
65
66
67#: The nightly's dispatch input naming the scheduled tasks a run takes,
68#: comma-separated; empty runs the whole schedule. A rehearsal names the
69#: loop alone, ``fm ci.dispatch --point=nightly --only=ci.e2e``.
70ONLY = "only"
71
72
73@dataclass(frozen=True)
74class Input:
75 """One input a dispatched point takes, as the forge prompts for it.
76
77 Attributes:
78 name: The input's name, as the dispatch passes it.
79 description: What the input is, for the person dispatching.
80 required: Whether a dispatch without it is refused.
81 default: The value an absent optional input takes.
82 """
83
84 name: str
85 description: str
86 required: bool = False
87 default: str = ""
88
89
90@dataclass(frozen=True)
91class Job:
92 """One job of a point's shell, in the workshop's words.
93
94 Each forge's renderer says these in that forge's words: a grant, a
95 step, an action, an image. Nothing here is forge-shaped.
96
97 Attributes:
98 name: The job's name, and the ``--job`` its one call passes.
99 matrix: The legs the job fans out to: ``legs`` for one per
100 runner and gate Python, ``pythons`` for one per Python of
101 the whole matrix on the first runner, ``runners`` for one
102 per runner label the job's ``labels`` function names, with
103 no Python of its own, ``declared`` for one per runner and
104 Python the job itself names, ``""`` for one job on one
105 runner.
106 runners: The runners a ``declared`` matrix fans out to.
107 pythons: The Pythons a ``declared`` matrix fans out to.
108 labels: The function naming the runner labels a ``runners``
109 matrix fans out to, given the workspace's root; None for a
110 job of any other matrix. A ``runners`` job whose function
111 names no label renders no job, and a need on it drops.
112 needs: The jobs of the point this one waits for.
113 always: Whether the job runs when a job it needs was red, the
114 verdict job's shape.
115 fetch: How deep the checkout is: ``full`` for every commit,
116 ``tags`` for the tags as well, ``2`` for the commit and its
117 parent, ``""`` for the commit alone.
118 token: The credential the verb sees as ``FORGE_TOKEN``: ``job``
119 for the run's own token, ``repository`` for the repository's
120 secret when present and the job's otherwise, ``secret`` for
121 the repository's secret alone, ``admin`` for the admin
122 secret as ``FORGE_ADMIN_TOKEN``, ``""`` for none.
123 writes: Whether the job pushes to the repository (the state
124 store, a receipt tag), which needs the write grant.
125 pushes: Whether the job pushes through git itself, so the
126 checkout carries the credential the push needs.
127 publishes_index: Whether the job uploads to a package index,
128 so the index token reaches it as ``UV_PUBLISH_TOKEN``.
129 installs: The function naming the system packages the job
130 installs before it enters, given the workspace's root;
131 None for none. The extension that contributes the job
132 names it, so the render installs them without knowing
133 what they are for.
134 conan_cache: Whether the job builds native packages, so the
135 lane restores and saves conan's home around it.
136 cache_dir: Workspace-relative directory restored before the job
137 enters and saved after, keyed on the job name, runner,
138 ``uv.lock`` and commit; ``""`` for none.
139 deploy: The function naming the seam the job publishes a site
140 through after the call, given the workspace's root; None
141 for a job that publishes none. A ``pages`` seam is the
142 forge's own hosting: GitHub's grant and upload, GitLab's
143 ``pages`` job.
144 publishes: The artifact the job uploads, ``""`` for none.
145 paths: The paths the uploaded artifact carries, as the forge
146 globs them; ``()`` for a job that publishes none.
147 upload_always: Whether the artifact upload runs even when a
148 previous step failed (``if: always()`` / ``when: always``),
149 so red legs still hand diagnostic rows to downstream jobs.
150 retention_days: Days the forge retains the uploaded artifact
151 before automatic expiry; ``0`` uses the forge default.
152 collects: The artifact the job downloads first, ``""`` for none.
153 environment: The named deployment environment the job runs in,
154 ``""`` for none.
155 isolated: Module path of an isolated Tier 1 entry point (such
156 as ``livery.workshop._govern_entry``) that runs via
157 ``uv run --isolated --no-project`` under ``python3 -I``
158 without entering the workspace, loading ``tasks.py``, or
159 folding ``.repo.env``; ``""`` for normal workspace jobs.
160 dispatches: Whether the job starts another workflow through the
161 forge's API, which GitHub's workflow token may do only with
162 the ``actions: write`` grant.
163 inputs: The files the job's entries read, declared as a step
164 declares its own: a pull request's run that changed none of
165 them skips the entries. None for a job that always runs.
166 step: What the forge's run page calls the one call; the job's
167 name capitalised when empty.
168 note: The comment the rendered shell prints above the job.
169 joins: Whether the job is a contribution to a job the point
170 already has, declared or inherited. It renders as no job of
171 its own: its entries follow that job's, and its plumbing,
172 what it collects and publishes, the seam it deploys through
173 and the packages it installs, renders on that job under the
174 contributing point's own event condition.
175 """
176
177 name: str
178 matrix: str = ""
179 runners: tuple[str, ...] = ()
180 pythons: tuple[str, ...] = ()
181 labels: Callable[[Path], Sequence[str]] | None = None
182 needs: tuple[str, ...] = ()
183 always: bool = False
184 fetch: str = ""
185 token: str = ""
186 writes: bool = False
187 pushes: bool = False
188 publishes_index: bool = False
189 installs: Callable[[Path], Sequence[str]] | None = None
190 conan_cache: bool = False
191 cache_dir: str = ""
192 deploy: Callable[[Path], str] | None = None
193 publishes: str = ""
194 paths: tuple[str, ...] = ()
195 upload_always: bool = False
196 retention_days: int = 0
197 collects: str = ""
198 environment: str = ""
199 isolated: str = ""
200 dispatches: bool = False
201 inputs: Inputs | None = None
202 step: str = ""
203 note: str = ""
204 joins: bool = False
205
206
207@dataclass(frozen=True)
208class Point:
209 """One point: its workflow file, its events, and its jobs.
210
211 Attributes:
212 name: The point's name, and the ``--point`` its jobs pass.
213 workflow: The workflow file the point's shell is, as GitHub and
214 Gitea address a dispatch and name a run. Two points may
215 share one, the gate and the merge point do, when their
216 events do not overlap. GitLab has one pipeline document and
217 names a dispatched pipeline after this.
218 events: The events that start the point's runs, from
219 `EVENT_NAMES`.
220 jobs: The point's own jobs, in order.
221 inherits: A point whose jobs this one runs first, the gate's
222 for the merge point; ``""`` for none.
223 inputs: The inputs a dispatch takes. A point with a required
224 one is dispatched by a verb that supplies it, never by
225 hand. Every job of a point that takes a ``workshop`` input
226 installs the released workshop it names, over the
227 checkout's own, before its one call.
228 ref_input: The input naming the commit the jobs check out,
229 ``""`` for the run's own commit.
230 cron: When the clock starts the point, for a point whose
231 events include ``schedule``, in cron's five fields, UTC.
232 GitHub and Gitea read it from the workflow file; on
233 GitLab the clock is a pipeline schedule the governance
234 reconcile creates from it.
235 note: The comment the rendered shell prints under its name.
236 """
237
238 name: str
239 workflow: str
240 events: tuple[str, ...]
241 jobs: tuple[Job, ...] = ()
242 inherits: str = ""
243 inputs: tuple[Input, ...] = ()
244 ref_input: str = ""
245 cron: str = ""
246 note: str = ""
247
248
249#: When the clock starts a scheduled point, UTC: the nightly's hour,
250#: and every contributed point's, whose cadence is judged on the
251#: runner by `due` rather than by a cron of its own.
252CLOCK = "17 4 * * *"
253
254#: The four builtin points, in the order a change meets them.
255DECLARED: tuple[Point, ...] = (
256 Point(
257 "gate",
258 "ci.yml",
259 ("pull_request", "workflow_dispatch"),
260 note=(
261 "A pull request, a push to main, and a dispatch by hand. A"
262 " dispatched run pays the full gate: the check verb reads the"
263 " event and narrows on a pull request alone, so every event"
264 " spells the same call."
265 ),
266 jobs=(
267 Job(
268 "check",
269 matrix="legs",
270 fetch="full",
271 publishes="run-legs",
272 paths=(".workshop/run-legs",),
273 upload_always=True,
274 retention_days=1,
275 note=(
276 "The check legs: each runs the gate read-only and uploads"
277 " its timing row and spooled leg files as an ephemeral"
278 " artifact for the gate job, even when a leg is red. The"
279 " scoped gate measures from the proved tree nearest the"
280 " checkout's, an earlier push's merge rebuilt from its two"
281 " commits among them, or from the merge base with the pull"
282 " request's base branch; each needs history a shallow clone"
283 " lacks."
284 ),
285 ),
286 Job(
287 "gate",
288 needs=("check",),
289 always=True,
290 fetch="full",
291 token="job",
292 writes=True,
293 collects="run-legs",
294 dispatches=True,
295 step="Verdict",
296 note=(
297 "The one required context. Branch protection points"
298 " here, so the matrix can grow or shrink without touching"
299 " repository settings. Its entries run the judges the"
300 " extensions add, collect the run's timing rows, ask the"
301 " forge for the jobs it needs, and stamp the tree a green"
302 " run proved; a red run is judged too. The stamp composes"
303 " a narrowed run with the record of the tree its legs"
304 " measured from, and names the two commits a merge"
305 " checkout joined. On a push to main the same job then"
306 " dispatches the release wave, runs what the extensions"
307 " add to the merge point, and runs the janitor."
308 ),
309 ),
310 ),
311 ),
312 Point(
313 "merge",
314 "ci.yml",
315 ("push",),
316 inherits="gate",
317 jobs=(
318 Job(
319 "govern",
320 fetch="2",
321 token="admin",
322 environment="govern",
323 isolated="livery.workshop._govern_entry",
324 note=(
325 "The repository settings reconciled when the merge"
326 " changed a contract or the owners file. The commit's own"
327 " file list decides whether anything is governed; a depth"
328 " of one would read a squash as a root."
329 ),
330 ),
331 ),
332 ),
333 Point(
334 "nightly",
335 "nightly.yml",
336 ("schedule", "workflow_dispatch"),
337 inputs=(
338 Input(
339 ONLY,
340 "the scheduled tasks to run, comma-separated; empty runs the"
341 " whole schedule",
342 ),
343 ),
344 cron=CLOCK,
345 note=(
346 "The nightly point: the clock and a dispatch entry, one call per"
347 " Python. What runs is the workshop's builtin schedule plus"
348 " [[ci.schedule]] in workshop.toml, and the tests that declare"
349 " the nightly point are selected in."
350 ),
351 jobs=(
352 Job(
353 "nightly",
354 matrix="pythons",
355 fetch="full",
356 token="repository",
357 writes=True,
358 pushes=True,
359 environment="bot",
360 note=(
361 "A verification checks the tree out at a release tag. A pull"
362 " request a scheduled task opens with the job token starts"
363 " no workflow and cannot push a workflow file, so the"
364 " repository's token carries the checkout and the nightly"
365 " where there is one. The job's profile trace rides the"
366 " state store at its end, which needs the write grant as"
367 " the check legs' puts do."
368 ),
369 ),
370 Job(
371 "suite",
372 matrix="legs",
373 fetch="full",
374 token="job",
375 writes=True,
376 conan_cache=True,
377 note=(
378 "The scheduled full run of every test across every"
379 " platform. Skipped by the due job when the head has not"
380 " moved since the last verdict."
381 ),
382 ),
383 ),
384 ),
385 Point(
386 "release",
387 "release.yml",
388 ("workflow_dispatch",),
389 inputs=(
390 Input("ref", "the release squash to publish", required=True),
391 Input(
392 "workshop",
393 "a released livery-workshop version to drive the wave; empty"
394 " runs the squash's own",
395 ),
396 ),
397 ref_input="ref",
398 note=(
399 "The train: a workflow.release PR merges, this publishes its"
400 " squash, and the receipt tags are cut only after the index"
401 " confirms each member. A tag is a receipt, never a trigger: the"
402 " merge point's dispatch job starts the wave at the release"
403 " squash, and a hand dispatch with --ref is the recovery entry"
404 " when a publish died mid-wave; --workshop names a released"
405 " driver for a wave whose own workshop was the fault."
406 ),
407 jobs=(
408 Job(
409 "build",
410 fetch="full",
411 publishes="dists",
412 paths=(
413 "packages/*/dist/*",
414 "packages/*/*/dist/*",
415 "packages/.release-dists.json",
416 ),
417 retention_days=1,
418 step="Build release distributions",
419 note=(
420 "Build the release's distributions in an unprivileged job"
421 " with no publishing credentials, record their SHA-256"
422 " digests, and hand them to the isolated publish job as an"
423 " artifact."
424 ),
425 ),
426 Job(
427 "publish",
428 needs=("build",),
429 collects="dists",
430 fetch="full",
431 token="repository",
432 writes=True,
433 pushes=True,
434 publishes_index=True,
435 environment="pypi",
436 isolated="livery.workshop._publish_entry",
437 step="Publish the wave",
438 note=(
439 "The wave: verify prebuilt distributions in isolation,"
440 " publish the ref, and cut the receipt tags after the index"
441 " confirms each member. The receipt push carries the"
442 " repository's token where there is one: the job token may"
443 " not push a ref whose commit carries a workflow file that"
444 " differs from the tip's."
445 ),
446 ),
447 ),
448 ),
449)
450
451
452def verify_points(points: tuple[Point, ...]) -> None:
453 """Refuse a set of declarations a shell cannot be rendered from.
454
455 A point name declared twice, an event outside `EVENT_NAMES`, a
456 point inheriting one that is not declared, two points sharing a
457 workflow file whose events overlap (a run would belong to both),
458 a job name declared twice in one point, a job needing a job the
459 point does not have, a job collecting an artifact no job of the
460 point publishes, and a job collecting an artifact from jobs it
461 does not wait for each refuse naming the point and the fault. A
462 job starts once the jobs it needs end, so a job it does not wait
463 for may not have uploaded the artifact yet. A join waits for what
464 the job it joins waits for.
465 """
466 by_name: dict[str, Point] = {}
467 for point in points:
468 if point.name in by_name:
469 fail(f"the {point.name} point is declared twice")
470 by_name[point.name] = point
471 for point in points:
472 for event in point.events:
473 if event not in EVENT_NAMES:
474 fail(
475 f"the {point.name} point runs on {event!r}, which is not an"
476 f" event; the events are {', '.join(EVENT_NAMES)}"
477 )
478 if point.inherits and point.inherits not in by_name:
479 fail(
480 f"the {point.name} point inherits {point.inherits!r}, which is"
481 " not a declared point"
482 )
483 if ("schedule" in point.events) != bool(point.cron):483 ↛ 484line 483 didn't jump to line 484 because the condition on line 483 was never true
484 fail(
485 f"the {point.name} point "
486 + (
487 "runs on the clock and names no cron"
488 if "schedule" in point.events
489 else "names a cron and does not run on the clock"
490 )
491 )
492 for other in points:
493 if other.name >= point.name or other.workflow != point.workflow:
494 continue
495 shared = sorted(set(point.events) & set(other.events))
496 if shared:
497 fail(
498 f"the {other.name} and {point.name} points share"
499 f" {point.workflow} and both run on {', '.join(shared)}:"
500 " a run would belong to both"
501 )
502 inherited = by_name[point.inherits].jobs if point.inherits else ()
503 names: list[str] = [job.name for job in inherited if not job.joins]
504 for job in point.jobs:
505 if job.joins:
506 continue
507 if job.name in names:
508 fail(f"the {point.name} point declares the job {job.name!r} twice")
509 names.append(job.name)
510 lineage = (*inherited, *point.jobs)
511 # A join renders on the job it joins: it waits for what that job
512 # waits for, and its own needs never render.
513 waits = {job.name: job.needs for job in lineage if not job.joins}
514 for job in point.jobs:
515 for need in job.needs:
516 if need not in names:
517 fail(
518 f"the {point.name} point's {job.name} job needs"
519 f" {need!r}, which the point does not have; its jobs"
520 f" are {', '.join(names)}"
521 )
522 if not job.collects:
523 continue
524 publishers = list(
525 dict.fromkeys(
526 other.name for other in lineage if other.publishes == job.collects
527 )
528 )
529 if not publishers:
530 fail(
531 f"the {point.name} point's {job.name} job collects"
532 f" {job.collects!r}, which no job of the point publishes"
533 )
534 if not set(publishers) & set(waits.get(job.name, job.needs)):
535 fail(
536 f"the {point.name} point's {job.name} job collects"
537 f" {job.collects!r} and waits for no job that publishes it"
538 f" ({', '.join(publishers)}); a job collects only from the"
539 " jobs it needs"
540 )
541
542
543verify_points(DECLARED)
544
545#: The builtin points by name.
546POINT_BY_NAME: dict[str, Point] = {point.name: point for point in DECLARED}
547
548#: The builtin points, in the order a change meets them. A workspace
549#: may have more: `points` adds the ones its packages contribute.
550POINTS = tuple(point.name for point in DECLARED)
551
552#: What a contributed point's name may look like: a workflow file
553#: name and a job name at once.
554POINT_NAME = re.compile(r"^[a-z][a-z0-9-]*$")
555
556
557#: The runner's merged task tree, kept by the workshop's ``pre_tasks``
558#: hook for the span of one invocation: discovery merges every extension's
559#: tree into the invocation and resets the module-level root, so a
560#: check against what this runner mounts reads it here.
561MOUNTED: Tasks | None = None
562
563
564def _mounted(task: str) -> bool:
565 """Whether the runner mounts the task at the dotted address *task*.
566
567 The invocation's merged tree when a run kept one. A process that
568 kept no tree, a test reading the repository's own contract, holds
569 only what it happened to import, never the workspace's mounted
570 set, so it cannot answer and defers: the runner checks at the
571 point's dispatch and at every load inside a run.
572 """
573 if MOUNTED is None:573 ↛ 575line 573 didn't jump to line 575 because the condition on line 573 was always true
574 return True
575 return MOUNTED.get(task) is not None
576
577
578@dataclass(frozen=True)
579class Contribution:
580 """A point a package contributes, and the entry that runs it.
581
582 Attributes:
583 point: The point, a scheduled one with a dispatch entry and
584 one job named after it.
585 entry: The task the job runs, with its cadence.
586 """
587
588 point: Point
589 entry: Entry
590
591
592def contributed(
593 root: Path, *, mounted: Callable[[str], bool] | None = None
594) -> tuple[Contribution, ...]:
595 """The ``[[ci.point]]`` declarations of *root*'s packages, refusing bad ones.
596
597 Each table names a ``name`` (the point's, a workflow file name and
598 a job name at once), a ``task``, and optionally ``args``,
599 ``every`` (a cadence from `CADENCES`), ``runners`` (the root
600 contract's when absent) and ``pythons`` (the newest gate Python
601 when absent). A name that is a builtin point or that two packages
602 claim, a name `POINT_NAME` refuses, a cadence that is not one, a
603 task *mounted* does not know (the runner's own registry when
604 absent), and a permission, secret or environment key each refuse
605 at load, naming the package and the point.
606 """
607 from livery.workshop._packages import discover_packages
608 from livery.workshop._pythons import gate_pythons
609
610 mounted = mounted or _mounted
611 contract = load_contract(root / "workshop.toml")
612 ci_table = contract.get("ci") or {}
613 default_runners = tuple(
614 str(r) for r in (ci_table.get("runners") or ["ubuntu-latest"])
615 )
616 default_pythons: tuple[str, ...] | None = None
617 found: dict[str, str] = {}
618 contributions: list[Contribution] = []
619 for package in discover_packages(root):
620 package_contract = load_contract(package.directory / "workshop.toml")
621 raw = (package_contract.get("ci") or {}).get("point") or []
622 if not isinstance(raw, list):622 ↛ 623line 622 didn't jump to line 623 because the condition on line 622 was never true
623 fail(f"{package.path}: [ci] point must be a list of [[ci.point]] tables")
624 for index, item in enumerate(raw, start=1):
625 where = f"{package.path} [[ci.point]] entry {index}"
626 if not isinstance(item, dict):626 ↛ 627line 626 didn't jump to line 627 because the condition on line 626 was never true
627 fail(f"{where} is not a table")
628 name = str(item.get("name", ""))
629 task = str(item.get("task", ""))
630 if not name:
631 fail(f"{where}: names no point")
632 if name in POINT_BY_NAME:
633 fail(
634 f"{where}: {name!r} is a builtin point; a package contributes"
635 " a point of its own and adds no job to the gate"
636 )
637 if not POINT_NAME.match(name):
638 fail(
639 f"{where}: {name!r} is not a point name; a name is a workflow"
640 " file's, lower-case letters, digits and dashes, starting"
641 " with a letter"
642 )
643 if name in found:
644 fail(
645 f"{where}: {name!r} is already the point {found[name]}"
646 " declares; two packages cannot share one"
647 )
648 if not task:
649 fail(f"{where} ({name}): names no task")
650 if not mounted(task):
651 fail(
652 f"{where} ({name}): the runner mounts no task {task!r}; a"
653 " point runs a task some extension mounts"
654 )
655 args = item.get("args", [])
656 every = str(item.get("every", ""))
657 runners = item.get("runners", list(default_runners))
658 pythons = item.get("pythons")
659 if pythons is None:
660 if default_pythons is None:660 ↛ 662line 660 didn't jump to line 662 because the condition on line 660 was always true
661 default_pythons = (gate_pythons(root)[-1],)
662 pythons = list(default_pythons)
663 for label, values in (("runners", runners), ("pythons", pythons)):
664 if not values or not all(values):
665 fail(
666 f"{where} ({name}): {label} must be a non-empty list of strings"
667 )
668 found[name] = package.path
669 point = Point(
670 name,
671 f"{name}.yml",
672 ("schedule", "workflow_dispatch"),
673 cron=CLOCK,
674 note=(
675 f"The {name} point, contributed by {package.path}: the clock"
676 " and a dispatch entry, one call per runner and Python it"
677 " names, with the job token and nothing more."
678 ),
679 jobs=(
680 Job(
681 name,
682 matrix="declared",
683 runners=tuple(str(r) for r in runners),
684 pythons=tuple(str(v) for v in pythons),
685 token="job",
686 ),
687 ),
688 )
689 entry = Entry(
690 name, name, task, tuple(args), source=package.path, every=every
691 )
692 contributions.append(Contribution(point, entry))
693 return tuple(contributions)
694
695
696@dataclass(frozen=True)
697class JobContribution:
698 """One job a mounted extension adds to a builtin point, with its entries.
699
700 Attributes:
701 point: The builtin point the job joins.
702 job: The job, as the point would declare it.
703 entries: The tasks the job runs, each naming the point and the job.
704 gates: Whether the point's verdict waits for the job.
705 extension: The extension that contributed it, for a refusal.
706 """
707
708 point: str
709 job: Job
710 entries: tuple[Entry, ...] = ()
711 gates: bool = False
712 extension: str = ""
713
714
715_CONTRIBUTED_JOBS: dict[tuple[str, str], JobContribution] = {}
716
717#: The jobs the extensions joined, by point, job and extension: several
718#: extensions may join one job.
719_JOINED_JOBS: dict[tuple[str, str, str], JobContribution] = {}
720
721
722def point_has_job(point: str, name: str) -> bool:
723 """Whether the builtin *point* has the job *name*, declared, inherited or added."""
724 by_name = {declared.name: declared for declared in DECLARED}
725 if point not in by_name:725 ↛ 726line 725 didn't jump to line 726 because the condition on line 725 was never true
726 return False
727 lineage = [point]
728 if by_name[point].inherits:
729 lineage.append(by_name[point].inherits)
730 for name_ in lineage:
731 if name in {job.name for job in by_name[name_].jobs}:
732 return True
733 if any(item.job.name == name for item in contributed_jobs(name_)):
734 return True
735 return False
736
737
738def verdict_jobs() -> tuple[tuple[str, str], ...]:
739 """Each builtin point that declares a verdict job of its own, with the job's name.
740
741 A verdict job runs whatever the jobs it needs did; the judges an
742 extension adds join one of these.
743 """
744 return tuple(
745 (point.name, job.name) for point in DECLARED for job in point.jobs if job.always
746 )
747
748
749def judges_refusal(point: str, job: str) -> str:
750 """Why judges may not join *job* of *point*; empty when they may.
751
752 Judges join a point's own verdict job alone: they run before it
753 collects the run's rows, and a red one stops it before the verdict
754 and the stamp.
755 """
756 known = verdict_jobs()
757 if (point, job) in known:
758 return ""
759 listed = ", ".join(f"the {name} point's {verdict} job" for name, verdict in known)
760 return (
761 f"names judges on the {point} point's {job} job, which is not a verdict"
762 f" job a point declares; judges join {listed}, before it collects the"
763 " run's rows"
764 )
765
766
767def contribute_job(
768 point: str,
769 job: Job,
770 *,
771 entries: tuple[Entry, ...] = (),
772 gates: bool = False,
773 extension: str,
774) -> None:
775 """Add *job* to the builtin *point* on behalf of *extension*, or join one.
776
777 The job sits before the first job of the point that needs it, else
778 before the point's verdict job, else last (`composed_points`), so a
779 contributed job renders before the jobs that wait for it and where
780 a declared one would; a gating job joins the verdict's needs. A
781 *job* that ``joins`` names a job the point already has
782 (`point_has_job`): its entries follow that job's own, before any
783 the job runs last, its plumbing renders on that job, and its needs
784 join the needs of a job the point has of its own. Refuses a point
785 that is not builtin, a job name the point already has when the job
786 does not join, a join of a job the point does not have, a join that
787 gates, a name another extension contributed, an entry naming
788 another point or job, and a judge on a job that is not the point's
789 own verdict job (`judges_refusal`).
790 """
791 by_name = {declared.name: declared for declared in DECLARED}
792 if point not in by_name:
793 fail(
794 f"{extension} contributes the job {job.name!r} to {point!r}, which is not a"
795 f" builtin point; the points are {', '.join(by_name)}"
796 )
797 for entry in entries:
798 if entry.point != point or entry.job != job.name:
799 fail(
800 f"{extension} contributes the job {job.name!r} to the {point} point"
801 f" with an entry for {entry.point}/{entry.job}; an entry names"
802 " the job it runs in"
803 )
804 if any(entry.judges for entry in entries):
805 why = judges_refusal(point, job.name)
806 if why:
807 fail(f"{extension} {why}")
808 if job.joins:
809 if not point_has_job(point, job.name):
810 fail(
811 f"{extension} joins the job {job.name!r} of the {point} point,"
812 " which has no such job"
813 )
814 if gates:
815 fail(
816 f"{extension} joins the job {job.name!r} of the {point} point and"
817 " gates; a join adds entries and plumbing, and the verdict's"
818 " needs stay the job's own"
819 )
820 _JOINED_JOBS[(point, job.name, extension)] = JobContribution(
821 point, job, tuple(entries), False, extension
822 )
823 return
824 declared_names = [declared.name for declared in by_name[point].jobs]
825 if job.name in declared_names:
826 fail(
827 f"{extension} contributes the job {job.name!r} to the {point} point, which"
828 " declares it already"
829 )
830 other = _CONTRIBUTED_JOBS.get((point, job.name))
831 if other is not None and other.extension != extension:
832 fail(
833 f"{extension} contributes the job {job.name!r} to the {point} point, which"
834 f" {other.extension} contributed already"
835 )
836 _CONTRIBUTED_JOBS[(point, job.name)] = JobContribution(
837 point, job, tuple(entries), gates, extension
838 )
839
840
841def snapshot(
842 *, initial: bool = False
843) -> tuple[
844 dict[tuple[str, str], JobContribution],
845 dict[tuple[str, str, str], JobContribution],
846 Tasks | None,
847]:
848 """The jobs the extensions added and joined, and the kept task tree, for restore.
849
850 Judges ride their joins' entries. [livery.workshop._points.restore][]
851 puts all three back. With *initial*, the state a process starts with
852 instead: no job added or joined, and no task tree kept.
853 """
854 if initial:
855 return {}, {}, None
856 return dict(_CONTRIBUTED_JOBS), dict(_JOINED_JOBS), MOUNTED
857
858
859def restore(
860 state: tuple[
861 dict[tuple[str, str], JobContribution],
862 dict[tuple[str, str, str], JobContribution],
863 Tasks | None,
864 ],
865) -> None:
866 """Put the added jobs, the joins and the kept task tree back to *state*."""
867 global MOUNTED
868 added, joined, tree = state
869 _CONTRIBUTED_JOBS.clear()
870 _CONTRIBUTED_JOBS.update(added)
871 _JOINED_JOBS.clear()
872 _JOINED_JOBS.update(joined)
873 MOUNTED = tree
874
875
876def contributed_jobs(point: str) -> tuple[JobContribution, ...]:
877 """The jobs the extensions contributed to *point*, in contribution order."""
878 return tuple(item for item in _CONTRIBUTED_JOBS.values() if item.point == point)
879
880
881def joined_jobs(point: str) -> tuple[JobContribution, ...]:
882 """The joins the extensions made to *point*'s jobs, in contribution order."""
883 return tuple(item for item in _JOINED_JOBS.values() if item.point == point)
884
885
886def contributor_of(point: str, job: str) -> str:
887 """The extension that contributed *job* to *point*; the base for its own jobs."""
888 item = _CONTRIBUTED_JOBS.get((point, job))
889 return item.extension if item is not None else "livery.workshop"
890
891
892def verdict_needs(point: str) -> tuple[str, ...]:
893 """What *point*'s verdict waits for: its declared needs, then the gating jobs."""
894 declared = {item.name: item for item in DECLARED}
895 verdict = next((job for job in declared[point].jobs if job.always), None)
896 needs = tuple(verdict.needs) if verdict is not None else ()
897 return needs + tuple(
898 item.job.name for item in contributed_jobs(point) if item.gates
899 )
900
901
902def composed_points() -> tuple[Point, ...]:
903 """The builtin points with the extensions' contributed jobs in place.
904
905 A contributed job sits before the first job of its point that needs
906 it, else before the point's verdict job, else last: a job renders
907 before the jobs that wait for it, and where a declared one would.
908 The verdict waits for what `verdict_needs` names. A join's needs
909 join the needs of the job it joins when the point has that job of
910 its own, declared or contributed; the read of a declaration refuses
911 needs on a join of a job the point inherits, whose needs are the
912 point's it inherits from.
913 """
914 composed: list[Point] = []
915 for point in DECLARED:
916 added = [item.job for item in contributed_jobs(point.name)]
917 joined = [item.job for item in joined_jobs(point.name)]
918 if not added and not joined:
919 composed.append(point)
920 continue
921 jobs = [
922 _waiting(
923 replace(job, needs=verdict_needs(point.name)) if job.always else job,
924 joined,
925 )
926 for job in point.jobs
927 ]
928 for job in added:
929 needing = [i for i, other in enumerate(jobs) if job.name in other.needs]
930 verdict = [i for i, other in enumerate(jobs) if other.always]
931 jobs.insert((needing or verdict or [len(jobs)])[0], _waiting(job, joined))
932 # A join renders as no job: it rides the point's jobs so every
933 # reader of what a job installs, deploys and publishes sees it.
934 jobs.extend(joined)
935 composed.append(replace(point, jobs=tuple(jobs)))
936 return tuple(composed)
937
938
939def _waiting(job: Job, joins: Sequence[Job]) -> Job:
940 """*job* with the needs of each of *joins* that joins it added to its own."""
941 extra = [need for join in joins if join.name == job.name for need in join.needs]
942 if not extra:
943 return job
944 return replace(job, needs=tuple(dict.fromkeys((*job.needs, *extra))))
945
946
947def points(root: Path | None) -> tuple[Point, ...]:
948 """Every point *root* has: the builtin four, then the ones its packages contribute.
949
950 ``None`` is a process outside any workspace, which has the builtin
951 four alone, with the jobs the mounted extensions contributed in place.
952 The whole set is verified as one: a contributed point cannot
953 share a file or a name with another.
954 """
955 builtin = composed_points()
956 if root is None:
957 verify_points(builtin)
958 return builtin
959 everything = builtin + tuple(item.point for item in contributed(root))
960 verify_points(everything)
961 return everything
962
963
964def emitted_points(root: Path) -> tuple[Point, ...]:
965 """`points`, plus a job for each name only the contract's entries give.
966
967 A ``[[ci.schedule]]`` entry in the root contract may name a job its
968 point does not declare (`jobs_of` lists it); the shell needs that
969 job to call it. The job runs on one runner, the newest gate
970 Python, with the checkout depth, token and write grant of the
971 point's first job: the root contract is where a grant is decided,
972 so this widens nothing a package could reach.
973 """
974 everything = points(root)
975 entries = declared(root)
976 out: list[Point] = []
977 for point in everything:
978 names = {job.name for job in point.jobs} | {point.name}
979 names |= {job.name for job in inherited_jobs(point, everything)}
980 model = point.jobs[0] if point.jobs else Job(point.name)
981 added: list[Job] = []
982 for entry in entries:
983 if entry.point != point.name or entry.job in names:
984 continue
985 names.add(entry.job)
986 added.append(
987 Job(
988 entry.job,
989 fetch=model.fetch,
990 token=model.token,
991 writes=model.writes,
992 note=(
993 f"The {entry.job} job: the [[ci.schedule]] entries"
994 " that name it, on one runner."
995 ),
996 )
997 )
998 out.append(replace(point, jobs=(*point.jobs, *added)) if added else point)
999 return tuple(out)
1000
1001
1002def inherited_jobs(point: Point, everything: tuple[Point, ...]) -> tuple[Job, ...]:
1003 """The jobs *point* runs before its own, from the point it inherits."""
1004 if not point.inherits:
1005 return ()
1006 return next(other for other in everything if other.name == point.inherits).jobs
1007
1008
1009def point_by_name(root: Path | None) -> dict[str, Point]:
1010 """`points`, by name."""
1011 return {point.name: point for point in points(root)}
1012
1013
1014def jobs_reading(root: Path, path: str) -> tuple[str, ...]:
1015 """The jobs whose declared inputs read *path*, each ``<point>/<job>``."""
1016 from livery.workshop._influence import reads
1017
1018 return tuple(
1019 f"{point.name}/{job.name}"
1020 for point in points(root)
1021 for job in point.jobs
1022 if job.inputs is not None and reads(job.inputs, root, path)
1023 )
1024
1025
1026def unread_by_the_job(root: Path, point: str, job: str) -> str:
1027 """The line that skips *job* of *point* when nothing it reads changed, or empty.
1028
1029 Only a job that declares ``inputs`` skips, and only on a pull
1030 request's run in a workspace declaring ``[ci] affected-legs``, the
1031 terms the check legs narrow on: a push, a dispatch, the clock and a
1032 person's own run always run every entry. The changes are the run's
1033 own ([livery.workshop.ci_changes][]), read the way the check legs
1034 read them, and the inputs select as a step's do, so a change to
1035 the sources of the extension that contributed the job runs it.
1036 """
1037 from livery.workshop._extensions import extension_provider
1038 from livery.workshop._influence import select
1039 from livery.workshop._packages import discover_packages
1040 from livery.workshop._quality import ci_changes
1041
1042 declared = next(
1043 (item for item in point_by_name(root)[point].jobs if item.name == job), None
1044 )
1045 if declared is None or declared.inputs is None:
1046 return ""
1047 changes = ci_changes(root)
1048 if changes is None:
1049 return ""
1050 packages = discover_packages(root) if (root / "packages").is_dir() else ()
1051 provider = extension_provider(contributor_of(point, job), packages)
1052 if select(declared.inputs, changes, provider=provider).runs:
1053 return ""
1054 return (
1055 f" {point}/{job}: nothing the job reads changed in this run"
1056 f" ({len(changes.paths)} path(s) changed); its entries are skipped"
1057 )
1058
1059
1060def job_installs(
1061 root: Path, everything: tuple[Point, ...] | None = None
1062) -> dict[tuple[str, str], tuple[str, ...]]:
1063 """What each job installs before it enters, by its point and its name.
1064
1065 Only a job that names an ``installs`` function has an entry. Its
1066 packages are sorted and named once, so the rendered file is the
1067 same on every run. *everything* is the points to read; *root*'s
1068 when absent.
1069 """
1070 everything = everything if everything is not None else points(root)
1071 return {
1072 (point.name, job.name): tuple(sorted(set(job.installs(root))))
1073 for point in everything
1074 for job in point.jobs
1075 if job.installs is not None
1076 }
1077
1078
1079def job_seams(
1080 root: Path, everything: tuple[Point, ...] | None = None
1081) -> dict[tuple[str, str], str]:
1082 """The seam each deploying job publishes through, by its point and its name.
1083
1084 Only a job that names a ``deploy`` function has an entry.
1085 *everything* is the points to read; *root*'s when absent.
1086 """
1087 everything = everything if everything is not None else points(root)
1088 return {
1089 (point.name, job.name): job.deploy(root)
1090 for point in everything
1091 for job in point.jobs
1092 if job.deploy is not None
1093 }
1094
1095
1096def job_runners(
1097 root: Path, everything: tuple[Point, ...] | None = None
1098) -> dict[tuple[str, str], tuple[str, ...]]:
1099 """The runner labels each job's ``labels`` function names, by point and job.
1100
1101 Only a job that names a ``labels`` function has an entry: the
1102 labels the function names for *root*, in its order and each once,
1103 so the rendered file is the same on every run. An empty entry is a
1104 ``runners`` job this workspace renders no job for. *everything* is
1105 the points to read; *root*'s when absent.
1106 """
1107 everything = everything if everything is not None else points(root)
1108 return {
1109 (point.name, job.name): tuple(dict.fromkeys(job.labels(root)))
1110 for point in everything
1111 for job in point.jobs
1112 if job.labels is not None
1113 }
1114
1115
1116def events_of(root: Path | None, point: str) -> tuple[str, ...]:
1117 """The events that start *point*'s runs; refuses a name that is not a point."""
1118 by_name = point_by_name(root)
1119 if point not in by_name:1119 ↛ 1120line 1119 didn't jump to line 1120 because the condition on line 1119 was never true
1120 fail(f"{point!r} is not a point; the points are {', '.join(by_name)}")
1121 return by_name[point].events
1122
1123
1124def dispatchable(root: Path | None) -> tuple[str, ...]:
1125 """The points a person starts by hand: a dispatch entry and no input to supply.
1126
1127 An optional input, the nightly's ``only``, leaves a point
1128 dispatchable; a required one, the release's ``ref``, does not.
1129 """
1130 return tuple(
1131 point.name
1132 for point in points(root)
1133 if "workflow_dispatch" in point.events
1134 and not any(item.required for item in point.inputs)
1135 )
1136
1137
1138#: The events that trigger each point's runs, in the forges' words.
1139EVENTS = {point.name: point.events for point in DECLARED}
1140
1141#: The points a person starts by hand through ``ci.dispatch``: a
1142#: dispatch entry and no input to supply. The merge point runs on a
1143#: push alone, and the release wave takes a required input, so the
1144#: merge point dispatches it through ``workflow.release.dispatch``.
1145DISPATCHABLE = tuple(
1146 point.name
1147 for point in DECLARED
1148 if "workflow_dispatch" in point.events
1149 and not any(item.required for item in point.inputs)
1150)
1151
1152#: A point whose jobs include another point's: the merge point runs
1153#: the gate's jobs and its own.
1154INHERITS = {point.name: point.inherits for point in DECLARED if point.inherits}
1155
1156
1157def _tracing(root: Path) -> bool:
1158 """Whether the jobs run profiled, for their timing rows (``[ci] timing``)."""
1159 from livery.workshop._traces import policy
1160
1161 kept, _why = policy(root)
1162 return kept.timing
1163
1164
1165def _pushing(root: Path) -> bool:
1166 """Whether a job pushes its trace to the trace refs (``[ci] profile``)."""
1167 from livery.workshop._traces import policy
1168
1169 kept, _why = policy(root)
1170 return kept.profile
1171
1172
1173def profile_box() -> AbstractContextManager[Path]:
1174 """The job's drop box, where every entry leaves its own timeline.
1175
1176 The plugin owns the directory and its sweeping; this names it to the
1177 entries through the environment the runner already builds for them,
1178 which is why nothing here writes this process's own.
1179 """
1180 from livery.footman.profile import box
1181
1182 return box()
1183
1184
1185def _push_about(root: Path) -> None:
1186 """Record the commit this run ran on, where the forge files it elsewhere.
1187
1188 A line and never a verdict, like the trace beside it. Written per
1189 job because any job of the run can write it and the write merges;
1190 a run whose own head is the commit it checked out writes nothing.
1191 """
1192 from livery.workshop._traces import about
1193
1194 try:
1195 line = about(root)
1196 except Exception as error:
1197 line = f"profile: what this run ran on was not recorded ({error})"
1198 if line:
1199 print(f" {line}")
1200
1201
1202def _push_job(root: Path, drop: Path, *, job: str, leg: str) -> None:
1203 """Write the job's own trace from what its entries left, and push it.
1204
1205 *leg* is the label this job gave the entries it spawned. This
1206 process is not one of them, so its own environment never carried
1207 the label and the push has to be told.
1208
1209 Every line is printed and none is a verdict: a job's timeline is
1210 something noticed about the work, never part of deciding it.
1211 """
1212 from livery.footman.profile import as_trace, swept
1213 from livery.workshop._traces import push
1214
1215 try:
1216 events, origin = swept(drop)
1217 if not events:1217 ↛ 1218line 1217 didn't jump to line 1218 because the condition on line 1217 was never true
1218 return
1219 written = drop.parent / f"{drop.name}.json"
1220 written.write_text(as_trace(events, origin=origin), encoding="utf-8")
1221 line = push(root, written, job=job, leg=leg)
1222 written.unlink(missing_ok=True)
1223 except Exception as error:
1224 line = f"profile: the job's trace was not kept ({error})"
1225 if line:1225 ↛ exitline 1225 didn't return from function '_push_job' because the condition on line 1225 was always true
1226 print(f" {line}")
1227
1228
1229def trace_file(task: str) -> str:
1230 """The file an entry's own trace is written to, named after the task.
1231
1232 One file per entry rather than one per job: the leg's timing row reads
1233 the gate's own file, and a person reading a runner's working directory
1234 can tell which entry a trace belongs to.
1235 """
1236 from livery.git import slug
1237
1238 return f"fm-profile-{slug(task)}.json"
1239
1240
1241#: The gate's own trace, which the leg's timing row reads.
1242TRACE = trace_file("check")
1243
1244
1245@dataclass(frozen=True)
1246class Entry:
1247 """One scheduled task: at which point and job, which task, which arguments.
1248
1249 Attributes:
1250 point: One of `POINTS`.
1251 job: The job of the point the entry runs in.
1252 task: The task's dotted address, as the workspace mounts it.
1253 args: The arguments, each formatted with the run's facts:
1254 ``{display}`` the job's display name, ``{label}`` the
1255 leg's label, ``{os}`` and ``{python}`` the matrix values,
1256 ``{shard}`` the leg's shard spelled ``<i>of<n>`` (``1of1``
1257 on a leg that is not split), and each of the point's
1258 dispatch inputs by name (``{ref}`` on the release), empty
1259 when the run was not dispatched with it.
1260 source: Where the entry was declared.
1261 every: The cadence, ``""`` for every run of the point, ``1w``
1262 for one run a week, ``2w`` for one run every two weeks;
1263 a run on any other day skips the entry and names the day
1264 it runs next.
1265 if_changed: Whether the entry runs only when the ref's head has
1266 moved since the point last reached a verdict there, green or
1267 red; false when absent. A dispatch by hand runs regardless.
1268 once: Whether the entry runs on a matrix job's first leg alone,
1269 the first runner and the first Python, and on that leg's
1270 first shard alone; every leg and shard otherwise.
1271 sharded: Whether the entry takes the leg's shard,
1272 ``--shard=<i>of<n>`` after its arguments, when the leg
1273 runs as one of several shards; on a leg that runs as one
1274 shard of one the entry takes nothing more.
1275 last: Whether the entry runs after every entry an extension
1276 adds to the job, the janitor's shape; the added entries go
1277 before the first such entry.
1278 judges: Whether the entry judges the run before the verdict:
1279 a judge an extension adds to a point's verdict job runs
1280 before the job collects the run's rows, and a red one stops
1281 the job there, as a red builtin entry does.
1282 """
1283
1284 point: str
1285 job: str
1286 task: str
1287 args: tuple[str, ...] = ()
1288 source: str = "builtin"
1289 every: str = ""
1290 if_changed: bool = False
1291 once: bool = False
1292 last: bool = False
1293 judges: bool = False
1294 sharded: bool = False
1295
1296
1297#: The cadences an entry may declare, in days.
1298CADENCES = {"1w": 7, "2w": 14}
1299
1300#: The verdicts that count as a finished run for ``if-changed``.
1301VERDICTS = frozenset({"green", "red"})
1302
1303today: Callable[[], date] = date.today
1304"""The day a run judges a cadence on, UTC as the runners keep it.
1305
1306A variable, not a function, so a test fixes the day instead of
1307waiting for a Monday.
1308"""
1309
1310
1311def due(every: str, on: date) -> tuple[bool, date]:
1312 """Whether a cadence runs on *on*, and the day it runs next.
1313
1314 A weekly entry runs on Mondays; a two-weekly entry on the Monday
1315 of an even ISO week, so every workspace agrees on the day without
1316 a record of the last run. An empty cadence is due on every run.
1317 """
1318 if not every:
1319 return True, on
1320 monday = on - timedelta(days=on.weekday())
1321 if every == "1w":
1322 return on == monday, (monday if on == monday else monday + timedelta(days=7))
1323 even = monday.isocalendar().week % 2 == 0
1324 if on == monday and even:
1325 return True, on
1326 following = monday + timedelta(days=7)
1327 if following.isocalendar().week % 2 != 0:
1328 following += timedelta(days=7)
1329 return False, following
1330
1331
1332def _row_matches_point(data: Mapping[str, Any], point: str) -> bool:
1333 """Whether a metrics row *data* belongs to *point*."""
1334 trigger = str(data.get("trigger") or "")
1335 if trigger:1335 ↛ 1337line 1335 didn't jump to line 1337 because the condition on line 1335 was always true
1336 return trigger == point
1337 jobs = data.get("jobs")
1338 if isinstance(jobs, Mapping):
1339 return any(
1340 name == point or name.startswith(f"{point} (") or name.startswith("suite")
1341 for name in jobs
1342 )
1343 return False
1344
1345
1346def last_verdict_sha(
1347 root: Path,
1348 *,
1349 point: str,
1350 ref: str = "",
1351 rows: Sequence[Row] | None = None,
1352) -> tuple[str, str, str]:
1353 """The commit SHA, verdict and run id of *point*'s latest finished row on *ref*.
1354
1355 A finished row carries ``verdict`` in `VERDICTS` (``green`` or ``red``).
1356 A cancelled or incomplete row has no verdict and is skipped. Returns
1357 ``("", "", "")`` when no finished row exists or the store cannot be read.
1358 """
1359 from livery import git
1360 from livery.workshop._metrics import SERIES as METRICS
1361
1362 if rows is None:1362 ↛ 1370line 1362 didn't jump to line 1370 because the condition on line 1362 was always true
1363 try:
1364 found = METRICS.rows(state_store(root))
1365 except git.GitError:
1366 return "", "", ""
1367 if found.failed:
1368 return "", "", ""
1369 rows = found.rows
1370 for row in rows:
1371 data = row.data
1372 if not _row_matches_point(data, point):1372 ↛ 1373line 1372 didn't jump to line 1373 because the condition on line 1372 was never true
1373 continue
1374 row_ref = str(data.get("ref") or "")
1375 if ref and row_ref and row_ref != ref:1375 ↛ 1376line 1375 didn't jump to line 1376 because the condition on line 1375 was never true
1376 continue
1377 verdict = str(data.get("verdict") or "")
1378 if verdict not in VERDICTS:
1379 continue
1380 return (
1381 str(data.get("sha") or ""),
1382 verdict,
1383 str(data.get("run") or ""),
1384 )
1385 return "", "", ""
1386
1387
1388def _safe_head_sha(root: Path) -> str:
1389 """HEAD's commit SHA, or ``""`` outside a git checkout."""
1390 from livery import git
1391
1392 try:
1393 return git.head_sha(root)
1394 except git.GitError:
1395 return ""
1396
1397
1398def entry_due(
1399 root: Path,
1400 entry: Entry,
1401 *,
1402 point: str,
1403 on: date | None = None,
1404 run: RunContext | None = None,
1405 head_sha: str | None = None,
1406 last_verdict: tuple[str, str, str] | None = None,
1407) -> tuple[bool, str]:
1408 """Whether *entry* is due to run now, and the reason when skipped.
1409
1410 A dispatch by hand (``workflow_dispatch``) is always due. Otherwise
1411 ``every`` checks the day (`due`) and ``if_changed`` checks whether
1412 ``HEAD`` has moved since *point* last reached a verdict (`VERDICTS`)
1413 on the run's ref.
1414 """
1415 if run is not None and run.event == "workflow_dispatch":
1416 return True, ""
1417 if entry.every:
1418 is_due, when = due(entry.every, on or today())
1419 if not is_due:
1420 return (
1421 False,
1422 f"runs every {entry.every}; next on {when:%Y-%m-%d}, skipped",
1423 )
1424 if entry.if_changed:
1425 sha = _safe_head_sha(root) if head_sha is None else head_sha
1426 if sha:
1427 if last_verdict is None:1427 ↛ 1428line 1427 didn't jump to line 1428 because the condition on line 1427 was never true
1428 ref = run.ref if run is not None else ""
1429 last_verdict = last_verdict_sha(root, point=point, ref=ref)
1430 last_sha, verdict, run_id = last_verdict
1431 if last_sha and last_sha == sha:
1432 return (
1433 False,
1434 f"head {sha[:12]} has not moved since run {run_id}"
1435 f" ({verdict}); skipped",
1436 )
1437 return True, ""
1438
1439
1440def due_jobs(
1441 root: Path,
1442 point: str,
1443 *,
1444 only: str = "",
1445 on: date | None = None,
1446 run: RunContext | None = None,
1447 output: Path | None = None,
1448) -> dict[str, bool]:
1449 """Which jobs of *point* have a due task; prints reasons and writes *output*.
1450
1451 Used by a scheduled workflow's first job (``fm ci.due``) so a job with
1452 no due task never starts a runner. Every entry other than `RECORD_TASK`
1453 is judged with `entry_due` (and `--only` when given). When *output* is
1454 given, writes ``<job>=true`` or ``<job>=false`` lines for GitHub / Gitea
1455 job outputs.
1456 """
1457 current = run_context() if run is None else run
1458 asked = asked_tasks(root, point, only)
1459 day = on or today()
1460 jobs = jobs_of(root, point)
1461 job_entries = {
1462 job: tuple(
1463 entry
1464 for entry in entries_for(root, point, job)
1465 if entry.task != RECORD_TASK
1466 )
1467 for job in jobs
1468 }
1469 needs_head = (current is None or current.event != "workflow_dispatch") and any(
1470 entry.if_changed for entries in job_entries.values() for entry in entries
1471 )
1472 head_sha = _safe_head_sha(root) if needs_head else ""
1473 ref = current.ref if current is not None else ""
1474 last_verdict = (
1475 last_verdict_sha(root, point=point, ref=ref) if needs_head else ("", "", "")
1476 )
1477 result: dict[str, bool] = {}
1478 for job, entries in job_entries.items():
1479 due_tasks: list[str] = []
1480 for entry in entries:
1481 if asked and entry.task not in asked:1481 ↛ 1482line 1481 didn't jump to line 1482 because the condition on line 1481 was never true
1482 print(
1483 f" {point}/{job}: {entry.task} ({entry.source}) is not"
1484 " among the tasks this dispatch asked for; skipped"
1485 )
1486 continue
1487 is_due, why = entry_due(
1488 root,
1489 entry,
1490 point=point,
1491 on=day,
1492 run=current,
1493 head_sha=head_sha,
1494 last_verdict=last_verdict,
1495 )
1496 if not is_due:
1497 print(f" {point}/{job}: {entry.task} ({entry.source}) {why}")
1498 continue
1499 due_tasks.append(entry.task)
1500 result[job] = bool(due_tasks)
1501 if due_tasks:
1502 print(f" {point}/{job}: due ({', '.join(due_tasks)})")
1503 else:
1504 print(f" {point}/{job}: no task due; job skipped")
1505 if output is not None:
1506 lines = "".join(
1507 f"{job}={'true' if flag else 'false'}\n" for job, flag in result.items()
1508 )
1509 with output.open("a", encoding="utf-8") as handle:
1510 handle.write(lines)
1511 return result
1512
1513
1514#: The task that collects the run's rows in the verdict job: the
1515#: judges the extensions add run before it, so what they leave for
1516#: the run's row is folded in.
1517COLLECT = "ci.metrics.collect"
1518
1519#: The task that drops the run's per-run refs, the last entry of a job
1520#: that collected: after its verdict, and only once every job that
1521#: puts a half has completed green.
1522DROP_TASK = "ci.metrics.drop"
1523
1524#: The task that ends every job of a point with no verdict job: it
1525#: puts the job's half from the traces its entries left, collects the
1526#: run's row, and drops the refs when it is the run's last green job.
1527RECORD_TASK = "ci.metrics.record"
1528
1529#: The workshop's own schedule. Every entry runs profiled, so a job's
1530#: own timeline is the union of the work it did; the gate's check job
1531#: also records the leg's timing row, and its verdict job collects the
1532#: run's rows, then judges the jobs it needs. The merge
1533#: point adds the deploy, the governance reconcile, which classifies
1534#: its own commit and exits fast when no contract path changed, and
1535#: the release dispatch, green unless a merged release is unpublished.
1536BUILTIN: tuple[Entry, ...] = (
1537 # The walk takes the leg's shard when the leg is one of several, so
1538 # the steps that split run their share; an unsplit leg calls it bare.
1539 Entry("gate", "check", "check", sharded=True),
1540 # The leg's one write, after whatever the extensions add to the
1541 # job: its timing row and every file their entries left go on its
1542 # per-run ref together.
1543 Entry("gate", "check", "ci.leg", ("--job={display}",), last=True),
1544 # The title check first: it reads the pull request's title from
1545 # the event payload, is green off a release branch, and refuses a
1546 # release title the changelogs do not match before anything else
1547 # is judged. It runs here so the legs never wait for a job of
1548 # its own. The judges the extensions add run after it, before the
1549 # collect, so what they leave rides the run's row.
1550 Entry("gate", "gate", "workflow.release.check-title"),
1551 # The fold next, before any judge reads the run's refs: a platform
1552 # that ran as shards has one ref per shard, and the judges, the
1553 # collect and the stamp read one leg per platform.
1554 Entry("gate", "gate", "ci.fold"),
1555 Entry("gate", "gate", COLLECT),
1556 # The speed judge reads the run's row the collect just put: a
1557 # suite over its mark for the second run in a row is red here,
1558 # before the verdict, so the record never names a slow tree green.
1559 Entry("gate", "gate", "speed.judge"),
1560 # The verdict waits for the check and for every contributed job that
1561 # gates; `schedule` writes the composed list into this entry.
1562 Entry("gate", "gate", "ci.verdict", ("--needs=check",)),
1563 # After a green verdict, so the forge's merge follows it as closely as
1564 # it can: a release pull request whose base moved under its set is
1565 # refused before the merge, where the publish would refuse it after.
1566 # Green off a release branch.
1567 Entry("gate", "gate", "workflow.release.check-fresh"),
1568 # Last of all, after a green verdict and whatever the extensions
1569 # add: the legs' per-run refs go only once this job has nothing
1570 # left to read from them, so a red attempt leaves them for its
1571 # re-run, which runs this job again without its legs.
1572 Entry("gate", "gate", DROP_TASK, ("--point=gate", "--job={display}"), last=True),
1573 Entry("merge", "govern", "workflow.configure", ("--if-changed",)),
1574 # The wave is dispatched from the gate job itself, right after
1575 # main's own verdict: the verb reads the manifest at HEAD and the
1576 # receipts on the remote, and is green unless a merged release is
1577 # unpublished. A job of its own cost a runner's entry for a second
1578 # of work.
1579 Entry("merge", "gate", "workflow.release.dispatch"),
1580 # The janitor after the stamp, on the merge point alone, and after
1581 # whatever the extensions add to the job: every merge tidies the
1582 # remote store, and a pull request's run writes nothing it does
1583 # not own.
1584 Entry("merge", "gate", "janitor", last=True),
1585 # The clock's point: the doctor first, so the night's record opens
1586 # with the runner's and the forge's state, mending what footman
1587 # can (a runner that keeps its caches across jobs holds the scratch
1588 # of processes that died there; a finding that stands after the
1589 # mend is still red), then the whole check with the tests that
1590 # declare the nightly point selected in, on every python of the
1591 # matrix.
1592 Entry("nightly", "nightly", "doctor", ("--fix",), if_changed=True),
1593 Entry("nightly", "nightly", "check", if_changed=True),
1594 Entry("nightly", "suite", "check", sharded=True, if_changed=True),
1595 # The unprivileged build job builds pure distributions and writes
1596 # their SHA-256 manifest before the isolated publish job runs.
1597 Entry("release", "build", "workflow.release.build", ("--ref={ref}",)),
1598 # The wave, at the squash the dispatch names: the publish that cuts
1599 # the receipts. The verb decides for itself what the ref holds, and
1600 # whether a job of the run already built its wheels.
1601 Entry("release", "publish", "workflow.release.publish", ("--ref={ref}",)),
1602)
1603
1604
1605def declared(root: Path) -> tuple[Entry, ...]:
1606 """The ``[[ci.schedule]]`` entries of *root*'s contract, refusing bad ones.
1607
1608 Each entry names a ``point`` (one of `points`), a ``task``, and
1609 optionally a ``job`` (the point's own name when absent), ``args``
1610 and ``every``, a cadence from `CADENCES`. An unknown point, a
1611 missing task, arguments that are not strings, or a cadence that
1612 is not one refuse at load, naming the entry.
1613 """
1614 contract = load_contract(root / "workshop.toml")
1615 raw = (contract.get("ci") or {}).get("schedule") or []
1616 if not isinstance(raw, list):1616 ↛ 1617line 1616 didn't jump to line 1617 because the condition on line 1616 was never true
1617 fail("[ci] schedule must be a list of [[ci.schedule]] tables")
1618 entries: list[Entry] = []
1619 names = tuple(point.name for point in points(root))
1620 for index, item in enumerate(raw, start=1):
1621 if not isinstance(item, dict):1621 ↛ 1622line 1621 didn't jump to line 1622 because the condition on line 1621 was never true
1622 fail(f"[[ci.schedule]] entry {index} is not a table")
1623 point = str(item.get("point", ""))
1624 task = str(item.get("task", ""))
1625 if point not in names:
1626 fail(
1627 f"[[ci.schedule]] entry {index}: point {point!r} is not a"
1628 f" point; the points are {', '.join(names)}"
1629 )
1630 if not task:
1631 fail(f"[[ci.schedule]] entry {index} ({point}): names no task")
1632 # The contract's judge holds the arguments to strings and the
1633 # cadence to one of `CADENCES`.
1634 args = item.get("args", [])
1635 every = str(item.get("every", ""))
1636 if_changed = bool(item.get("if-changed", False))
1637 once = bool(item.get("once", False))
1638 entries.append(
1639 Entry(
1640 point,
1641 str(item.get("job", point)),
1642 task,
1643 tuple(args),
1644 source="workshop.toml",
1645 every=every,
1646 if_changed=if_changed,
1647 once=once,
1648 )
1649 )
1650 return tuple(entries)
1651
1652
1653def builtin_schedule() -> tuple[Entry, ...]:
1654 """The builtin entries with the extensions' contributed jobs' entries in place.
1655
1656 A contributed job's entries follow the declared entries of its
1657 point's jobs before the verdict, and the verdict's ``--needs``
1658 names the composed list.
1659 """
1660 from dataclasses import replace
1661
1662 composed: list[Entry] = []
1663 for entry in BUILTIN:
1664 if entry.task == "ci.verdict":
1665 for item in contributed_jobs(entry.point):
1666 composed.extend(item.entries)
1667 composed.append(
1668 replace(
1669 entry, args=(f"--needs={','.join(verdict_needs(entry.point))}",)
1670 )
1671 )
1672 continue
1673 composed.append(entry)
1674 seen = {(entry.point, entry.job, entry.task) for entry in composed}
1675 for point in DECLARED:
1676 if any(job.always for job in point.jobs):
1677 continue
1678 for item in contributed_jobs(point.name):
1679 composed.extend(
1680 entry
1681 for entry in item.entries
1682 if (entry.point, entry.job, entry.task) not in seen
1683 )
1684 for point in DECLARED:
1685 for item in joined_jobs(point.name):
1686 _join_entries(composed, item)
1687 return tuple(composed)
1688
1689
1690def _join_entries(composed: list[Entry], item: JobContribution) -> None:
1691 """Put *item*'s entries into *composed* where its job runs what it adds.
1692
1693 Before the first entry of the job that runs last, else after the
1694 job's last entry, else at the end: the join's entries run after
1695 the job's own and before its sweep. A judge goes before the job's
1696 collect (`COLLECT`), so what it leaves for the run's row is folded
1697 in, and the verdict and the stamp come after it.
1698 """
1699 key = (item.point, item.job.name)
1700 owned = [i for i, e in enumerate(composed) if (e.point, e.job) == key]
1701 judges = [entry for entry in item.entries if entry.judges]
1702 if judges:
1703 at = next((i for i in owned if composed[i].task == COLLECT), None)
1704 if at is None:1704 ↛ 1705line 1704 didn't jump to line 1705 because the condition on line 1704 was never true
1705 at = owned[-1] + 1 if owned else len(composed)
1706 composed[at:at] = judges
1707 owned = [i for i, e in enumerate(composed) if (e.point, e.job) == key]
1708 at = next((i for i in owned if composed[i].last), None)
1709 if at is None:
1710 at = owned[-1] + 1 if owned else len(composed)
1711 composed[at:at] = [entry for entry in item.entries if not entry.judges]
1712
1713
1714def schedule(root: Path) -> tuple[Entry, ...]:
1715 """Every entry: the builtin ones, the packages' contributed ones, the contract's.
1716
1717 Then the record each job of a point without a verdict job ends
1718 with (`recording`), after every entry the contract gave the job.
1719 """
1720 scheduled = (
1721 builtin_schedule()
1722 + tuple(item.entry for item in contributed(root))
1723 + declared(root)
1724 )
1725 return scheduled + recording(root, scheduled)
1726
1727
1728def _has_verdict_job(point: Point) -> bool:
1729 """Whether *point*, or the point it inherits, declares a verdict job."""
1730 verdicts = {name for name, _job in verdict_jobs()}
1731 return point.name in verdicts or point.inherits in verdicts
1732
1733
1734def recording(root: Path, scheduled: tuple[Entry, ...]) -> tuple[Entry, ...]:
1735 """The record ending every job of each point of *root* with no verdict job.
1736
1737 A verdict job collects what its point's legs put; a point without
1738 one (the nightly, the release, every point a package contributes)
1739 would leave no row of its run, so each of its jobs ends with
1740 `RECORD_TASK`, which puts the job's own half, collects the run's
1741 row and drops the per-run refs when it is the run's last green
1742 job. The jobs are the point's declared ones and any a
1743 ``[[ci.schedule]]`` entry in *scheduled* names.
1744 """
1745 entries: list[Entry] = []
1746 for point in points(root):
1747 if _has_verdict_job(point):
1748 continue
1749 jobs = [job.name for job in point.jobs]
1750 for entry in scheduled:
1751 if entry.point == point.name and entry.job not in jobs:
1752 jobs.append(entry.job)
1753 entries.extend(
1754 Entry(
1755 point.name,
1756 job,
1757 RECORD_TASK,
1758 (f"--point={point.name}", "--job={display}"),
1759 last=True,
1760 )
1761 for job in jobs
1762 )
1763 return tuple(entries)
1764
1765
1766def half_writers(root: Path, point: str) -> tuple[str, ...]:
1767 """The jobs of *point* that put a half of the run's row, by their schedule names.
1768
1769 The check legs of a point with a verdict job (`ci.leg`), and every
1770 job of a point without one (`RECORD_TASK`). A forge lists a matrix
1771 job's legs under the job's name with the leg in brackets, so a
1772 reader matches by prefix.
1773 """
1774 return tuple(
1775 dict.fromkeys(
1776 entry.job
1777 for entry in schedule(root)
1778 if entry.task in ("ci.leg", RECORD_TASK)
1779 and entry.point in (INHERITS.get(point), point)
1780 )
1781 )
1782
1783
1784def workflow_of(point: str, root: Path | None = None) -> str:
1785 """The workflow file *point*'s shell is; refuses a name that is not a point."""
1786 by_name = point_by_name(root)
1787 if point not in by_name:
1788 fail(f"{point!r} is not a point; the points are {', '.join(by_name)}")
1789 return by_name[point].workflow
1790
1791
1792def jobs_of(root: Path, point: str) -> tuple[str, ...]:
1793 """The jobs *point* has: declared ones, inherited first, then any an entry names.
1794
1795 A ``[[ci.schedule]]`` entry may name a job no declaration has; it
1796 is listed after the declared jobs, in schedule order.
1797 """
1798 by_name = point_by_name(root)
1799 if point not in by_name:
1800 fail(f"{point!r} is not a point; the points are {', '.join(by_name)}")
1801 declared_point = by_name[point]
1802 inherited = by_name[declared_point.inherits].jobs if declared_point.inherits else ()
1803 names: list[str] = []
1804 for job in (*inherited, *declared_point.jobs):
1805 if job.name not in names:
1806 names.append(job.name)
1807 for entry in schedule(root):
1808 if entry.point in (INHERITS.get(point), point) and entry.job not in names:
1809 names.append(entry.job)
1810 return tuple(names)
1811
1812
1813def first_leg(root: Path, point: str, job: str) -> tuple[str, str]:
1814 """The first leg of *job* at *point*: its first runner and its first Python.
1815
1816 An axis the job does not have is empty. The check legs fan out
1817 over ``[ci] runners`` and the gate's Pythons, the nightly over every
1818 Python on the first runner, a declared job over its own lists. A
1819 ``runners`` job's call names no leg and a job with no matrix has
1820 none, so neither has a leg to name.
1821 """
1822 from livery.workshop._pythons import gate_pythons, python_matrix
1823
1824 found = next(
1825 (item for item in point_by_name(root)[point].jobs if item.name == job), None
1826 )
1827 if found is None or not found.matrix:
1828 return "", ""
1829 ci = load_contract(root / "workshop.toml").get("ci") or {}
1830 runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
1831 if found.matrix == "legs":1831 ↛ 1832line 1831 didn't jump to line 1832 because the condition on line 1831 was never true
1832 return runners[0], gate_pythons(root)[0]
1833 if found.matrix == "pythons":1833 ↛ 1835line 1833 didn't jump to line 1835 because the condition on line 1833 was always true
1834 return "", python_matrix(root)[0]
1835 if found.matrix == "declared":
1836 return (
1837 found.runners[0] if found.runners else "",
1838 found.pythons[0] if found.pythons else "",
1839 )
1840 return "", ""
1841
1842
1843def entries_for(root: Path, point: str, job: str) -> tuple[Entry, ...]:
1844 """The entries *job* of *point* runs, in order; refuses an unknown job.
1845
1846 A point's own name is always a job of it, with nothing scheduled
1847 until an entry attaches: the nightly shell exists before its
1848 first entry, and runs green and empty until then.
1849 """
1850 jobs = jobs_of(root, point)
1851 if job not in jobs and job != point:
1852 fail(
1853 f"the {point} point has no job {job!r}; its jobs are"
1854 f" {', '.join(jobs) or 'none'}"
1855 )
1856 return tuple(
1857 entry
1858 for entry in schedule(root)
1859 if entry.point in (INHERITS.get(point), point) and entry.job == job
1860 )
1861
1862
1863def scheduled_tasks(root: Path, point: str) -> tuple[str, ...]:
1864 """Every task *point* runs, across its jobs, in schedule order, once each."""
1865 found: dict[str, None] = {}
1866 for job in jobs_of(root, point):
1867 for entry in entries_for(root, point, job):
1868 found.setdefault(entry.task, None)
1869 return tuple(found)
1870
1871
1872def asked_tasks(root: Path, point: str, only: str) -> tuple[str, ...]:
1873 """The tasks a dispatch's *only* names, judged against what *point* runs.
1874
1875 Empty for an empty *only*, which runs the whole schedule.
1876
1877 Raises:
1878 Failed: when *only* names a task the point does not run, naming
1879 the ones it does.
1880 """
1881 asked = tuple(
1882 dict.fromkeys(name.strip() for name in only.split(",") if name.strip())
1883 )
1884 if not asked:
1885 return ()
1886 runs = scheduled_tasks(root, point)
1887 unknown = [name for name in asked if name not in runs]
1888 if unknown:
1889 fail(
1890 f"the {point} point runs {', '.join(runs) or 'nothing'}; --only names"
1891 f" {', '.join(unknown)}, which it does not run"
1892 )
1893 return asked
1894
1895
1896#: The label a pull request carries so the gate runs every runner for
1897#: it, where its check legs run on fewer. `fm submit
1898#: --every-runner` sets it through the forge, and a person sets it on
1899#: the forge by hand; the gate workflow runs on ``labeled``, its legs
1900#: job picks the full matrix while the label is there, and the coverage
1901#: union expects every leg. The repository configuration creates the
1902#: label (`fm workflow.configure`).
1903EVERY_RUNNER_LABEL = "ci:every-runner"
1904
1905
1906def pull_request_runners(ci: dict[str, Any]) -> list[str]:
1907 """The runners a pull request's check legs fan out to.
1908
1909 ``[ci] pull-request-runners`` when the contract declares it, else
1910 the first runner ``[ci] runners`` names (``ubuntu-latest`` without
1911 that key). A one-runner pull request carries the other legs'
1912 coverage rows from main's record, so a package whose floor needs
1913 the platform legs' fresh rows on a pull request lists every runner.
1914 A label the runners list does not name refuses naming both lists,
1915 since a pull request's legs run on runners every event runs on; an
1916 empty list refuses too.
1917 """
1918 runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
1919 declared: Any = ci.get("pull-request-runners")
1920 if declared is None:
1921 return runners[:1]
1922 chosen = [str(runner) for runner in declared]
1923 strangers = [runner for runner in chosen if runner not in runners]
1924 if strangers:
1925 fail(
1926 f"[ci] pull-request-runners names {', '.join(strangers)}, which [ci]"
1927 f" runners does not list ({', '.join(runners)}); a pull request's"
1928 " legs run on runners every event runs on"
1929 )
1930 if not chosen:
1931 fail(
1932 "[ci] pull-request-runners is empty; name a runner [ci] runners"
1933 " lists, or remove the key so the first runner runs"
1934 )
1935 return chosen
1936
1937
1938def pull_request_listed(ci: dict[str, Any]) -> str:
1939 """Name the list a pull request's runners come from, for a shard refusal.
1940
1941 ``[ci] pull-request-runners`` when the contract declares it. When
1942 the key is absent the refusal names it and the first runner
1943 ``[ci] runners`` names, which stands in for it.
1944 """
1945 if ci.get("pull-request-runners") is not None:
1946 return "[ci] pull-request-runners"
1947 return "[ci] pull-request-runners (absent, so the first of [ci] runners)"
1948
1949
1950def pull_request_legs(root: Path) -> list[str]:
1951 """Name the check legs a pull request's run produces, ``check-<os>-<python>`` each.
1952
1953 One per runner the root contract's ``[ci] pull-request-runners``
1954 names and Python the gate runs; the first runner's legs among those
1955 [livery.workshop.check_legs][] names when the key is absent. The
1956 task fails, naming both lists, when the key names a runner
1957 ``[ci] runners`` does not list, and when it is empty.
1958 """
1959 from livery.workshop._pythons import gate_pythons
1960
1961 contract = load_contract(root / "workshop.toml")
1962 ci = contract.get("ci") or {}
1963 pythons = gate_pythons(root)
1964 return [
1965 f"check-{runner}-{python}"
1966 for runner in pull_request_runners(ci)
1967 for python in pythons
1968 ]
1969
1970
1971def check_legs(root: Path) -> list[str]:
1972 """Name the check legs the gate produces, ``check-<os>-<python>`` each.
1973
1974 One per runner the root contract names (``[ci] runners``,
1975 ``ubuntu-latest`` without it) and Python the gate runs: the
1976 contract's ``[ci] python-versions``, or the newest Python of the
1977 derived matrix. Each label is spelled as the job runner names the
1978 leg it runs, the key of the leg's rows on the state store.
1979 """
1980 from livery.workshop._pythons import gate_pythons
1981
1982 contract = load_contract(root / "workshop.toml")
1983 runners = list((contract.get("ci") or {}).get("runners") or ["ubuntu-latest"])
1984 pythons = gate_pythons(root)
1985 return [f"check-{runner}-{python}" for runner in runners for python in pythons]
1986
1987
1988#: The most shards a runner may take while ``[ci] shards-max`` is absent.
1989SHARDS_MAX = 4
1990
1991
1992def shards_max(ci: dict[str, Any]) -> int:
1993 """The most shards a runner may take: ``[ci] shards-max``, `SHARDS_MAX` when absent.
1994
1995 A value that is not a whole number, or is below 1, fails naming it.
1996 """
1997 declared: Any = ci.get("shards-max")
1998 if declared is None:
1999 return SHARDS_MAX
2000 if isinstance(declared, bool) or not isinstance(declared, int):
2001 fail(
2002 f"[ci] shards-max is {declared!r}, which is not a whole number; it is"
2003 " the most shards a runner may take"
2004 )
2005 if declared < 1:
2006 fail(f"[ci] shards-max is {declared}; the cap is at least 1")
2007 return declared
2008
2009
2010def shard_counts(
2011 ci: dict[str, Any], *, key: str, runners: Sequence[str], listed: str
2012) -> dict[str, int]:
2013 """The shards per runner ``[ci] <key>`` gives, one for a runner it does not name.
2014
2015 *runners* are the labels the legs fan out to and *listed* names the
2016 key they came from, for the refusal. The task fails, naming the key
2017 and the runner, when the table names a runner *runners* does not
2018 hold, gives a count below 1 or above `shards_max`, or gives one
2019 that is not a whole number.
2020 """
2021 cap = shards_max(ci)
2022 counts = dict.fromkeys(runners, 1)
2023 declared: Any = ci.get(key)
2024 if declared is None:
2025 return counts
2026 if not isinstance(declared, dict):
2027 fail(f"[ci] {key} is {declared!r}; it is a table of runner label to count")
2028 table: dict[str, Any] = declared
2029 strangers = [runner for runner in table if runner not in runners]
2030 if strangers:
2031 fail(
2032 f"[ci] {key} names {', '.join(strangers)}, which {listed} does not list"
2033 f" ({', '.join(runners)}); a count belongs to a runner the legs run on"
2034 )
2035 for runner, count in table.items():
2036 if isinstance(count, bool) or not isinstance(count, int):
2037 fail(
2038 f"[ci] {key} gives {runner} {count!r}, which is not a whole number;"
2039 f" a count is from 1 to {cap}"
2040 )
2041 if count < 1:
2042 fail(f"[ci] {key} gives {runner} {count}; a count is at least 1")
2043 if count > cap:
2044 fail(
2045 f"[ci] {key} gives {runner} {count}, above the cap of {cap}"
2046 " ([ci] shards-max); lower the count or raise the cap"
2047 )
2048 counts[runner] = count
2049 return counts
2050
2051
2052def _shard_legs(
2053 runners: Sequence[str], pythons: Sequence[str], counts: Mapping[str, int]
2054) -> list[str]:
2055 """One leg per runner and Python, split into shards where the count is above 1."""
2056 legs: list[str] = []
2057 for runner in runners:
2058 count = counts.get(runner, 1)
2059 for python in pythons:
2060 leg = f"check-{runner}-{python}"
2061 if count == 1:
2062 legs.append(leg)
2063 else:
2064 legs.extend(
2065 f"{leg}-{Shard(index, count)}" for index in range(1, count + 1)
2066 )
2067 return legs
2068
2069
2070def check_shards(root: Path) -> list[str]:
2071 """Name the shard legs the gate produces, split as ``[ci] shards`` says.
2072
2073 One leg per runner and Python [livery.workshop.check_legs][] names,
2074 spelled as that leg, ``check-<os>-<python>``, for a count of one,
2075 the count of every runner the table does not name; and
2076 ``check-<os>-<python>-<i>of<n>`` for each of the ``n`` shards
2077 otherwise, in order. ``[ci] shards-max`` caps a count, 4 when
2078 absent. The task fails, naming the key and the runner, when the
2079 table names a runner ``[ci] runners`` does not list, gives a count
2080 below 1 or above the cap, or gives one that is not a whole number.
2081 """
2082 from livery.workshop._pythons import gate_pythons
2083
2084 contract = load_contract(root / "workshop.toml")
2085 ci = contract.get("ci") or {}
2086 runners = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
2087 counts = shard_counts(ci, key="shards", runners=runners, listed="[ci] runners")
2088 return _shard_legs(runners, gate_pythons(root), counts)
2089
2090
2091def pull_request_shards(root: Path) -> list[str]:
2092 """Name the shard legs a pull request's run produces, split as the contract says.
2093
2094 One leg per runner and Python [livery.workshop.pull_request_legs][]
2095 names, split as [livery.workshop.check_shards][] splits the gate's:
2096 by ``[ci] pull-request-shards``, judged against the pull request's
2097 runners, or by ``[ci] shards`` when that key is absent. The task
2098 fails as `check_shards` fails, and as `pull_request_legs` fails.
2099 """
2100 from livery.workshop._pythons import gate_pythons
2101
2102 contract = load_contract(root / "workshop.toml")
2103 ci = contract.get("ci") or {}
2104 runners = pull_request_runners(ci)
2105 if ci.get("pull-request-shards") is None:
2106 every = [str(runner) for runner in ci.get("runners") or ["ubuntu-latest"]]
2107 counts = shard_counts(ci, key="shards", runners=every, listed="[ci] runners")
2108 else:
2109 counts = shard_counts(
2110 ci,
2111 key="pull-request-shards",
2112 runners=runners,
2113 listed=pull_request_listed(ci),
2114 )
2115 return _shard_legs(runners, gate_pythons(root), counts)
2116
2117
2118def sharded_legs(root: Path) -> list[str]:
2119 """The platform legs the contract splits into shards, on any event.
2120
2121 Each platform leg once, in matrix order: one ``[ci] shards`` or
2122 ``[ci] pull-request-shards`` gives above one
2123 ([livery.workshop.check_shards][],
2124 [livery.workshop.pull_request_shards][]). Empty without a root
2125 contract. The task fails as those fail, naming the key and the
2126 runner.
2127 """
2128 if not (root / "workshop.toml").is_file():
2129 return []
2130 found: dict[str, None] = {}
2131 for leg in (*check_shards(root), *pull_request_shards(root)):
2132 if shard_of(leg) != ONE:
2133 found.setdefault(platform_leg(leg), None)
2134 return list(found)
2135
2136
2137def effective_point(point: str) -> str:
2138 """The point a shell's ``gate`` means on a push: the merge point.
2139
2140 The shared jobs spell ``--point=gate``; inside CI, a push event
2141 is the merge point, so the promotion happens here and never in
2142 the YAML. Outside CI, and on every other event, the point stands.
2143 """
2144 run = run_context()
2145 if point == "gate" and run is not None and run.event == "push":
2146 return "merge"
2147 return point
2148
2149
2150def _spawn(argv: list[str], env: dict[str, str]) -> int:
2151 """Run one entry as a child of the runner's own command; its exit code.
2152
2153 Streamed, never captured: the job's log is the run's evidence,
2154 and what each verb said belongs there in order, green or red.
2155 *env* is the child's whole environment.
2156 """
2157 from livery.footman import run
2158
2159 return run(argv, nofail=True, capture=False, env=env).code
2160
2161
2162def run_point(
2163 root: Path,
2164 point: str,
2165 job: str,
2166 *,
2167 os_label: str = "",
2168 python: str = "",
2169 shard: str = "",
2170 spawn: Callable[[list[str], dict[str, str]], int] = _spawn,
2171) -> None:
2172 """Run every entry of *job* at *point*, in order; a red entry fails the job.
2173
2174 A red builtin entry stops the job at once, since the entries after
2175 it read its verdict, and so does a red judge an extension adds to
2176 the verdict job; a red entry of the contract's schedule stands
2177 on its own, so the scheduled entries after it still run, and the
2178 job fails at the end naming each red one. A dispatch that names
2179 tasks in the nightly's ``only`` input runs those alone, builtin or
2180 scheduled, and says what it skipped.
2181
2182 *os_label* and *python* are the matrix facts the shell passes for
2183 a matrix job; they format the entries' arguments and name the
2184 leg. *shard* is the leg's shard, ``2of4``, on a check leg the
2185 contract splits; empty runs as one shard of one. A count above
2186 one ends the label and the display name
2187 (``check-windows-latest-3.14-2of4``, ``check (windows-latest,
2188 3.14, 2of4)``, and on GitLab ``check: [2of4]``, as it lists a job
2189 run as ``parallel: matrix``), and an entry declared ``sharded``
2190 takes ``--shard=2of4``; one shard of one leaves the label, the
2191 display name and every call as the unsplit leg's. A spelling outside
2192 ``<i>of<n>`` fails naming it, before any entry runs. An entry
2193 with ``once`` runs on the first leg's first shard alone, and the
2194 skip line names the shard when the leg is the first. An entry
2195 with a cadence runs only on its day, judged by
2196 `today`, and says when it runs next otherwise. Every entry runs
2197 under ``--profile``, writing its own trace beside the others, and
2198 the job's box collects them into one timeline, which the runner
2199 pushes where ``[ci] profile`` asks; ``[ci] timing = false`` does
2200 none of that. Every child's
2201 environment names the leg in
2202 `livery.workshop._ci_context.LEG_VARIABLE`, the key of the leg's rows
2203 and stamps, and the resolved point in
2204 [livery.workshop.POINT_VARIABLE][], which selects the tests a point
2205 runs. A job that declares ``inputs`` runs no entry on
2206 a pull request that changed nothing it reads (`unread_by_the_job`).
2207 *spawn* runs one entry's command in that environment and returns
2208 its exit code; the default is the runner's own child.
2209 """
2210 from livery.git import remote_snapshot
2211 from livery.workshop._ci_context import SNAPSHOT_VARIABLE
2212
2213 try:
2214 split = Shard.parse(shard) if shard else ONE
2215 except ValueError as error:
2216 fail(str(error))
2217 resolved = effective_point(point)
2218 entries = entries_for(root, resolved, job)
2219 if resolved != point:
2220 print(f" point: {point} on a push is the {resolved} point")
2221 skip = unread_by_the_job(root, resolved, job)
2222 if skip:2222 ↛ 2223line 2222 didn't jump to line 2223 because the condition on line 2222 was never true
2223 print(skip)
2224 return
2225 # The display name is the job's name as the forge lists it, since
2226 # the collect step joins the leg's row with the forge's job by it:
2227 # GitHub and Gitea show a matrix job as ``check (ubuntu-latest,
2228 # 3.14)``; GitLab names the job by its key alone, the matrix
2229 # riding its variables and never its name, except that a job run
2230 # as ``parallel: matrix`` is listed as ``check: [2of4]``.
2231 run = run_context()
2232 # Only the dimensions the matrix actually has: the nightly point runs a
2233 # matrix of pythons and no runners, and the forge lists that job as
2234 # ``nightly (3.14)``. Spelling an absent dimension as an empty one gave
2235 # ``nightly (, 3.14)``, which matched no job the forge had.
2236 parts = [part for part in (os_label, python) if part]
2237 # The shard ends the label and the display name only where the leg
2238 # is one of several: one shard of one is the unsplit leg, spelled
2239 # as the platform leg every record is keyed by.
2240 if split.count > 1:
2241 parts.append(str(split))
2242 gitlab = run is not None and run.forge == "gitlab"
2243 if gitlab:
2244 display = f"{job}: [{split}]" if split.count > 1 else job
2245 else:
2246 display = f"{job} ({', '.join(parts)})" if parts else job
2247 label = "-".join([job, *parts])
2248 facts = {
2249 "display": display,
2250 "label": label,
2251 "os": os_label,
2252 "python": python,
2253 "shard": str(split),
2254 }
2255 # A dispatched point's inputs, as the run received them, by name:
2256 # the release's ``{ref}`` names the squash the wave publishes.
2257 from livery.workshop._ci_context import dispatch_inputs
2258
2259 facts.update(
2260 dispatch_inputs(
2261 tuple(item.name for item in point_by_name(root)[resolved].inputs)
2262 )
2263 )
2264 asked = asked_tasks(root, resolved, facts.get(ONLY, ""))
2265 prog = footman.prog()
2266 # One listing of the state store's namespace for the whole job:
2267 # every entry reads through it and records what it writes for the
2268 # entries after it, so the job lists once, not once per entry.
2269 with contextlib.ExitStack() as scope:
2270 # Every entry writes its own trace and drops a copy in the job's
2271 # box, so the job's own timeline is the union of the work it did,
2272 # and a check leg's timing row is read from the gate's. `[ci]
2273 # timing = false` opens no box, passes no flag, and pushes
2274 # nothing: off costs nothing rather than less. `[ci] profile`
2275 # decides whether the box's union leaves the runner at the end;
2276 # off, nothing is assembled from the box at all.
2277 drop = scope.enter_context(profile_box()) if _tracing(root) else None
2278 pushing = drop is not None and _pushing(root)
2279 published = scope.enter_context(
2280 remote_snapshot(state_store(root), publish=True)
2281 )
2282 env = {**os.environ, LEG_VARIABLE: label, POINT_VARIABLE: resolved}
2283 if (
2284 run is not None
2285 and run.forge == "github"
2286 and env.get("FORGE_TOKEN")
2287 and not env.get("GH_TOKEN")
2288 and not env.get("GITHUB_TOKEN")
2289 ):
2290 # Tools that read GitHub's API (such as toolroom.refresh)
2291 # authenticate with GH_TOKEN / GITHUB_TOKEN; the rendered step
2292 # hands the run's token as FORGE_TOKEN alone. Only on GitHub:
2293 # a Gitea or GitLab token must never reach GitHub's API host.
2294 env["GH_TOKEN"] = env["FORGE_TOKEN"]
2295 if published:
2296 env[SNAPSHOT_VARIABLE] = published
2297 if drop is not None:
2298 # Named here and nowhere else: a workspace that keeps no traces
2299 # never imports the plugin that writes them.
2300 from livery.footman.profile import DROP
2301
2302 env[DROP] = str(drop)
2303 red: list[str] = []
2304 failed = False
2305 needs_head = (run is None or run.event != "workflow_dispatch") and any(
2306 entry.if_changed for entry in entries
2307 )
2308 head_sha = _safe_head_sha(root) if needs_head else ""
2309 ref = run.ref if run is not None else ""
2310 last_verdict = (
2311 last_verdict_sha(root, point=resolved, ref=ref)
2312 if needs_head
2313 else ("", "", "")
2314 )
2315 try:
2316 for entry in entries:
2317 if asked and entry.task not in asked:
2318 print(
2319 f" {resolved}/{job}: {entry.task} ({entry.source}) is not"
2320 " among the tasks this dispatch asked for; skipped"
2321 )
2322 continue
2323 if entry.once:
2324 first_os, first_python = first_leg(root, resolved, job)
2325 leg_is_first = (not os_label or os_label == first_os) and (
2326 not python or python == first_python
2327 )
2328 if not leg_is_first:
2329 first = ", ".join(
2330 part for part in (first_os, first_python) if part
2331 )
2332 print(
2333 f" {resolved}/{job}: {entry.task} ({entry.source}) runs"
2334 f" once, on the first leg ({first}); skipped"
2335 )
2336 continue
2337 if not split.first:
2338 print(
2339 f" {resolved}/{job}: {entry.task} ({entry.source}) runs"
2340 f" once, on the first shard ({Shard(1, split.count)});"
2341 " skipped"
2342 )
2343 continue
2344 is_due, why = entry_due(
2345 root,
2346 entry,
2347 point=resolved,
2348 run=run,
2349 head_sha=head_sha,
2350 last_verdict=last_verdict,
2351 )
2352 if not is_due:
2353 print(f" {resolved}/{job}: {entry.task} ({entry.source}) {why}")
2354 continue
2355 argv = [prog]
2356 if drop is not None:
2357 argv.append(f"--profile={trace_file(entry.task)}")
2358 argv.append(entry.task)
2359 argv.extend(arg.format(**facts) for arg in entry.args)
2360 if entry.sharded and split.count > 1:
2361 argv.append(f"--shard={split}")
2362 print(f" {resolved}/{job}: {entry.task} ({entry.source})")
2363 # The record lists the store for itself: a sibling job's
2364 # half may have landed after this job's listing was
2365 # taken, and the job's listing never learns a new ref.
2366 handed = env
2367 if entry.task == RECORD_TASK:
2368 handed = {k: v for k, v in env.items() if k != SNAPSHOT_VARIABLE}
2369 code = spawn(argv, handed)
2370 if code != 0:
2371 reason = f"{resolved}/{job}: {entry.task} exited {code}"
2372 if entry.source == "builtin" or entry.judges:
2373 failed = True
2374 fail(reason)
2375 print(f" {reason}; the scheduled entries after it still run")
2376 red.append(reason)
2377 if red:
2378 failed = True
2379 finally:
2380 # A red gate job still collects a metrics row with its red
2381 # verdict, so red runs appear beside green ones in the store.
2382 if failed and any(entry.task == COLLECT for entry in entries):
2383 collect_argv = [
2384 prog,
2385 COLLECT,
2386 "--verdict=red",
2387 f"--trigger={resolved}",
2388 ]
2389 try:
2390 spawn(collect_argv, env)
2391 except Exception as error:
2392 print(f" {resolved}/{job}: red metrics collect failed ({error})")
2393 # A red job's timeline is the one most worth having, so the
2394 # push happens whatever the entries did. What the run ran on
2395 # is a row the merge point reads, so every job records it,
2396 # traced or not.
2397 if drop is not None and pushing:
2398 _push_job(root, drop, job=display, leg=label)
2399 _push_about(root)
2400 if red:
2401 fail("; ".join(red))
2402 if not entries:2402 ↛ 2403line 2402 didn't jump to line 2403 because the condition on line 2402 was never true
2403 print(f" {resolved}/{job}: nothing scheduled")