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

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_run.py, packages/workshop/tests/test_workshop_root_attribution.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_quality.py, packages/workshop/tests/test_workshop_publish.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_parts.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.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_isolated.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_influence.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_e2e.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_dev_release.py, packages/extensions/python/tests/test_release_driver.py, packages/extensions/python/tests/test_python_phases.py, packages/extensions/pytest/tests/test_pytest.py, packages/extensions/nanobind/tests/test_kind_publish.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/mkdocstrings/tests/test_mkdocstrings.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_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.py, packages/extensions/coverage/tests/test_coverage_proved_parts.py, packages/extensions/conan/tests/test_cross_kind.py ran.

1"""The affected engine: which packages a change can influence.
2
3The workspace graph is the ``[[depends]]`` edges the contracts
4declare. A changed file maps to the package whose directory holds it,
5and the affected set is that package plus everything that depends on
6it, transitively (the dependents' closure): a change can break its
7consumers, never its dependencies. A change outside every package,
8the root configuration, the templates, the workspace tests, affects
9everything, because the root files configure every gate. A change
10can reach further than its package's dependents: a listed extension
11says how far through the ``reaches`` query, as python does for a
12module pytest loads as a plugin into every suite it runs.
13
14``fm graph.affected`` prints the verdict; the quality family's
15the reflex and the CI legs scope work to it.
16"""
17
18from __future__ import annotations
19
20import functools
21from collections.abc import Callable, Iterable, Mapping
22from dataclasses import dataclass, field
23from pathlib import Path
24
25from livery import git
26from livery.footman import group
27from livery.workshop._packages import Package, discover_packages
28
29graph = group("graph", help="The workspace dependency graph")
30
31
32def dependents_closure(
33 packages: tuple[Package, ...], seeds: set[str]
34) -> tuple[Package, ...]:
35 """*seeds* (package paths) plus everything depending on them.
36
37 Follows the reversed ``[[depends]]`` edges to a fixed point, and
38 answers in discovery order so output stays deterministic.
39 """
40 dependents: dict[str, set[str]] = {package.path: set() for package in packages}
41 for package in packages:
42 for edge in package.depends:
43 dependents.setdefault(edge.path, set()).add(package.path)
44 affected = set(seeds)
45 frontier = list(seeds)
46 while frontier:
47 for consumer in dependents.get(frontier.pop(), ()):
48 if consumer not in affected:
49 affected.add(consumer)
50 frontier.append(consumer)
51 return tuple(package for package in packages if package.path in affected)
52
53
54def dependencies_closure(
55 packages: tuple[Package, ...], seeds: set[str]
56) -> tuple[Package, ...]:
57 """*seeds* (package paths) plus everything they depend on, transitively.
58
59 Follows the ``[[depends]]`` edges to a fixed point, and answers in
60 discovery order; [livery.workshop.order_topologically][]
61 puts each dependency before its dependents.
62 """
63 by_path = {package.path: package for package in packages}
64 needed = set(seeds)
65 frontier = list(seeds)
66 while frontier:
67 package = by_path.get(frontier.pop())
68 for edge in package.depends if package is not None else ():
69 if edge.path not in needed:
70 needed.add(edge.path)
71 frontier.append(edge.path)
72 return tuple(package for package in packages if package.path in needed)
73
74
75#: The prose directory: nothing under it reaches a gate.
76NOTES = "notes/"
77
78#: The site's own files at the root: its configuration and its pages.
79SITE_CONFIG = "zensical.toml"
80SITE_DOCS = "docs/"
81
82#: Files at the root that configure no package's steps: the licence,
83#: the CI files and the code-owners file the forge reads, the editor's
84#: and the agent's settings, git's own files, the entry script, the
85#: release's member list, the site's theme and the render's receipt.
86#: A workspace step that reads one still judges it.
87NO_PACKAGE = (
88 "LICENSE",
89 ".github/**",
90 ".gitea/**",
91 ".gitlab/**",
92 ".gitlab-ci.yml",
93 "CODEOWNERS",
94 "docs/CODEOWNERS",
95 ".vscode/**",
96 ".claude/**",
97 ".agents/**",
98 ".gitattributes",
99 ".gitignore",
100 "setup.sh",
101 ".release-manifest.json",
102 "overrides/**",
103 ".workshop-rendered",
104)
105
106
107def reaches_no_package(path: str) -> bool:
108 """Whether *path* is a root file no package's steps read.
109
110 A change to one gates no package; the workspace steps that read it
111 still judge it ([livery.workshop._steps.selected][]).
112 """
113 from livery.workshop._categories import matches
114
115 return any(matches(pattern, path) for pattern in NO_PACKAGE)
116
117
118def is_site(path: str) -> bool:
119 """Whether *path* is the site's own: the root ``zensical.toml`` or ``docs/`` tree.
120
121 Only the site build reads them, and it runs on every run, so
122 they reach no format, lint, type, or test gate. A package's
123 ``docs/`` directory is the package's, not the site's.
124 """
125 return path == SITE_CONFIG or path.startswith(SITE_DOCS)
126
127
128def is_prose(path: str) -> bool:
129 """Whether *path* is prose: under ``notes/``, or a markdown file anywhere.
130
131 Prose reaches no format, lint, type, or test gate. The site build
132 is where markdown is judged, and it runs on every run.
133 """
134 return path.startswith(NOTES) or path.endswith(".md")
135
136
137def affected_packages(root: Path, *, base: str = "main") -> tuple[Package, ...] | None:
138 """The packages this branch's changes can influence, and the workspace's own tests.
139
140 None means everything: a touched file outside every package (the
141 root configuration, templates) configures every gate, so no
142 narrowing is honest, and the file is named. Prose (`is_prose`)
143 and the site's own files (`is_site`) affect no package wherever
144 they live, so a diff confined to them affects nothing. A change
145 under the workspace's own ``tests/`` affects that unit alone,
146 which the answer then carries as a package of its own
147 ([livery.workshop.workspace_suite][]): its tests
148 reach every package, and every leg that runs a suite runs them
149 anyway, so no package's suite has to run for it. An empty tuple
150 means the branch changes nothing a gate reads.
151 """
152 scope = affected_by(
153 root,
154 git.changed_paths(root, base),
155 # Asked only for a change outside every package, or one inside a
156 # package the listed extensions are asked about.
157 before=lambda: git.merge_base(root, base),
158 )
159 return None if scope is None else scope.packages
160
161
162def affected_by(
163 root: Path, paths: Iterable[str], *, before: str | Callable[[], str]
164) -> Scope | None:
165 """What *paths*, changed since *before*, reach among the workspace's packages.
166
167 `affected_from_paths` over the packages discovered under *root*.
168 ``None`` means everything.
169 """
170 packages = discover_packages(root)
171 return affected_from_paths(root, packages, paths, before=before)
172
173
174@dataclass(frozen=True)
175class Scope:
176 """What a change reaches: the packages, and the tests that stand for some.
177
178 Attributes:
179 packages: The packages to gate, in discovery order, the
180 workspace's own tests unit last when its files changed.
181 tests: Per package, the test files that stand for its suite;
182 the walk names none until a better narrowing exists, so
183 every package runs its suite whole.
184 examples: The package paths whose changed files are examples
185 and nothing else: their examples run and no suite. A
186 package reached through its source runs both.
187 """
188
189 packages: tuple[Package, ...]
190 tests: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
191 examples: tuple[str, ...] = ()
192
193
194def docs_page(packages: tuple[Package, ...], path: str) -> Package | None:
195 """The package whose authored docs page *path* is, or None for any other path."""
196 if not path.endswith(".md") or "/_generated/" in path:
197 return None
198 for package in packages:
199 if path.startswith(package.path + "/docs/"):
200 return package
201 return None
202
203
204def affected_from_paths(
205 root: Path,
206 packages: tuple[Package, ...],
207 paths: Iterable[str],
208 *,
209 before: str | Callable[[], str] = "",
210) -> Scope | None:
211 """What a change to *paths* reaches: the packages, and the tests that stand alone.
212
213 The classification `affected_packages` applies to a branch's
214 changes, for any set of paths: the reflex hands it the paths
215 between a proved tree and the working tree. Each path is
216 classified by its package's kind: a test file reaches its own
217 package alone, since nothing imports a test, and that package
218 runs its whole suite; source, test support, and configuration
219 reach the package's dependents and run the suites. A change under
220 the workspace's own tests runs that unit whole. A docs page
221 reaches nothing: the site build reads it. An example file reaches
222 its package's examples step
223 and no suite, unless source of the package changed too. A file
224 outside every package reaches everything, unless *before* (the
225 commit or tree the paths were taken from) shows the change is
226 about the packages added or removed, or, for ``uv.lock``, about
227 the members whose resolution it moves
228 ([livery.workshop._root_attribution][]): then it reaches those.
229 A change inside a package reaches further when a listed extension
230 says so: each answer to the ``reaches`` query is called with the
231 change, and every member it names for a changed path runs with
232 its dependents (`_reached`).
233 *before* may be a function answering it, asked once, and only
234 when a path outside every package or an answer to ``reaches``
235 needs it.
236 ``None`` means everything, an empty scope nothing a gate reads.
237 """
238 from livery.workshop._categories import EXAMPLE, TEST, category_of
239 from livery.workshop._packages import WORKSPACE_TESTS, workspace_suite
240
241 paths = tuple(paths)
242 if not isinstance(before, str):
243 before = functools.cache(before)
244 seeds: set[str] = set()
245 # A package whose test files changed runs its whole suite; nothing
246 # imports a test, so its dependents' suites do not run. The suite
247 # is not narrowed to the changed files until a better narrowing
248 # exists: the tests a change reaches are more than the ones it edits.
249 suites: set[str] = set()
250 examples: set[str] = set()
251 tests_changed = False
252 inside = False
253 outside: list[str] = []
254 for path in paths:
255 if docs_page(packages, path) is not None:
256 continue
257 if is_prose(path) or is_site(path) or reaches_no_package(path):
258 continue
259 if path.startswith(WORKSPACE_TESTS + "/"):
260 tests_changed = True
261 continue
262 for package in packages:
263 if path.startswith(package.path + "/"):
264 inside = True
265 relative = path[len(package.path) + 1 :]
266 category = category_of(package, relative).name
267 if category == EXAMPLE:
268 examples.add(package.path)
269 elif category == TEST:
270 suites.add(package.path)
271 else:
272 seeds.add(package.path)
273 break
274 else:
275 outside.append(path)
276 if outside:
277 attributed = _attribute(root, packages, outside, before=before)
278 if attributed is None:
279 return None
280 seeds |= attributed
281 if inside:
282 widened = _reached(root, packages, paths, before=before)
283 if widened is None:
284 return None
285 seeds |= widened
286 reached = {package.path for package in dependents_closure(packages, seeds)}
287 alone = tuple(
288 sorted(path for path in examples if path not in reached and path not in suites)
289 )
290 members = tuple(
291 package
292 for package in packages
293 if package.path in reached or package.path in suites or package.path in alone
294 )
295 if not tests_changed:
296 return Scope(members, {}, alone)
297 unit = workspace_suite(root)
298 if unit is None:
299 print(f" {WORKSPACE_TESTS}/: changed and gone; everything runs")
300 return None
301 return Scope((*members, unit), {}, alone)
302
303
304def _attribute(
305 root: Path,
306 packages: tuple[Package, ...],
307 paths: list[str],
308 *,
309 before: str | Callable[[], str],
310) -> set[str] | None:
311 """The packages the changes to *paths*, all outside every package, are about.
312
313 None means everything, and the first path that forces it is
314 named: without *before* there is nothing to compare with, and a
315 change the package set does not explain configures every gate.
316 """
317 from livery.workshop._root_attribution import (
318 LOCK,
319 explained,
320 lock_affected,
321 package_delta,
322 )
323
324 point = before if isinstance(before, str) else before()
325 if root is None or not point:
326 print(f" {paths[0]}: outside the packages; everything runs")
327 return None
328 delta = package_delta(root, point, packages)
329 seeds = {package.path for package in delta.added}
330 for path in paths:
331 if delta.holds(path):
332 continue # a removed package's own files: nothing depends on it now
333 old = git.file_at(root, point, path)
334 target = root / path
335 new = target.read_text("utf-8") if target.is_file() else ""
336 if path == LOCK:336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true
337 moved = lock_affected(old, new, delta)
338 if moved is None:
339 print(
340 f" {path}: a resolution beyond the members moved; everything runs"
341 )
342 return None
343 seeds |= moved
344 continue
345 if not explained(old, new, delta):
346 print(f" {path}: outside the packages; everything runs")
347 return None
348 print(f" {path}: names only the packages added or removed")
349 return seeds
350
351
352def _reached(
353 root: Path,
354 packages: tuple[Package, ...],
355 paths: tuple[str, ...],
356 *,
357 before: str | Callable[[], str],
358) -> set[str] | None:
359 """The members the listed extensions say the change to *paths* reaches.
360
361 Each function the extensions answer the ``reaches`` query with
362 ([livery.workshop._queries.REACHES][]) is called with the change,
363 *before* resolved only when one answers. Each changed path an
364 answer widens is printed with why, and with how many members it
365 reaches. None means everything, and the line names the extension:
366 an answer raised, or named a path outside the members.
367 """
368 from livery.workshop._influence import Changes
369 from livery.workshop._queries import REACHES, answers
370
371 try:
372 answered = answers(root, REACHES)
373 except Exception as error:
374 print(f" reaches: {error}; everything runs")
375 return None
376 if not answered:
377 return set()
378 point = before if isinstance(before, str) else before()
379 changes = Changes(root, paths, point)
380 members = {package.path for package in packages}
381 seeds: set[str] = set()
382 for name, functions in answered.items():
383 try:
384 widened = [
385 (path, why, tuple(found))
386 for function in functions
387 for path, (why, found) in function(changes).items()
388 ]
389 except Exception as error:
390 print(
391 f" {name} could not say what the change reaches ({error});"
392 " everything runs"
393 )
394 return None
395 for path, why, found in widened:
396 unknown = sorted(set(found) - members)
397 if unknown:
398 print(
399 f" {path}: {name} says it reaches {', '.join(unknown)},"
400 " outside the members; everything runs"
401 )
402 return None
403 print(f" {path}: {why}; it reaches {len(found)} package(s)")
404 seeds.update(found)
405 return seeds
406
407
408@graph.task(name="affected")
409def graph_affected(base: str = "main") -> None:
410 """Print the affected packages for this branch, one per line.
411
412 Args:
413 base: the branch the change will merge into
414 """
415 from livery.workshop._extensions import workspace_root
416
417 root = workspace_root()
418 if root is None:418 ↛ 419line 418 didn't jump to line 419 because the condition on line 418 was never true
419 print(" no workspace: no workshop.toml above the working directory")
420 return
421 git.fetch(root)
422 affected = affected_packages(root, base=base)
423 if affected is None:
424 print(" everything: a change outside the packages configures every gate")
425 return
426 if not affected:426 ↛ 427line 426 didn't jump to line 427 because the condition on line 426 was never true
427 print(" nothing: the branch changes no files")
428 return
429 for package in affected:
430 print(f" {package.path} ({package.name})")
431
432
433def order_topologically(packages: tuple[Package, ...]) -> tuple[Package, ...]:
434 """*packages* in release order: every dependency before its dependents.
435
436 Kahn's walk over the ``[[depends]]`` edges restricted to the given
437 set; ties keep the input order so the result is deterministic. A
438 cycle cannot arise, the layering lint refuses one long before a
439 release asks.
440 """
441 chosen = {p.path for p in packages}
442 remaining = list(packages)
443 ordered: list[Package] = []
444 placed: set[str] = set()
445 while remaining:
446 for index, package in enumerate(remaining):
447 needs = {
448 edge.path
449 for edge in package.depends
450 if edge.path in chosen and edge.path not in placed
451 }
452 if not needs:
453 ordered.append(package)
454 placed.add(package.path)
455 del remaining[index]
456 break
457 else: # pragma: no cover - guarded by the layering lint
458 ordered.extend(remaining)
459 break
460 return tuple(ordered)