evaltrack 0.1.0__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.
Files changed (54) hide show
  1. evaltrack/__init__.py +65 -0
  2. evaltrack/cli.py +606 -0
  3. evaltrack/config.py +185 -0
  4. evaltrack/context.py +112 -0
  5. evaltrack/core/__init__.py +26 -0
  6. evaltrack/core/errors.py +59 -0
  7. evaltrack/core/eval_round.py +123 -0
  8. evaltrack/core/gate.py +77 -0
  9. evaltrack/core/projection.py +124 -0
  10. evaltrack/core/recorder.py +176 -0
  11. evaltrack/core/refs.py +82 -0
  12. evaltrack/core/repetition.py +152 -0
  13. evaltrack/core/results.py +167 -0
  14. evaltrack/core/run_context.py +12 -0
  15. evaltrack/core/run_record.py +319 -0
  16. evaltrack/core/score_bars.py +70 -0
  17. evaltrack/core/user_values.py +162 -0
  18. evaltrack/failure.py +110 -0
  19. evaltrack/history/__init__.py +4 -0
  20. evaltrack/history/reliability.py +180 -0
  21. evaltrack/history/score_history.py +175 -0
  22. evaltrack/history/segments.py +106 -0
  23. evaltrack/marked_test.py +352 -0
  24. evaltrack/py.typed +0 -0
  25. evaltrack/pytest_plugin.py +521 -0
  26. evaltrack/repositories/__init__.py +68 -0
  27. evaltrack/repositories/azure.py +179 -0
  28. evaltrack/repositories/file.py +153 -0
  29. evaltrack/repositories/lifecycle.py +147 -0
  30. evaltrack/repositories/repository.py +438 -0
  31. evaltrack/repositories/store.py +56 -0
  32. evaltrack/translators/__init__.py +120 -0
  33. evaltrack/translators/deepeval.py +260 -0
  34. evaltrack/translators/protocol.py +13 -0
  35. evaltrack/translators/pydantic_evals.py +195 -0
  36. evaltrack/ui/__init__.py +7 -0
  37. evaltrack/ui/app.py +173 -0
  38. evaltrack/ui/models.py +77 -0
  39. evaltrack/ui/routes/__init__.py +6 -0
  40. evaltrack/ui/routes/history.py +119 -0
  41. evaltrack/ui/routes/meta.py +29 -0
  42. evaltrack/ui/routes/refs.py +114 -0
  43. evaltrack/ui/routes/runs.py +116 -0
  44. evaltrack/ui/routes/static.py +37 -0
  45. evaltrack/ui/security.py +41 -0
  46. evaltrack/ui/static/assets/index-BZO2JqWB.css +1 -0
  47. evaltrack/ui/static/assets/index-Cg522kcf.js +56 -0
  48. evaltrack/ui/static/favicon.svg +9 -0
  49. evaltrack/ui/static/index.html +14 -0
  50. evaltrack-0.1.0.dist-info/METADATA +281 -0
  51. evaltrack-0.1.0.dist-info/RECORD +54 -0
  52. evaltrack-0.1.0.dist-info/WHEEL +4 -0
  53. evaltrack-0.1.0.dist-info/entry_points.txt +5 -0
  54. evaltrack-0.1.0.dist-info/licenses/LICENSE +21 -0
