Coverage for packages/workshop/src/livery/workshop/_quality.py: 83%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_submit.py, packages/workshop/tests/test_workshop_speed.py, packages/workshop/tests/test_workshop_skip_marks.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_proved_shadow.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_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_phase_verbs.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_env.py, packages/workshop/tests/test_workshop_conformance.py, packages/workshop/tests/test_workshop_categories.py, packages/workshop/tests/test_workshop_affected_legs.py, packages/extensions/ruff/tests/test_ruff.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_extensions_docs.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/coverage/tests/test_extensions_coverage.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/coverage/tests/test_affected_legs.py, packages/extensions/conan/tests/test_extensions_conan.py, packages/extensions/cmake/tests/test_cmake.py, packages/extensions/agents/tests/test_agents.py ran.

1"""The quality verbs: the gate and its parts, over the packages the contracts declare.
2
3Each verb discovers the packages by their ``workshop.toml`` and runs
4its phase's registered steps over them, each step over the packages
5whose extensions it judges. ``check`` is the whole local gate; CI runs
6the same command.
7"""
8
9from __future__ import annotations
10
11from collections.abc import Callable, Mapping, Sequence
12from dataclasses import replace
13from pathlib import Path
14from typing import TYPE_CHECKING, Annotated, Any
15
16from livery import git
17
18if TYPE_CHECKING:
19 from livery.workshop._influence import Changes
20
21import livery.footman as footman
22from livery.footman import Forward, doc, fail, group, task
23from livery.workshop import _steps
24from livery.workshop._ci_context import RunContext, state_store
25from livery.workshop._extensions import workspace_root
26from livery.workshop._packages import Package, discover_packages
27from livery.workshop._phases import PhaseContext, walk_steps
28from livery.workshop._shard import (
29 ONE,
30 Shard,
31 checkout_time,
32 files_digest,
33 leave_shard,
34 shard_of,
35)
36
37# Re-exported by name: the drift step's body looks it up on this
38# module at run time, which is where the gate's characterisation tests
39# patch it.
40from livery.workshop._templates import drift_check as drift_check
41
42
43def _packages() -> tuple[Package, ...]:
44 """The workspace's packages, discovered before anything runs."""
45 root = workspace_root()
46 if root is None:46 ↛ 47line 46 didn't jump to line 47 because the condition on line 46 was never true
47 raise ValueError("no workspace: no workshop.toml above the working directory")
48 return discover_packages(root)
49
50
51def _context(
52 *,
53 subset: tuple[Package, ...] | None = None,
54 fix: bool = False,
55 files: tuple[str, ...] = (),
56 safe: bool = False,
57 point: str = "",
58 shard: Shard = ONE,
59 tests: Mapping[str, tuple[str, ...]] | None = None,
60 examples: tuple[str, ...] = (),
61 changes: Changes | None = None,
62 arguments: tuple[str, ...] = (),
63) -> PhaseContext:
64 """This workspace's gate context: the root, every package, and the run's scope."""
65 root = workspace_root()
66 if root is None:66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true
67 raise ValueError("no workspace: no workshop.toml above the working directory")
68 return PhaseContext(
69 root=root,
70 packages=_packages(),
71 subset=subset,
72 tests=tests or {},
73 examples=examples,
74 fix=fix,
75 files=files,
76 safe=safe,
77 point=point,
78 shard=shard,
79 changes=changes,
80 arguments=arguments,
81 )
82
83
84#: What the gate gives its phases: the build phase's tree side, in the
85#: instrumented configuration.
86GATE_INPUTS: Mapping[str, Mapping[str, object]] = {
87 "build": {"isolated": False, "configuration": "instrumented"}
88}
89
90#: What a phase's own verb gives its phases: the build phase's tree side,
91#: in the debug configuration, so a bare ``fm build`` builds what
92#: ``fm run`` starts, and the gate alone instruments.
93VERB_INPUTS: Mapping[str, Mapping[str, object]] = {
94 "build": {"isolated": False, "configuration": "debug"}
95}
96
97
98def walk(
99 ctx: PhaseContext,
100 *,
101 between: Callable[[], None] | None = None,
102 judge: bool = True,
103 only: frozenset[str] | None = None,
104 inputs: Mapping[str, Mapping[str, object]] = GATE_INPUTS,
105 record_proved: bool = False,
106 skip_units: frozenset[str] = frozenset(),
107) -> None:
108 """Walk the registry: the one place the gate's order lives.
109
110 Every gate comes here, the whole one, CI's narrowed legs and a
111 machine's narrowed step alike, and runs the registry's steps
112 through the one walk ([livery.workshop._phases.walk_steps][]). Each
113 step an extension registered is named first. Under ``--fix`` every
114 fixer that applies runs, one at a time in the rewriters' order,
115 before any judge reads the tree, and a step that rewrote is not
116 judged again in the run; then *between* runs, where a machine's
117 run measures the tree the judges read; then every judge runs in
118 one parallel block, the steps a judge runs after among them, and
119 one refusal is the verdict. A step whose claims reach no file in
120 scope is said and not started. On a shard other than the first, a
121 step that does not read the shard is left to the first shard and
122 said ([livery.workshop._steps.on_this_shard][]). Without *judge*
123 the walk stops after the fixers, the post-edit hook's run. *only*
124 keeps the named steps alone, a generated verb's run. *inputs* are
125 the keys the walk gives each phase, the gate's own
126 ([livery.workshop._quality.GATE_INPUTS][]) unless another engine
127 names its. With *record_proved* inside CI, every step unit outcome
128 is written to the ``proved`` store family beside today's records.
129 """
130 from livery.workshop._phases import StepOutcome
131
132 for line in _steps.narrowings():
133 print(line)
134 ctx = replace(ctx, catalogue=_steps.catalogue(ctx))
135
136 def kept(names: tuple[str, ...]) -> tuple[str, ...]:
137 if only is not None:
138 names = tuple(n for n in names if n in only)
139 return _steps.on_this_shard(_steps.with_files(names, ctx), ctx)
140
141 for name in kept(_steps.rewriters(ctx)):
142 walk_steps(ctx, (_steps.step_for(name),), inputs=inputs, fixing=True)
143 if ctx.fix and between is not None:
144 between()
145 if not judge:
146 return
147 if not record_proved:
148 walk_steps(
149 ctx,
150 _steps.with_earlier(kept(_steps.judges(ctx))),
151 inputs=inputs,
152 skip_units=skip_units,
153 )
154 return
155 outcomes: list[StepOutcome] = []
156 candidates = _steps.judges(ctx)
157 if only is not None:157 ↛ 158line 157 didn't jump to line 158 because the condition on line 157 was never true
158 candidates = tuple(n for n in candidates if n in only)
159 after_files = _steps.with_files(candidates, ctx)
160 dropped_by_files = tuple(n for n in candidates if n not in after_files)
161 # Record steps skipped for having no matching files only on the shard
162 # that owns them (shard 1 for unsharded steps), never as green.
163 for name in _steps.on_this_shard(dropped_by_files, ctx):
164 record = _steps.step_for(name)
165 if record.scope == _steps.PACKAGE or record.extensions:165 ↛ 172line 165 didn't jump to line 172 because the condition on line 165 was always true
166 matched = [p for p in ctx.judged if _steps.judges_unit(record, p)]
167 if matched:167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true
168 for package in matched:
169 if f"{record.name}@{package.path}" not in skip_units:
170 outcomes.append(StepOutcome(record, package.path, "skipped"))
171 continue
172 if f"{record.name}@." not in skip_units:172 ↛ 163line 172 didn't jump to line 163 because the condition on line 172 was always true
173 outcomes.append(StepOutcome(record, ".", "skipped"))
174 running = _steps.on_this_shard(after_files, ctx)
175 try:
176 walk_steps(
177 ctx,
178 _steps.with_earlier(running),
179 inputs=inputs,
180 outcomes=outcomes,
181 skip_units=skip_units,
182 )
183 finally:
184 _flush_proved(ctx, outcomes)
185
186
187def _flush_proved(ctx: PhaseContext, outcomes: Sequence[Any]) -> None:
188 """Write *outcomes* to CI's proved store family or local ``proved-local``."""
189 from livery.workshop import _proved
190 from livery.workshop._ci_context import run_context
191
192 if not outcomes:192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true
193 return
194 run = run_context()
195 if run is None and ctx.shard != ONE:195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true
196 return
197 try:
198 fp_cache = _proved.FingerprintContext.for_root(ctx.root, ctx.packages)
199 plat = _proved.current_platform(run.leg if run is not None else "")
200 branch = (
201 (run.head_ref or run.ref.removeprefix("refs/heads/"))
202 if run is not None
203 else ""
204 )
205 trigger = _current_point()
206 immediate: list[_proved.Observation] = []
207 deferred: list[_proved.Observation] = []
208 for outcome in outcomes:
209 obs = _proved.Observation(
210 step=outcome.record.name,
211 target=outcome.target,
212 verdict=outcome.verdict,
213 fingerprint=_proved.step_fingerprint(
214 outcome.record, ctx, outcome.target, cache=fp_cache
215 ),
216 platform=plat,
217 run=run.run_id if run is not None else "",
218 sha=run.head_sha if run is not None else "",
219 branch=branch,
220 attempt=run.attempt if run is not None else "",
221 trigger=trigger,
222 )
223 # On a sharded CI leg, shardable steps (e.g. test steps) run only a
224 # slice of each unit on each shard. Writing a green whole-unit row
225 # mid-run would let a later-starting shard skip its slice and diverge
226 # in scope; spool them until ci.fold proves every shard succeeded.
227 if (227 ↛ 233line 227 didn't jump to line 233 because the condition on line 227 was never true
228 run is not None
229 and ctx.shard.count > 1
230 and "shard" in outcome.record.flags
231 and outcome.verdict != _proved.RED
232 ):
233 deferred.append(obs)
234 else:
235 immediate.append(obs)
236 if run is None:
237 why = _proved.write_observations(ctx.root, immediate, local=True)
238 if not why:238 ↛ 242line 238 didn't jump to line 242 because the condition on line 238 was always true
239 print(
240 f" proved: wrote {len(immediate)} unit(s) to {_proved.LOCAL.name}"
241 )
242 elif "not a git repository" not in why:
243 print(f" proved: {why}")
244 return
245 base = _proved.leg_base(run)
246 leg = _proved.leg_key(run)
247 if trigger in ("gate", "merge"):247 ↛ 258line 247 didn't jump to line 258 because the condition on line 247 was always true
248 spooled_all = [*immediate, *deferred]
249 if spooled_all:249 ↛ 257line 249 didn't jump to line 257 because the condition on line 249 was always true
250 _proved.spool_proved_observations(
251 ctx.root, spooled_all, base=base, leg=leg
252 )
253 print(
254 f" proved: spooled {len(spooled_all)} unit(s) for gate on"
255 f" {_proved.FAMILY.name}/{base}/{leg}"
256 )
257 return
258 if immediate:
259 why = _proved.write_observations(ctx.root, immediate, base=base, leg=leg)
260 if why:
261 print(f" proved: {why}")
262 else:
263 print(
264 f" proved: wrote {len(immediate)} unit(s) to"
265 f" {_proved.FAMILY.name}/{base}/{leg}"
266 )
267 if deferred:
268 _proved.spool_proved_observations(ctx.root, deferred, base=base, leg=leg)
269 print(
270 f" proved: spooled {len(deferred)} sharded unit(s) for fold on"
271 f" {_proved.FAMILY.name}/{base}/{leg}"
272 )
273 except Exception as error:
274 print(f" proved: recording failed ({error})")
275
276
277def _candidate_units(ctx: PhaseContext) -> list[tuple[_steps.StepRecord, str]]:
278 """Every applicable judge unit owned by this shard for *ctx*'s judged packages."""
279 from dataclasses import replace
280
281 from livery.workshop._packages import workspace_suite
282 from livery.workshop._phases import set_deletions, step_address
283
284 if ctx.catalogue is None:
285 cat = _steps.catalogue(ctx)
286 if cat is not None:286 ↛ 288line 286 didn't jump to line 288 because the condition on line 286 was always true
287 ctx = replace(ctx, catalogue=cat)
288 suite = workspace_suite(ctx.root) if ctx.subset is None else None
289 removed: dict[str, dict[str, tuple[str, str]]] = {}
290
291 def _applicable(record: _steps.StepRecord, package: Package) -> bool:
292 if package.path not in removed:
293 removed[package.path] = set_deletions(package)
294 if step_address(record) in removed[package.path]:294 ↛ 295line 294 didn't jump to line 295 because the condition on line 294 was never true
295 return False
296 if not _steps.option_value(record, package, "enabled"):296 ↛ 297line 296 didn't jump to line 297 because the condition on line 296 was never true
297 return False
298 return _steps.reads_files(record, ctx, (package.path,))
299
300 units: list[tuple[_steps.StepRecord, str]] = []
301 for name in _steps.on_this_shard(_steps.judges(ctx), ctx):
302 record = _steps.step_for(name)
303 if record.scope == _steps.PACKAGE or record.extensions:
304 matched = [
305 p
306 for p in ctx.judged
307 if _steps.judges_unit(record, p) and _applicable(record, p)
308 ]
309 for package in matched:
310 units.append((record, package.path))
311 if (
312 record.scope != _steps.PACKAGE
313 and suite is not None
314 and _steps.judges_unit(record, suite)
315 and _applicable(record, suite)
316 ):
317 units.append((record, suite.path))
318 elif _steps.reads_files(record, ctx, None):318 ↛ 301line 318 didn't jump to line 301 because the condition on line 318 was always true
319 units.append((record, "."))
320 return units
321
322
323def _proved_decision(
324 root: Path,
325 *,
326 run: RunContext | None,
327 point: str,
328 shard: Shard,
329 pre_fix: Callable[[], None] | None = None,
330) -> tuple[PhaseContext, Any, Any] | None:
331 """Compute the proved-record gate decision, or ``None`` when no rows exist."""
332 from livery.workshop import _proved
333
334 try:
335 ctx_all = _context(point=point, shard=shard)
336 candidates = _candidate_units(ctx_all)
337 if not candidates:337 ↛ 338line 337 didn't jump to line 338 because the condition on line 337 was never true
338 return None
339 plat = _proved.current_platform(run.leg if run is not None else "")
340 primary, branch_rows, why = _proved.lookup_proved_rows_for_decision(
341 root, run=run, platform=plat
342 )
343 if not primary and not branch_rows:
344 if why and run is not None:344 ↛ 345line 344 didn't jump to line 345 because the condition on line 344 was never true
345 print(f" proved: {why}; falling back")
346 return None
347 if pre_fix is not None:347 ↛ 348line 347 didn't jump to line 348 because the condition on line 347 was never true
348 pre_fix()
349 ctx_all = _context(point=point, shard=shard)
350 candidates = _candidate_units(ctx_all)
351 # On a sharded leg, every shard must agree on which units are proved so
352 # every shard partitions the same test set and writes one scope for
353 # ci.fold. Hosted runner pools routinely serve adjacent ImageVersion
354 # builds side-by-side during rollouts, so sharded decisions match OS
355 # family and Python minor (matching ci.legs) instead of per-VM image.
356 decision = _proved.decide_units(
357 ctx_all,
358 candidate_units=candidates,
359 primary_rows=primary,
360 branch_rows=branch_rows,
361 platform=plat,
362 exact_image=run is not None and shard == ONE,
363 )
364 return ctx_all, decision, plat
365 except Exception as error:
366 print(f" proved: decision failed ({error}); falling back")
367 return None
368
369
370def _sibling_scope(root: Path, run: RunContext) -> Any:
371 """Read a passing sibling shard's scope on attempt > 1 when present locally."""
372 from livery import git
373 from livery.workshop import _metrics, _scope
374 from livery.workshop._shard import platform_leg
375
376 if not run.run_id or not run.leg or run.shard.count <= 1:376 ↛ 377line 376 didn't jump to line 377 because the condition on line 376 was never true
377 return None
378 if not run.attempt.isdigit() or int(run.attempt) <= 1:
379 return None
380 own_slug = git.slug(run.leg)
381 own_platform = git.slug(platform_leg(run.leg))
382 for slug, leg_dir in _metrics.run_leg_dirs(root):
383 if slug == own_slug or git.slug(platform_leg(slug)) != own_platform:
384 continue
385 row, why = _metrics.read_leg_json(leg_dir, _metrics.ROW_FILE)
386 if why or row is None:386 ↛ 387line 386 didn't jump to line 387 because the condition on line 386 was never true
387 continue
388 raw_scope = row.get("scope")
389 if not isinstance(raw_scope, Mapping):389 ↛ 390line 389 didn't jump to line 390 because the condition on line 389 was never true
390 continue
391 kind = str(raw_scope.get("scope", "") or "")
392 if not kind:392 ↛ 393line 392 didn't jump to line 393 because the condition on line 392 was never true
393 continue
394 raw_pkgs = raw_scope.get("packages") or ()
395 packages = tuple(str(p) for p in raw_pkgs) if isinstance(raw_pkgs, list) else ()
396 return _scope.LegScope(
397 kind,
398 packages,
399 leg=str(raw_scope.get("leg", "") or slug),
400 base_tree=str(raw_scope.get("base_tree", "") or ""),
401 branch=str(raw_scope.get("branch", "") or ""),
402 )
403 return None
404
405
406def _align_with_sibling(
407 ctx_all: PhaseContext,
408 proved_units: frozenset[str],
409 running_units: Sequence[tuple[_steps.StepRecord, str, str]],
410 sibling: Any,
411 *,
412 proving_branch: str,
413) -> tuple[frozenset[str], bool, str, tuple[str, ...], str]:
414 """Align test-phase units with *sibling*'s scope so shards partition one set."""
415 from livery.workshop import _proved, _scope
416
417 candidates = _candidate_units(ctx_all)
418 test_units = [
419 (rec, tgt) for rec, tgt in candidates if rec.phase == "test" and tgt != "."
420 ]
421 non_test_running = [
422 (rec, tgt) for rec, tgt, _ in running_units if rec.phase != "test"
423 ]
424 skip_units = set(proved_units)
425 branch = sibling.branch or proving_branch
426
427 if sibling.scope == _scope.FULL:
428 for rec, tgt in test_units:
429 skip_units.discard(_proved.unit_id(rec.name, tgt))
430 return frozenset(skip_units), False, _scope.FULL, (), branch
431
432 if sibling.scope == _scope.AFFECTED:
433 wanted = set(sibling.packages)
434 for rec, tgt in test_units:
435 uid = _proved.unit_id(rec.name, tgt)
436 if tgt in wanted:
437 skip_units.discard(uid)
438 else:
439 skip_units.add(uid)
440 return frozenset(skip_units), False, _scope.AFFECTED, sibling.packages, branch
441
442 for rec, tgt in test_units:
443 skip_units.add(_proved.unit_id(rec.name, tgt))
444 skip_gate = sibling.scope == _scope.VERIFIED and not non_test_running
445 return frozenset(skip_units), skip_gate, sibling.scope, (), branch
446
447
448def _refuse_both(fix: bool, safe_fix: bool) -> None:
449 if fix and safe_fix:
450 fail(
451 "--fix and --safe-fix are two answers to one question: --fix"
452 " applies every safe fix, --safe-fix withholds the"
453 " code-removing ones. Pass one."
454 )
455
456
457#: The contract key that lets CI's check legs run the scoped gate.
458AFFECTED_LEGS_KEY = "affected-legs"
459
460
461def affected_legs(root: Path) -> bool:
462 """The contract's ``[ci] affected-legs``; false when undeclared.
463
464 The contract's judge holds the value to a boolean: the legs either
465 narrow or they do not, and a stray string would read as true.
466 """
467 from livery.workshop._contract import load_contract
468
469 ci = load_contract(root / "workshop.toml").get("ci") or {}
470 return bool(ci.get(AFFECTED_LEGS_KEY, False))
471
472
473def ci_affected_base(root: Path, run: RunContext | None) -> str:
474 """The base branch a pull request's check leg narrows against, or empty.
475
476 Empty outside CI, when the contract does not declare
477 ``[ci] affected-legs``, on any event but a pull request, and when
478 the payload names no base.
479 """
480 if run is None or not affected_legs(root):
481 return ""
482 if run.event == "push":
483 return ""
484 if run.event != "pull_request":
485 print(
486 f" affected-legs: a {run.event or 'non pull request'} run pays"
487 " the full gate"
488 )
489 return ""
490 if not run.base_ref:
491 print(" affected-legs: the event payload names no base branch; full gate")
492 return ""
493 return run.base_ref
494
495
496def ci_changes(root: Path) -> Changes | None:
497 """What this CI run changed against the base it measures from; None for everything.
498
499 A pull request's run in a workspace that declares ``[ci]
500 affected-legs`` measures from its base branch: the paths changed
501 since the merge base with ``origin/<base>``, committed or not, with
502 that merge base, so a ``widen`` reference can read a file as it
503 was. None at a desk, on any other event, without
504 ``affected-legs``, and when git cannot answer; the run then judges
505 everything, and the line printed says why.
506 """
507 from livery.workshop._ci_context import run_context
508 from livery.workshop._influence import Changes
509
510 run = run_context()
511 base = ci_affected_base(root, run) if run is not None else ""
512 if not base:
513 return None
514 try:
515 git.fetch(root)
516 paths = tuple(git.changed_paths(root, base))
517 before = git.merge_base(root, base)
518 except git.GitError as error:
519 print(
520 f" affected-legs: no diff against origin/{base}; everything is"
521 f" judged ({error})"
522 )
523 return None
524 return Changes(root, paths, before)
525
526
527@task
528def check(
529 *paths: str,
530 full: Annotated[bool, doc("run everything, whatever the record proves")] = False,
531 fix: Forward[bool] = False,
532 safe_fix: Annotated[
533 bool, doc("fix, removing no code: safe for an edit in flight")
534 ] = False,
535 base: Annotated[str, doc("the branch the chain's root is taken from")] = "main",
536 point: Annotated[str, doc("run the tests of this CI point, nightly say")] = "",
537 shard: Annotated[
538 str,
539 doc("run this shard's share of a sharded check leg: <i>of<n>, such as 2of4"),
540 ] = "",
541) -> None:
542 """Run the gate: every registered step, the rewriters first under --fix.
543
544 With *paths*, exactly those files are checked, or the files under
545 those directories: every step whose claims reach one of them runs
546 over them and no other, a step without claims does not run, and
547 nothing is recorded as proved. ``--safe-fix`` runs the fixers in
548 their in-flight mode, which removes no code, and refuses beside
549 ``--fix``. ``--point`` hands a CI point to the test phase, which
550 selects that point's tests instead of the gate's.
551
552 ``--shard`` names the shard of a sharded check leg this run is,
553 ``2of4``: a step that reads the shard runs its share, every other
554 step runs on the first shard alone, and the walk names each step
555 it leaves there. Inside CI the leg's label names the shard and the
556 flag is not needed. A sharded run records no tree as proved, since
557 a share of the gate ran. A shard outside the form, ``0of2``,
558 refuses naming it.
559
560 On a machine and inside CI, the gate reads the proved record
561 ([livery.workshop._proved][]): each unit whose inputs match an
562 existing green row for this platform is skipped, and every unproved
563 unit runs and records its verdict. ``--full`` runs everything
564 whatever the record says. On a push to ``main``, matched branch rows
565 are copied onto ``proved/main/<leg>`` so an already-proved tree
566 skips the gate.
567
568 ``--fix`` runs format and lint in their fix modes: each prints
569 what it found, rewrites what is mechanical, and still fails on
570 what is not. The two rewrite the same files, so under ``--fix``
571 they run one after the other before the rest of the gate.
572
573 ``--fix`` refuses inside CI: a runner's checkout is judged,
574 never rewritten, because a fix there mutates a copy nobody
575 keeps and hides the finding from the verdict. Run the fix
576 locally and push the result.
577
578 On a machine the state store is read from what the last ``sync``
579 or ``start`` fetched ([livery.git.fetched_snapshot][]):
580 nothing the gate runs reaches origin, and a checkout the store was
581 never fetched into roots its chain on a full gate and says so.
582 Inside CI the legs read the store as the run's own snapshot.
583 """
584 from contextlib import nullcontext
585
586 from livery.git import fetched_snapshot
587 from livery.workshop._ci_context import run_context
588 from livery.workshop._steps import arguments_refusal, split_arguments
589
590 _refuse_both(fix, safe_fix)
591 chosen = _current_shard(shard)
592 paths, arguments = split_arguments(paths)
593 if arguments:
594 verb = f"{footman.prog()} check"
595 fail(arguments_refusal(verb, _steps.steps_by_name().values()))
596 if paths:
597 _check_files(
598 paths, fix=fix or safe_fix, safe=safe_fix, point=point, shard=chosen
599 )
600 return
601 root = workspace_root()
602 scope = (
603 fetched_snapshot(state_store(root))
604 if root is not None and run_context() is None
605 else nullcontext()
606 )
607 with scope:
608 _run_check(
609 full=full,
610 fix=fix or safe_fix,
611 base=base,
612 point=point,
613 safe=safe_fix,
614 shard=chosen,
615 )
616
617
618def named_files(root: Path, paths: tuple[str, ...]) -> tuple[str, ...]:
619 """*paths* as the files they name, root-relative: a file, or a directory's files.
620
621 A directory stands for the files git holds under it, tracked or
622 untracked and not ignored, or every file under it outside a git
623 checkout. A path outside the root, or naming nothing, is left out.
624 """
625 found: set[str] = set()
626 for path in paths:
627 target = Path(path).resolve()
628 try:
629 relative = target.relative_to(root.resolve()).as_posix()
630 except ValueError:
631 continue
632 if target.is_file():
633 found.add(relative)
634 elif target.is_dir():
635 try:
636 found.update(git.ls_files(root, relative, others=True))
637 except git.GitError:
638 found.update(
639 p.relative_to(root.resolve()).as_posix()
640 for p in target.rglob("*")
641 if p.is_file()
642 )
643 return tuple(sorted(name for name in found if (root / name).is_file()))
644
645
646def _in_workspace(root: Path, path: str) -> bool:
647 """Whether *path* is a file or a directory under *root*."""
648 target = Path(path).resolve()
649 return target.is_relative_to(root.resolve()) and target.exists()
650
651
652def _check_files(
653 paths: tuple[str, ...],
654 *,
655 fix: bool,
656 safe: bool,
657 point: str,
658 shard: Shard = ONE,
659 judge: bool = True,
660 only: frozenset[str] | None = None,
661 arguments: tuple[str, ...] = (),
662 inputs: Mapping[str, Mapping[str, object]] = GATE_INPUTS,
663) -> None:
664 """The gate over the named files: the walk narrowed to them, nothing recorded.
665
666 A person's path that names nothing in the workspace refuses, since
667 running nothing there would pass: a typo, or a tool's own argument
668 after ``--``, which the steps never pass through. The post-edit
669 hook, which judges nothing, may name a file already deleted.
670 """
671 import os
672
673 root = workspace_root()
674 if root is None:674 ↛ 675line 674 didn't jump to line 675 because the condition on line 674 was never true
675 fail("no workspace: no workshop.toml above the working directory")
676 if fix and os.environ.get("CI"):676 ↛ 677line 676 didn't jump to line 677 because the condition on line 676 was never true
677 fail(
678 "check --fix inside CI: the runner's checkout is judged, never rewritten."
679 f" Run `{footman.prog()} check --fix` locally and push the result."
680 )
681 if judge:
682 unknown = [path for path in paths if not _in_workspace(root, path)]
683 if unknown:
684 fail(
685 "not a file or directory in the workspace:"
686 f" {', '.join(unknown)}. Name files or directories; a step's"
687 " own verb hands its tool the words after --:"
688 f" `{footman.prog()} <phase>.<step> <paths> -- <words>`."
689 )
690 files = named_files(root, paths)
691 if not files:
692 print(" nothing to check: no file under the named paths")
693 return
694 from livery.workshop._packages import workspace_suite
695 from livery.workshop._provenance import unit_of
696
697 packages = _packages()
698 holders = {unit_of(root, packages, name)[0] for name in files}
699 # The packages holding a named file, and the workspace's tests unit
700 # when a root file is named; the unit of a root without tests is no
701 # package, and joins no subset.
702 subset = [package for package in packages if package in holders]
703 suite = workspace_suite(root)
704 if suite is not None and suite in holders:704 ↛ 705line 704 didn't jump to line 705 because the condition on line 704 was never true
705 subset.append(suite)
706 ctx = _context(
707 subset=tuple(subset),
708 fix=fix,
709 files=files,
710 safe=safe,
711 point=point,
712 shard=shard,
713 arguments=arguments,
714 )
715 walk(ctx, judge=judge, only=only, inputs=inputs)
716
717
718def run_steps(
719 names: tuple[str, ...],
720 paths: tuple[str, ...] = (),
721 *,
722 fix: bool = False,
723 safe_fix: bool = False,
724 point: str = "",
725 shard: str = "",
726 arguments: tuple[str, ...] = (),
727) -> None:
728 """Run the steps *names* through the walk: a generated verb's body.
729
730 Over the named paths, or the whole workspace; nothing is recorded
731 as proved, since a part of the gate ran. *arguments*, the words
732 after ``--`` on a step's own verb, reach that step's tool. *shard*
733 is the ``--shard`` flag's text, read as `check` reads it. The
734 phases take the verb's inputs
735 ([livery.workshop._quality.VERB_INPUTS][]), not the gate's.
736 """
737 import os
738
739 _refuse_both(fix, safe_fix)
740 if (fix or safe_fix) and os.environ.get("CI"):
741 fail(
742 "a fix inside CI: the runner's checkout is judged, never rewritten."
743 f" Run `{footman.prog()} check --fix` locally and push the result."
744 )
745 chosen = _current_shard(shard)
746 only = frozenset(names)
747 if paths:
748 _check_files(
749 paths,
750 fix=fix or safe_fix,
751 safe=safe_fix,
752 point=point,
753 shard=chosen,
754 only=only,
755 arguments=arguments,
756 inputs=VERB_INPUTS,
757 )
758 return
759 context = _context(
760 fix=fix or safe_fix,
761 safe=safe_fix,
762 point=point,
763 shard=chosen,
764 arguments=arguments,
765 )
766 walk(context, only=only, inputs=VERB_INPUTS)
767
768
769def run_phase_over(
770 phase: str,
771 packages: tuple[Package, ...],
772 *,
773 tests: Mapping[str, tuple[str, ...]] | None = None,
774) -> None:
775 """Run the steps of *phase* over *packages* whole; nothing recorded as proved.
776
777 The gate's walk ([livery.workshop._quality.walk][]) narrowed to the
778 steps the extensions register for *phase*, and the steps they run
779 after, over the named packages alone, with the gate's inputs. A
780 package no step of the phase judges is skipped by the walk, and a
781 phase with no step runs nothing. An extension runs a phase this
782 way over packages the gate did not run it on. When *tests* names
783 specific test items per package, only those items run and live
784 per-item selection is bypassed so every requested item executes.
785 Inside CI the leg's label names the shard the run is, as `check`
786 reads it without the flag.
787 """
788 from livery.workshop import _proved
789
790 names = tuple(
791 record.name
792 for record in _steps.steps_by_name().values()
793 if record.phase == phase
794 )
795 if not names:795 ↛ 796line 795 didn't jump to line 796 because the condition on line 795 was never true
796 return
797 with _proved.without_item_selection():
798 walk(
799 _context(subset=packages, shard=_current_shard(), tests=tests),
800 only=frozenset(names),
801 )
802
803
804def fix_files(paths: tuple[str, ...], *, safe: bool = True) -> None:
805 """Run the gate's fixers over *paths*, judging nothing.
806
807 Every step whose claims reach a file fixes it, and a file no claim
808 reaches is left alone. *safe* keeps to the fixes a step marks
809 safe, which never remove code an edit in flight still needs; an
810 agent's post-edit hook runs it after each edit.
811 """
812 _check_files(paths, fix=True, safe=safe, point="", judge=False)
813
814
815def _run_check(
816 full: bool,
817 fix: bool,
818 base: str,
819 point: str = "",
820 safe: bool = False,
821 shard: Shard = ONE,
822) -> None:
823 """The gate itself; `check` opens the state store's snapshot around it."""
824 import os
825
826 if fix and os.environ.get("CI"):
827 fail(
828 "check --fix inside CI: the runner's checkout is judged,"
829 " never rewritten. A fix here would mutate a copy nobody"
830 " keeps and hide the finding from the verdict. Run"
831 f" `{footman.prog()} check --fix` locally and push the result."
832 )
833 from livery.workshop import _proved, _scope
834 from livery.workshop._ci_context import run_context
835
836 del base
837 root_for_ci = workspace_root()
838 if root_for_ci is not None:838 ↛ 840line 838 didn't jump to line 840 because the condition on line 838 was always true
839 _proved.clear_ran_items(root_for_ci)
840 run = run_context()
841 if root_for_ci is not None and run is not None:
842 _leave_empty_share(root_for_ci, shard, attempt=run.attempt)
843 # The nightly point and a manual dispatch pay the whole gate: the
844 # proved record is set aside so a scheduled audit or an explicit
845 # dispatch proves the checkout fresh.
846 nightly = _current_point() == "nightly"
847 dispatched = run is not None and run.event == "workflow_dispatch"
848 if nightly:848 ↛ 849line 848 didn't jump to line 849 because the condition on line 848 was never true
849 print(" nightly: the whole gate, the proved record set aside")
850 elif dispatched:
851 print(" dispatched: the whole gate, the proved record set aside")
852 if not (nightly or dispatched) and root_for_ci is not None and run is not None:
853 sibling = _sibling_scope(root_for_ci, run) if shard != ONE else None
854 decided = _proved_decision(root_for_ci, run=run, point=point, shard=shard)
855 if decided is not None or sibling is not None:855 ↛ 978line 855 didn't jump to line 978 because the condition on line 855 was always true
856 proving_branch = ""
857 if decided is not None:857 ↛ 885line 857 didn't jump to line 885 because the condition on line 857 was always true
858 ctx_all, decision, plat = decided
859 if _proved.leg_base(run) == _proved.MAIN and decision.copied:
860 proving_branch = next(
861 (
862 obs.branch
863 for obs in decision.copied
864 if obs.branch and obs.branch != _proved.MAIN
865 ),
866 "",
867 )
868 _proved.spool_proved_observations(
869 root_for_ci,
870 decision.copied,
871 base=_proved.MAIN,
872 leg=_proved.leg_key(run),
873 matched_branches=decision.matched_branches,
874 platform=plat,
875 exact_image=shard == ONE,
876 )
877 print(
878 f" proved: spooled {len(decision.copied)} unit(s) from"
879 f" branch record for {_proved.FAMILY.name}/{_proved.MAIN}/"
880 f"{_proved.leg_key(run)}"
881 )
882 proved_units = decision.proved
883 running_units = decision.running
884 else:
885 ctx_all = _context(point=point, shard=shard)
886 proved_units = frozenset()
887 running_units = tuple(
888 (rec, tgt, "no row") for rec, tgt in _candidate_units(ctx_all)
889 )
890 if sibling is not None:890 ↛ 891line 890 didn't jump to line 891 because the condition on line 890 was never true
891 print(
892 f" proved: rerun attempt {run.attempt} aligns test suites"
893 f" with passing sibling ({sibling.scope})"
894 )
895 skip_units, skip_gate, marker_scope, marker_pkgs, marker_branch = (
896 _align_with_sibling(
897 ctx_all,
898 proved_units,
899 running_units,
900 sibling,
901 proving_branch=proving_branch,
902 )
903 )
904 if skip_gate:
905 say_skipped(
906 "proved: passing sibling proved the gate; skipping the gate"
907 )
908 _scope.write_marker(
909 root_for_ci,
910 _scope.VERIFIED,
911 leg=run.leg,
912 branch=marker_branch,
913 )
914 return
915 _scope.write_marker(
916 root_for_ci,
917 marker_scope,
918 marker_pkgs,
919 leg=run.leg,
920 branch=marker_branch,
921 )
922 walk(ctx_all, skip_units=skip_units, record_proved=True)
923 return
924 total_units = len(proved_units) + len(running_units)
925 if not running_units:
926 say_skipped(
927 f"proved: all {total_units} unit(s) proved green; skipping the gate"
928 )
929 _scope.write_marker(
930 root_for_ci,
931 _scope.VERIFIED,
932 leg=run.leg,
933 branch=proving_branch,
934 )
935 return
936 print(
937 f" proved: {len(proved_units)}/{total_units} unit(s) proved"
938 f" green; running {len(running_units)} unit(s)"
939 )
940 for rec, tgt, why_run in running_units[:10]:
941 print(f" {rec.name}@{tgt}: {why_run}")
942 if len(running_units) > 10:942 ↛ 943line 942 didn't jump to line 943 because the condition on line 942 was never true
943 print(f" ... and {len(running_units) - 10} more")
944 all_test_pkgs = {
945 tgt
946 for rec, tgt in _candidate_units(ctx_all)
947 if rec.phase == "test" and tgt != "."
948 }
949 running_test_pkgs = {
950 tgt
951 for rec, tgt, _ in running_units
952 if rec.phase == "test" and tgt != "."
953 }
954 if not running_test_pkgs:954 ↛ 955line 954 didn't jump to line 955 because the condition on line 954 was never true
955 _scope.write_marker(
956 root_for_ci,
957 _scope.NOTHING,
958 leg=run.leg,
959 branch=proving_branch,
960 )
961 elif all_test_pkgs and running_test_pkgs >= all_test_pkgs:961 ↛ 962line 961 didn't jump to line 962 because the condition on line 961 was never true
962 _scope.write_marker(
963 root_for_ci,
964 _scope.FULL,
965 leg=run.leg,
966 branch=proving_branch,
967 )
968 else:
969 _scope.write_marker(
970 root_for_ci,
971 _scope.AFFECTED,
972 tuple(sorted(running_test_pkgs)),
973 leg=run.leg,
974 branch=proving_branch,
975 )
976 walk(ctx_all, skip_units=proved_units, record_proved=True)
977 return
978 if run is None and root_for_ci is not None:
979 if full:
980 print(" full: everything runs, whatever the record proves")
981 else:
982 pre_fix = (
983 (
984 lambda: walk(
985 _context(fix=True, safe=safe, point=point, shard=shard),
986 judge=False,
987 )
988 )
989 if fix
990 else None
991 )
992 decided = _proved_decision(
993 root_for_ci, run=None, point=point, shard=shard, pre_fix=pre_fix
994 )
995 if decided is not None:
996 ctx_all, decision, _plat = decided
997 total_units = len(decision.proved) + len(decision.running)
998 if not decision.running:
999 say_skipped("proved: every unit is green already; nothing to run")
1000 return
1001 print(
1002 f" proved: {len(decision.proved)}/{total_units} unit(s) proved"
1003 f" green; running {len(decision.running)} unit(s)"
1004 )
1005 for rec, tgt, why_run in decision.running[:10]:
1006 print(f" {rec.name}@{tgt}: {why_run}")
1007 if len(decision.running) > 10:1007 ↛ 1008line 1007 didn't jump to line 1008 because the condition on line 1007 was never true
1008 print(f" ... and {len(decision.running) - 10} more")
1009 walk(
1010 ctx_all,
1011 skip_units=decision.proved,
1012 record_proved=shard == ONE,
1013 )
1014 return
1015 if root_for_ci is not None and run is not None:
1016 _scope.write_marker(root_for_ci, _scope.FULL, leg=run.leg)
1017
1018 walk(
1019 _context(fix=fix, safe=safe, point=point, shard=shard),
1020 record_proved=(run is not None) or (shard == ONE),
1021 )
1022
1023
1024def _current_point() -> str:
1025 """The point this process runs at, as the job runner named it; gate outside CI."""
1026 import os
1027
1028 from livery.workshop._ci_context import POINT_VARIABLE
1029
1030 return os.environ.get(POINT_VARIABLE, "gate")
1031
1032
1033def _leave_empty_share(root: Path, shard: Shard, *, attempt: str = "") -> None:
1034 """Leave the shard's record of an empty set, before the gate decides.
1035
1036 The gate job's fold proves a platform's shards from the record each
1037 one leaves of what it partitioned, and the test step leaves that
1038 record only when it runs. A shard whose gate skips on the verified
1039 record, finds nothing affected, or reaches no suite leaves this one
1040 instead: no item, no durations row, the checkout's time as the
1041 bound, the same on every shard of the platform, so the fold folds
1042 the platform's skipped shards into one skipped leg. The test step's
1043 own record replaces it when the step runs. One shard of one leaves
1044 none. *attempt* is the run's attempt, recorded as the test step
1045 records it.
1046 """
1047 if shard == ONE:
1048 return
1049 leave_shard(
1050 root,
1051 shard=shard,
1052 digest=files_digest(()),
1053 items=(),
1054 rows=(),
1055 before=checkout_time(root),
1056 attempt=attempt,
1057 )
1058
1059
1060def _current_shard(given: str = "") -> Shard:
1061 """The shard this run is: *given* when there is one, else the CI leg's.
1062
1063 *given* is the ``--shard`` flag's text, ``2of4``. Without it,
1064 inside CI, the leg's label ends in the shard
1065 ([livery.workshop.shard_of][]), and a label without one is one
1066 shard of one; outside CI every run is one shard of one.
1067
1068 Raises:
1069 Failed: When *given*, or the label's tail, spells no shard,
1070 naming it.
1071 """
1072 from livery.workshop._ci_context import LEG_VARIABLE, run_context
1073
1074 if given:
1075 try:
1076 return Shard.parse(given)
1077 except ValueError as error:
1078 fail(str(error))
1079 run = run_context()
1080 if run is None:
1081 return ONE
1082 try:
1083 return shard_of(run.leg)
1084 except ValueError as error:
1085 fail(f"{LEG_VARIABLE}={run.leg}: {error}")
1086
1087
1088def say_skipped(text: str) -> None:
1089 """Print a skip, and put it on the timeline as an event.
1090
1091 Work left undone because something already proves it is the one thing
1092 an account of a run must not show as merely fast: a gate that skipped
1093 and a gate that flew look identical from outside. The printed line is
1094 unchanged, so a log reads as it always did, and the mark is what makes
1095 the picture honest about why a leg was quick.
1096
1097 Marks only inside a task, since that is where a timeline exists; a
1098 plain call outside a run prints and nothing more.
1099 """
1100 print(f" {text}")
1101 if footman.current().in_task:
1102 footman.mark(f"skipped: {text}")
1103
1104
1105def _git_identity(root: Path) -> str:
1106 """Who is accepting: the git identity, or the user name the shell has."""
1107 import os
1108
1109 return git.config_get(root, "user.name") or os.environ.get("USER", "unknown")
1110
1111
1112caches = group("caches", help="The workspace's derived caches")
1113
1114
1115@caches.task(name="clear")
1116def caches_clear() -> None:
1117 """Remove build artifacts, checker caches, and legacy root cache directories.
1118
1119 A step's own cache directory, ``.workshop/.cache/<step>/``, goes
1120 whole; legacy root caches left by older checkouts (``.mypy_cache``,
1121 ``.ruff_cache``, ``.pytest_cache``, ``.docs-build``, ``.cache``) are
1122 cleaned alongside ``dist``. Never touches ``.workshop/`` whole so
1123 tracked ``.workshop/graphs/`` stays intact.
1124 """
1125 import shutil
1126
1127 root = workspace_root()
1128 if root is None:1128 ↛ 1129line 1128 didn't jump to line 1129 because the condition on line 1128 was never true
1129 return
1130 for name in (
1131 "dist",
1132 ".workshop/.cache",
1133 ".mypy_cache",
1134 ".ruff_cache",
1135 ".pytest_cache",
1136 ".docs-build",
1137 ".cache",
1138 ):
1139 shutil.rmtree(root / name, ignore_errors=True)