onelook 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
onelook/reporting.py ADDED
@@ -0,0 +1,376 @@
1
+ """The README report: a paragraph and a table per sealed set.
2
+
3
+ The report is a pure function of the ledger and the files on disk. It
4
+ contains no generation time, so ``onelook verify`` can regenerate it and
5
+ compare it with the copy in a README.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from ._errors import OnelookError
13
+ from .ledger import Ledger, SetStatus, set_status
14
+
15
+ CAVEAT = (
16
+ "onelook records which files and which code each run measured; it cannot "
17
+ "show that the set was unseen while the code was written."
18
+ )
19
+
20
+ _BLOCK_RE = re.compile(
21
+ r"<!-- onelook:begin (?P<name>[A-Za-z0-9._-]+) -->.*?<!-- onelook:end (?P=name) -->",
22
+ re.S,
23
+ )
24
+
25
+
26
+ def _plural(count: int, word: str) -> str:
27
+ return f"{count} {word}" + ("" if count == 1 else "s")
28
+
29
+
30
+ def _times(count: int) -> str:
31
+ return {0: "never", 1: "once", 2: "twice"}.get(count, f"{count} times")
32
+
33
+
34
+ def _short(digest: str | None) -> str:
35
+ return (digest or "")[:12]
36
+
37
+
38
+ def _date(timestamp: str | None) -> str:
39
+ return (timestamp or "")[:10]
40
+
41
+
42
+ def _ranges(numbers: list[int]) -> str:
43
+ """[2, 3, 4, 6] -> '2-4, 6'."""
44
+ parts = []
45
+ start = previous = None
46
+ for number in numbers + [None]:
47
+ if start is None:
48
+ start = previous = number
49
+ elif number is not None and number == previous + 1:
50
+ previous = number
51
+ else:
52
+ parts.append(str(start) if start == previous else f"{start}-{previous}")
53
+ start = previous = number
54
+ return ", ".join(parts)
55
+
56
+
57
+ def flatten(metrics: dict | None, prefix: str = "") -> dict:
58
+ """Flatten a metrics object to scalar values with dotted keys.
59
+
60
+ Lists are left out; nested objects are flattened.
61
+ """
62
+ out: dict = {}
63
+ for key, value in (metrics or {}).items():
64
+ name = prefix + str(key)
65
+ if isinstance(value, dict):
66
+ out.update(flatten(value, name + "."))
67
+ elif value is None or isinstance(value, (bool, int, float, str)):
68
+ out[name] = value
69
+ return out
70
+
71
+
72
+ def format_value(value) -> str:
73
+ if value is None:
74
+ return "-"
75
+ if isinstance(value, bool):
76
+ return "true" if value else "false"
77
+ if isinstance(value, float):
78
+ return format(value, ".4g")
79
+ return str(value)
80
+
81
+
82
+ def _metrics_phrase(run: dict) -> str | None:
83
+ flat = flatten(run.get("metrics"))
84
+ if not flat:
85
+ return None
86
+ return ", ".join(f"{key} {format_value(value)}" for key, value in flat.items())
87
+
88
+
89
+ def _run_summary(run: dict) -> dict:
90
+ return {
91
+ "run": run["run"],
92
+ "label": run["label"],
93
+ "status": run.get("status", "completed"),
94
+ "time": run["time"],
95
+ "exit_code": run["exit_code"],
96
+ "engine_fingerprint": run["engine_fingerprint"],
97
+ "engine_changed_since_blind": run["engine_changed_since_blind"],
98
+ "metrics": run.get("metrics"),
99
+ }
100
+
101
+
102
+ def _config_changed(run: dict, blind: dict) -> bool:
103
+ """Did this run use a different engine configuration from the blind run?"""
104
+ if "engine_config_changed_since_blind" in run:
105
+ return bool(run["engine_config_changed_since_blind"])
106
+ return run.get("engine_config") != blind.get("engine_config")
107
+
108
+
109
+ def _engine_changed(run: dict, blind: dict) -> bool:
110
+ """Did this run measure different engine code from the blind run?
111
+
112
+ Fingerprints taken with different configurations are not comparable, so
113
+ a run whose configuration differs is judged by its fingerprint under the
114
+ blind run's configuration, as recorded when it ran.
115
+ """
116
+ if run.get("engine_config_changed_since_blind"):
117
+ measured = run.get("engine_fingerprint_with_blind_config")
118
+ else:
119
+ measured = run["engine_fingerprint"]
120
+ return measured != blind["engine_fingerprint"]
121
+
122
+
123
+ def set_report(ledger: Ledger, name: str, status: SetStatus | None = None) -> dict:
124
+ """Facts about one sealed set, plus the paragraph (``text``) and table."""
125
+ status = status or set_status(ledger, name)
126
+ sealed = ledger.version(name)
127
+ runs = list(status.runs)
128
+ blind = runs[0] if runs else None
129
+ facts = {
130
+ "set": name,
131
+ "version": sealed["version"],
132
+ "sealed_at": sealed["sealed_at"],
133
+ "note": sealed.get("note"),
134
+ "newlines": sealed["newlines"],
135
+ "files": len(sealed["files"]),
136
+ "items": sealed.get("items"),
137
+ "set_hash": sealed["set_hash"],
138
+ "intact": status.check.intact,
139
+ "changed": list(status.check.changed),
140
+ "missing": list(status.check.missing),
141
+ "added": list(status.check.added),
142
+ "run_count": len(runs),
143
+ "blind_run": _run_summary(blind) if blind else None,
144
+ "repeat_runs": [_run_summary(r) for r in runs[1:]],
145
+ "engine_fingerprint_at_blind_run": blind["engine_fingerprint"] if blind else None,
146
+ "engine_fingerprint_now": status.engine_now,
147
+ "engine_error": status.engine_error,
148
+ "engine_matches_blind_run": status.engine_matches,
149
+ "runs_with_changed_engine": [r["run"] for r in runs[1:] if _engine_changed(r, blind)],
150
+ "runs_with_changed_engine_config": [
151
+ r["run"] for r in runs[1:] if _config_changed(r, blind)
152
+ ],
153
+ "earlier_versions": [
154
+ {
155
+ "version": v["version"],
156
+ "sealed_at": v["sealed_at"],
157
+ "run_count": len(ledger.runs_for(name, v["version"])),
158
+ }
159
+ for v in ledger.versions(name)[:-1]
160
+ ],
161
+ "holds": status.ok,
162
+ }
163
+ facts["text"] = _paragraph(facts, runs)
164
+ facts["table"] = _table(runs)
165
+ return facts
166
+
167
+
168
+ def _paragraph(facts: dict, runs: list[dict]) -> str:
169
+ parts = []
170
+ head = f"Sealed set `{facts['set']}`"
171
+ if facts["version"] > 1:
172
+ head += f" (version {facts['version']})"
173
+ size = _plural(facts["files"], "file")
174
+ if facts["items"] is not None:
175
+ size += f", {_plural(facts['items'], 'item')}"
176
+ head += f": {size}, sealed {_date(facts['sealed_at'])}"
177
+ if facts["note"]:
178
+ head += f" (note: {facts['note']})"
179
+ parts.append(head + ".")
180
+ for earlier in facts["earlier_versions"]:
181
+ parts.append(
182
+ f"Version {earlier['version']} of this set was sealed "
183
+ f"{_date(earlier['sealed_at'])} and run {_times(earlier['run_count'])} "
184
+ "before it was replaced."
185
+ )
186
+
187
+ if facts["intact"]:
188
+ parts.append(
189
+ f"The sealed files are unchanged since sealing (set hash `{_short(facts['set_hash'])}`)."
190
+ )
191
+ else:
192
+ detail = "; ".join(
193
+ f"{label}: {', '.join(facts[label])}"
194
+ for label in ("changed", "missing", "added")
195
+ if facts[label]
196
+ )
197
+ parts.append(
198
+ f"The sealed files have changed since sealing ({detail}), so the recorded "
199
+ "numbers do not describe the files in this checkout."
200
+ )
201
+
202
+ if not runs:
203
+ parts.append("No run has been recorded against this set, so there is no number to report.")
204
+ parts.append(CAVEAT)
205
+ return " ".join(parts)
206
+
207
+ blind = runs[0]
208
+ blind_numbers = _metrics_phrase(blind)
209
+ if len(runs) == 1:
210
+ parts.append(f"It has been run once, on {_date(blind['time'])}; that run is the blind run.")
211
+ else:
212
+ parts.append(
213
+ f"It has been run {_times(len(runs))}; only run 1, on {_date(blind['time'])}, is blind."
214
+ )
215
+ if blind.get("status") == "interrupted":
216
+ parts.append("The blind run was interrupted before the command finished.")
217
+ elif blind["exit_code"] != 0:
218
+ parts.append(f"The blind run exited with code {blind['exit_code']}.")
219
+ if blind_numbers:
220
+ parts.append(f"Blind-run numbers: {blind_numbers}.")
221
+ else:
222
+ parts.append("The blind run recorded no metrics.")
223
+ if len(runs) > 1:
224
+ latest = runs[-1]
225
+ sentence = (
226
+ f"The latest run is run {latest['run']} of the same set, a repeat, "
227
+ "and is not blind"
228
+ )
229
+ latest_numbers = _metrics_phrase(latest)
230
+ sentence += f": {latest_numbers}" if latest_numbers else "; it recorded no metrics"
231
+ sentence += "; the first-run numbers were " + (
232
+ blind_numbers if blind_numbers else "not recorded"
233
+ )
234
+ parts.append(sentence + ".")
235
+
236
+ recorded = f"The engine fingerprint at the blind run was `{_short(blind['engine_fingerprint'])}`"
237
+ if facts["engine_matches_blind_run"]:
238
+ parts.append(recorded + "; the engine files in this checkout match it.")
239
+ elif facts["engine_fingerprint_now"] is None:
240
+ parts.append(
241
+ recorded + "; it cannot be recomputed in this checkout, so the numbers "
242
+ "cannot be tied to this code."
243
+ )
244
+ else:
245
+ parts.append(
246
+ recorded + "; the engine files in this checkout have a different fingerprint "
247
+ f"(`{_short(facts['engine_fingerprint_now'])}`), so the blind-run numbers "
248
+ "describe earlier code, not this checkout."
249
+ )
250
+ changed = facts["runs_with_changed_engine"]
251
+ if changed:
252
+ parts.append(
253
+ "The engine was changed after the blind run: "
254
+ f"{'run' if len(changed) == 1 else 'runs'} {_ranges(changed)} measured "
255
+ "different code."
256
+ )
257
+ reconfigured = facts["runs_with_changed_engine_config"]
258
+ if reconfigured:
259
+ same = [r for r in reconfigured if r not in changed]
260
+ sentence = (
261
+ "The engine configuration (which files count as the engine) was edited "
262
+ f"after the blind run: {'run' if len(reconfigured) == 1 else 'runs'} "
263
+ f"{_ranges(reconfigured)} used a different configuration"
264
+ )
265
+ if same:
266
+ sentence += (
267
+ f"; compared with the blind run's configuration, "
268
+ f"{'run' if len(same) == 1 else 'runs'} {_ranges(same)} measured the "
269
+ "same engine files as the blind run"
270
+ )
271
+ parts.append(sentence + ".")
272
+ parts.append(CAVEAT)
273
+ return " ".join(parts)
274
+
275
+
276
+ def _cell(text: str) -> str:
277
+ return text.replace("|", "\\|").replace("\n", " ")
278
+
279
+
280
+ def _table(runs: list[dict]) -> dict | None:
281
+ if not runs:
282
+ return None
283
+ keys: list[str] = []
284
+ flats = []
285
+ for run in runs:
286
+ flat = flatten(run.get("metrics"))
287
+ flats.append(flat)
288
+ keys.extend(k for k in flat if k not in keys)
289
+ columns = ["run", "label", "date", "exit", "engine"] + keys
290
+ rows = []
291
+ for run, flat in zip(runs, flats):
292
+ rows.append(
293
+ [
294
+ str(run["run"]),
295
+ run["label"],
296
+ _date(run["time"]),
297
+ str(run["exit_code"]),
298
+ f"`{_short(run['engine_fingerprint'])}`",
299
+ ]
300
+ + [format_value(flat[k]) if k in flat else "-" for k in keys]
301
+ )
302
+ return {"columns": columns, "rows": rows}
303
+
304
+
305
+ def render_block(facts: dict) -> str:
306
+ """Markdown for one set, wrapped in the markers ``verify`` looks for."""
307
+ lines = [f"<!-- onelook:begin {facts['set']} -->", facts["text"]]
308
+ table = facts["table"]
309
+ if table:
310
+ lines.append("")
311
+ lines.append("| " + " | ".join(_cell(c) for c in table["columns"]) + " |")
312
+ lines.append("|" + "|".join(" --- " for _ in table["columns"]) + "|")
313
+ for row in table["rows"]:
314
+ lines.append("| " + " | ".join(_cell(c) for c in row) + " |")
315
+ lines.append("")
316
+ lines.append(f"<!-- onelook:end {facts['set']} -->")
317
+ return "\n".join(lines)
318
+
319
+
320
+ def report(ledger: Ledger, names: list[str] | None = None) -> list[dict]:
321
+ """Report facts for the named sets, or for every set in name order."""
322
+ names = list(names) if names else sorted(ledger.sets)
323
+ if not names:
324
+ raise OnelookError("the ledger has no sealed sets to report on")
325
+ return [set_report(ledger, name) for name in names]
326
+
327
+
328
+ def render_markdown(reports: list[dict]) -> str:
329
+ return "\n\n".join(render_block(r) for r in reports) + "\n"
330
+
331
+
332
+ def extract_blocks(text: str) -> list[tuple[str, str]]:
333
+ """Find ``(set name, block text)`` for each onelook block in a document."""
334
+ return [(m.group("name"), m.group(0)) for m in _BLOCK_RE.finditer(text)]
335
+
336
+
337
+ def normalise_block(text: str) -> str:
338
+ """Ignore line-ending style and trailing spaces when comparing blocks."""
339
+ lines = text.replace("\r\n", "\n").split("\n")
340
+ return "\n".join(line.rstrip() for line in lines).strip()
341
+
342
+
343
+ def write_blocks(path: str, reports: list[dict]) -> list[str]:
344
+ """Replace each set's block in a file, appending blocks that are absent.
345
+
346
+ Returns one line per set saying what was done. The file's existing
347
+ line-ending style is kept.
348
+ """
349
+ try:
350
+ with open(path, encoding="utf-8", newline="") as handle:
351
+ text = handle.read()
352
+ except FileNotFoundError:
353
+ text = ""
354
+ except OSError as exc:
355
+ raise OnelookError(f"cannot read {path}: {exc}") from exc
356
+ newline = "\r\n" if "\r\n" in text else "\n"
357
+ done = []
358
+ for facts in reports:
359
+ block = render_block(facts).replace("\n", newline)
360
+ pattern = re.compile(
361
+ r"<!-- onelook:begin {0} -->.*?<!-- onelook:end {0} -->".format(
362
+ re.escape(facts["set"])
363
+ ),
364
+ re.S,
365
+ )
366
+ if pattern.search(text):
367
+ text = pattern.sub(lambda _match: block, text, count=1)
368
+ done.append(f"updated the block for {facts['set']!r}")
369
+ else:
370
+ if text and not text.endswith(("\n", "\r")):
371
+ text += newline
372
+ text += (newline if text else "") + block + newline
373
+ done.append(f"appended a block for {facts['set']!r}")
374
+ with open(path, "w", encoding="utf-8", newline="") as handle:
375
+ handle.write(text)
376
+ return done
@@ -0,0 +1,139 @@
1
+ """``onelook verify``: recompute everything and test the published claim.
2
+
3
+ Three things are checked, in this order:
4
+
5
+ 1. The ledger is internally consistent (run numbers, labels and hashes are
6
+ what onelook would have written).
7
+ 2. Each sealed set is re-hashed and the engine is re-fingerprinted.
8
+ 3. If the README contains onelook report blocks, each block is compared
9
+ with the report regenerated from the ledger and the files present.
10
+
11
+ The verdict depends on whether there is a published claim to test. With
12
+ report blocks in the README, verification succeeds when every block says
13
+ exactly what is true now; a block that honestly states "the engine has
14
+ changed" verifies, and a block that says it has not when it has is refuted.
15
+ Without blocks, verification succeeds when every set is intact and the
16
+ engine still matches each blind run (the same test as ``onelook status``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import difflib
22
+ import os
23
+ from dataclasses import dataclass
24
+
25
+ from ._errors import OnelookError
26
+ from .ledger import Ledger, check_ledger, status
27
+ from .reporting import extract_blocks, normalise_block, render_block, set_report
28
+
29
+ OK, FAIL, NOTE = "ok", "FAIL", "note"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Verification:
34
+ ok: bool
35
+ lines: tuple[tuple[str, str], ...]
36
+ readme: str | None
37
+ blocks: int
38
+
39
+
40
+ def verify(ledger: Ledger, readme: str | os.PathLike | None = None) -> Verification:
41
+ """Verify the ledger against the files, and a README against both.
42
+
43
+ ``readme`` defaults to ``README.md`` beside the ledger when that file
44
+ exists. Naming a README that has no onelook block is a failure; the
45
+ default README having none is not.
46
+ """
47
+ lines: list[tuple[str, str]] = []
48
+ explicit = readme is not None
49
+ if readme is None:
50
+ candidate = os.path.join(ledger.root, "README.md")
51
+ readme = candidate if os.path.isfile(candidate) else None
52
+ else:
53
+ readme = os.fspath(readme)
54
+
55
+ problems = check_ledger(ledger)
56
+ if problems:
57
+ lines.extend((FAIL, f"ledger: {p}") for p in problems)
58
+ lines.append((NOTE, "the ledger is inconsistent, so nothing else was checked"))
59
+ return Verification(False, tuple(lines), readme, 0)
60
+ lines.append(
61
+ (
62
+ OK,
63
+ f"ledger is internally consistent ({len(ledger.sets)} sealed "
64
+ f"set{'s' if len(ledger.sets) != 1 else ''}, {len(ledger.runs)} run "
65
+ f"record{'s' if len(ledger.runs) != 1 else ''})",
66
+ )
67
+ )
68
+
69
+ blocks: list[tuple[str, str]] = []
70
+ if readme is not None:
71
+ try:
72
+ with open(readme, encoding="utf-8") as handle:
73
+ blocks = extract_blocks(handle.read())
74
+ except (OSError, UnicodeDecodeError) as exc:
75
+ raise OnelookError(f"cannot read {readme}: {exc}") from exc
76
+
77
+ ok = True
78
+ current = status(ledger)
79
+ bad = NOTE if blocks else FAIL # with a published claim, the claim is the test
80
+ for item in current.sets:
81
+ label = f"set {item.name!r} (version {item.version})"
82
+ if item.check.intact:
83
+ lines.append((OK, f"{label}: sealed files match their recorded hashes"))
84
+ else:
85
+ lines.append((bad, f"{label}: sealed files differ ({item.check.describe()})"))
86
+ if item.engine_matches is None:
87
+ lines.append((NOTE, f"{label}: no run recorded"))
88
+ elif item.engine_matches:
89
+ lines.append((OK, f"{label}: engine matches the blind run's fingerprint"))
90
+ elif item.engine_error:
91
+ lines.append((bad, f"{label}: engine cannot be fingerprinted ({item.engine_error})"))
92
+ else:
93
+ lines.append((bad, f"{label}: engine differs from the blind run's fingerprint"))
94
+ if item.repeats:
95
+ lines.append(
96
+ (NOTE, f"{label}: {item.repeats} repeat run{'s' if item.repeats != 1 else ''} on record")
97
+ )
98
+ if not blocks and not item.ok:
99
+ ok = False
100
+
101
+ if blocks:
102
+ shown = os.path.basename(readme)
103
+ for name, body in blocks:
104
+ if name not in ledger.sets:
105
+ lines.append((FAIL, f"{shown}: has a block for {name!r}, which is not in the ledger"))
106
+ ok = False
107
+ continue
108
+ expected = render_block(set_report(ledger, name))
109
+ if normalise_block(body) == normalise_block(expected):
110
+ lines.append(
111
+ (OK, f"{shown}: the report for {name!r} matches the ledger and the files here")
112
+ )
113
+ else:
114
+ ok = False
115
+ lines.append(
116
+ (FAIL, f"{shown}: the report for {name!r} does not match; differences "
117
+ "(- README, + recomputed):")
118
+ )
119
+ diff = difflib.unified_diff(
120
+ normalise_block(body).split("\n"),
121
+ normalise_block(expected).split("\n"),
122
+ lineterm="",
123
+ n=0,
124
+ )
125
+ lines.extend(
126
+ (FAIL, " " + line)
127
+ for line in diff
128
+ if not line.startswith(("---", "+++", "@@"))
129
+ )
130
+ elif readme is not None and explicit:
131
+ lines.append((FAIL, f"{os.path.basename(readme)}: no onelook report block found"))
132
+ ok = False
133
+ elif readme is not None:
134
+ lines.append(
135
+ (NOTE, f"{os.path.basename(readme)}: no onelook report block; checked the ledger and files only")
136
+ )
137
+ else:
138
+ lines.append((NOTE, "no README checked; checked the ledger and files only"))
139
+ return Verification(ok, tuple(lines), readme, len(blocks))