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.
Keys
- r m x p show or hide the lines of a kind
- j k the next or previous highlighted chunk
- 0 the top of the page
- 1 the first highlighted chunk
- [ ] the previous or next file
- u the index
- ? show or hide this help
1"""``fm store.ls`` and ``fm store.show``: the state store, read by hand.
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.
13from __future__ import annotations
15import json as _json
16from pathlib import Path
17from typing import Annotated, Any
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
24store = group("store", help="The state store, read by hand")
27def _root() -> Path:
28 root = workspace_root()
30 fail("no workspace: no workshop.toml above the working directory")
34def _declared(root: Path) -> tuple[git.Series | git.Keyed, ...]:
35 from livery.workshop._series import declared
37 return declared(root)
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
44 window = "no window" if item.window is None else f"window {item.window}"
47 elif mirrored(item):
48 where = "remote, mirrored by sync"
50 where = "remote, fetched on read"
51 return f"{where}, {window}"
54def ls_flow(root: Path) -> list[str]:
55 """One line per declared series or family: scope, window, and what it holds.
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.
61 with git.remote_snapshot(state_store(root), fetch=git.WHOLE):
62 return _ls_lines(root)
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))
71 held = found.reason
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}")
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}")
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]")
94 parts.append(f"{name}: {value}")
95 return ", ".join(parts)
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]
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}")
122 differences: bool = False,
124 escapes: bool = False,
126 as_json: bool = False,
128 """A series' rows newest first, a single row in full, or the rows as JSON.
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
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:
147 f"no series named {name!r}; the series are"
148 f" {', '.join(each.name for each in declared)}"
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):
162 "cannot combine --differences with --key, --row, --run, --item,"
163 " --flaky, or --escapes"
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
174 with git.remote_snapshot(state_store(root), fetch=(SHADOW_DIFFS.name,)):
175 return _show_proved_differences(root, limit=limit, as_json=as_json)
177 with git.remote_snapshot(state_store(root), fetch=(name,)):
178 return _show_proved_flaky(root, limit=limit, as_json=as_json)
180 from livery.workshop._proved import ESCAPES
182 with git.remote_snapshot(state_store(root), fetch=(ESCAPES.name,)):
183 return _show_proved_escapes(root, limit=limit, as_json=as_json)
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(
200 with git.remote_snapshot(state_store(root), fetch=(name,)):
201 return _show_item(
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
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
220 return [_json.dumps([e.to_dict() for e in found], indent=1, sort_keys=True)]
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"
229 f" {esc.unit} [{esc.leg}] package={esc.package}"
230 f" changed={changed} {esc.when or '(unstamped)'}"
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
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
242 selected = matched[:limit] if limit else matched
248 "platform": unit_row.platform.to_dict(),
249 "step": unit_row.step,
250 "target": unit_row.target,
251 "unit": unit_row.unit,
254 for base, leg, unit_row, entry in selected
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)
264 f" {unit_row.unit} [{base}/{leg}] [flaky] green={greens} red={reds}"
265 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
270def _show_proved_item(
271 root: Path, item_path: str, *, limit: int, as_json: bool
273 """Format recorded reads for one test *item_path* across proved refs."""
274 from livery.workshop._proved import item_read_details
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
279 selected = matched[:limit] if limit else matched
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,
292 for base, leg, unit_row, entry, decoded in selected
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 ""
301 f" {unit_row.unit} [{base}/{leg}] {entry.verdict}{flaky}"
302 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
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)")
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)}")
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
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
337 return [_json.dumps(list(rows), indent=1, sort_keys=True)]
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
344 sum(float(r.get("items-ratio", 0.0)) for r in selected_rows)
349 sum(float(r.get("seconds-ratio", 0.0)) for r in selected_rows)
354 f" (selected mean: {mean_items:.1f}% items, {mean_secs:.1f}% test seconds)"
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
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}"
375 lines.append(f" run={run_id} {leg} {_compact(entry)}")
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
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
387 return [_json.dumps(list(rows), indent=1, sort_keys=True)]
389 return [" proved: no shadow runs recorded yet"]
391 return [f" proved: 0 differences across {total} run(s)"]
393 f" proved: {len(rows)} run(s) with differences (of {total} shadow run(s))"
395 for entry in rows:
396 diffs = entry.get("differences") or []
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)')}"
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
406 f" {diff.get('unit', '?')}: today={diff.get('today', '?')},"
407 f" proved={diff.get('proved', '?')} ({diff.get('reason', '')})"
412def _show_proved_run(
413 root: Path, run_id: str, *, limit: int, as_json: bool
415 """Format every proved unit entry written by *run_id* across legs."""
416 from livery.workshop._proved import rows_for_run
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
421 selected = matched[:limit] if limit else matched
427 "platform": unit_row.platform.to_dict(),
428 "step": unit_row.step,
429 "target": unit_row.target,
430 "unit": unit_row.unit,
433 for base, leg, unit_row, entry in selected
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}"]
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)"
443 lines = [header]
444 for base, leg, unit_row, entry in selected:
445 flaky = " [flaky]" if entry.flaky else ""
447 f" {unit_row.unit} [{base}/{leg}] {entry.verdict}{flaky}"
448 f" fp={entry.fingerprint[:12]} {entry.when or '(unstamped)'}"
455 item: git.Series | git.Keyed,
461 as_json: bool = False,
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):
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)"]
477 if len(parts) != len(item.keys):
479 f"{item.name} is keyed by {', '.join(item.keys)}; --key names"
480 f" {len(parts)} part(s)"
482 series = item.at(*parts)
484 fail(f"{item.name} is not keyed; drop --key")
487 found = series.rows(state_store(root))
488 if found.failed:
489 fail(found.reason)
491 matched = _select_row(found.rows, row, series.ref)
494 {"name": matched.name, **matched.data}, indent=1, sort_keys=True
497 selected = found.rows[:limit] if limit else found.rows
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)"
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)
514@store.task(name="ls")
515def store_ls() -> None:
516 """List every series the workshop keeps: its scope, its window, what it holds.
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.
522 for line in ls_flow(_root()):
526@store.task(name="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")
537 bool, doc("list units flagged flaky (both green and red on one fingerprint)")
540 bool, doc("list selection escapes caught on scheduled audit runs")
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,
545 """Print a series' rows newest first, through the reader the verdicts use.
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
561 for line in show_flow(
568 differences=differences,