Coverage for packages/workshop/src/livery/workshop/_e2e_rows.py: 92%

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_install.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_runs.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_extension_mount.py, packages/workshop/tests/test_workshop_e2e_rows.py, packages/workshop/tests/test_workshop_e2e.py, packages/workshop/tests/test_workshop_credential_traces.py, packages/extensions/python/tests/test_extensions_python.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/cpp/tests/test_extensions_cpp.py, packages/extensions/conan/tests/test_extensions_conan.py ran.

1"""What the newborn's store says a run did: the rows the loop's proofs read.
2
3A proof asks the rows the legs wrote, never a job's log: a run's
4metrics row (each check leg's scope and the coverage section the gate
5job left), the verified series (the tree a run proved and what it
6rests on), a base's coverage record (which run measured each unit),
7the coverage marks, and a platform leg's durations series (the seconds
8per item a run's gate job recorded). A platform that ran as
9shards has one check row, the fold's, keyed by the platform leg with
10its shards listed under ``shard``; the forge's rows of the shards
11stand beside it with their times alone, and no proof reads them as
12the leg. Every reader fails naming the series, the file and the run
13when the row it needs is not there, so a proof that fails says what
14the legs did not write.
15
16The coverage rows are read by their ref and a few fields, since the
17loop lives in the base and the base imports no extension; their schema
18is the coverage extension's, and the loop leaves the base with phase
1915 of the destination note.
20"""
21
22from __future__ import annotations
23
24import json
25from dataclasses import dataclass
26from typing import TYPE_CHECKING, Any
27
28from livery import git
29from livery.footman import fail
30from livery.workshop import _metrics, _proved, _scope, _shard
31from livery.workshop._ci_context import state_store
32from livery.workshop._speed import forge_shard_row
33
34if TYPE_CHECKING:
35 from pathlib import Path
36
37#: The coverage extension's record family and marks series, by ref alone.
38COVERAGE_RECORD = git.Keyed("coverage", ("base", "leg"))
39COVERAGE_MARKS = git.Series("coverage/marks", window=400, ci_only=False)
40
41
42@dataclass(frozen=True)
43class ShardFacts:
44 """One shard of a folded check leg, as the fold listed it.
45
46 Attributes:
47 shard: The shard, ``1of2``.
48 leg: The shard's leg label (``check-ubuntu-latest-3.14-1of2``).
49 job: The shard's job name, as the forge lists it.
50 items: How many items the shard ran.
51 """
52
53 shard: str
54 leg: str
55 job: str
56 items: int
57
58
59@dataclass(frozen=True)
60class FoldFacts:
61 """The fold's record on a platform's check row: what its shards partitioned.
62
63 Attributes:
64 count: How many shards the platform ran as.
65 digest: The digest of the set the shards partitioned.
66 rows: The durations rows the shards partitioned by, newest
67 first; empty when no row was there to read.
68 shards: Each shard, in order.
69 """
70
71 count: int
72 digest: str
73 rows: tuple[str, ...]
74 shards: tuple[ShardFacts, ...]
75
76
77@dataclass(frozen=True)
78class LegFacts:
79 """One job's half of a run's metrics row: what its gate ran.
80
81 Attributes:
82 job: The job's name, as the forge lists it.
83 scope: What the leg's gate ran: ``full``, ``affected``,
84 ``nothing``, ``verified``, or ``unknown`` when the leg
85 left no marker.
86 packages: The suites a narrowed gate ran.
87 base_tree: The tree a narrowed gate measured from; empty
88 otherwise.
89 leg: The leg's label, the key of its coverage record
90 (``check-ubuntu-latest-3.14``).
91 tasks: The tasks the job ran, by the names its trace recorded:
92 the top-level tasks and each task's steps.
93 shard: The shard whose own row this is (``1of2``), when the
94 gate job's fold did not fold it into its platform's row;
95 empty for a platform's row.
96 fold: What the fold recorded on a platform's row; ``None`` for
97 a leg that ran as one shard of one.
98 """
99
100 job: str
101 scope: str
102 packages: tuple[str, ...]
103 base_tree: str
104 leg: str
105 tasks: tuple[str, ...]
106 shard: str = ""
107 fold: FoldFacts | None = None
108
109
110@dataclass(frozen=True)
111class RunFacts:
112 """A run's metrics row, read for a proof.
113
114 Attributes:
115 run: The run's id.
116 jobs: Each job's facts, by the job's name; the forge's rows of
117 a platform's shards are not among them.
118 coverage: The coverage section the gate job left: the percent
119 each unit was judged at, by the unit's path; empty when
120 the gate job judged nothing.
121 shard_jobs: The names of the forge's rows of a platform's
122 shards, kept beside the fold's row with their times alone.
123 """
124
125 run: str
126 jobs: dict[str, LegFacts]
127 coverage: dict[str, float]
128 shard_jobs: tuple[str, ...] = ()
129
130 def job(self, prefix: str) -> LegFacts:
131 """The one job whose name starts with *prefix*; fails naming the row.
132
133 The answer is the leg's own row: for a platform that ran as
134 shards, the fold's, never the forge's row of a shard. A row
135 that is one shard's own, or shard rows with no fold's row
136 among them, say the gate job's fold did not run, and the
137 answer fails naming them.
138 """
139 found = [facts for name, facts in self.jobs.items() if name.startswith(prefix)]
140 shards = [name for name in self.shard_jobs if name.startswith(prefix)]
141 if shards and not found:
142 fail(
143 f"run {self.run}: {_metrics.SERIES.ref}'s row names"
144 f" {', '.join(shards)} and no folded row of their platform; the"
145 " gate job's fold did not run"
146 )
147 own = [f"{facts.job} ({facts.shard})" for facts in found if facts.shard]
148 if own:
149 fail(
150 f"run {self.run}: {_metrics.SERIES.ref}'s row holds"
151 f" {', '.join(own)}, one shard's own row each, not the platform's;"
152 " the gate job's fold did not run"
153 )
154 if len(found) != 1:
155 fail(
156 f"run {self.run}: {_metrics.SERIES.ref}'s row names"
157 f" {len(found)} job(s) starting with {prefix!r}, expected one:"
158 f" {', '.join(sorted(self.jobs))}"
159 )
160 return found[0]
161
162
163def run_facts(root: Path, run_id: int | str) -> RunFacts:
164 """The metrics row of *run_id*, fetched fresh from the newborn's origin.
165
166 Fails naming the series and the file when the row is not there:
167 the gate job's collect did not write it.
168 """
169 store = state_store(root)
170 name = _metrics.run_file(str(run_id))
171 with git.remote_snapshot(store, fetch=(_metrics.SERIES.name,)):
172 found = _metrics.SERIES.rows(store, only=lambda file: file == name)
173 if found.failed:173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true
174 fail(f"run {run_id}: {_metrics.SERIES.ref} could not be read: {found.reason}")
175 row = next((item for item in found.rows if item.name == name), None)
176 if row is None:
177 fail(
178 f"run {run_id}: no row {name} on {_metrics.SERIES.ref}; the gate job's"
179 " collect did not write the run's row"
180 )
181 jobs: dict[str, LegFacts] = {}
182 shard_jobs: list[str] = []
183 for job, data in dict(row.data.get("jobs") or {}).items():
184 if forge_shard_row(str(job), data):
185 shard_jobs.append(str(job))
186 continue
187 scope = data.get("scope") or {}
188 tasks = (*data.get("tasks", {}), *data.get("task_steps", {}))
189 leg = str(scope.get("leg") or "")
190 own, fold = _shard_facts(leg, data.get("shard"))
191 jobs[str(job)] = LegFacts(
192 job=str(job),
193 scope=str(scope.get("scope", "unknown")),
194 packages=tuple(str(p) for p in scope.get("packages") or ()),
195 base_tree=str(scope.get("base_tree") or ""),
196 leg=leg,
197 tasks=tuple(str(t) for t in tasks),
198 shard=own,
199 fold=fold,
200 )
201 section = (row.data.get("sections") or {}).get("coverage") or {}
202 coverage = {
203 str(path): float(value)
204 for path, value in dict(section.get("packages") or {}).items()
205 }
206 return RunFacts(str(run_id), jobs, coverage, tuple(shard_jobs))
207
208
209def _shard_facts(leg: str, shard: Any) -> tuple[str, FoldFacts | None]:
210 """The row's shard: its own, when it is one shard's row, or the fold's record.
211
212 A row whose ``shard`` lists ``shards`` is the fold's; one whose
213 ``shard`` is a shard's own record, or whose leg label ends in a
214 shard, is one shard's row the fold did not fold.
215 """
216 if isinstance(shard, dict) and "shards" in shard:
217 listed: Any = shard.get("shards")
218 entries = tuple(
219 ShardFacts(
220 str(item.get("shard") or ""),
221 str(item.get("leg") or ""),
222 str(item.get("job") or ""),
223 int(item.get("items") or 0),
224 )
225 for item in (listed if isinstance(listed, list) else [])
226 if isinstance(item, dict)
227 )
228 return "", FoldFacts(
229 int(shard.get("count") or 0),
230 str(shard.get("digest") or ""),
231 tuple(str(name) for name in shard.get("rows") or ()),
232 entries,
233 )
234 if isinstance(shard, dict):
235 return str(shard.get("shard") or ""), None
236 try:
237 own = _shard.shard_of(leg)
238 except ValueError:
239 return "", None
240 return ("" if own == _shard.ONE else str(own)), None
241
242
243@dataclass(frozen=True)
244class DurationsRow:
245 """What a platform leg's durations series holds for one run.
246
247 Attributes:
248 ref: The series' ref, ``durations/<platform leg>`` under the
249 store's namespace.
250 name: The row's file name, the run's.
251 items: The seconds per item the row holds; ``None`` when the
252 series holds no row of the run.
253 """
254
255 ref: str
256 name: str
257 items: dict[str, float] | None
258
259
260def durations_row(root: Path, run_id: int | str, leg: str) -> DurationsRow:
261 """The durations row *run_id*'s gate job wrote on *leg*'s platform, fetched fresh.
262
263 The series is the platform leg's ([livery.workshop.platform_leg][]),
264 so a shard's label reads its platform's. Fails naming the series
265 when it cannot be read; a series without the run's row answers
266 ``items`` as ``None``.
267 """
268 series = _shard.DURATIONS.series(_shard.platform_leg(leg))
269 name = _metrics.run_file(str(run_id))
270 store = state_store(root)
271 with git.remote_snapshot(store, fetch=(series.name,)):
272 found = series.rows(store, only=name.__eq__)
273 if found.failed:
274 fail(f"run {run_id}: {series.ref} could not be read: {found.reason}")
275 row = next((item for item in found.rows if item.name == name), None)
276 if row is None:
277 return DurationsRow(series.ref, name, None)
278 items = {
279 str(each): float(seconds)
280 for each, seconds in dict(row.data.get("items") or {}).items()
281 if isinstance(seconds, int | float) and not isinstance(seconds, bool)
282 }
283 return DurationsRow(series.ref, name, items)
284
285
286def proved_by(
287 root: Path, run_id: int | str
288) -> tuple[tuple[str, str, _proved.UnitRow, _proved.ReadSetEntry], ...]:
289 """The proved unit rows written by *run_id*; fails naming the store when none."""
290 rows, why = _proved.rows_for_run(root, str(run_id))
291 if why:291 ↛ 292line 291 didn't jump to line 292 because the condition on line 291 was never true
292 fail(f"run {run_id}: {_proved.FAMILY.prefix}* could not be read: {why}")
293 if not rows:
294 fail(
295 f"run {run_id}: no row under {_proved.FAMILY.prefix}* names it;"
296 " the check leg did not write proved rows"
297 )
298 return rows
299
300
301def proved_branch(root: Path) -> str:
302 """The pull request branch whose proved rows cover *root*'s tree; fails if none."""
303 found = _scope.verified_branch(root)
304 if found.reason:304 ↛ 305line 304 didn't jump to line 305 because the condition on line 304 was never true
305 fail(f"proved branch could not be read: {found.reason}")
306 if not found.branch:
307 fail(f"no pull request branch under {_proved.FAMILY.prefix}* proves this tree")
308 return found.branch
309
310
311@dataclass(frozen=True)
312class UnitRow:
313 """One unit of a base's coverage record: the run that measured it.
314
315 Attributes:
316 unit: The unit's path (``packages/loop-echo``, or ``tests``).
317 run: The run that measured it.
318 sha: The commit that run checked out.
319 closure: The closure identity the measurement is keyed by.
320 """
321
322 unit: str
323 run: str
324 sha: str
325 closure: str
326
327
328def record_units(root: Path, base: str, leg: str) -> dict[str, UnitRow]:
329 """*base*'s coverage record on *leg*: the current row of each unit, by path.
330
331 A current row is named by its unit's slug alone; a kept row, named
332 by its moment and closure as well, and a fixed-facts file under
333 ``facts/`` are not units of the record. The rows are read raw and
334 four fields taken, so the loop carries neither the coverage
335 extension's schema number nor its parser. Fails naming the ref when
336 it cannot be read; an absent record is empty.
337 """
338 series = COVERAGE_RECORD.series(base, leg)
339 store = state_store(root)
340
341 def current(name: str) -> bool:
342 return name.count(".") == 1 and "/" not in name
343
344 with git.remote_snapshot(store, fetch=(series.name,)):
345 found = git.read(store, series.ref, only=current)
346 if found.failed:346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true
347 fail(f"{series.ref} could not be read: {found.reason}")
348 units: dict[str, UnitRow] = {}
349 for _name, text in sorted((found.files or {}).items()):
350 try:
351 data = json.loads(text)
352 except ValueError:
353 continue
354 if not isinstance(data, dict):354 ↛ 355line 354 didn't jump to line 355 because the condition on line 354 was never true
355 continue
356 unit = str(data.get("unit") or "")
357 if unit:357 ↛ 349line 357 didn't jump to line 349 because the condition on line 357 was always true
358 units[unit] = UnitRow(
359 unit,
360 str(data.get("run") or ""),
361 str(data.get("sha") or ""),
362 str(data.get("closure") or ""),
363 )
364 return units
365
366
367@dataclass(frozen=True)
368class MarkRow:
369 """A package's current coverage mark: the newest row that set it.
370
371 Attributes:
372 package: The package path.
373 value: The mark, in percent.
374 kind: ``first``, ``ratchet`` or ``accept``.
375 by: The run id or the person that wrote the row.
376 """
377
378 package: str
379 value: float
380 kind: str
381 by: str
382
383
384def marks(root: Path) -> dict[str, MarkRow]:
385 """The current mark per package, the newest row each; fails when unreadable."""
386 store = state_store(root)
387 with git.remote_snapshot(store, fetch=(COVERAGE_MARKS.name,)):
388 found = COVERAGE_MARKS.rows(store)
389 if found.failed:389 ↛ 390line 389 didn't jump to line 390 because the condition on line 389 was never true
390 fail(f"{COVERAGE_MARKS.ref} could not be read: {found.reason}")
391 current: dict[str, MarkRow] = {}
392 for row in found.rows:
393 data: dict[str, Any] = row.data
394 package = str(data.get("package") or "")
395 if not package or package in current:
396 continue
397 try:
398 value = float(data["value"])
399 except (KeyError, TypeError, ValueError):
400 continue
401 current[package] = MarkRow(
402 package, value, str(data.get("kind") or ""), str(data.get("by") or "")
403 )
404 return current