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/ledger.py ADDED
@@ -0,0 +1,786 @@
1
+ """The ledger file and the operations that read and extend it.
2
+
3
+ The ledger is one JSON file, ``onelook.json``, meant to be committed. Its
4
+ directory is the root that every recorded path is relative to. Records are
5
+ only ever appended: sealing a changed set adds a version, and every run
6
+ against a set adds a run record.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import csv
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import time
18
+ from dataclasses import dataclass
19
+ from datetime import datetime, timezone
20
+ from typing import Callable, Iterable, Sequence
21
+
22
+ from ._errors import OnelookError
23
+ from .hashing import (
24
+ DEFAULT_IGNORE,
25
+ Fingerprint,
26
+ check_newlines,
27
+ clean_pattern,
28
+ combine,
29
+ escape_glob,
30
+ expand,
31
+ fingerprint,
32
+ hash_file,
33
+ )
34
+
35
+ LEDGER_NAME = "onelook.json"
36
+ FORMAT = 1
37
+ BLIND = "blind"
38
+ REPEAT = "repeat"
39
+
40
+ _NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
41
+
42
+
43
+ def utc_now() -> str:
44
+ """Current time in UTC as ``YYYY-MM-DDTHH:MM:SSZ``."""
45
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
46
+
47
+
48
+ # --------------------------------------------------------------------------
49
+ # Ledger
50
+
51
+
52
+ class Ledger:
53
+ """An ``onelook.json`` file held in memory.
54
+
55
+ ``path`` may be the file or the directory that contains (or will
56
+ contain) it. Use :meth:`load` to read an existing ledger.
57
+ """
58
+
59
+ def __init__(self, path: str | os.PathLike = LEDGER_NAME, data: dict | None = None):
60
+ path = os.fspath(path)
61
+ if os.path.isdir(path):
62
+ path = os.path.join(path, LEDGER_NAME)
63
+ self.path = os.path.abspath(path)
64
+ self.data = data if data is not None else {
65
+ "onelook": FORMAT,
66
+ "engine": None,
67
+ "sets": {},
68
+ "runs": [],
69
+ }
70
+
71
+ @classmethod
72
+ def load(cls, path: str | os.PathLike = LEDGER_NAME, create: bool = False) -> "Ledger":
73
+ """Read a ledger. With ``create``, a missing file gives an empty ledger."""
74
+ ledger = cls(path)
75
+ if not os.path.exists(ledger.path):
76
+ if create:
77
+ return ledger
78
+ raise OnelookError(
79
+ f"no ledger at {ledger.path} (it is created by `onelook seal` "
80
+ "or `onelook fingerprint --save`)"
81
+ )
82
+ try:
83
+ with open(ledger.path, encoding="utf-8") as handle:
84
+ data = json.load(handle)
85
+ except (OSError, ValueError) as exc:
86
+ raise OnelookError(f"cannot read ledger {ledger.path}: {exc}") from exc
87
+ if not isinstance(data, dict) or data.get("onelook") != FORMAT:
88
+ raise OnelookError(
89
+ f"{ledger.path} is not a onelook ledger of format {FORMAT}"
90
+ )
91
+ data.setdefault("engine", None)
92
+ if not isinstance(data.setdefault("sets", {}), dict) or not isinstance(
93
+ data.setdefault("runs", []), list
94
+ ):
95
+ raise OnelookError(f"{ledger.path}: 'sets' must be an object and 'runs' a list")
96
+ ledger.data = data
97
+ return ledger
98
+
99
+ def save(self) -> None:
100
+ """Write the ledger as indented UTF-8 JSON with LF line endings.
101
+
102
+ The write is atomic: the text goes to a temporary file that is
103
+ flushed to disk and then renamed over the ledger, so an interruption
104
+ leaves either the old ledger or the new one, never half of one.
105
+ """
106
+ text = json.dumps(self.data, indent=2, ensure_ascii=False) + "\n"
107
+ temporary = self.path + ".tmp"
108
+ with open(temporary, "w", encoding="utf-8", newline="\n") as handle:
109
+ handle.write(text)
110
+ handle.flush()
111
+ os.fsync(handle.fileno())
112
+ os.replace(temporary, self.path)
113
+
114
+ # -- locations ---------------------------------------------------------
115
+
116
+ @property
117
+ def root(self) -> str:
118
+ """The directory holding the ledger; recorded paths are relative to it."""
119
+ return os.path.dirname(self.path)
120
+
121
+ @property
122
+ def name(self) -> str:
123
+ return os.path.basename(self.path)
124
+
125
+ def full_path(self, relative: str) -> str:
126
+ return os.path.join(self.root, *relative.split("/"))
127
+
128
+ def pattern_for(self, path: str | os.PathLike) -> str:
129
+ """Turn a path or glob into a pattern relative to the ledger directory.
130
+
131
+ A relative argument is taken relative to the ledger directory. If
132
+ the path exists, glob characters in it are escaped so that it is
133
+ matched literally.
134
+ """
135
+ path = os.fspath(path)
136
+ full = os.path.normpath(path if os.path.isabs(path) else os.path.join(self.root, path))
137
+ relative = self._relative(full, path)
138
+ pattern = "" if relative == "." else relative.replace(os.sep, "/")
139
+ if os.path.lexists(full):
140
+ pattern = escape_glob(pattern)
141
+ return clean_pattern(pattern)
142
+
143
+ def _relative(self, full: str, original: str) -> str:
144
+ for target, base in ((full, self.root), (os.path.realpath(full), os.path.realpath(self.root))):
145
+ try:
146
+ relative = os.path.relpath(target, base)
147
+ except ValueError:
148
+ continue
149
+ if relative != ".." and not relative.startswith(".." + os.sep):
150
+ return relative
151
+ raise OnelookError(f"{original} is outside the ledger directory {self.root}")
152
+
153
+ # -- engine ------------------------------------------------------------
154
+
155
+ @property
156
+ def engine(self) -> dict | None:
157
+ """The engine configuration: ``include``, ``ignore``, ``newlines``."""
158
+ return self.data.get("engine")
159
+
160
+ def set_engine(
161
+ self,
162
+ include: Sequence[str],
163
+ ignore: Sequence[str] = DEFAULT_IGNORE,
164
+ newlines: str = "lf",
165
+ ) -> dict:
166
+ """Set which paths constitute the engine. Does not save."""
167
+ include = [self.pattern_for(p) for p in include]
168
+ if not include:
169
+ raise OnelookError("the engine needs at least one path or pattern")
170
+ self.data["engine"] = {
171
+ "include": include,
172
+ "ignore": [clean_pattern(p) for p in ignore],
173
+ "newlines": check_newlines(newlines),
174
+ }
175
+ return self.data["engine"]
176
+
177
+ # -- sets and runs -----------------------------------------------------
178
+
179
+ @property
180
+ def sets(self) -> dict:
181
+ return self.data["sets"]
182
+
183
+ @property
184
+ def runs(self) -> list:
185
+ return self.data["runs"]
186
+
187
+ def versions(self, name: str) -> list:
188
+ try:
189
+ return self.sets[name]["versions"]
190
+ except KeyError:
191
+ known = ", ".join(sorted(self.sets)) or "none"
192
+ raise OnelookError(f"no sealed set named {name!r} (sealed sets: {known})") from None
193
+
194
+ def version(self, name: str, version: int | None = None) -> dict:
195
+ """One version record of a set; the latest when ``version`` is None."""
196
+ versions = self.versions(name)
197
+ if version is None:
198
+ return versions[-1]
199
+ for record in versions:
200
+ if record.get("version") == version:
201
+ return record
202
+ raise OnelookError(f"set {name!r} has no version {version}")
203
+
204
+ def runs_for(self, name: str, version: int | None = None) -> list:
205
+ """Run records for one version of a set, in the order they were made."""
206
+ if version is None:
207
+ version = self.version(name)["version"]
208
+ return [
209
+ r for r in self.runs if r.get("set") == name and r.get("set_version") == version
210
+ ]
211
+
212
+
213
+ # --------------------------------------------------------------------------
214
+ # Sealing
215
+
216
+
217
+ def count_items(path: str) -> int | None:
218
+ """Count the items in a file whose format is recognised, else None.
219
+
220
+ ``.jsonl`` / ``.ndjson``: non-blank lines. ``.csv`` / ``.tsv``: non-empty
221
+ rows after the header row. ``.json``: length of a top-level array.
222
+ """
223
+ extension = os.path.splitext(path)[1].lower()
224
+ try:
225
+ if extension in (".jsonl", ".ndjson"):
226
+ with open(path, encoding="utf-8-sig") as handle:
227
+ return sum(1 for line in handle if line.strip())
228
+ if extension in (".csv", ".tsv"):
229
+ with open(path, encoding="utf-8-sig", newline="") as handle:
230
+ reader = csv.reader(handle, delimiter="\t" if extension == ".tsv" else ",")
231
+ rows = sum(1 for row in reader if any(cell.strip() for cell in row))
232
+ return max(rows - 1, 0)
233
+ if extension == ".json":
234
+ with open(path, encoding="utf-8-sig") as handle:
235
+ data = json.load(handle)
236
+ return len(data) if isinstance(data, list) else None
237
+ except (OSError, ValueError, csv.Error):
238
+ return None
239
+ return None
240
+
241
+
242
+ @dataclass(frozen=True)
243
+ class SealResult:
244
+ """The version record for a set and whether this call created it."""
245
+
246
+ record: dict
247
+ created: bool
248
+
249
+
250
+ def seal(
251
+ ledger: Ledger,
252
+ name: str,
253
+ files: Iterable[str | os.PathLike],
254
+ *,
255
+ note: str | None = None,
256
+ new_version: bool = False,
257
+ newlines: str = "lf",
258
+ now: str | None = None,
259
+ ) -> SealResult:
260
+ """Seal a blind set: record the hash of every file, and save the ledger.
261
+
262
+ ``files`` may be files, directories or glob patterns; relative ones are
263
+ taken relative to the ledger directory. Sealing the same content again
264
+ under the same name changes nothing. Sealing different content under an
265
+ existing name raises unless ``new_version`` is set, in which case a new
266
+ version is appended and the earlier ones are kept.
267
+ """
268
+ if not _NAME_RE.match(name or ""):
269
+ raise OnelookError(
270
+ f"invalid set name {name!r}: use letters, digits, '.', '_' and '-'"
271
+ )
272
+ check_newlines(newlines)
273
+ sources: list[str] = []
274
+ for item in files:
275
+ pattern = ledger.pattern_for(item)
276
+ if pattern not in sources:
277
+ sources.append(pattern)
278
+ if not sources:
279
+ raise OnelookError("nothing to seal: give at least one file")
280
+ paths = expand(ledger.root, sources, exclude=(ledger.name,))
281
+ if not paths:
282
+ raise OnelookError("nothing to seal: no file matches " + ", ".join(sources))
283
+
284
+ entries = []
285
+ for path in paths:
286
+ full = ledger.full_path(path)
287
+ digest, size = hash_file(full, newlines)
288
+ entries.append(
289
+ {"path": path, "sha256": digest, "size": size, "items": count_items(full)}
290
+ )
291
+ set_hash = combine((e["path"], e["sha256"]) for e in entries)
292
+ counts = [e["items"] for e in entries]
293
+ total = sum(counts) if all(c is not None for c in counts) else None
294
+
295
+ existing = ledger.sets.get(name, {}).get("versions", [])
296
+ if existing:
297
+ current = existing[-1]
298
+ if current["set_hash"] == set_hash and current["newlines"] == newlines:
299
+ return SealResult(current, created=False)
300
+ if not new_version:
301
+ raise OnelookError(
302
+ f"set {name!r} is already sealed (version {current['version']}) and "
303
+ f"what you are sealing differs from it ({_difference(current, entries, newlines)}). "
304
+ "A sealed set is not meant to change; if this is deliberate, "
305
+ "use --new-version, which keeps the earlier version and its runs on record."
306
+ )
307
+ record = {
308
+ "version": len(existing) + 1,
309
+ "sealed_at": now or utc_now(),
310
+ "note": note,
311
+ "newlines": newlines,
312
+ "sources": sources,
313
+ "files": entries,
314
+ "items": total,
315
+ "set_hash": set_hash,
316
+ }
317
+ ledger.sets.setdefault(name, {"versions": []})["versions"].append(record)
318
+ ledger.save()
319
+ return SealResult(record, created=True)
320
+
321
+
322
+ def _difference(current: dict, entries: list[dict], newlines: str) -> str:
323
+ if current["newlines"] != newlines:
324
+ return f"newline mode {current['newlines']} -> {newlines}"
325
+ old = {e["path"]: e["sha256"] for e in current["files"]}
326
+ new = {e["path"]: e["sha256"] for e in entries}
327
+ return _describe(
328
+ changed=[p for p in old if p in new and old[p] != new[p]],
329
+ missing=[p for p in old if p not in new],
330
+ added=[p for p in new if p not in old],
331
+ )
332
+
333
+
334
+ def _describe(changed: Sequence[str], missing: Sequence[str], added: Sequence[str]) -> str:
335
+ parts = []
336
+ for label, paths in (("changed", changed), ("missing", missing), ("added", added)):
337
+ if paths:
338
+ parts.append(f"{label}: {', '.join(paths)}")
339
+ return "; ".join(parts) or "no difference"
340
+
341
+
342
+ # --------------------------------------------------------------------------
343
+ # Checking a sealed set
344
+
345
+
346
+ @dataclass(frozen=True)
347
+ class SetCheck:
348
+ """The result of comparing a sealed version with the files on disk."""
349
+
350
+ name: str
351
+ version: int
352
+ intact: bool
353
+ changed: tuple[str, ...]
354
+ missing: tuple[str, ...]
355
+ added: tuple[str, ...]
356
+ set_hash: str
357
+
358
+ def describe(self) -> str:
359
+ return "unchanged" if self.intact else _describe(self.changed, self.missing, self.added)
360
+
361
+
362
+ def check_set(ledger: Ledger, name: str, version: int | None = None) -> SetCheck:
363
+ """Re-hash a sealed set and report changed, missing and added files.
364
+
365
+ A file is "added" when it matches what was originally sealed (a
366
+ directory or a glob) but is not in the sealed file list.
367
+ """
368
+ record = ledger.version(name, version)
369
+ changed, missing = [], []
370
+ recorded = {e["path"]: e["sha256"] for e in record["files"]}
371
+ for path, digest in recorded.items():
372
+ full = ledger.full_path(path)
373
+ if not os.path.isfile(full):
374
+ missing.append(path)
375
+ elif hash_file(full, record["newlines"])[0] != digest:
376
+ changed.append(path)
377
+ added = [
378
+ p
379
+ for p in expand(ledger.root, record["sources"], exclude=(ledger.name,))
380
+ if p not in recorded
381
+ ]
382
+ return SetCheck(
383
+ name=name,
384
+ version=record["version"],
385
+ intact=not (changed or missing or added),
386
+ changed=tuple(changed),
387
+ missing=tuple(missing),
388
+ added=tuple(added),
389
+ set_hash=record["set_hash"],
390
+ )
391
+
392
+
393
+ # --------------------------------------------------------------------------
394
+ # Engine fingerprint
395
+
396
+
397
+ def fingerprint_config(ledger: Ledger, config: dict | None = None) -> Fingerprint:
398
+ """Fingerprint the engine as configured in the ledger (or ``config``)."""
399
+ config = config if config is not None else ledger.engine
400
+ if not config or not config.get("include"):
401
+ raise OnelookError(
402
+ "no engine is configured; say which paths are the engine with "
403
+ "`onelook fingerprint --save PATHS...`"
404
+ )
405
+ return fingerprint(
406
+ ledger.root,
407
+ config["include"],
408
+ config.get("ignore", ()),
409
+ config.get("newlines", "lf"),
410
+ exclude=(ledger.name,),
411
+ )
412
+
413
+
414
+ # --------------------------------------------------------------------------
415
+ # Runs
416
+
417
+
418
+ @dataclass(frozen=True)
419
+ class RunResult:
420
+ """The appended run record and the command's full output."""
421
+
422
+ record: dict
423
+ output: bytes
424
+
425
+
426
+ COMPLETED = "completed"
427
+ INTERRUPTED = "interrupted"
428
+ _BATCH_EXTENSIONS = (".bat", ".cmd")
429
+
430
+
431
+ def _file_state(path: str) -> tuple[int, int] | None:
432
+ try:
433
+ info = os.stat(path)
434
+ except OSError:
435
+ return None
436
+ return info.st_mtime_ns, info.st_size
437
+
438
+
439
+ def is_batch_file(program: str) -> bool:
440
+ """True if Windows would run ``program`` through cmd.exe: a ``.bat`` or
441
+ ``.cmd`` file (Windows ignores trailing dots and spaces in a name)."""
442
+ return program.rstrip(". ").lower().endswith(_BATCH_EXTENSIONS)
443
+
444
+
445
+ def _stop(process: subprocess.Popen) -> None:
446
+ """End a child process that is still running, and reap it."""
447
+ try:
448
+ if process.poll() is None:
449
+ process.kill()
450
+ process.wait(timeout=10)
451
+ except (OSError, subprocess.TimeoutExpired):
452
+ pass
453
+ try:
454
+ if process.stdout is not None:
455
+ process.stdout.close()
456
+ except OSError:
457
+ pass
458
+
459
+
460
+ def _engine_comparison(
461
+ ledger: Ledger, previous: list, config: dict | None, engine: Fingerprint
462
+ ) -> tuple[bool, bool, str | None]:
463
+ """(engine changed since blind, configuration changed since blind,
464
+ fingerprint of this code under the blind run's configuration).
465
+
466
+ Fingerprints made with different configurations are not comparable, so
467
+ when the configuration has changed since the blind run, the code being
468
+ measured now is fingerprinted again with the blind run's configuration
469
+ and that is what is compared.
470
+ """
471
+ if not previous:
472
+ return False, False, engine.hash
473
+ blind = previous[0]
474
+ blind_config = blind.get("engine_config")
475
+ current = json.loads(json.dumps(config))
476
+ if blind_config is None or blind_config == current:
477
+ return blind.get("engine_fingerprint") != engine.hash, False, engine.hash
478
+ try:
479
+ comparable = fingerprint_config(ledger, blind_config).hash
480
+ except OnelookError:
481
+ comparable = None
482
+ return blind.get("engine_fingerprint") != comparable, True, comparable
483
+
484
+
485
+ def record_run(
486
+ ledger: Ledger,
487
+ name: str,
488
+ command: Sequence[str],
489
+ *,
490
+ shell: bool = False,
491
+ metrics_file: str | os.PathLike | None = None,
492
+ cwd: str | os.PathLike | None = None,
493
+ tail_lines: int = 20,
494
+ now: str | None = None,
495
+ echo: Callable[[bytes], None] | None = None,
496
+ ) -> RunResult:
497
+ """Run an evaluation command against a sealed set and record the run.
498
+
499
+ Before the command starts, the sealed files are re-hashed (a changed set
500
+ raises and nothing is recorded) and the engine fingerprint is computed.
501
+ The command runs without a shell unless ``shell`` is set; its standard
502
+ output and error are captured together and passed to ``echo`` as they
503
+ arrive. Whatever the exit code, a run record is appended and the ledger
504
+ saved: run 1 of a set version is labelled ``blind``, every later run
505
+ ``repeat``. If the run is interrupted once the command has started (for
506
+ example by Ctrl-C, a ``KeyboardInterrupt``), the command is stopped, the
507
+ run is recorded with status ``interrupted`` (it still takes its number
508
+ and label) and the exception is raised again.
509
+
510
+ On Windows, a ``.bat`` or ``.cmd`` program is always run by cmd.exe,
511
+ which interprets ``&``, ``|``, ``>`` and other characters in the
512
+ arguments even without ``shell``; such a program is refused unless
513
+ ``shell`` is set.
514
+
515
+ ``metrics_file`` (relative to ``cwd``) is read after the command ends
516
+ and must hold a JSON object.
517
+ """
518
+ command = [os.fspath(c) for c in command]
519
+ if not command:
520
+ raise OnelookError("no command given")
521
+ if not shell and os.name == "nt" and is_batch_file(command[0]):
522
+ raise OnelookError(
523
+ f"refusing to run {command[0]!r} without --shell: on Windows a .bat or "
524
+ ".cmd file is always run by cmd.exe, which interprets characters such "
525
+ "as & | < > ^ % in its arguments, so the arguments would not be passed "
526
+ "as given. Pass --shell only if you accept that the command line is "
527
+ "interpreted by cmd.exe (quote the arguments yourself); nothing recorded"
528
+ )
529
+ sealed = ledger.version(name)
530
+ check = check_set(ledger, name)
531
+ if not check.intact:
532
+ raise OnelookError(
533
+ f"sealed set {name!r} no longer matches its seal ({check.describe()}); "
534
+ "refusing to run, nothing recorded"
535
+ )
536
+ config = ledger.engine
537
+ engine = fingerprint_config(ledger, config)
538
+ previous = ledger.runs_for(name, sealed["version"])
539
+ number = len(previous) + 1
540
+ engine_changed, config_changed, comparable = _engine_comparison(
541
+ ledger, previous, config, engine
542
+ )
543
+
544
+ working = os.fspath(cwd) if cwd is not None else os.getcwd()
545
+ metrics_path = None
546
+ before = None
547
+ if metrics_file is not None:
548
+ metrics_path = os.path.join(working, os.fspath(metrics_file))
549
+ before = _file_state(metrics_path)
550
+
551
+ started_at = now or utc_now()
552
+ started = time.monotonic()
553
+ try:
554
+ process = subprocess.Popen(
555
+ " ".join(command) if shell else command,
556
+ shell=shell,
557
+ cwd=working,
558
+ stdout=subprocess.PIPE,
559
+ stderr=subprocess.STDOUT,
560
+ )
561
+ except OSError as exc:
562
+ raise OnelookError(
563
+ f"cannot start {command[0]!r}: {exc.strerror or exc}; nothing recorded"
564
+ ) from exc
565
+ chunks = []
566
+ interruption: BaseException | None = None
567
+ assert process.stdout is not None
568
+ try:
569
+ for chunk in iter(lambda: process.stdout.read1(65536), b""):
570
+ chunks.append(chunk)
571
+ if echo is not None:
572
+ echo(chunk)
573
+ process.stdout.close()
574
+ exit_code = process.wait()
575
+ except BaseException as exc: # KeyboardInterrupt above all
576
+ interruption = exc
577
+ _stop(process)
578
+ exit_code = process.returncode
579
+ duration = time.monotonic() - started
580
+ output = b"".join(chunks)
581
+ lines = output.decode("utf-8", "replace").splitlines()
582
+
583
+ record = {
584
+ "set": name,
585
+ "set_version": sealed["version"],
586
+ "run": number,
587
+ "label": BLIND if number == 1 else REPEAT,
588
+ "status": COMPLETED if interruption is None else INTERRUPTED,
589
+ "time": started_at,
590
+ "set_hash": sealed["set_hash"],
591
+ "engine_fingerprint": engine.hash,
592
+ "engine_files": len(engine.files),
593
+ "engine_config": json.loads(json.dumps(config)),
594
+ "engine_changed_since_blind": engine_changed,
595
+ "engine_config_changed_since_blind": config_changed,
596
+ "command": command,
597
+ "shell": shell,
598
+ "exit_code": exit_code,
599
+ "duration_seconds": round(duration, 3),
600
+ "metrics": None,
601
+ "output_sha256": hashlib.sha256(output).hexdigest(),
602
+ "output_lines": len(lines),
603
+ "output_tail": lines[-tail_lines:] if tail_lines > 0 else [],
604
+ }
605
+ if config_changed:
606
+ # The fingerprint of the measured code under the blind run's
607
+ # configuration; this is what engine_changed_since_blind compares.
608
+ record["engine_fingerprint_with_blind_config"] = comparable
609
+ if interruption is not None:
610
+ record["interrupted_by"] = type(interruption).__name__
611
+ ledger.runs.append(record)
612
+ ledger.save()
613
+ raise interruption
614
+ if metrics_path is not None:
615
+ record["metrics_file"] = os.fspath(metrics_file).replace("\\", "/")
616
+ try:
617
+ with open(metrics_path, encoding="utf-8-sig") as handle:
618
+ metrics = json.load(handle)
619
+ if not isinstance(metrics, dict):
620
+ raise ValueError("the file must contain a JSON object")
621
+ record["metrics"] = metrics
622
+ if before is not None and before == _file_state(metrics_path):
623
+ # Same modification time and size as before the command ran:
624
+ # the command probably did not write it.
625
+ record["metrics_file_unchanged"] = True
626
+ except (OSError, ValueError) as exc:
627
+ record["metrics_error"] = str(exc)
628
+ ledger.runs.append(record)
629
+ ledger.save()
630
+ return RunResult(record=record, output=output)
631
+
632
+
633
+ # --------------------------------------------------------------------------
634
+ # Status
635
+
636
+
637
+ @dataclass(frozen=True)
638
+ class SetStatus:
639
+ """What currently holds for the latest version of one sealed set."""
640
+
641
+ name: str
642
+ version: int
643
+ check: SetCheck
644
+ runs: tuple[dict, ...]
645
+ engine_now: str | None
646
+ engine_error: str | None
647
+ engine_matches: bool | None # None when there is no run to compare with
648
+ engine_config_differs: bool
649
+
650
+ @property
651
+ def blind_run(self) -> dict | None:
652
+ return self.runs[0] if self.runs else None
653
+
654
+ @property
655
+ def repeats(self) -> int:
656
+ return max(len(self.runs) - 1, 0)
657
+
658
+ @property
659
+ def ok(self) -> bool:
660
+ """True when the set is intact and the engine matches the blind run."""
661
+ return self.check.intact and self.engine_matches is not False
662
+
663
+
664
+ @dataclass(frozen=True)
665
+ class Status:
666
+ sets: tuple[SetStatus, ...]
667
+
668
+ @property
669
+ def ok(self) -> bool:
670
+ return all(s.ok for s in self.sets)
671
+
672
+
673
+ def set_status(ledger: Ledger, name: str, _cache: dict | None = None) -> SetStatus:
674
+ """Status of one set. The engine is fingerprinted with the configuration
675
+ stored in the blind run's record, so that changing the configuration
676
+ afterwards cannot make changed code look unchanged."""
677
+ cache = _cache if _cache is not None else {}
678
+ sealed = ledger.version(name)
679
+ runs = tuple(ledger.runs_for(name, sealed["version"]))
680
+ engine_now = engine_error = None
681
+ engine_matches = None
682
+ config_differs = False
683
+ if runs:
684
+ config = runs[0].get("engine_config") or ledger.engine
685
+ config_differs = config != ledger.engine
686
+ key = json.dumps(config, sort_keys=True)
687
+ if key not in cache:
688
+ try:
689
+ cache[key] = (fingerprint_config(ledger, config).hash, None)
690
+ except OnelookError as exc:
691
+ cache[key] = (None, str(exc))
692
+ engine_now, engine_error = cache[key]
693
+ engine_matches = engine_now is not None and engine_now == runs[0].get(
694
+ "engine_fingerprint"
695
+ )
696
+ return SetStatus(
697
+ name=name,
698
+ version=sealed["version"],
699
+ check=check_set(ledger, name),
700
+ runs=runs,
701
+ engine_now=engine_now,
702
+ engine_error=engine_error,
703
+ engine_matches=engine_matches,
704
+ engine_config_differs=config_differs,
705
+ )
706
+
707
+
708
+ def status(ledger: Ledger) -> Status:
709
+ """Status of every sealed set, in name order."""
710
+ cache: dict = {}
711
+ return Status(tuple(set_status(ledger, name, cache) for name in sorted(ledger.sets)))
712
+
713
+
714
+ # --------------------------------------------------------------------------
715
+ # Internal consistency
716
+
717
+
718
+ def check_ledger(ledger: Ledger) -> list[str]:
719
+ """Look for records that onelook itself would never have written.
720
+
721
+ This catches careless hand edits (a renumbered run, a relabelled repeat,
722
+ a file hash that no longer adds up to the set hash). It cannot catch a
723
+ careful one; for that, read the file's history in version control.
724
+ """
725
+ problems: list[str] = []
726
+ sealed: dict[tuple[str, int], str] = {}
727
+ for name, entry in ledger.sets.items():
728
+ versions = entry.get("versions") if isinstance(entry, dict) else None
729
+ if not isinstance(versions, list) or not versions:
730
+ problems.append(f"set {name!r} has no versions")
731
+ continue
732
+ for index, record in enumerate(versions, start=1):
733
+ try:
734
+ if record["version"] != index:
735
+ problems.append(
736
+ f"set {name!r}: version {record['version']} is in position {index}"
737
+ )
738
+ combined = combine((e["path"], e["sha256"]) for e in record["files"])
739
+ if combined != record["set_hash"]:
740
+ problems.append(
741
+ f"set {name!r} version {index}: the set hash does not follow "
742
+ "from the recorded file hashes"
743
+ )
744
+ check_newlines(record["newlines"])
745
+ record["sources"], record["sealed_at"]
746
+ sealed[(name, index)] = record["set_hash"]
747
+ except (KeyError, TypeError, AttributeError, OnelookError):
748
+ problems.append(f"set {name!r} version {index}: malformed record")
749
+ seen: dict[tuple[str, int], list[dict]] = {}
750
+ for position, run in enumerate(ledger.runs, start=1):
751
+ try:
752
+ key = (run["set"], run["set_version"])
753
+ if key not in sealed:
754
+ problems.append(
755
+ f"run record {position} refers to set {key[0]!r} version {key[1]}, "
756
+ "which is not in the ledger"
757
+ )
758
+ continue
759
+ earlier = seen.setdefault(key, [])
760
+ where = f"set {key[0]!r} version {key[1]} run {run['run']}"
761
+ if run["run"] != len(earlier) + 1:
762
+ problems.append(
763
+ f"{where}: expected run number {len(earlier) + 1} at this position"
764
+ )
765
+ expected = BLIND if not earlier else REPEAT
766
+ if run["label"] != expected:
767
+ problems.append(f"{where}: labelled {run['label']!r}, expected {expected!r}")
768
+ if run["set_hash"] != sealed[key]:
769
+ problems.append(f"{where}: its set hash is not the sealed set hash")
770
+ measured = (
771
+ run.get("engine_fingerprint_with_blind_config")
772
+ if run.get("engine_config_changed_since_blind")
773
+ else run["engine_fingerprint"]
774
+ )
775
+ changed = bool(earlier) and earlier[0]["engine_fingerprint"] != measured
776
+ if run["engine_changed_since_blind"] != changed:
777
+ problems.append(
778
+ f"{where}: 'engine_changed_since_blind' contradicts the fingerprints"
779
+ )
780
+ if earlier and run["time"] < earlier[-1]["time"]:
781
+ problems.append(f"{where}: dated before the run that precedes it")
782
+ run["exit_code"], run["metrics"]
783
+ earlier.append(run)
784
+ except (KeyError, TypeError):
785
+ problems.append(f"run record {position}: malformed record")
786
+ return problems