evaltrack/__init__.py ADDED
@@ -0,0 +1,65 @@
1
+ """evaltrack records, gates and tracks LLM eval runs from pytest."""
2
+
3
+ import importlib.metadata
4
+
5
+ from evaltrack.core.errors import (
6
+ CorruptRecordError,
7
+ EvalDefinitionError,
8
+ EvalExecutionError,
9
+ EvaltrackError,
10
+ InvalidIdentifierError,
11
+ RepositoryUnavailableError,
12
+ TranslatorNotFoundError,
13
+ UnsupportedSchemaError,
14
+ )
15
+ from evaltrack.core.eval_round import (
16
+ AttemptErrorRecord,
17
+ EvalRound,
18
+ RoundAttempt,
19
+ RoundErrorRecord,
20
+ )
21
+ from evaltrack.core.results import (
22
+ EvaluatorInfo,
23
+ EvaluatorResult,
24
+ RunnerInfo,
25
+ )
26
+ from evaltrack.core.run_record import (
27
+ AttemptRecord,
28
+ CaseRecord,
29
+ MarkerSettings,
30
+ RecordedTest,
31
+ RunRecord,
32
+ )
33
+ from evaltrack.marked_test import repeats, run, run_async
34
+ from evaltrack.repositories import open_repository
35
+
36
+ __version__ = importlib.metadata.version("evaltrack")
37
+
38
+ # Hand-maintained. A name belongs here when a user writes it or catches it.
39
+ __all__ = [
40
+ "AttemptErrorRecord",
41
+ "AttemptRecord",
42
+ "CaseRecord",
43
+ "CorruptRecordError",
44
+ "EvalDefinitionError",
45
+ "EvalExecutionError",
46
+ "EvalRound",
47
+ "EvaltrackError",
48
+ "EvaluatorInfo",
49
+ "EvaluatorResult",
50
+ "InvalidIdentifierError",
51
+ "MarkerSettings",
52
+ "RecordedTest",
53
+ "RepositoryUnavailableError",
54
+ "RoundAttempt",
55
+ "RoundErrorRecord",
56
+ "RunRecord",
57
+ "RunnerInfo",
58
+ "TranslatorNotFoundError",
59
+ "UnsupportedSchemaError",
60
+ "__version__",
61
+ "open_repository",
62
+ "repeats",
63
+ "run",
64
+ "run_async",
65
+ ]
evaltrack/cli.py ADDED
@@ -0,0 +1,606 @@
1
+ """The evaltrack command line."""
2
+
3
+ import argparse
4
+ import importlib.metadata
5
+ import os
6
+ import sys
7
+ import traceback
8
+ from collections.abc import Callable
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime
11
+ from pathlib import Path
12
+
13
+ from pydantic import ValidationError
14
+
15
+ from evaltrack.config import (
16
+ DEFAULT_LOCAL_PATH,
17
+ LOCAL_ENV,
18
+ REMOTE_ENV,
19
+ ConfiguredRemote,
20
+ EvaltrackConfig,
21
+ RepositoryRole,
22
+ load_config,
23
+ resolve_local,
24
+ resolve_remote,
25
+ )
26
+ from evaltrack.core.errors import (
27
+ CorruptRecordError,
28
+ EvaltrackError,
29
+ InvalidIdentifierError,
30
+ RepositoryUnavailableError,
31
+ )
32
+ from evaltrack.core.refs import BASELINE_REF, Ref, RefKind, ReflogEntry
33
+ from evaltrack.core.run_record import dump_run_json, parse_run_json
34
+ from evaltrack.repositories import (
35
+ RunRepository,
36
+ RunSummary,
37
+ open_repository,
38
+ promote,
39
+ )
40
+
41
+ # The dashboard is unauthenticated, so it binds loopback only.
42
+ _UI_HOST = "127.0.0.1"
43
+
44
+ # sysexits.h EX_SOFTWARE, clear of the command exit codes.
45
+ _EXIT_INTERNAL_ERROR = 70
46
+
47
+ _ISSUES_URL = "https://github.com/jesrav/evaltrack/issues"
48
+
49
+
50
+ # --- entry point ---
51
+
52
+
53
+ def main(argv: list[str] | None = None) -> int:
54
+ """Run one invocation and return the exit code (`docs/cli.md` lists them)."""
55
+ args = _build_parser().parse_args(argv)
56
+ try:
57
+ # Every subparser stores its handler, and the parser refuses a session
58
+ # with none.
59
+ code = args.func(args)
60
+ # Flush here rather than at exit. A closed pipe raises at the flush,
61
+ # and at exit nothing is left to catch it.
62
+ sys.stdout.flush()
63
+ return code
64
+ except BrokenPipeError:
65
+ return _end_on_broken_pipe()
66
+ except (EvaltrackError, ValueError, ImportError, OSError) as exc:
67
+ # User errors and environment problems get a clean message, no traceback.
68
+ print(f"error: {exc}", file=sys.stderr)
69
+ return 2
70
+ except Exception:
71
+ traceback.print_exc()
72
+ print(
73
+ "error: this is a bug in evaltrack. Please report it at "
74
+ f"{_ISSUES_URL} with the traceback above.",
75
+ file=sys.stderr,
76
+ )
77
+ return _EXIT_INTERNAL_ERROR
78
+
79
+
80
+ def _end_on_broken_pipe() -> int:
81
+ """Point stdout at the null device, so the interpreter's shutdown flush cannot fail
82
+ again."""
83
+ try:
84
+ stdout_fd = sys.stdout.fileno()
85
+ except (OSError, ValueError):
86
+ # Captured stdout has no descriptor.
87
+ return 0
88
+ devnull_fd = os.open(os.devnull, os.O_WRONLY)
89
+ try:
90
+ os.dup2(devnull_fd, stdout_fd)
91
+ finally:
92
+ os.close(devnull_fd)
93
+ return 0
94
+
95
+
96
+ # --- the parser ---
97
+
98
+
99
+ def _int_in_range(lo: int, hi: int | None, *, what: str) -> Callable[[str], int]:
100
+ """Argparse type for an int of at least `lo` and, unless None, at most `hi`. A
101
+ rejection names the value as `what`."""
102
+
103
+ def parse(text: str) -> int:
104
+ try:
105
+ value = int(text)
106
+ except ValueError:
107
+ raise argparse.ArgumentTypeError(f"invalid int value: {text!r}") from None
108
+ if value < lo:
109
+ raise argparse.ArgumentTypeError(f"{what} is at least {lo}, got {value}")
110
+ if hi is not None and value > hi:
111
+ raise argparse.ArgumentTypeError(f"{what} is at most {hi}, got {value}")
112
+ return value
113
+
114
+ return parse
115
+
116
+
117
+ def _add_repository_flags(
118
+ command: argparse.ArgumentParser, *, required: bool, url_help: str
119
+ ) -> None:
120
+ """Add the mutually exclusive `--repository`, `--local` and `--remote` flags."""
121
+ group = command.add_mutually_exclusive_group(required=required)
122
+ group.add_argument(
123
+ "--repository",
124
+ default=None,
125
+ dest="repository_url",
126
+ help=url_help,
127
+ )
128
+ group.add_argument(
129
+ "--local",
130
+ action="store_true",
131
+ default=False,
132
+ help=f"The configured local repository: ${LOCAL_ENV}, then "
133
+ f"[tool.evaltrack].local, else {DEFAULT_LOCAL_PATH} under the project.",
134
+ )
135
+ group.add_argument(
136
+ "--remote",
137
+ action="store_true",
138
+ default=False,
139
+ help=f"The configured remote repository: ${REMOTE_ENV}, then "
140
+ "[tool.evaltrack].remote.",
141
+ )
142
+
143
+
144
+ def _build_parser() -> argparse.ArgumentParser:
145
+ # Subparsers do not inherit `allow_abbrev`, so every `add_parser` repeats it.
146
+ parser = argparse.ArgumentParser(
147
+ prog="evaltrack",
148
+ description="Record, push, and promote evaltrack runs.",
149
+ allow_abbrev=False,
150
+ )
151
+ parser.add_argument(
152
+ "--version",
153
+ action="version",
154
+ version=f"evaltrack {importlib.metadata.version('evaltrack')}",
155
+ )
156
+ # Required, so a missing subcommand is a usage error rather than a silent
157
+ # success. `evaltrack "$CMD"` with an empty variable must not exit 0.
158
+ sub = parser.add_subparsers(dest="command", required=True)
159
+
160
+ push = sub.add_parser(
161
+ "push",
162
+ help="Copy a run JSON file into a repository.",
163
+ allow_abbrev=False,
164
+ )
165
+ push.set_defaults(func=_cmd_push)
166
+ push.add_argument(
167
+ "--run-file",
168
+ required=True,
169
+ type=Path,
170
+ help="Path to a run JSON file (typically produced by "
171
+ "`pytest --evaltrack-run-file`).",
172
+ )
173
+ _add_repository_flags(
174
+ push,
175
+ required=False,
176
+ url_help="Repository path or URL. Defaults to the configured remote.",
177
+ )
178
+ push.add_argument(
179
+ "--ref",
180
+ default=None,
181
+ help="If set, point this ref at the run after saving.",
182
+ )
183
+ push.add_argument(
184
+ "--commit",
185
+ default=None,
186
+ help="Record this commit on the reflog entry written by --ref.",
187
+ )
188
+ push.add_argument(
189
+ "--pr",
190
+ type=_int_in_range(1, None, what="a PR number"),
191
+ default=None,
192
+ help="Record this PR number on the reflog entry written by --ref.",
193
+ )
194
+ push.add_argument(
195
+ "--title",
196
+ default=None,
197
+ help="Record this PR title on the reflog entry written by --ref (needs --pr).",
198
+ )
199
+
200
+ promote = sub.add_parser(
201
+ "promote",
202
+ help="Move `baseline` to the run that <ref> targets and append a reflog entry.",
203
+ allow_abbrev=False,
204
+ )
205
+ promote.set_defaults(func=_cmd_promote)
206
+ promote.add_argument("ref", help="Source ref to promote (for example pr/123).")
207
+ _add_repository_flags(
208
+ promote,
209
+ required=False,
210
+ url_help="Repository path or URL. Defaults to the configured remote.",
211
+ )
212
+ promote.add_argument(
213
+ "--commit",
214
+ default=None,
215
+ help="Squash-merge commit SHA to record on the baseline reflog. Not "
216
+ "recorded if baseline already points at the run.",
217
+ )
218
+ promote.add_argument(
219
+ "--cleanup",
220
+ action="store_true",
221
+ default=False,
222
+ help="After the promote, delete the source ref and its superseded runs. "
223
+ "The promoted run survives, because baseline still reaches it.",
224
+ )
225
+
226
+ runs = sub.add_parser(
227
+ "runs",
228
+ help="List recorded runs, newest first.",
229
+ allow_abbrev=False,
230
+ )
231
+ runs.set_defaults(func=_cmd_runs)
232
+ _add_repository_flags(runs, required=True, url_help="Repository path or URL.")
233
+ runs.add_argument(
234
+ "--limit",
235
+ type=_int_in_range(1, None, what="the limit"),
236
+ default=20,
237
+ help="How many runs to list (default 20).",
238
+ )
239
+
240
+ refs = sub.add_parser(
241
+ "refs",
242
+ help="List refs and the runs they point at.",
243
+ allow_abbrev=False,
244
+ )
245
+ refs.set_defaults(func=_cmd_refs)
246
+ _add_repository_flags(refs, required=True, url_help="Repository path or URL.")
247
+
248
+ export = sub.add_parser(
249
+ "export",
250
+ help="Print a recorded run as JSON.",
251
+ allow_abbrev=False,
252
+ )
253
+ export.set_defaults(func=_cmd_export)
254
+ export.add_argument("run_id", help="The run id (ULID) to export.")
255
+ _add_repository_flags(
256
+ export, required=True, url_help="Repository path or URL the run lives in."
257
+ )
258
+
259
+ ui = sub.add_parser(
260
+ "ui",
261
+ help="Serve the dashboard over the configured repositories.",
262
+ allow_abbrev=False,
263
+ description=(
264
+ "Serve the dashboard and print its URL. The repositories "
265
+ "come from the configuration, not from flags. Local is "
266
+ "$EVALTRACK_LOCAL, then [tool.evaltrack].local, else "
267
+ "./.evaltrack under the project. The remote is "
268
+ "$EVALTRACK_REMOTE, then [tool.evaltrack].remote, and is mounted "
269
+ "only when one of them names it."
270
+ ),
271
+ )
272
+ ui.set_defaults(func=_cmd_ui)
273
+ ui.add_argument(
274
+ "--port",
275
+ type=_int_in_range(1, 65535, what="a port (1-65535)"),
276
+ default=8765,
277
+ help="Bind port, 1-65535 (default 8765).",
278
+ )
279
+ ui.add_argument(
280
+ "--run-id",
281
+ default=None,
282
+ dest="run_id",
283
+ help="Point the printed URL at this run.",
284
+ )
285
+
286
+ return parser
287
+
288
+
289
+ # --- opening a repository ---
290
+
291
+
292
+ def _open_remote_repository(config: EvaltrackConfig) -> ConfiguredRemote:
293
+ """The configured remote, required."""
294
+ remote = resolve_remote(config)
295
+ if remote is None:
296
+ raise ValueError(
297
+ f"no remote configured. Set ${REMOTE_ENV} or add "
298
+ "[tool.evaltrack].remote to pyproject.toml. You can also name a "
299
+ "repository with --repository <path-or-url>, --local or --remote."
300
+ )
301
+ return remote
302
+
303
+
304
+ @dataclass(frozen=True)
305
+ class _OpenedRepository:
306
+ """An open repository and the URL it was opened from."""
307
+
308
+ repository: RunRepository
309
+ url: str
310
+
311
+
312
+ def _open_resolved_repository(args: argparse.Namespace) -> _OpenedRepository:
313
+ """Open the repository the flags name, or the remote, echoed to stderr."""
314
+ source: str | None = None
315
+ if args.repository_url is not None:
316
+ url = args.repository_url
317
+ if not url.strip():
318
+ # Not read as an absent flag. Falling back to the configured
319
+ # remote would retarget the push without saying so.
320
+ raise ValueError(
321
+ "--repository is empty. Name a path or URL, or use --local or "
322
+ "--remote for a configured repository. An unset shell variable "
323
+ "expands to an empty string, so check the value you passed."
324
+ )
325
+ else:
326
+ # Read once here, so a named repository costs no read at all.
327
+ config = load_config()
328
+ if args.local:
329
+ url = resolve_local(config)
330
+ elif args.remote:
331
+ url = _open_remote_repository(config).url
332
+ else:
333
+ default = _open_remote_repository(config)
334
+ url = default.url
335
+ source = default.source
336
+ repository = open_repository(url)
337
+ # Echoed after the open, so a URL the open rejects is never announced.
338
+ if source is not None:
339
+ print(f"using repository {url} (from {source})", file=sys.stderr)
340
+ return _OpenedRepository(repository, url)
341
+
342
+
343
+ # --- the commands ---
344
+
345
+
346
+ def _describe_run_errors(exc: ValidationError) -> str:
347
+ """Render the rejected fields without their values, which are whatever file the
348
+ caller named: a mistyped --run-file points at one holding secrets."""
349
+ return "".join(
350
+ f"\n {'.'.join(str(part) for part in error['loc']) or 'file'}: {error['msg']}"
351
+ for error in exc.errors(include_input=False)
352
+ )
353
+
354
+
355
+ def _cmd_push(args: argparse.Namespace) -> int:
356
+ ref_metadata_given = (
357
+ args.commit is not None or args.pr is not None or args.title is not None
358
+ )
359
+ if args.ref is None and ref_metadata_given:
360
+ print(
361
+ "error: --commit/--pr/--title only apply to the reflog entry written "
362
+ "by --ref. Pass --ref or drop them.",
363
+ file=sys.stderr,
364
+ )
365
+ return 2
366
+ if args.title is not None and args.pr is None:
367
+ print(
368
+ "error: --title records a PR title, so it needs --pr.",
369
+ file=sys.stderr,
370
+ )
371
+ return 2
372
+ run_path: Path = args.run_file
373
+ if not run_path.exists():
374
+ print(f"error: run file not found: {run_path}", file=sys.stderr)
375
+ return 2
376
+ if not run_path.is_file():
377
+ print(f"error: not a file: {run_path}", file=sys.stderr)
378
+ return 2
379
+ # Parse before touching the repository, so an unreadable file fails before
380
+ # anything is saved.
381
+ try:
382
+ run = parse_run_json(run_path.read_bytes())
383
+ except ValidationError as exc:
384
+ print(
385
+ f"error: {run_path} does not parse as a run file:"
386
+ f"{_describe_run_errors(exc)}",
387
+ file=sys.stderr,
388
+ )
389
+ return 2
390
+
391
+ target = _open_resolved_repository(args)
392
+ if args.ref is not None:
393
+ # Before the save, so an invalid name cannot leave an orphan run behind.
394
+ target.repository.validate_ref_name(args.ref)
395
+ target.repository.save_run(run)
396
+
397
+ if args.ref is not None:
398
+ target.repository.move_ref(
399
+ args.ref,
400
+ run.id,
401
+ commit=args.commit,
402
+ pr=args.pr,
403
+ title=args.title,
404
+ )
405
+ print(f"pushed run {run.id} to {target.url}. ref {args.ref} -> {run.id}")
406
+ else:
407
+ print(f"pushed run {run.id} to {target.url}")
408
+ return 0
409
+
410
+
411
+ def _cmd_promote(args: argparse.Namespace) -> int:
412
+ if args.ref == BASELINE_REF:
413
+ print(
414
+ f"error: cannot promote {BASELINE_REF!r}: promoting the baseline "
415
+ "onto itself does nothing, and --cleanup would delete the "
416
+ "baseline ref. Pass a source ref such as pr/123.",
417
+ file=sys.stderr,
418
+ )
419
+ return 2
420
+ target = _open_resolved_repository(args)
421
+ result = promote(
422
+ target.repository, args.ref, commit=args.commit, cleanup=args.cleanup
423
+ )
424
+ baseline = result.baseline
425
+ # Print the reflog's commit rather than the flag, since a re-promote keeps
426
+ # the tip's stored commit.
427
+ print(
428
+ f"promoted {args.ref} -> baseline ({baseline.run_id})"
429
+ + (f" at commit {_printable(baseline.commit)}" if baseline.commit else "")
430
+ )
431
+ if result.cleanup is not None:
432
+ print(f"cleaned up {args.ref} and its superseded runs")
433
+ return 0
434
+
435
+
436
+ def _cmd_runs(args: argparse.Namespace) -> int:
437
+ target = _open_resolved_repository(args)
438
+ listed = 0
439
+ for listed, summary in enumerate(target.repository.list_runs(), start=1):
440
+ print(_format_run(summary))
441
+ if listed == args.limit:
442
+ break
443
+ if not listed:
444
+ print(f"note: {target.url} holds no runs yet", file=sys.stderr)
445
+ return 0
446
+
447
+
448
+ def _cmd_refs(args: argparse.Namespace) -> int:
449
+ target = _open_resolved_repository(args)
450
+ lines = _format_ref_lines(target.repository)
451
+ for line in lines:
452
+ print(line)
453
+ if not lines:
454
+ print(f"note: {target.url} holds no refs yet", file=sys.stderr)
455
+ return 0
456
+
457
+
458
+ def _cmd_export(args: argparse.Namespace) -> int:
459
+ target = _open_resolved_repository(args)
460
+ run = target.repository.load_run(args.run_id)
461
+ if run is None:
462
+ # A missing run is a defined outcome, so exit 1, not the usage error 2.
463
+ print(f"export: run {args.run_id!r} not found in {target.url}", file=sys.stderr)
464
+ return 1
465
+ print(dump_run_json(run).decode())
466
+ return 0
467
+
468
+
469
+ def _resolve_ui_mounts(config: EvaltrackConfig) -> list[tuple[str, RepositoryRole]]:
470
+ """The (url, role) pairs `evaltrack ui` mounts, the remote only when configured."""
471
+ mounts: list[tuple[str, RepositoryRole]] = [(resolve_local(config), "local")]
472
+ remote = resolve_remote(config)
473
+ if remote is not None:
474
+ mounts.append((remote.url, "remote"))
475
+ return mounts
476
+
477
+
478
+ def _cmd_ui(args: argparse.Namespace) -> int:
479
+ # Imported late, so the other commands do not pay the FastAPI/uvicorn cost.
480
+ try:
481
+ import uvicorn
482
+
483
+ from evaltrack.ui.app import MountedRepository, create_app
484
+ except ImportError as exc: # pragma: no cover - exercised only when extras missing
485
+ print(
486
+ f"error: the dashboard requires the `evaltrack[ui]` extra ({exc}).",
487
+ file=sys.stderr,
488
+ )
489
+ return 2
490
+
491
+ config = load_config()
492
+ ui_url = _build_ui_url(args.port, args.run_id)
493
+
494
+ # The role is the slug, since there is at most one mount per role.
495
+ # A URL that carries a credential is rejected when it is opened, so an
496
+ # opened URL is safe to print and an unopened one is not.
497
+ repositories: dict[str, MountedRepository] = {}
498
+ for url, role in _resolve_ui_mounts(config):
499
+ try:
500
+ repository = open_repository(url)
501
+ if role == "local":
502
+ # A network remote can take a minute to fail, and the dashboard
503
+ # should be serving local runs before then. An unreachable remote
504
+ # fails per request.
505
+ repository.verify_available()
506
+ except (ValueError, ImportError, RepositoryUnavailableError) as exc:
507
+ if role == "local":
508
+ raise
509
+ print(
510
+ f"warning: skipping the configured remote: {_first_line(exc)}. "
511
+ "Serving the local repository only.",
512
+ file=sys.stderr,
513
+ )
514
+ continue
515
+ # Naming the repository shows a plugin and a dashboard that landed on
516
+ # different pyproject.toml files.
517
+ print(f"mounted {role} repository {url}", file=sys.stderr)
518
+ repositories[role] = MountedRepository(
519
+ url=url, repository=repository, role=role
520
+ )
521
+
522
+ app = create_app(repositories, pr_url_template=config.pr_url_template)
523
+
524
+ # Printed before the server takes over the process, so the link is on
525
+ # screen whether or not uvicorn binds.
526
+ print(f"dashboard: {ui_url}", file=sys.stderr)
527
+ uvicorn.run(app, host=_UI_HOST, port=args.port)
528
+ return 0
529
+
530
+
531
+ # --- formatting output ---
532
+
533
+
534
+ def _format_run(run: RunSummary) -> str:
535
+ """One line: run id, time, the checkout it ran on, its outcome, its branch."""
536
+ commit = _printable(run.commit[:8]) if run.commit else "no-commit"
537
+ if run.worktree_dirty:
538
+ commit += "-dirty"
539
+ if run.tests_total == 0:
540
+ outcome = "no tests"
541
+ elif run.tests_failed:
542
+ outcome = f"{run.tests_failed}/{run.tests_total} failed"
543
+ else:
544
+ # The summary counts failures only. Skipped and expected-failure
545
+ # tests are in the total, so the line cannot claim they all passed.
546
+ outcome = f"{run.tests_total} tests, none failed"
547
+ # 14 is the widest commit column, eight characters plus the dirty marker.
548
+ fields = [run.id, _format_time(run.created_at), commit.ljust(14), outcome]
549
+ if branch := run.labels.get("branch"):
550
+ fields.append(f"({_printable(branch)})")
551
+ return " ".join(fields)
552
+
553
+
554
+ # Baseline first, since the mainline is what a reader looks for.
555
+ _REF_ORDER = {RefKind.BASELINE: 0, RefKind.PR: 1, RefKind.OTHER: 2}
556
+
557
+
558
+ def _format_ref_lines(repository: RunRepository) -> list[str]:
559
+ """One ref per line, ordered by kind then name. An unreadable ref is listed
560
+ without a target."""
561
+ rows: list[tuple[Ref, str]] = []
562
+ for name in repository.list_refs():
563
+ try:
564
+ tip = repository.get_ref(name)
565
+ except (CorruptRecordError, InvalidIdentifierError):
566
+ rows.append((Ref(name=name), "unreadable history"))
567
+ continue
568
+ rows.append((Ref(name=name, tip=tip), _format_ref_target(tip)))
569
+ rows.sort(key=lambda row: (_REF_ORDER[row[0].kind], row[0].name))
570
+ width = max((len(ref.name) for ref, _ in rows), default=0)
571
+ return [f"{_printable(ref.name).ljust(width)} {target}" for ref, target in rows]
572
+
573
+
574
+ def _format_ref_target(tip: ReflogEntry | None) -> str:
575
+ """The run a ref points at, when it moved there, and the PR when the move recorded
576
+ one."""
577
+ if tip is None:
578
+ return "no target"
579
+ fields = [tip.run_id, _format_time(tip.moved_at)]
580
+ if tip.pr is not None:
581
+ fields.append(
582
+ f"#{tip.pr}" if tip.title is None else f"#{tip.pr} {_printable(tip.title)}"
583
+ )
584
+ return " ".join(fields)
585
+
586
+
587
+ def _printable(text: str) -> str:
588
+ # A commit, a branch and a PR title all come from outside, so keep escape
589
+ # sequences out of the terminal.
590
+ return "".join(char if char.isprintable() else "?" for char in text)
591
+
592
+
593
+ def _format_time(when: datetime) -> str:
594
+ """Timestamps in UTC, so runs recorded on different machines line up."""
595
+ return when.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
596
+
597
+
598
+ def _first_line(exc: BaseException) -> str:
599
+ """A storage SDK can raise a multi-line message. One line is enough for a warning."""
600
+ text = str(exc).strip()
601
+ return text.splitlines()[0].rstrip(".") if text else type(exc).__name__
602
+
603
+
604
+ def _build_ui_url(port: int, run_id: str | None) -> str:
605
+ base = f"http://{_UI_HOST}:{port}/"
606
+ return base if run_id is None else f"{base}?run={run_id}"