Coverage for packages/workshop/src/livery/workshop/_diagnostics.py: 97%

Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop, packages/extensions/ty, packages/extensions/ruff, packages/extensions/python, packages/extensions/pytest, packages/extensions/pyrefly, packages/extensions/nanobind, packages/extensions/mypy, packages/extensions/mkdocstrings, packages/extensions/lfs, packages/extensions/docs, packages/extensions/cpp, packages/extensions/coverage, packages/extensions/conan, packages/extensions/cmake, packages/extensions/claude, packages/extensions/clang-tidy, packages/extensions/clang-format, packages/extensions/changelog, packages/extensions/basedpyright ran.

1"""Diagnostic bundles: the classifier's raw inputs, kept for reading.
2
3Every non-merged watch outcome writes one bundle as a row of a local
4series of the state store ([livery.git][]): in the
5checkout's git directory, never in its working tree (it would get
6committed) and never on the forge (it would get published). The
7premise: a predicate vector nobody has seen before IS an uncovered
8case, findable by reading bundles instead of waiting for it to bite
9again.
10
11Each section guards itself, so a token that cannot read one still
12yields the rest, and the section's own error is recorded as data;
13for a scope-poor token that error is itself the diagnosis.
14Structural fields only, no bodies, no tokens: a bundle is shareable.
15"""
16
17from __future__ import annotations
18
19from collections.abc import Callable
20from dataclasses import asdict
21from datetime import UTC, datetime
22from pathlib import Path
23from typing import Any
24
25from livery import git
26from livery.forge import Repository
27from livery.workshop._ci_context import state_store
28from livery.workshop._verdict import Verdict
29
30#: Bundle format version; bump on any structural change.
31SCHEMA = 1
32
33#: Newest bundles kept; the window drops the older ones on each write.
34KEEP = 20
35
36#: The bundles: a local series, one row per non-merged ending.
37SERIES = git.Series(
38 "diagnostics", window=KEEP, ci_only=False, local=True, schema=SCHEMA
39)
40
41
42def _safely(section: Callable[[], Any]) -> Any:
43 """A section's value, or its own error recorded as data."""
44 try:
45 return section()
46 except (Exception, SystemExit) as exc:
47 return {"error": f"{type(exc).__name__}: {exc}"}
48
49
50def gather_bundle(repo: Repository, verdict: Verdict, *, branch: str) -> dict[str, Any]:
51 """The bundle's content for one verdict on one branch."""
52
53 def _pr() -> Any:
54 pr = repo.pr.find_by_head(branch, state="all")
55 if pr is None:
56 return None
57 return {
58 "number": pr.number,
59 "state": pr.state,
60 "merged": pr.merged,
61 "head_sha": pr.head_sha,
62 "base_branch": pr.base_branch,
63 "author": pr.author,
64 }
65
66 def _protection() -> Any:
67 protection = repo.protection("main")
68 return None if protection is None else asdict(protection)
69
70 def _reviews() -> Any:
71 pr = repo.pr.find_by_head(branch, state="all")
72 if pr is None:
73 return []
74 return [asdict(review) for review in repo.pr.reviews(pr.number)]
75
76 def _schedule() -> Any:
77 pr = repo.pr.find_by_head(branch, state="all")
78 if pr is None:
79 return []
80 return [asdict(event) for event in repo.pr.schedule_events(pr.number)]
81
82 def _status() -> Any:
83 pr = repo.pr.find_by_head(branch, state="all")
84 if pr is None:
85 return None
86 status = repo.checks.status(pr.head_sha)
87 return {"state": status.state, "contexts": status.contexts}
88
89 return {
90 "branch": branch,
91 "verdict": {
92 "state": verdict.state,
93 "exit_code": verdict.exit_code,
94 "detail": verdict.detail,
95 "pr_number": verdict.pr_number,
96 },
97 "pull_request": _safely(_pr),
98 "protection": _safely(_protection),
99 "reviews": _safely(_reviews),
100 "schedule_events": _safely(_schedule),
101 "combined_status": _safely(_status),
102 }
103
104
105def record(
106 root: Path, repo: Repository, verdict: Verdict, *, branch: str
107) -> tuple[str, str]:
108 """Write one bundle as a row of the local series in *root*'s checkout.
109
110 Returns the row's name and ``""``, or ``""`` and why nothing was
111 written. Never raises: the verdict being recorded is the thing
112 worth seeing, and a failed recording must not take it down.
113 """
114 try:
115 stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
116 name = f"{stamp}-{branch.replace('/', '-')}-{verdict.state}"
117 why = SERIES.put(
118 state_store(root),
119 {name: gather_bundle(repo, verdict, branch=branch)},
120 message=f"diagnostics: {branch} {verdict.state}",
121 )
122 except (Exception, SystemExit) as exc:
123 return "", f"{type(exc).__name__}: {exc}"
124 return ("", why) if why else (name, "")