Coverage for packages/workshop/src/livery/workshop/_store_tasks.py: 88%

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_store_tasks.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_proved_shadow.py, packages/workshop/tests/test_workshop_proved_flaky.py, packages/workshop/tests/test_workshop_proved_escapes.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/extensions/pytest/tests/test_pytest_observer_shadow.py, packages/extensions/docs/tests/test_task_links.py ran.

1"""``fm store.ls`` and ``fm store.show``: the state store, read by hand.
2
3Every row the workshop keeps is a declared series of the state store
4([livery.git][]), gathered in one place
5([livery.workshop._series][]). ``store.ls`` names each series and
6family with its scope (local, or remote and mirrored by a sync, or
7remote and fetched on read), its window, and what it holds; ``store.show``
8prints a series' rows newest first through the same reader the
9verdicts use, so what a person reads is what the gate judged. Both
10only read: the gate's verbs write, and the janitor bounds.
11"""
12
13from __future__ import annotations
14
15import json as _json
16from pathlib import Path
17from typing import Annotated, Any
18
19from livery import git
20from livery.footman import doc, fail, group
21from livery.workshop._ci_context import state_store
22from livery.workshop._extensions import workspace_root
23
24store = group("store", help="The state store, read by hand")
25
26
27def _root() -> Path:
28 root = workspace_root()
29 if root is None:
30 fail("no workspace: no workshop.toml above the working directory")
31 return root
32
33
34def _declared(root: Path) -> tuple[git.Series | git.Keyed, ...]:
35 from livery.workshop._series import declared
36
37 return declared(root)
38
39
40def _scope(item: git.Series | git.Keyed) -> str:
41 """Where *item* lives, how a desk reads it, and its window."""
42 from livery.workshop._series import mirrored
43
44 window = "no window" if item.window is None else f"window {item.window}"
45 if item.local:
46 where = "local"
47 elif mirrored(item):
48 where = "remote, mirrored by sync"
49 else:
50 where = "remote, fetched on read"
51 return f"{where}, {window}"
52
53
54def ls_flow(root: Path) -> list[str]:
55 """One line per declared series or family: scope, window, and what it holds.
56
57 One listing of the remote namespace and one fetch of what the
58 checkout lacks serve every series, so the call costs two round
59 trips whatever the store holds.
60 """
61 with git.remote_snapshot(state_store(root), fetch=git.WHOLE):
62 return _ls_lines(root)
63
64
65def _ls_lines(root: Path) -> list[str]:
66 lines: list[str] = []
67 for item in _declared(root):
68 if isinstance(item, git.Series):
69 found = item.rows(state_store(root))
70 if found.failed:
71 held = found.reason
72 else:
73 held = f"{len(found.rows)} row(s)"
74 if found.skipped:74 ↛ 75line 74 didn't jump to line 75 because the condition on line 74 was never true
75 held += f", {len(found.skipped)} skipped"
76 lines.append(f" {item.name}: {_scope(item)}; {held}")
77 continue
78 keys = item.listed(state_store(root))
79 held = "could not be listed" if keys is None else f"{len(keys)} key(s)"
80 spelled = "/".join(f"<{part}>" for part in item.keys)
81 lines.append(f" {item.name}/{spelled}: {_scope(item)}; {held}")
82 return lines
83
84
85def _compact(fields: dict[str, Any]) -> str:
86 """The row's fields on one line: scalars as they are, containers by size."""
87 parts: list[str] = []
88 for name, value in sorted(fields.items()):
89 if isinstance(value, dict):
90 parts.append(f"{name}: {{{len(value)} entries}}")
91 elif isinstance(value, list):91 ↛ 92line 91 didn't jump to line 92 because the condition on line 91 was never true
92 parts.append(f"{name}: [{len(value)} items]")
93 else:
94 parts.append(f"{name}: {value}")
95 return ", ".join(parts)
96
97
98def _select_row(rows: tuple[git.Row, ...], name: str, ref: str) -> git.Row:
99 """Pick one row of *ref* by exact *name* or unique prefix, or refuse."""
100 exact = [entry for entry in rows if entry.name == name]
101 if exact:
102 return exact[0]
103 prefix = [entry for entry in rows if entry.name.startswith(name)]
104 if len(prefix) == 1:
105 return prefix[0]
106 if len(prefix) > 1:
107 sample = ", ".join(entry.name for entry in prefix[:5])
108 fail(f"{name!r} matches {len(prefix)} rows in {ref}: {sample}")
109 newest = ", ".join(entry.name for entry in rows[:5])
110 hint = f"; newest: {newest}" if newest else " (series is empty)"
111 fail(f"no row matching {name!r} in {ref}{hint}")
112
113
114def show_flow(
115 root: Path,
116 name: str,
117 *,
118 key: str = "",
119 row: str = "",
120 run: str = "",
121 item: str = "",
122 differences: bool = False,
123 flaky: bool = False,
124 escapes: bool = False,
125 limit: int = 0,
126 as_json: bool = False,
127) -> list[str]:
128 """A series' rows newest first, a single row in full, or the rows as JSON.
129
130 Refuses an unknown name (naming the known ones), a negative
131 *limit*, combining *row* and *limit*, a family without its key
132 (listing the keys it holds, unless *run*, *item* or *differences*
133 inspects the ``proved`` family), a key of the wrong shape, an unknown
134 or ambiguous *row*, and a series the store cannot read (with the
135 store's reason). Local series read directly from the checkout's git
136 directory; remote series go through one listing of the remote
137 namespace.
138 """
139 if limit < 0:
140 fail("limit must be non-negative")
141 if row and limit:
142 fail("cannot combine --row and --limit")
143 declared = _declared(root)
144 series_decl = next((each for each in declared if each.name == name), None)
145 if series_decl is None:
146 fail(
147 f"no series named {name!r}; the series are"
148 f" {', '.join(each.name for each in declared)}"
149 )
150 if run and name != "proved":150 ↛ 151line 150 didn't jump to line 151 because the condition on line 150 was never true
151 fail("--run applies only to the proved family")
152 if item and name != "proved":
153 fail("--item applies only to the proved family")
154 if differences and name != "proved":
155 fail("--differences applies only to the proved family")
156 if flaky and name != "proved":
157 fail("--flaky applies only to the proved family")
158 if escapes and name != "proved":
159 fail("--escapes applies only to the proved family")
160 if differences and (key or row or run or item or flaky or escapes):
161 fail(
162 "cannot combine --differences with --key, --row, --run, --item,"
163 " --flaky, or --escapes"
164 )
165 if flaky and (key or row or run or item or escapes):
166 fail("cannot combine --flaky with --key, --row, --run, --item, or --escapes")
167 if escapes and (key or row or run or item):
168 fail("cannot combine --escapes with --key, --row, --run, or --item")
169 if item and (key or row or run):
170 fail("cannot combine --item with --key, --row, or --run")
171 if differences:
172 from livery.workshop._proved import SHADOW_DIFFS
173
174 with git.remote_snapshot(state_store(root), fetch=(SHADOW_DIFFS.name,)):
175 return _show_proved_differences(root, limit=limit, as_json=as_json)
176 if flaky:
177 with git.remote_snapshot(state_store(root), fetch=(name,)):
178 return _show_proved_flaky(root, limit=limit, as_json=as_json)
179 if escapes:
180 from livery.workshop._proved import ESCAPES
181
182 with git.remote_snapshot(state_store(root), fetch=(ESCAPES.name,)):
183 return _show_proved_escapes(root, limit=limit, as_json=as_json)
184 if item:
185 with git.remote_snapshot(state_store(root), fetch=(name,)):
186 return _show_proved_item(root, item, limit=limit, as_json=as_json)
187 if name == "measures" and not row and not key:
188 with git.remote_snapshot(state_store(root), fetch=(name,)):
189 return _show_measures(root, limit=limit, as_json=as_json)
190 if series_decl.local:
191 return _show_item(
192 root,
193 series_decl,
194 key=key,
195 row=row,
196 run=run,
197 limit=limit,
198 as_json=as_json,
199 )
200 with git.remote_snapshot(state_store(root), fetch=(name,)):
201 return _show_item(
202 root,
203 series_decl,
204 key=key,
205 row=row,
206 run=run,
207 limit=limit,
208 as_json=as_json,
209 )
210
211
212def _show_proved_escapes(root: Path, *, limit: int, as_json: bool) -> list[str]:
213 """Format recorded selection escapes caught by scheduled full runs."""
214 from livery.workshop._proved import read_escapes
215
216 found, why = read_escapes(root, limit=limit)
217 if why:217 ↛ 218line 217 didn't jump to line 218 because the condition on line 217 was never true
218 fail(why)
219 if as_json:
220 return [_json.dumps([e.to_dict() for e in found], indent=1, sort_keys=True)]
221 if not found:
222 return [" proved: no escapes recorded"]
223 lines = [f" proved (escapes): {len(found)} record(s)"]
224 for esc in found:
225 changed = ", ".join(esc.changed_files[:5]) or "(unknown)"
226 if len(esc.changed_files) > 5:226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 changed += f", +{len(esc.changed_files) - 5} more"
228 lines.append(
229 f" {esc.unit} [{esc.leg}] package={esc.package}"
230 f" changed={changed} {esc.when or '(unstamped)'}"
231 )
232 return lines
233
234
235def _show_proved_flaky(root: Path, *, limit: int, as_json: bool) -> list[str]:
236 """Format flagged flaky unit entries across proved refs."""
237 from livery.workshop._proved import GREEN, RED, flaky_units
238
239 matched, why = flaky_units(root)
240 if why:240 ↛ 241line 240 didn't jump to line 241 because the condition on line 240 was never true
241 fail(why)
242 selected = matched[:limit] if limit else matched
243 if as_json:
244 payload = [
245 {
246 "base": base,
247 "leg": leg,
248 "platform": unit_row.platform.to_dict(),
249 "step": unit_row.step,
250 "target": unit_row.target,
251 "unit": unit_row.unit,
252 **entry.to_dict(),
253 }
254 for base, leg, unit_row, entry in selected
255 ]
256 return [_json.dumps(payload, indent=1, sort_keys=True)]
257 if not selected:
258 return [" proved: no flaky units recorded"]
259 lines = [f" proved (flaky): {len(selected)} record(s)"]
260 for base, leg, unit_row, entry in selected:
261 greens = entry.counts.get(GREEN, 0)
262 reds = entry.counts.get(RED, 0)
263 lines.append(
264 f" {unit_row.unit} [{base}/{leg}] [flaky] green={greens} red={reds}"
265 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
266 )
267 return lines
268
269
270def _show_proved_item(
271 root: Path, item_path: str, *, limit: int, as_json: bool
272) -> list[str]:
273 """Format recorded reads for one test *item_path* across proved refs."""
274 from livery.workshop._proved import item_read_details
275
276 matched, why = item_read_details(root, item_path)
277 if why:277 ↛ 278line 277 didn't jump to line 278 because the condition on line 277 was never true
278 fail(why)
279 selected = matched[:limit] if limit else matched
280 if as_json:
281 payload = [
282 {
283 "base": base,
284 "leg": leg,
285 "platform": unit_row.platform.to_dict(),
286 "reads": decoded.to_dict() if decoded is not None else None,
287 "step": unit_row.step,
288 "target": unit_row.target,
289 "unit": unit_row.unit,
290 **entry.to_dict(),
291 }
292 for base, leg, unit_row, entry, decoded in selected
293 ]
294 return [_json.dumps(payload, indent=1, sort_keys=True)]
295 if not selected:295 ↛ 296line 295 didn't jump to line 296 because the condition on line 295 was never true
296 return [f" proved: no rows for item {item_path}"]
297 lines = [f" proved (item {item_path}): {len(selected)} record(s)"]
298 for base, leg, unit_row, entry, decoded in selected:
299 flaky = " [flaky]" if entry.flaky else ""
300 lines.append(
301 f" {unit_row.unit} [{base}/{leg}] {entry.verdict}{flaky}"
302 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
303 )
304 if decoded is None:304 ↛ 305line 304 didn't jump to line 305 because the condition on line 304 was never true
305 lines.append(" reads: (none recorded)")
306 continue
307 if decoded.unrecorded:307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true
308 lines.append(" unrecorded: child lost observer hook")
309 lines.append(f" files ({len(decoded.files)}):")
310 for path in sorted(decoded.files):
311 lines.append(f" {path}")
312 if decoded.absent:312 ↛ 316line 312 didn't jump to line 316 because the condition on line 312 was always true
313 lines.append(f" absent ({len(decoded.absent)}):")
314 for path in decoded.absent:
315 lines.append(f" {path}")
316 if decoded.dirs:316 ↛ 320line 316 didn't jump to line 320 because the condition on line 316 was always true
317 lines.append(f" dirs ({len(decoded.dirs)}):")
318 for path in sorted(decoded.dirs):
319 lines.append(f" {path}")
320 if decoded.dists:320 ↛ 324line 320 didn't jump to line 324 because the condition on line 320 was always true
321 lines.append(f" dists ({len(decoded.dists)}):")
322 for dist, ver in sorted(decoded.dists.items()):
323 lines.append(f" {dist}=={ver}")
324 if decoded.native_tools:324 ↛ 325line 324 didn't jump to line 325 because the condition on line 324 was never true
325 lines.append(f" native-tools: {', '.join(decoded.native_tools)}")
326 return lines
327
328
329def _show_measures(root: Path, *, limit: int, as_json: bool) -> list[str]:
330 """Format recorded ``measures`` rows (including ``selected`` share per run)."""
331 from livery.workshop._proved import read_measures
332
333 rows, why = read_measures(root, limit=limit)
334 if why:334 ↛ 335line 334 didn't jump to line 335 because the condition on line 334 was never true
335 fail(why)
336 if as_json:
337 return [_json.dumps(list(rows), indent=1, sort_keys=True)]
338 if not rows:
339 return [" measures: no rows recorded yet"]
340 selected_rows = [r for r in rows if r.get("measure") == "selected"]
341 summary = f" measures: {len(rows)} row(s)"
342 if selected_rows:342 ↛ 356line 342 didn't jump to line 356 because the condition on line 342 was always true
343 mean_items = (
344 sum(float(r.get("items-ratio", 0.0)) for r in selected_rows)
345 / len(selected_rows)
346 * 100.0
347 )
348 mean_secs = (
349 sum(float(r.get("seconds-ratio", 0.0)) for r in selected_rows)
350 / len(selected_rows)
351 * 100.0
352 )
353 summary += (
354 f" (selected mean: {mean_items:.1f}% items, {mean_secs:.1f}% test seconds)"
355 )
356 lines = [summary]
357 for entry in rows:
358 run_id = entry.get("run", "")
359 leg = entry.get("leg", "")
360 branch = entry.get("branch", "")
361 when = entry.get("when", "")
362 if entry.get("measure") == "selected":362 ↛ 375line 362 didn't jump to line 375 because the condition on line 362 was always true
363 i_sel = entry.get("items-selected", 0)
364 i_tot = entry.get("items-total", 0)
365 i_pct = float(entry.get("items-ratio", 0.0)) * 100.0
366 s_sel = float(entry.get("seconds-selected", 0.0))
367 s_tot = float(entry.get("seconds-total", 0.0))
368 s_pct = float(entry.get("seconds-ratio", 0.0)) * 100.0
369 lines.append(
370 f" run={run_id} {leg}"
371 f" selected: {i_sel}/{i_tot} items ({i_pct:.1f}%),"
372 f" {s_sel:.1f}/{s_tot:.1f}s ({s_pct:.1f}%) [{branch}] {when}"
373 )
374 else:
375 lines.append(f" run={run_id} {leg} {_compact(entry)}")
376 return lines
377
378
379def _show_proved_differences(root: Path, *, limit: int, as_json: bool) -> list[str]:
380 """Format recorded shadow differences across CI runs."""
381 from livery.workshop._proved import read_shadow_differences
382
383 total, rows, why = read_shadow_differences(root, limit=limit)
384 if why:384 ↛ 385line 384 didn't jump to line 385 because the condition on line 384 was never true
385 fail(why)
386 if as_json:
387 return [_json.dumps(list(rows), indent=1, sort_keys=True)]
388 if total == 0:
389 return [" proved: no shadow runs recorded yet"]
390 if not rows:
391 return [f" proved: 0 differences across {total} run(s)"]
392 lines = [
393 f" proved: {len(rows)} run(s) with differences (of {total} shadow run(s))"
394 ]
395 for entry in rows:
396 diffs = entry.get("differences") or []
397 lines.append(
398 f" run {entry.get('run', '?')} [{entry.get('leg', '?')}]"
399 f" branch={entry.get('branch', '?')}"
400 f" {len(diffs)} difference(s) {entry.get('when', '(unstamped)')}"
401 )
402 for diff in diffs:
403 if not isinstance(diff, dict):403 ↛ 404line 403 didn't jump to line 404 because the condition on line 403 was never true
404 continue
405 lines.append(
406 f" {diff.get('unit', '?')}: today={diff.get('today', '?')},"
407 f" proved={diff.get('proved', '?')} ({diff.get('reason', '')})"
408 )
409 return lines
410
411
412def _show_proved_run(
413 root: Path, run_id: str, *, limit: int, as_json: bool
414) -> list[str]:
415 """Format every proved unit entry written by *run_id* across legs."""
416 from livery.workshop._proved import rows_for_run
417
418 matched, why = rows_for_run(root, run_id)
419 if why:419 ↛ 420line 419 didn't jump to line 420 because the condition on line 419 was never true
420 fail(why)
421 selected = matched[:limit] if limit else matched
422 if as_json:
423 payload = [
424 {
425 "base": base,
426 "leg": leg,
427 "platform": unit_row.platform.to_dict(),
428 "step": unit_row.step,
429 "target": unit_row.target,
430 "unit": unit_row.unit,
431 **entry.to_dict(),
432 }
433 for base, leg, unit_row, entry in selected
434 ]
435 return [_json.dumps(payload, indent=1, sort_keys=True)]
436 if not selected:436 ↛ 437line 436 didn't jump to line 437 because the condition on line 436 was never true
437 return [f" proved: no rows for run {run_id}"]
438 header = (
439 f" proved (run {run_id}): showing {len(selected)} of {len(matched)} row(s)"
440 if limit and len(selected) < len(matched)
441 else f" proved (run {run_id}): {len(matched)} row(s)"
442 )
443 lines = [header]
444 for base, leg, unit_row, entry in selected:
445 flaky = " [flaky]" if entry.flaky else ""
446 lines.append(
447 f" {unit_row.unit} [{base}/{leg}] {entry.verdict}{flaky}"
448 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
449 )
450 return lines
451
452
453def _show_item(
454 root: Path,
455 item: git.Series | git.Keyed,
456 *,
457 key: str = "",
458 row: str = "",
459 run: str = "",
460 limit: int = 0,
461 as_json: bool = False,
462) -> list[str]:
463 if run and item.name == "proved":
464 return _show_proved_run(root, run, limit=limit, as_json=as_json)
465 parts = tuple(part for part in key.split(",") if part) if key else ()
466 if isinstance(item, git.Keyed):
467 if not parts:
468 if row:
469 fail(f"{item.name} is keyed; pass --key with --row")
470 keys = item.listed(state_store(root))
471 if keys is None:471 ↛ 472line 471 didn't jump to line 472 because the condition on line 471 was never true
472 fail(f"{item.name}: its keys could not be listed")
473 spelled = ",".join(f"<{part}>" for part in item.keys)
474 lines = [f" {item.name} is keyed; --key={spelled} picks one of:"]
475 lines += [f" {','.join(found)}" for found in keys] or [" (none yet)"]
476 return lines
477 if len(parts) != len(item.keys):
478 fail(
479 f"{item.name} is keyed by {', '.join(item.keys)}; --key names"
480 f" {len(parts)} part(s)"
481 )
482 series = item.at(*parts)
483 elif parts:
484 fail(f"{item.name} is not keyed; drop --key")
485 else:
486 series = item
487 found = series.rows(state_store(root))
488 if found.failed:
489 fail(found.reason)
490 if row:
491 matched = _select_row(found.rows, row, series.ref)
492 return [
493 _json.dumps(
494 {"name": matched.name, **matched.data}, indent=1, sort_keys=True
495 )
496 ]
497 selected = found.rows[:limit] if limit else found.rows
498 if as_json:
499 rows = [{"name": entry.name, **entry.data} for entry in selected]
500 return [_json.dumps(rows, indent=1, sort_keys=True)]
501 if limit and len(selected) < len(found.rows):
502 header = f" {series.ref}: showing {len(selected)} of {len(found.rows)} row(s)"
503 else:
504 header = f" {series.ref}: {len(found.rows)} row(s)"
505 lines = [header]
506 for entry in selected:
507 fields = {k: v for k, v in entry.data.items() if k not in ("schema", "when")}
508 lines.append(f" {entry.name} {entry.when or '(unstamped)'}")
509 lines.append(f" {_compact(fields)}")
510 lines.extend(f" {skipped}" for skipped in found.skipped)
511 return lines
512
513
514@store.task(name="ls")
515def store_ls() -> None:
516 """List every series the workshop keeps: its scope, its window, what it holds.
517
518 A remote series is read from origin, a local one from this
519 checkout's git directory; a series that cannot be read prints the
520 store's reason in its place.
521 """
522 for line in ls_flow(_root()):
523 print(line)
524
525
526@store.task(name="show")
527def store_show(
528 series: Annotated[str, doc("the series' name, as store.ls lists it")],
529 key: Annotated[str, doc("a family's key, its parts comma-separated")] = "",
530 row: Annotated[str, doc("one row by name or unique prefix, printed in full")] = "",
531 run: Annotated[str, doc("filter proved rows to one forge run id")] = "",
532 item: Annotated[str, doc("show recorded reads for one proved test item path")] = "",
533 differences: Annotated[
534 bool, doc("list shadow comparison differences for the proved family")
535 ] = False,
536 flaky: Annotated[
537 bool, doc("list units flagged flaky (both green and red on one fingerprint)")
538 ] = False,
539 escapes: Annotated[
540 bool, doc("list selection escapes caught on scheduled audit runs")
541 ] = False,
542 limit: Annotated[int, doc("maximum number of newest rows to show (0 for all)")] = 0,
543 json: Annotated[bool, doc("the rows as JSON, newest first")] = False,
544) -> None:
545 """Print a series' rows newest first, through the reader the verdicts use.
546
547 Each row prints as its file name and stamp, then its fields on one
548 line with containers by size; ``--row`` prints one row in full as
549 JSON (by exact name or unique prefix, as the ``diagnostics:`` line
550 names it), ``--run`` lists every row written by one run in the
551 ``proved`` family, ``--item`` lists what one test item read in the
552 ``proved`` family, ``--differences`` lists shadow comparison
553 disagreements recorded for the ``proved`` family, ``--flaky`` lists
554 units flagged flaky in the ``proved`` family, ``--escapes`` lists
555 selection escapes recorded for the ``proved`` family, ``--limit``
556 caps how many newest rows print, and ``--json`` prints every
557 selected row as JSON. A family (``store.ls`` shows its key parts) is
558 shown one key at a time, and without ``--key`` lists the keys it
559 holds.
560 """
561 for line in show_flow(
562 _root(),
563 series,
564 key=key,
565 row=row,
566 run=run,
567 item=item,
568 differences=differences,
569 flaky=flaky,
570 escapes=escapes,
571 limit=limit,
572 as_json=json,
573 ):
574 print(line)