diffscore 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.
- diffscore/__init__.py +3 -0
- diffscore/api.py +729 -0
- diffscore/calibration.py +374 -0
- diffscore/cli.py +867 -0
- diffscore/config.py +88 -0
- diffscore/db/__init__.py +27 -0
- diffscore/db/base.py +25 -0
- diffscore/db/migrate.py +61 -0
- diffscore/db/models.py +257 -0
- diffscore/db/session.py +37 -0
- diffscore/diffing.py +292 -0
- diffscore/graders.py +281 -0
- diffscore/jobs.py +161 -0
- diffscore/judge.py +355 -0
- diffscore/labeling.py +167 -0
- diffscore/llm.py +120 -0
- diffscore/migrations/README +1 -0
- diffscore/migrations/env.py +84 -0
- diffscore/migrations/script.py.mako +28 -0
- diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
- diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
- diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
- diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
- diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
- diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
- diffscore/queries.py +165 -0
- diffscore/runner.py +393 -0
- diffscore/secrets.py +130 -0
- diffscore/stats.py +83 -0
- diffscore/suite.py +329 -0
- diffscore/templates/env.example +14 -0
- diffscore/templates/example-prompt.md +14 -0
- diffscore/templates/example.yaml +75 -0
- diffscore-0.1.0.dist-info/METADATA +351 -0
- diffscore-0.1.0.dist-info/RECORD +38 -0
- diffscore-0.1.0.dist-info/WHEEL +4 -0
- diffscore-0.1.0.dist-info/entry_points.txt +2 -0
- diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/cli.py
ADDED
|
@@ -0,0 +1,867 @@
|
|
|
1
|
+
"""`diffscore` command line. A thin layer: every command calls a service function
|
|
2
|
+
(`runner`, `queries`) and only formats what comes back."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from decimal import Decimal
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Annotated
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.markup import escape
|
|
15
|
+
from rich.progress import BarColumn, MofNCompleteColumn, Progress, TextColumn, TimeElapsedColumn
|
|
16
|
+
from rich.table import Table
|
|
17
|
+
from sqlalchemy.exc import OperationalError, ProgrammingError
|
|
18
|
+
from sqlalchemy.orm import Session
|
|
19
|
+
|
|
20
|
+
from diffscore import __version__
|
|
21
|
+
from diffscore.config import get_settings
|
|
22
|
+
from diffscore.llm import describe_error
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from diffscore.llm import CompleteFn
|
|
26
|
+
from diffscore.suite import LoadedSuite, SuiteFile
|
|
27
|
+
|
|
28
|
+
app = typer.Typer(no_args_is_help=True, add_completion=False)
|
|
29
|
+
console = Console()
|
|
30
|
+
|
|
31
|
+
STYLE = {"pass": "green", "fail": "red", "error": "yellow", "ungraded": "dim"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@contextmanager
|
|
35
|
+
def _db() -> Iterator[Session]:
|
|
36
|
+
"""A session, with the two setup mistakes turned into instructions."""
|
|
37
|
+
from diffscore.db.session import make_session
|
|
38
|
+
|
|
39
|
+
session: Session | None = None
|
|
40
|
+
try:
|
|
41
|
+
session = make_session() # on SQLite this also creates or upgrades the schema
|
|
42
|
+
yield session
|
|
43
|
+
except OperationalError as exc:
|
|
44
|
+
hint = (
|
|
45
|
+
"Check that the folder is writable, or set DATABASE_URL."
|
|
46
|
+
if get_settings().database_url.startswith("sqlite")
|
|
47
|
+
else "Start it with [bold]docker compose up -d[/bold] and check DATABASE_URL."
|
|
48
|
+
)
|
|
49
|
+
console.print(
|
|
50
|
+
f"[red]database not reachable.[/red] {hint}\n"
|
|
51
|
+
f"[dim]{escape(describe_error(exc.orig or exc))}[/dim]"
|
|
52
|
+
)
|
|
53
|
+
raise typer.Exit(2) from exc
|
|
54
|
+
except ModuleNotFoundError as exc:
|
|
55
|
+
if exc.name != "psycopg":
|
|
56
|
+
raise
|
|
57
|
+
console.print(
|
|
58
|
+
"[red]DATABASE_URL points at Postgres, but its driver isn't installed.[/red] "
|
|
59
|
+
'Run [bold]pip install "diffscore\\[postgres]"[/bold], or unset DATABASE_URL '
|
|
60
|
+
"to use the local SQLite file."
|
|
61
|
+
)
|
|
62
|
+
raise typer.Exit(2) from exc
|
|
63
|
+
except ProgrammingError as exc:
|
|
64
|
+
if "does not exist" not in str(exc):
|
|
65
|
+
raise
|
|
66
|
+
console.print(
|
|
67
|
+
"[red]database schema missing or out of date.[/red] Run [bold]diffscore migrate[/bold]."
|
|
68
|
+
)
|
|
69
|
+
raise typer.Exit(2) from exc
|
|
70
|
+
finally:
|
|
71
|
+
if session is not None:
|
|
72
|
+
session.close()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _load(path: Path) -> LoadedSuite:
|
|
76
|
+
from diffscore.suite import SuiteError, load_suite
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
return load_suite(path)
|
|
80
|
+
except SuiteError as exc:
|
|
81
|
+
console.print(f"[red]{escape(exc.path)} is not a valid suite:[/red]")
|
|
82
|
+
for line in exc.problems:
|
|
83
|
+
console.print(f" - {escape(line)}")
|
|
84
|
+
raise typer.Exit(2) from exc
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _paced(spec: SuiteFile, rpm: float | None, judge_rpm: float | None) -> CompleteFn:
|
|
88
|
+
"""The real model function, paced per model: answers at RPM, judges at JUDGE_RPM."""
|
|
89
|
+
from diffscore.judge import parse_config
|
|
90
|
+
from diffscore.llm import complete, throttled
|
|
91
|
+
|
|
92
|
+
settings = get_settings()
|
|
93
|
+
answers = rpm if rpm is not None else settings.model_rpm
|
|
94
|
+
judges = judge_rpm if judge_rpm is not None else settings.judge_rpm
|
|
95
|
+
per_model: dict[str, float | None] = {
|
|
96
|
+
parse_config(g.arg).judge_model(): judges or answers
|
|
97
|
+
for g in spec.all_graders()
|
|
98
|
+
if g.name == "judge"
|
|
99
|
+
}
|
|
100
|
+
return throttled(complete, answers, per_model=per_model)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
JUDGE_RPM_HELP = "Max judge calls per minute (default: JUDGE_RPM, else --rpm)."
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _short(text: str, width: int = 90) -> str:
|
|
107
|
+
flat = " ".join(text.split())
|
|
108
|
+
return flat if len(flat) <= width else flat[: width - 3] + "..."
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _money(value: Decimal | float) -> str:
|
|
112
|
+
return f"${float(value):.6f}"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# ------------------------------------------------------------------ commands
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@app.command()
|
|
119
|
+
def version() -> None:
|
|
120
|
+
"""Print the installed version."""
|
|
121
|
+
console.print(f"diffscore {__version__}")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@app.command()
|
|
125
|
+
def validate(suite: Annotated[Path, typer.Argument(help="Suite YAML file.")]) -> None:
|
|
126
|
+
"""Check a suite file without running it."""
|
|
127
|
+
loaded = _load(suite)
|
|
128
|
+
spec = loaded.spec
|
|
129
|
+
graders = sum(len(spec.graders_for(c)) for c in spec.cases)
|
|
130
|
+
console.print(
|
|
131
|
+
f"[green]ok[/green] {escape(spec.name)}: {len(spec.cases)} cases, "
|
|
132
|
+
f"{graders} grader checks, model {escape(spec.model or get_settings().default_model)}"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@app.command()
|
|
137
|
+
def run(
|
|
138
|
+
suite: Annotated[Path, typer.Argument(help="Suite YAML file.")],
|
|
139
|
+
model: Annotated[
|
|
140
|
+
str | None, typer.Option(help="Override the suite's model (any LiteLLM model string).")
|
|
141
|
+
] = None,
|
|
142
|
+
rpm: Annotated[
|
|
143
|
+
float | None,
|
|
144
|
+
typer.Option(help="Max model calls per minute (default: MODEL_RPM). Cache hits are free."),
|
|
145
|
+
] = None,
|
|
146
|
+
judge_rpm: Annotated[float | None, typer.Option(help=JUDGE_RPM_HELP)] = None,
|
|
147
|
+
baseline: Annotated[
|
|
148
|
+
str | None,
|
|
149
|
+
typer.Option(
|
|
150
|
+
help="Compare against this run id, or 'previous' for the last completed run of "
|
|
151
|
+
"the suite. Default: the suite's baseline."
|
|
152
|
+
),
|
|
153
|
+
] = None,
|
|
154
|
+
no_diff: Annotated[
|
|
155
|
+
bool, typer.Option("--no-diff", help="Don't compare against a baseline.")
|
|
156
|
+
] = False,
|
|
157
|
+
alpha: Annotated[float, typer.Option(help="Significance level for the verdict.")] = 0.05,
|
|
158
|
+
quiet: Annotated[bool, typer.Option("--quiet", "-q", help="Only print the summary.")] = False,
|
|
159
|
+
) -> None:
|
|
160
|
+
"""Run a suite, print per-case pass/fail, then diff against the baseline.
|
|
161
|
+
|
|
162
|
+
Exits 1 on a statistically significant regression (or a run that stopped
|
|
163
|
+
early), 0 otherwise, so it can gate CI.
|
|
164
|
+
"""
|
|
165
|
+
from diffscore.runner import CaseOutcome, run_suite
|
|
166
|
+
|
|
167
|
+
loaded = _load(suite)
|
|
168
|
+
settings = get_settings()
|
|
169
|
+
chosen = model or loaded.spec.model or settings.default_model
|
|
170
|
+
|
|
171
|
+
with (
|
|
172
|
+
_db() as session,
|
|
173
|
+
Progress(
|
|
174
|
+
TextColumn("[bold]{task.description}"),
|
|
175
|
+
BarColumn(),
|
|
176
|
+
MofNCompleteColumn(),
|
|
177
|
+
TimeElapsedColumn(),
|
|
178
|
+
TextColumn("[dim]{task.fields[last]}"),
|
|
179
|
+
console=console,
|
|
180
|
+
transient=True,
|
|
181
|
+
) as progress,
|
|
182
|
+
):
|
|
183
|
+
task = progress.add_task(loaded.spec.name, total=len(loaded.spec.cases), last="")
|
|
184
|
+
|
|
185
|
+
def tick(o: CaseOutcome) -> None:
|
|
186
|
+
progress.update(task, advance=1, last=f"{o.key}: {o.outcome}")
|
|
187
|
+
|
|
188
|
+
from diffscore.graders import GraderConfigError
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
summary = run_suite(
|
|
192
|
+
session,
|
|
193
|
+
loaded.spec,
|
|
194
|
+
_paced(loaded.spec, rpm, judge_rpm),
|
|
195
|
+
model=chosen,
|
|
196
|
+
max_tokens_per_run=settings.max_tokens_per_run,
|
|
197
|
+
on_case=tick,
|
|
198
|
+
)
|
|
199
|
+
except GraderConfigError as exc:
|
|
200
|
+
progress.stop()
|
|
201
|
+
console.print(f"[red]cannot run:[/red] {escape(str(exc))}")
|
|
202
|
+
raise typer.Exit(2) from exc
|
|
203
|
+
|
|
204
|
+
if not quiet:
|
|
205
|
+
table = Table(title=f"run #{summary.run_id} | {loaded.spec.name} | {chosen}")
|
|
206
|
+
table.add_column("case")
|
|
207
|
+
table.add_column("result")
|
|
208
|
+
table.add_column("why", overflow="fold")
|
|
209
|
+
for o in summary.cases:
|
|
210
|
+
mark = " [dim](cached)[/dim]" if o.cache_hit else ""
|
|
211
|
+
table.add_row(
|
|
212
|
+
escape(o.key),
|
|
213
|
+
f"[{STYLE[o.outcome]}]{o.outcome}[/]{mark}",
|
|
214
|
+
escape("; ".join(o.failures)),
|
|
215
|
+
)
|
|
216
|
+
console.print(table)
|
|
217
|
+
|
|
218
|
+
counts = summary.outcomes
|
|
219
|
+
parts = [f"[green]{counts['pass']} passed[/green]", f"[red]{counts['fail']} failed[/red]"]
|
|
220
|
+
if counts["error"]:
|
|
221
|
+
parts.append(f"[yellow]{counts['error']} errors[/yellow]")
|
|
222
|
+
if counts["ungraded"]:
|
|
223
|
+
parts.append(f"{counts['ungraded']} ungraded")
|
|
224
|
+
console.print(
|
|
225
|
+
f"{' | '.join(parts)} of {summary.total} | "
|
|
226
|
+
f"{summary.api_calls} API calls, {summary.cache_hits} cache hits | "
|
|
227
|
+
f"{summary.tokens_spent:,} tokens, {_money(summary.cost_spent)} spent | "
|
|
228
|
+
f"run #{summary.run_id}"
|
|
229
|
+
)
|
|
230
|
+
if summary.stopped_reason:
|
|
231
|
+
console.print(f"[yellow]stopped early:[/yellow] {escape(summary.stopped_reason)}")
|
|
232
|
+
raise typer.Exit(1)
|
|
233
|
+
if no_diff:
|
|
234
|
+
return
|
|
235
|
+
|
|
236
|
+
from diffscore.diffing import adopt_if_no_baseline, previous_run, suite_baseline
|
|
237
|
+
|
|
238
|
+
with _db() as session:
|
|
239
|
+
if baseline is None:
|
|
240
|
+
base_id = suite_baseline(session, summary.run_id)
|
|
241
|
+
elif baseline == "previous":
|
|
242
|
+
base_id = previous_run(session, summary.run_id)
|
|
243
|
+
if base_id is None:
|
|
244
|
+
console.print("[yellow]no earlier completed run to compare against.[/yellow]")
|
|
245
|
+
return
|
|
246
|
+
else:
|
|
247
|
+
base_id = _run_id(baseline)
|
|
248
|
+
|
|
249
|
+
if base_id is None:
|
|
250
|
+
if adopt_if_no_baseline(session, summary.run_id):
|
|
251
|
+
console.print(
|
|
252
|
+
f"\nrun #{summary.run_id} is now the baseline for "
|
|
253
|
+
f"[bold]{escape(loaded.spec.name)}[/bold]; later runs are diffed against it. "
|
|
254
|
+
"Move it with [bold]diffscore baseline <run>[/bold]."
|
|
255
|
+
)
|
|
256
|
+
return
|
|
257
|
+
_diff_and_exit(session, base_id, summary.run_id, alpha=alpha, show_all=False)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _run_id(text: str) -> int:
|
|
261
|
+
try:
|
|
262
|
+
return int(text.removeprefix("#"))
|
|
263
|
+
except ValueError:
|
|
264
|
+
console.print(f"[red]{escape(text)!r} is not a run id[/red] (or use 'previous')")
|
|
265
|
+
raise typer.Exit(2) from None
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
CHANGE_STYLE = {
|
|
269
|
+
"regressed": "red",
|
|
270
|
+
"improved": "green",
|
|
271
|
+
"unchanged": "dim",
|
|
272
|
+
"new": "cyan",
|
|
273
|
+
"removed": "magenta",
|
|
274
|
+
"excluded": "yellow",
|
|
275
|
+
}
|
|
276
|
+
VERDICT_STYLE = {
|
|
277
|
+
"regression": "bold white on red",
|
|
278
|
+
"improvement": "bold white on green",
|
|
279
|
+
"no_change": "bold",
|
|
280
|
+
"nothing_to_compare": "bold yellow",
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _diff_and_exit(session: Session, a_id: int, b_id: int, *, alpha: float, show_all: bool) -> None:
|
|
285
|
+
"""Print the verdict first, then the detail, and exit with the verdict's code."""
|
|
286
|
+
from diffscore.diffing import DiffError, diff_runs
|
|
287
|
+
|
|
288
|
+
try:
|
|
289
|
+
d = diff_runs(session, a_id, b_id, alpha=alpha)
|
|
290
|
+
except DiffError as exc:
|
|
291
|
+
console.print(f"[red]{escape(str(exc))}[/red]")
|
|
292
|
+
raise typer.Exit(2) from exc
|
|
293
|
+
|
|
294
|
+
console.print()
|
|
295
|
+
console.print(f" {d.headline} ", style=VERDICT_STYLE[d.verdict])
|
|
296
|
+
console.print(
|
|
297
|
+
f"run #{d.a.id} (baseline) -> run #{d.b.id} | {escape(d.what_changed)} | "
|
|
298
|
+
f"{escape(d.a.suite)}"
|
|
299
|
+
)
|
|
300
|
+
c = d.counts
|
|
301
|
+
detail = [
|
|
302
|
+
f"[red]{c['regressed']} regressed[/red]",
|
|
303
|
+
f"[green]{c['improved']} improved[/green]",
|
|
304
|
+
f"{c['unchanged']} unchanged",
|
|
305
|
+
]
|
|
306
|
+
detail += [f"{c[k]} {k}" for k in ("new", "removed", "excluded") if c[k]]
|
|
307
|
+
console.print(f"{', '.join(detail)} | {d.method}, alpha {d.alpha:g}")
|
|
308
|
+
if d.interval is not None:
|
|
309
|
+
i = d.interval
|
|
310
|
+
note = "" if i.excludes_zero else ", includes 0"
|
|
311
|
+
console.print(
|
|
312
|
+
f"mean score change {i.mean:+.3f} "
|
|
313
|
+
f"({i.level:.0%} CI {i.low:+.3f} to {i.high:+.3f}{note})"
|
|
314
|
+
)
|
|
315
|
+
if d.too_small_note:
|
|
316
|
+
console.print(f"[yellow]note:[/yellow] {escape(d.too_small_note)}")
|
|
317
|
+
|
|
318
|
+
shown = [x for x in d.cases if show_all or x.change != "unchanged"]
|
|
319
|
+
if shown:
|
|
320
|
+
table = Table()
|
|
321
|
+
table.add_column("case")
|
|
322
|
+
table.add_column("change")
|
|
323
|
+
table.add_column("before -> after")
|
|
324
|
+
table.add_column("why", overflow="fold")
|
|
325
|
+
for x in shown:
|
|
326
|
+
table.add_row(
|
|
327
|
+
escape(x.key),
|
|
328
|
+
f"[{CHANGE_STYLE[x.change]}]{x.change}[/]",
|
|
329
|
+
f"{x.before or '-'} -> {x.after or '-'}",
|
|
330
|
+
escape("; ".join(x.why)),
|
|
331
|
+
)
|
|
332
|
+
console.print(table)
|
|
333
|
+
raise typer.Exit(d.exit_code)
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
@app.command()
|
|
337
|
+
def diff(
|
|
338
|
+
runs: Annotated[
|
|
339
|
+
list[str],
|
|
340
|
+
typer.Argument(
|
|
341
|
+
help="BASELINE CANDIDATE, or just CANDIDATE to compare with its suite's baseline."
|
|
342
|
+
),
|
|
343
|
+
],
|
|
344
|
+
alpha: Annotated[float, typer.Option(help="Significance level for the verdict.")] = 0.05,
|
|
345
|
+
show_all: Annotated[bool, typer.Option("--all", help="Also list unchanged cases.")] = False,
|
|
346
|
+
) -> None:
|
|
347
|
+
"""Compare two runs: the verdict with a p-value, then the cases that changed.
|
|
348
|
+
|
|
349
|
+
Exits 1 on a statistically significant regression, 0 otherwise.
|
|
350
|
+
"""
|
|
351
|
+
from diffscore.diffing import DiffError, suite_baseline
|
|
352
|
+
|
|
353
|
+
if not 1 <= len(runs) <= 2:
|
|
354
|
+
console.print("[red]give one run id (diffed against its baseline) or two.[/red]")
|
|
355
|
+
raise typer.Exit(2)
|
|
356
|
+
ids = [_run_id(r) for r in runs]
|
|
357
|
+
with _db() as session:
|
|
358
|
+
if len(ids) == 1:
|
|
359
|
+
try:
|
|
360
|
+
base = suite_baseline(session, ids[0])
|
|
361
|
+
except DiffError as exc:
|
|
362
|
+
console.print(f"[red]{escape(str(exc))}[/red]")
|
|
363
|
+
raise typer.Exit(2) from exc
|
|
364
|
+
if base is None:
|
|
365
|
+
console.print(
|
|
366
|
+
f"[red]run #{ids[0]}'s suite has no other baseline.[/red] Set one with "
|
|
367
|
+
"[bold]diffscore baseline <run>[/bold] or pass two run ids."
|
|
368
|
+
)
|
|
369
|
+
raise typer.Exit(2)
|
|
370
|
+
ids.insert(0, base)
|
|
371
|
+
_diff_and_exit(session, ids[0], ids[1], alpha=alpha, show_all=show_all)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
@app.command(name="baseline")
|
|
375
|
+
def baseline_cmd(
|
|
376
|
+
run_id: Annotated[str, typer.Argument(help="Run to make its suite's baseline.")],
|
|
377
|
+
) -> None:
|
|
378
|
+
"""Make a run the baseline that later runs of its suite are diffed against."""
|
|
379
|
+
from diffscore.diffing import DiffError, set_baseline
|
|
380
|
+
|
|
381
|
+
with _db() as session:
|
|
382
|
+
try:
|
|
383
|
+
suite_name = set_baseline(session, _run_id(run_id))
|
|
384
|
+
except DiffError as exc:
|
|
385
|
+
console.print(f"[red]{escape(str(exc))}[/red]")
|
|
386
|
+
raise typer.Exit(2) from exc
|
|
387
|
+
console.print(
|
|
388
|
+
f"run #{_run_id(run_id)} is now the baseline for [bold]{escape(suite_name)}[/bold]"
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
@app.command()
|
|
393
|
+
def runs(
|
|
394
|
+
suite: Annotated[str | None, typer.Option(help="Only runs of this suite.")] = None,
|
|
395
|
+
limit: Annotated[int, typer.Option(help="How many to show.")] = 20,
|
|
396
|
+
) -> None:
|
|
397
|
+
"""List recent runs, newest first."""
|
|
398
|
+
from diffscore.diffing import baseline_ids
|
|
399
|
+
from diffscore.queries import list_runs
|
|
400
|
+
|
|
401
|
+
with _db() as session:
|
|
402
|
+
rows = list_runs(session, suite=suite, limit=limit)
|
|
403
|
+
baselines = baseline_ids(session)
|
|
404
|
+
if not rows:
|
|
405
|
+
console.print("no runs yet. Try [bold]diffscore run examples/support.yaml[/bold]")
|
|
406
|
+
return
|
|
407
|
+
|
|
408
|
+
table = Table()
|
|
409
|
+
for col in (
|
|
410
|
+
"run",
|
|
411
|
+
"suite",
|
|
412
|
+
"model",
|
|
413
|
+
"status",
|
|
414
|
+
"pass",
|
|
415
|
+
"fail",
|
|
416
|
+
"err",
|
|
417
|
+
"cached",
|
|
418
|
+
"spent",
|
|
419
|
+
"when",
|
|
420
|
+
):
|
|
421
|
+
table.add_column(
|
|
422
|
+
col, justify="right" if col in {"pass", "fail", "err", "cached"} else "left"
|
|
423
|
+
)
|
|
424
|
+
for r in rows:
|
|
425
|
+
table.add_row(
|
|
426
|
+
f"#{r.id}" + (" [bold cyan]base[/]" if r.id in baselines else ""),
|
|
427
|
+
escape(r.suite),
|
|
428
|
+
escape(r.model),
|
|
429
|
+
r.status,
|
|
430
|
+
f"[green]{r.outcomes['pass']}[/green]",
|
|
431
|
+
f"[red]{r.outcomes['fail']}[/red]",
|
|
432
|
+
str(r.outcomes["error"]),
|
|
433
|
+
f"{r.cache_hits}/{r.total}",
|
|
434
|
+
_money(r.cost),
|
|
435
|
+
r.created_at.strftime("%Y-%m-%d %H:%M"),
|
|
436
|
+
)
|
|
437
|
+
console.print(table)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
@app.command()
|
|
441
|
+
def show(
|
|
442
|
+
run_id: Annotated[int, typer.Argument(help="Run id, from `diffscore runs`.")],
|
|
443
|
+
failed: Annotated[
|
|
444
|
+
bool, typer.Option("--failed", help="Only failing and errored cases.")
|
|
445
|
+
] = False,
|
|
446
|
+
outputs: Annotated[bool, typer.Option("--outputs", help="Include model outputs.")] = False,
|
|
447
|
+
) -> None:
|
|
448
|
+
"""Show one run case by case."""
|
|
449
|
+
from diffscore.queries import run_detail
|
|
450
|
+
|
|
451
|
+
with _db() as session:
|
|
452
|
+
try:
|
|
453
|
+
run_row, cases = run_detail(session, run_id)
|
|
454
|
+
except LookupError as exc:
|
|
455
|
+
console.print(f"[red]{exc}[/red]")
|
|
456
|
+
raise typer.Exit(1) from exc
|
|
457
|
+
|
|
458
|
+
table = Table(title=f"run #{run_row.id} | {run_row.suite} | {run_row.model} | {run_row.status}")
|
|
459
|
+
table.add_column("case")
|
|
460
|
+
table.add_column("result")
|
|
461
|
+
table.add_column("ms", justify="right")
|
|
462
|
+
table.add_column("tokens", justify="right")
|
|
463
|
+
table.add_column("why", overflow="fold")
|
|
464
|
+
if outputs:
|
|
465
|
+
table.add_column("output", overflow="fold")
|
|
466
|
+
for c in cases:
|
|
467
|
+
if failed and c.outcome in {"pass", "ungraded"}:
|
|
468
|
+
continue
|
|
469
|
+
row = [
|
|
470
|
+
escape(c.key),
|
|
471
|
+
f"[{STYLE[c.outcome]}]{c.outcome}[/]" + (" [dim](cached)[/dim]" if c.cache_hit else ""),
|
|
472
|
+
"" if c.latency_ms is None else str(c.latency_ms),
|
|
473
|
+
"" if c.tokens is None else str(c.tokens),
|
|
474
|
+
escape("; ".join(c.failures)),
|
|
475
|
+
]
|
|
476
|
+
if outputs:
|
|
477
|
+
row.append(escape(_short(c.output or "", 200)))
|
|
478
|
+
table.add_row(*row)
|
|
479
|
+
console.print(table)
|
|
480
|
+
|
|
481
|
+
o = run_row.outcomes
|
|
482
|
+
console.print(
|
|
483
|
+
f"[green]{o['pass']} passed[/green] | [red]{o['fail']} failed[/red] | "
|
|
484
|
+
f"{o['error']} errors of {run_row.total} | {run_row.cache_hits} cached | "
|
|
485
|
+
f"{run_row.tokens:,} tokens, {_money(run_row.cost)} spent"
|
|
486
|
+
)
|
|
487
|
+
if run_row.error:
|
|
488
|
+
console.print(f"[yellow]stopped early:[/yellow] {escape(run_row.error)}")
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
@app.command()
|
|
492
|
+
def label(
|
|
493
|
+
run_id: Annotated[str, typer.Argument(help="Run whose outputs you want to label.")],
|
|
494
|
+
grader: Annotated[
|
|
495
|
+
str | None,
|
|
496
|
+
typer.Option(
|
|
497
|
+
help="Judge these labels calibrate, e.g. 'judge' or 'judge:tone'. Default: the "
|
|
498
|
+
"run's only judge, or an overall label if it has none."
|
|
499
|
+
),
|
|
500
|
+
] = None,
|
|
501
|
+
relabel: Annotated[
|
|
502
|
+
bool, typer.Option("--relabel", help="Also show outputs you've already labelled.")
|
|
503
|
+
] = False,
|
|
504
|
+
) -> None:
|
|
505
|
+
"""Label a run's outputs pass/fail yourself: the gold set the judge is measured against.
|
|
506
|
+
|
|
507
|
+
You see the input and the output, never the judge's verdict, so it can't anchor
|
|
508
|
+
you. One label covers that exact output in every run that reuses it.
|
|
509
|
+
"""
|
|
510
|
+
from rich.panel import Panel
|
|
511
|
+
|
|
512
|
+
from diffscore.labeling import LabelError, judges_in_run, label_queue, rubric_lines, save_label
|
|
513
|
+
|
|
514
|
+
rid = _run_id(run_id)
|
|
515
|
+
with _db() as session:
|
|
516
|
+
if grader is None:
|
|
517
|
+
judges = judges_in_run(session, rid)
|
|
518
|
+
if len(judges) > 1:
|
|
519
|
+
console.print(f"[red]run #{rid} has several judges[/red]; pick one with --grader")
|
|
520
|
+
raise typer.Exit(2)
|
|
521
|
+
grader = judges[0] if judges else None
|
|
522
|
+
try:
|
|
523
|
+
queue = label_queue(session, rid, grader, relabel=relabel)
|
|
524
|
+
except LabelError as exc:
|
|
525
|
+
console.print(f"[red]{escape(str(exc))}[/red]")
|
|
526
|
+
raise typer.Exit(2) from exc
|
|
527
|
+
if not queue:
|
|
528
|
+
console.print(f"nothing left to label in run #{rid} for {grader or 'overall'}.")
|
|
529
|
+
return
|
|
530
|
+
|
|
531
|
+
rubric = rubric_lines(session, rid, grader) if grader else []
|
|
532
|
+
console.print(
|
|
533
|
+
f"Labelling run #{rid} for [bold]{escape(grader or 'overall quality')}[/bold]: "
|
|
534
|
+
f"{len(queue)} outputs. Keys: [bold]p[/bold]ass [bold]f[/bold]ail "
|
|
535
|
+
"[bold]s[/bold]kip [bold]q[/bold]uit"
|
|
536
|
+
)
|
|
537
|
+
if rubric:
|
|
538
|
+
console.print("Judge as the rubric does. Pass only if every point holds:")
|
|
539
|
+
for line in rubric:
|
|
540
|
+
console.print(f" - {escape(line)}")
|
|
541
|
+
|
|
542
|
+
done = 0
|
|
543
|
+
for i, item in enumerate(queue, 1):
|
|
544
|
+
console.print()
|
|
545
|
+
console.print(
|
|
546
|
+
Panel(
|
|
547
|
+
escape(item.input), title=f"[{i}/{len(queue)}] {escape(item.case_key)}: input"
|
|
548
|
+
)
|
|
549
|
+
)
|
|
550
|
+
console.print(Panel(escape(item.output), title="output", border_style="cyan"))
|
|
551
|
+
while True:
|
|
552
|
+
key = console.input("[bold]p / f / s / q[/bold] > ").strip().lower()[:1]
|
|
553
|
+
if key in {"p", "f", "s", "q"}:
|
|
554
|
+
break
|
|
555
|
+
if key == "q":
|
|
556
|
+
break
|
|
557
|
+
if key == "s":
|
|
558
|
+
continue
|
|
559
|
+
note = console.input("why it fails (optional) > ").strip() if key == "f" else None
|
|
560
|
+
save_label(session, item.result_id, grader, "pass" if key == "p" else "fail", note)
|
|
561
|
+
done += 1
|
|
562
|
+
console.print(
|
|
563
|
+
f"\nsaved {done} label(s). Check the judge with [bold]diffscore calibrate[/bold]."
|
|
564
|
+
)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _flag(ok: bool) -> str:
|
|
568
|
+
return "[green]ok[/green]" if ok else "[red]FLAG[/red]"
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
@app.command()
|
|
572
|
+
def calibrate(
|
|
573
|
+
suite: Annotated[Path, typer.Argument(help="Suite YAML whose judge to calibrate.")],
|
|
574
|
+
grader: Annotated[
|
|
575
|
+
str | None, typer.Option(help="Which judge, if the suite has several.")
|
|
576
|
+
] = None,
|
|
577
|
+
judge_rpm: Annotated[float | None, typer.Option(help=JUDGE_RPM_HELP)] = None,
|
|
578
|
+
bias_checks: Annotated[
|
|
579
|
+
bool,
|
|
580
|
+
typer.Option(
|
|
581
|
+
"--bias-checks/--no-bias-checks",
|
|
582
|
+
help="Run the position and variance checks (extra judge calls).",
|
|
583
|
+
),
|
|
584
|
+
] = True,
|
|
585
|
+
disagreements: Annotated[
|
|
586
|
+
bool,
|
|
587
|
+
typer.Option(
|
|
588
|
+
"--disagreements",
|
|
589
|
+
help="List every output where you and the judge disagree, with its evidence.",
|
|
590
|
+
),
|
|
591
|
+
] = False,
|
|
592
|
+
) -> None:
|
|
593
|
+
"""Measure the judge against your labels: Cohen's kappa plus its known biases.
|
|
594
|
+
|
|
595
|
+
Re-judges your labelled outputs with the rubric as the suite file defines it
|
|
596
|
+
now, so after rewriting a rubric you calibrate again without regenerating
|
|
597
|
+
anything. Exits 1 if kappa is below 0.6.
|
|
598
|
+
"""
|
|
599
|
+
from diffscore.calibration import (
|
|
600
|
+
KAPPA_OK,
|
|
601
|
+
MIN_LABELS_ADVISED,
|
|
602
|
+
VERBOSITY_FLAG,
|
|
603
|
+
CalibrationError,
|
|
604
|
+
save_report,
|
|
605
|
+
)
|
|
606
|
+
from diffscore.calibration import calibrate as run_calibration
|
|
607
|
+
from diffscore.runner import cached_ask
|
|
608
|
+
|
|
609
|
+
loaded = _load(suite)
|
|
610
|
+
fn = _paced(loaded.spec, None, judge_rpm)
|
|
611
|
+
|
|
612
|
+
with _db() as session, console.status("calibrating ...") as status:
|
|
613
|
+
try:
|
|
614
|
+
r = run_calibration(
|
|
615
|
+
session,
|
|
616
|
+
loaded.spec,
|
|
617
|
+
cached_ask(session, fn),
|
|
618
|
+
grader=grader,
|
|
619
|
+
position_pairs=10 if bias_checks else 0,
|
|
620
|
+
variance_cases=20 if bias_checks else 0,
|
|
621
|
+
progress=lambda msg: status.update(msg),
|
|
622
|
+
)
|
|
623
|
+
except CalibrationError as exc:
|
|
624
|
+
console.print(f"[red]{escape(str(exc))}[/red]")
|
|
625
|
+
raise typer.Exit(2) from exc
|
|
626
|
+
save_report(session, r)
|
|
627
|
+
|
|
628
|
+
a = r.agreement
|
|
629
|
+
console.print()
|
|
630
|
+
console.print(
|
|
631
|
+
f"[bold]{escape(r.grader)}[/bold] (version {r.version}, judged by {escape(r.judge_model)})"
|
|
632
|
+
)
|
|
633
|
+
console.print(f"{a.n} labelled outputs, using {escape(r.label_source)}")
|
|
634
|
+
if r.skipped or r.errors:
|
|
635
|
+
console.print(
|
|
636
|
+
f"[dim]{r.skipped} skipped (case no longer in the suite), "
|
|
637
|
+
f"{r.errors} the judge failed to grade[/dim]"
|
|
638
|
+
)
|
|
639
|
+
if a.kappa is None:
|
|
640
|
+
console.print(f"[yellow]kappa n/a:[/yellow] {escape(a.note or '')}")
|
|
641
|
+
else:
|
|
642
|
+
verdict = (
|
|
643
|
+
"[green]trustworthy[/green]"
|
|
644
|
+
if a.ok
|
|
645
|
+
else f"[red]below {KAPPA_OK}: the judge is close to guessing; rewrite the rubric[/red]"
|
|
646
|
+
)
|
|
647
|
+
console.print(
|
|
648
|
+
f"\n [bold]kappa {a.kappa:.2f}[/bold] {verdict} (raw agreement {a.observed:.0%})"
|
|
649
|
+
)
|
|
650
|
+
console.print(
|
|
651
|
+
f" judge passed what you failed: {a.judge_pass_human_fail} "
|
|
652
|
+
f"judge failed what you passed: {a.judge_fail_human_pass}"
|
|
653
|
+
)
|
|
654
|
+
if a.n and a.n < MIN_LABELS_ADVISED:
|
|
655
|
+
console.print(
|
|
656
|
+
f" [yellow]only {a.n} labels; about {MIN_LABELS_ADVISED}-100 "
|
|
657
|
+
"make kappa stable[/yellow]"
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
console.print("\nbias checks")
|
|
661
|
+
v = r.verbosity
|
|
662
|
+
console.print(
|
|
663
|
+
" verbosity "
|
|
664
|
+
+ (
|
|
665
|
+
f"r = {v.r:+.2f} (score vs length, flag > {VERBOSITY_FLAG}) {_flag(not v.flagged)}"
|
|
666
|
+
if v.r is not None
|
|
667
|
+
else "n/a (scores or lengths don't vary)"
|
|
668
|
+
)
|
|
669
|
+
)
|
|
670
|
+
sp = r.self_preference
|
|
671
|
+
console.print(
|
|
672
|
+
f" self-preference judge {escape(sp.judge_model)} vs outputs from "
|
|
673
|
+
f"{escape(', '.join(sp.output_models))} {_flag(sp.ok)}"
|
|
674
|
+
)
|
|
675
|
+
if r.position is not None:
|
|
676
|
+
p = r.position
|
|
677
|
+
console.print(
|
|
678
|
+
" position "
|
|
679
|
+
+ (
|
|
680
|
+
f"{p.consistent}/{p.pairs} pairwise verdicts survive swapping the order "
|
|
681
|
+
f"({p.rate:.0%}) {_flag(not p.flagged)}"
|
|
682
|
+
if p.rate is not None
|
|
683
|
+
else "n/a (needs two different labelled outputs for a case: label a second run)"
|
|
684
|
+
)
|
|
685
|
+
)
|
|
686
|
+
if r.variance is not None and r.variance.cases:
|
|
687
|
+
va = r.variance
|
|
688
|
+
console.print(
|
|
689
|
+
f" variance {va.flipped}/{va.cases} verdicts flipped across {va.repeats} "
|
|
690
|
+
f"repeats, mean score spread {va.mean_spread:.2f} {_flag(not va.flagged)}"
|
|
691
|
+
)
|
|
692
|
+
if r.evidence_total:
|
|
693
|
+
console.print(
|
|
694
|
+
f" evidence {r.evidence_found}/{r.evidence_total} quotes found verbatim in "
|
|
695
|
+
"the output"
|
|
696
|
+
)
|
|
697
|
+
if disagreements and r.disagreements:
|
|
698
|
+
table = Table(title="where you and the judge disagree")
|
|
699
|
+
table.add_column("case")
|
|
700
|
+
table.add_column("you")
|
|
701
|
+
table.add_column("judge")
|
|
702
|
+
table.add_column("judge's reason and quote", overflow="fold")
|
|
703
|
+
table.add_column("output", overflow="fold")
|
|
704
|
+
for d in r.disagreements:
|
|
705
|
+
reason = f"{d.failed_criterion}: " if d.failed_criterion else ""
|
|
706
|
+
table.add_row(
|
|
707
|
+
escape(d.case_key),
|
|
708
|
+
d.human,
|
|
709
|
+
d.judge,
|
|
710
|
+
escape(f'{reason}"{d.evidence}"'),
|
|
711
|
+
escape(_short(d.output, 160)),
|
|
712
|
+
)
|
|
713
|
+
console.print()
|
|
714
|
+
console.print(table)
|
|
715
|
+
console.print(
|
|
716
|
+
"[dim]Judge too strict where you passed it, too lenient where you failed it. "
|
|
717
|
+
"Tighten the rubric wording for those criteria and calibrate again.[/dim]"
|
|
718
|
+
)
|
|
719
|
+
elif r.disagreements:
|
|
720
|
+
console.print(
|
|
721
|
+
f"{len(r.disagreements)} disagreements: see them with [bold]--disagreements[/bold]"
|
|
722
|
+
)
|
|
723
|
+
if a.kappa is not None and not a.ok:
|
|
724
|
+
raise typer.Exit(1)
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
@app.command()
|
|
728
|
+
def smoke(
|
|
729
|
+
model: Annotated[
|
|
730
|
+
str | None, typer.Option(help="Any LiteLLM model string. Defaults to DEFAULT_MODEL.")
|
|
731
|
+
] = None,
|
|
732
|
+
prompt: Annotated[str, typer.Option(help="What to send.")] = "Reply with exactly: pong",
|
|
733
|
+
) -> None:
|
|
734
|
+
"""Make one model call and print the reply."""
|
|
735
|
+
from diffscore.llm import complete
|
|
736
|
+
|
|
737
|
+
chosen = model or get_settings().default_model
|
|
738
|
+
console.print(f"[dim]calling {escape(chosen)} ...[/dim]")
|
|
739
|
+
try:
|
|
740
|
+
result = complete(chosen, [{"role": "user", "content": prompt}], {"max_tokens": 256})
|
|
741
|
+
except Exception as exc:
|
|
742
|
+
console.print(f"[red]model call failed:[/red] {type(exc).__name__}: {describe_error(exc)}")
|
|
743
|
+
raise typer.Exit(1) from exc
|
|
744
|
+
|
|
745
|
+
console.print(escape(result.text.strip()))
|
|
746
|
+
cost = "n/a" if result.cost_usd is None else _money(result.cost_usd)
|
|
747
|
+
console.print(
|
|
748
|
+
f"[dim]{result.input_tokens} in | {result.output_tokens} out | "
|
|
749
|
+
f"{result.latency_ms} ms | {cost}[/dim]"
|
|
750
|
+
)
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
def _needs_server_extra(*modules: str) -> None:
|
|
754
|
+
from importlib.util import find_spec
|
|
755
|
+
|
|
756
|
+
missing = [m for m in modules if find_spec(m) is None]
|
|
757
|
+
if missing:
|
|
758
|
+
console.print(
|
|
759
|
+
f"[red]this needs the server extras[/red] (missing: {', '.join(missing)}). "
|
|
760
|
+
'Install them with [bold]pip install "diffscore\\[server]"[/bold].'
|
|
761
|
+
)
|
|
762
|
+
raise typer.Exit(2)
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
@app.command()
|
|
766
|
+
def init(
|
|
767
|
+
directory: Annotated[
|
|
768
|
+
Path, typer.Argument(help="Project folder to set up (default: here).")
|
|
769
|
+
] = Path("."),
|
|
770
|
+
force: Annotated[
|
|
771
|
+
bool, typer.Option("--force", help="Overwrite files that already exist.")
|
|
772
|
+
] = False,
|
|
773
|
+
) -> None:
|
|
774
|
+
"""Create a starter suite, its prompt and a .env, ready for `diffscore run`."""
|
|
775
|
+
from importlib.resources import files
|
|
776
|
+
|
|
777
|
+
templates = files("diffscore") / "templates"
|
|
778
|
+
plan = [
|
|
779
|
+
(
|
|
780
|
+
"example.yaml",
|
|
781
|
+
directory / "evals" / "example.yaml",
|
|
782
|
+
"10 test cases for a small support bot",
|
|
783
|
+
),
|
|
784
|
+
(
|
|
785
|
+
"example-prompt.md",
|
|
786
|
+
directory / "evals" / "prompts" / "example.md",
|
|
787
|
+
"the prompt under test",
|
|
788
|
+
),
|
|
789
|
+
("env.example", directory / ".env", "add your provider key here"),
|
|
790
|
+
]
|
|
791
|
+
for template, target, what in plan:
|
|
792
|
+
if target.exists() and not force:
|
|
793
|
+
console.print(
|
|
794
|
+
f" [dim]kept[/dim] {target.as_posix()} [dim](exists; --force replaces)[/dim]"
|
|
795
|
+
)
|
|
796
|
+
continue
|
|
797
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
798
|
+
target.write_text((templates / template).read_text(encoding="utf-8"), encoding="utf-8")
|
|
799
|
+
console.print(f" [green]created[/green] {target.as_posix()} [dim]{what}[/dim]")
|
|
800
|
+
|
|
801
|
+
suite = (directory / "evals" / "example.yaml").as_posix()
|
|
802
|
+
console.print(
|
|
803
|
+
"\nNext:\n"
|
|
804
|
+
f" 1. Put your key in [bold]{(directory / '.env').as_posix()}[/bold] "
|
|
805
|
+
"(GEMINI_API_KEY has a free tier).\n"
|
|
806
|
+
f" 2. [bold]diffscore run {suite}[/bold] the first run becomes the baseline\n"
|
|
807
|
+
" 3. Edit the prompt, run again, and read the verdict.\n\n"
|
|
808
|
+
"[dim]Add .env and .diffscore/ to your .gitignore: the first holds your key, "
|
|
809
|
+
"the second your results and response cache.[/dim]"
|
|
810
|
+
)
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
@app.command()
|
|
814
|
+
def genkey() -> None:
|
|
815
|
+
"""Print a new FERNET_KEY for encrypting stored provider keys."""
|
|
816
|
+
_needs_server_extra("cryptography")
|
|
817
|
+
from cryptography.fernet import Fernet
|
|
818
|
+
|
|
819
|
+
console.print(Fernet.generate_key().decode())
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
@app.command()
|
|
823
|
+
def serve(
|
|
824
|
+
host: Annotated[str, typer.Option(help="Interface to listen on.")] = "127.0.0.1",
|
|
825
|
+
port: Annotated[int, typer.Option(help="Port.")] = 8000,
|
|
826
|
+
reload: Annotated[bool, typer.Option("--reload", help="Restart on code changes.")] = False,
|
|
827
|
+
) -> None:
|
|
828
|
+
"""Run the HTTP API for the web app (the queue worker runs separately)."""
|
|
829
|
+
_needs_server_extra("uvicorn", "fastapi", "rq")
|
|
830
|
+
import uvicorn
|
|
831
|
+
|
|
832
|
+
uvicorn.run("diffscore.api:app", host=host, port=port, reload=reload)
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
@app.command()
|
|
836
|
+
def migrate() -> None:
|
|
837
|
+
"""Create or upgrade the database schema at DATABASE_URL.
|
|
838
|
+
|
|
839
|
+
Only needed for Postgres: the default SQLite file sets itself up. Works from
|
|
840
|
+
a pip install as well as from the repo, since the migrations ship inside the
|
|
841
|
+
package.
|
|
842
|
+
"""
|
|
843
|
+
from diffscore.db.migrate import upgrade
|
|
844
|
+
|
|
845
|
+
try:
|
|
846
|
+
upgrade(get_settings().database_url)
|
|
847
|
+
except OperationalError as exc:
|
|
848
|
+
console.print(
|
|
849
|
+
"[red]database not reachable.[/red] Check DATABASE_URL "
|
|
850
|
+
f"[dim]({escape(describe_error(exc.orig or exc))})[/dim]"
|
|
851
|
+
)
|
|
852
|
+
raise typer.Exit(2) from exc
|
|
853
|
+
console.print("[green]database schema is up to date[/green]")
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
@app.command()
|
|
857
|
+
def dbcheck() -> None:
|
|
858
|
+
"""Connect to DATABASE_URL and report the current migration revision."""
|
|
859
|
+
from sqlalchemy import text
|
|
860
|
+
|
|
861
|
+
with _db() as session:
|
|
862
|
+
rev = session.execute(text("SELECT version_num FROM alembic_version")).scalar()
|
|
863
|
+
console.print(f"database reachable | alembic revision [bold]{rev}[/bold]")
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
if __name__ == "__main__":
|
|
867
|
+
app()
|