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.
Files changed (38) hide show
  1. diffscore/__init__.py +3 -0
  2. diffscore/api.py +729 -0
  3. diffscore/calibration.py +374 -0
  4. diffscore/cli.py +867 -0
  5. diffscore/config.py +88 -0
  6. diffscore/db/__init__.py +27 -0
  7. diffscore/db/base.py +25 -0
  8. diffscore/db/migrate.py +61 -0
  9. diffscore/db/models.py +257 -0
  10. diffscore/db/session.py +37 -0
  11. diffscore/diffing.py +292 -0
  12. diffscore/graders.py +281 -0
  13. diffscore/jobs.py +161 -0
  14. diffscore/judge.py +355 -0
  15. diffscore/labeling.py +167 -0
  16. diffscore/llm.py +120 -0
  17. diffscore/migrations/README +1 -0
  18. diffscore/migrations/env.py +84 -0
  19. diffscore/migrations/script.py.mako +28 -0
  20. diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
  21. diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
  22. diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
  23. diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
  24. diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
  25. diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
  26. diffscore/queries.py +165 -0
  27. diffscore/runner.py +393 -0
  28. diffscore/secrets.py +130 -0
  29. diffscore/stats.py +83 -0
  30. diffscore/suite.py +329 -0
  31. diffscore/templates/env.example +14 -0
  32. diffscore/templates/example-prompt.md +14 -0
  33. diffscore/templates/example.yaml +75 -0
  34. diffscore-0.1.0.dist-info/METADATA +351 -0
  35. diffscore-0.1.0.dist-info/RECORD +38 -0
  36. diffscore-0.1.0.dist-info/WHEEL +4 -0
  37. diffscore-0.1.0.dist-info/entry_points.txt +2 -0
  38. diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,69 @@
1
+ """judge calibration
2
+
3
+ Revision ID: 9dc97334c9d9
4
+ Revises: 8c8961902e49
5
+ Create Date: 2026-12-01 11:20:36.295018
6
+
7
+ """
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = "9dc97334c9d9"
16
+ down_revision: str | Sequence[str] | None = "8c8961902e49"
17
+ branch_labels: str | Sequence[str] | None = None
18
+ depends_on: str | Sequence[str] | None = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ # ### commands auto generated by Alembic - please adjust! ###
24
+ op.create_table(
25
+ "judge_calibration",
26
+ sa.Column("id", sa.Integer(), nullable=False),
27
+ sa.Column("suite_id", sa.Integer(), nullable=False),
28
+ sa.Column("grader_name", sa.String(length=100), nullable=False),
29
+ sa.Column("grader_version", sa.String(length=50), nullable=False),
30
+ sa.Column("judge_model", sa.String(length=200), nullable=False),
31
+ sa.Column("labels", sa.Integer(), nullable=False),
32
+ sa.Column("kappa", sa.Float(), nullable=True),
33
+ sa.Column("agreement", sa.Float(), nullable=False),
34
+ sa.Column("judge_pass_human_fail", sa.Integer(), nullable=False),
35
+ sa.Column("judge_fail_human_pass", sa.Integer(), nullable=False),
36
+ sa.Column("verbosity_r", sa.Float(), nullable=True),
37
+ sa.Column("self_preference_ok", sa.Boolean(), nullable=False),
38
+ sa.Column("position_pairs", sa.Integer(), nullable=True),
39
+ sa.Column("position_consistent", sa.Integer(), nullable=True),
40
+ sa.Column("variance_cases", sa.Integer(), nullable=True),
41
+ sa.Column("variance_flipped", sa.Integer(), nullable=True),
42
+ sa.Column("evidence_found", sa.Integer(), nullable=False),
43
+ sa.Column("evidence_total", sa.Integer(), nullable=False),
44
+ sa.Column(
45
+ "created_at",
46
+ sa.DateTime(timezone=True),
47
+ server_default=sa.text("now()"),
48
+ nullable=False,
49
+ ),
50
+ sa.ForeignKeyConstraint(
51
+ ["suite_id"],
52
+ ["suite.id"],
53
+ name=op.f("fk_judge_calibration_suite_id_suite"),
54
+ ondelete="CASCADE",
55
+ ),
56
+ sa.PrimaryKeyConstraint("id", name=op.f("pk_judge_calibration")),
57
+ )
58
+ op.create_index(
59
+ op.f("ix_judge_calibration_suite_id"), "judge_calibration", ["suite_id"], unique=False
60
+ )
61
+ # ### end Alembic commands ###
62
+
63
+
64
+ def downgrade() -> None:
65
+ """Downgrade schema."""
66
+ # ### commands auto generated by Alembic - please adjust! ###
67
+ op.drop_index(op.f("ix_judge_calibration_suite_id"), table_name="judge_calibration")
68
+ op.drop_table("judge_calibration")
69
+ # ### end Alembic commands ###
@@ -0,0 +1,32 @@
1
+ """run provider keys
2
+
3
+ Revision ID: a85ad738bd12
4
+ Revises: 053ee29c31c6
5
+ Create Date: 2026-12-01 11:25:31.089482
6
+
7
+ """
8
+
9
+ from collections.abc import Sequence
10
+
11
+ import sqlalchemy as sa
12
+ from alembic import op
13
+
14
+ # revision identifiers, used by Alembic.
15
+ revision: str = "a85ad738bd12"
16
+ down_revision: str | Sequence[str] | None = "053ee29c31c6"
17
+ branch_labels: str | Sequence[str] | None = None
18
+ depends_on: str | Sequence[str] | None = None
19
+
20
+
21
+ def upgrade() -> None:
22
+ """Upgrade schema."""
23
+ # ### commands auto generated by Alembic - please adjust! ###
24
+ op.add_column("run", sa.Column("provider_keys_encrypted", sa.LargeBinary(), nullable=True))
25
+ # ### end Alembic commands ###
26
+
27
+
28
+ def downgrade() -> None:
29
+ """Downgrade schema."""
30
+ # ### commands auto generated by Alembic - please adjust! ###
31
+ op.drop_column("run", "provider_keys_encrypted")
32
+ # ### end Alembic commands ###
diffscore/queries.py ADDED
@@ -0,0 +1,165 @@
1
+ """Read side: what `diffscore runs` and `diffscore show` print, and what the API serves."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime
8
+ from decimal import Decimal
9
+ from typing import Any
10
+
11
+ from sqlalchemy import select
12
+ from sqlalchemy.orm import Session, selectinload
13
+
14
+ from diffscore.db import Case, Project, Result, Run, Suite
15
+ from diffscore.labeling import input_text
16
+ from diffscore.runner import Outcome, outcome_of
17
+
18
+
19
+ @dataclass
20
+ class RunRow:
21
+ id: int
22
+ suite: str
23
+ suite_id: int
24
+ project: str
25
+ model: str
26
+ status: str
27
+ created_at: datetime
28
+ finished_at: datetime | None
29
+ error: str | None
30
+ outcomes: Counter[Outcome]
31
+ cache_hits: int
32
+ tokens: int # tokens actually spent, answers and judge (cache hits excluded)
33
+ cost: Decimal # dollars actually spent (cache hits excluded)
34
+ case_count: int # cases the run was started with
35
+ prompt_version_id: int = 0
36
+
37
+ @property
38
+ def total(self) -> int:
39
+ return sum(self.outcomes.values())
40
+
41
+ @property
42
+ def done(self) -> int:
43
+ return self.total
44
+
45
+
46
+ @dataclass
47
+ class GradeRow:
48
+ grader: str
49
+ verdict: str
50
+ score: float
51
+ reason: str | None
52
+ details: dict[str, Any]
53
+
54
+
55
+ @dataclass
56
+ class CaseRow:
57
+ key: str
58
+ outcome: Outcome
59
+ failures: list[str]
60
+ output: str | None
61
+ latency_ms: int | None
62
+ tokens: int | None
63
+ cache_hit: bool
64
+ input: str = ""
65
+ expect: str | None = None
66
+ grades: list[GradeRow] = field(default_factory=list)
67
+
68
+
69
+ def _summarise(run: Run) -> RunRow:
70
+ spent = [r for r in run.results if not r.cache_hit]
71
+ return RunRow(
72
+ id=run.id,
73
+ suite=run.suite.name,
74
+ suite_id=run.suite_id,
75
+ project=run.suite.project.name,
76
+ model=run.model,
77
+ status=run.status,
78
+ created_at=run.created_at,
79
+ finished_at=run.finished_at,
80
+ error=run.error,
81
+ outcomes=Counter(outcome_of(r) for r in run.results),
82
+ cache_hits=len(run.results) - len(spent),
83
+ # Runs record their own spend (including judge calls); older runs predate that.
84
+ tokens=run.tokens_spent
85
+ if run.tokens_spent is not None
86
+ else sum((r.input_tokens or 0) + (r.output_tokens or 0) for r in spent),
87
+ cost=run.cost_spent
88
+ if run.cost_spent is not None
89
+ else sum((r.cost_usd or Decimal(0) for r in spent), Decimal(0)),
90
+ case_count=len(run.case_keys) or len(run.results),
91
+ prompt_version_id=run.prompt_version_id,
92
+ )
93
+
94
+
95
+ def failures_of(result: Result) -> list[str]:
96
+ if result.error is not None:
97
+ # Grader and budget errors carry their own wording; a bare one is the model's.
98
+ own_words = "could not grade" in result.error or result.error.startswith("skipped:")
99
+ return [result.error if own_words else f"model call failed: {result.error}"]
100
+ return [f"{g.grader_name}: {g.reason}" for g in result.grades if g.verdict == "fail"]
101
+
102
+
103
+ def with_results() -> list[Any]:
104
+ """Eager-load what summaries and diffs read: suite, project, results, grades, cases."""
105
+ return [
106
+ selectinload(Run.suite).selectinload(Suite.project),
107
+ selectinload(Run.results).selectinload(Result.grades),
108
+ selectinload(Run.results).selectinload(Result.case),
109
+ ]
110
+
111
+
112
+ def list_runs(
113
+ session: Session,
114
+ suite: str | None = None,
115
+ limit: int = 20,
116
+ *,
117
+ projects: set[str] | None = None,
118
+ suite_id: int | None = None,
119
+ run_id: int | None = None,
120
+ ) -> list[RunRow]:
121
+ """Newest first. `projects` limits what a visitor may see; None means everything."""
122
+ stmt = select(Run).options(*with_results()).order_by(Run.id.desc()).limit(limit)
123
+ if suite or projects is not None or suite_id is not None:
124
+ stmt = stmt.join(Run.suite).join(Suite.project)
125
+ if suite:
126
+ stmt = stmt.where(Suite.name == suite)
127
+ if suite_id is not None:
128
+ stmt = stmt.where(Suite.id == suite_id)
129
+ if run_id is not None:
130
+ stmt = stmt.where(Run.id == run_id)
131
+ if projects is not None:
132
+ stmt = stmt.where(Project.name.in_(projects))
133
+ return [_summarise(r) for r in session.scalars(stmt)]
134
+
135
+
136
+ def load_run(session: Session, run_id: int) -> Run:
137
+ run = session.scalars(select(Run).options(*with_results()).where(Run.id == run_id)).first()
138
+ if run is None:
139
+ raise LookupError(f"no run with id {run_id}")
140
+ return run
141
+
142
+
143
+ def run_detail(session: Session, run_id: int) -> tuple[RunRow, list[CaseRow]]:
144
+ run = load_run(session, run_id)
145
+ rows: list[CaseRow] = []
146
+ for r in sorted(run.results, key=lambda r: r.id):
147
+ case: Case = r.case
148
+ rows.append(
149
+ CaseRow(
150
+ key=case.key,
151
+ outcome=outcome_of(r),
152
+ failures=failures_of(r),
153
+ output=r.output,
154
+ latency_ms=r.latency_ms,
155
+ tokens=None if r.input_tokens is None else r.input_tokens + (r.output_tokens or 0),
156
+ cache_hit=r.cache_hit,
157
+ input=input_text(case),
158
+ expect=case.reference_output,
159
+ grades=[
160
+ GradeRow(g.grader_name, g.verdict, g.score, g.reason, g.details)
161
+ for g in sorted(r.grades, key=lambda g: g.id)
162
+ ],
163
+ )
164
+ )
165
+ return _summarise(run), rows
diffscore/runner.py ADDED
@@ -0,0 +1,393 @@
1
+ """Run a suite: for each case, cache lookup -> model call -> store result -> grade.
2
+
3
+ This is a service function: the CLI calls it now and the API will call the same
4
+ function in Phase 5, so no business logic lives in either front end.
5
+
6
+ Sequential on purpose. The token ceiling is checked before every uncached call,
7
+ which is why it exists before any parallelism does.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, field
16
+ from datetime import UTC, datetime
17
+ from decimal import Decimal
18
+ from typing import Any, Literal
19
+
20
+ from sqlalchemy import func, select
21
+ from sqlalchemy.orm import Session
22
+
23
+ from diffscore.db import Cache, Case, Grade, Project, PromptVersion, Result, Run, Suite
24
+ from diffscore.graders import GraderDeps, GraderRuntimeError, Output, build
25
+ from diffscore.judge import check_not_self_judging, parse_config
26
+ from diffscore.llm import CompleteFn, Completion, Message, describe_error
27
+ from diffscore.suite import CaseSpec, SuiteFile
28
+
29
+ Outcome = Literal["pass", "fail", "error", "ungraded"]
30
+
31
+ # A bad key, a retired model or a missing dependency fails every call the same
32
+ # way. Stop instead of burning through the whole suite (and its rate limit).
33
+ MAX_CONSECUTIVE_ERRORS = 5
34
+
35
+
36
+ def cache_key(model: str, messages: list[Message], params: dict[str, Any]) -> str:
37
+ """sha256 over the rendered prompt + input (the messages), model and params."""
38
+ blob = json.dumps(
39
+ {"model": model, "messages": messages, "params": params},
40
+ sort_keys=True,
41
+ separators=(",", ":"),
42
+ ensure_ascii=False,
43
+ )
44
+ return hashlib.sha256(blob.encode()).hexdigest()
45
+
46
+
47
+ def prompt_hash(spec: SuiteFile) -> str:
48
+ blob = json.dumps(
49
+ {"template": spec.prompt, "user_template": spec.user_template},
50
+ sort_keys=True,
51
+ ensure_ascii=False,
52
+ )
53
+ return hashlib.sha256(blob.encode()).hexdigest()
54
+
55
+
56
+ def outcome_of(result: Result) -> Outcome:
57
+ if result.error is not None:
58
+ return "error"
59
+ if not result.grades:
60
+ return "ungraded"
61
+ return "pass" if all(g.verdict == "pass" for g in result.grades) else "fail"
62
+
63
+
64
+ @dataclass
65
+ class CaseOutcome:
66
+ key: str
67
+ outcome: Outcome
68
+ cache_hit: bool
69
+ failures: list[str] # "grader: reason" for each failing grade, or the error
70
+
71
+
72
+ @dataclass
73
+ class RunSummary:
74
+ run_id: int
75
+ status: str
76
+ total: int
77
+ outcomes: dict[Outcome, int] = field(
78
+ default_factory=lambda: {"pass": 0, "fail": 0, "error": 0, "ungraded": 0}
79
+ )
80
+ api_calls: int = 0
81
+ cache_hits: int = 0
82
+ tokens_spent: int = 0
83
+ cost_spent: Decimal = Decimal(0)
84
+ stopped_reason: str | None = None
85
+ cases: list[CaseOutcome] = field(default_factory=list)
86
+
87
+
88
+ ProgressFn = Callable[[CaseOutcome], None]
89
+
90
+
91
+ def _get_or_create[T](session: Session, model: type[T], defaults: dict[str, Any], **keys: Any) -> T:
92
+ found = session.scalars(select(model).filter_by(**keys)).first()
93
+ if found is None:
94
+ found = model(**keys, **defaults)
95
+ session.add(found)
96
+ session.flush()
97
+ return found
98
+
99
+
100
+ def _sync_cases(session: Session, suite: Suite, spec: SuiteFile) -> dict[str, Case]:
101
+ """Upsert cases by key. Cases dropped from the file stay in the DB for old runs."""
102
+ existing = {c.key: c for c in session.scalars(select(Case).where(Case.suite_id == suite.id))}
103
+ rows: dict[str, Case] = {}
104
+ for cs in spec.cases:
105
+ graders = [{"name": g.name, "arg": g.arg} for g in spec.graders_for(cs)]
106
+ row = existing.get(cs.id)
107
+ if row is None:
108
+ row = Case(suite=suite, key=cs.id)
109
+ session.add(row)
110
+ row.input = cs.input if isinstance(cs.input, dict) else {"input": cs.input}
111
+ row.reference_output = cs.expect
112
+ row.graders = graders
113
+ rows[cs.id] = row
114
+ session.flush()
115
+ return rows
116
+
117
+
118
+ def _store_cache(session: Session, **values: Any) -> None:
119
+ """Insert a cache row, tolerating a concurrent worker that stored it first."""
120
+ dialect = session.get_bind().dialect.name
121
+ if dialect == "postgresql":
122
+ from sqlalchemy.dialects.postgresql import insert as pg_insert
123
+
124
+ session.execute(pg_insert(Cache).values(**values).on_conflict_do_nothing())
125
+ elif dialect == "sqlite":
126
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
127
+
128
+ session.execute(sqlite_insert(Cache).values(**values).on_conflict_do_nothing())
129
+ else: # pragma: no cover
130
+ session.add(Cache(**values))
131
+ session.flush()
132
+
133
+
134
+ def cached_ask(
135
+ session: Session,
136
+ fn: CompleteFn,
137
+ *,
138
+ on_call: Callable[[], None] | None = None,
139
+ on_spend: Callable[[Completion], None] | None = None,
140
+ ) -> CompleteFn:
141
+ """Wrap a model function with the content-hash cache.
142
+
143
+ Used for generation and for the judge alike, so re-grading stored outputs
144
+ with an unchanged rubric is free too. Params starting with `_` shape the
145
+ cache key only (e.g. `_repeat` asks for a fresh sample) and are not sent.
146
+ Failed calls are never cached.
147
+ """
148
+
149
+ def ask(model: str, messages: list[Message], params: dict[str, Any]) -> Completion:
150
+ key = cache_key(model, messages, params)
151
+ hit = session.get(Cache, key)
152
+ if hit is not None:
153
+ hit.hit_count += 1
154
+ return Completion(
155
+ text=hit.output,
156
+ model=model,
157
+ input_tokens=hit.input_tokens or 0,
158
+ output_tokens=hit.output_tokens or 0,
159
+ latency_ms=hit.latency_ms or 0,
160
+ cost_usd=None if hit.cost_usd is None else float(hit.cost_usd),
161
+ cached=True,
162
+ )
163
+ if on_call:
164
+ on_call()
165
+ done = fn(model, messages, {k: v for k, v in params.items() if not k.startswith("_")})
166
+ _store_cache(
167
+ session,
168
+ key=key,
169
+ model=model,
170
+ output=done.text,
171
+ input_tokens=done.input_tokens,
172
+ output_tokens=done.output_tokens,
173
+ latency_ms=done.latency_ms,
174
+ cost_usd=None if done.cost_usd is None else Decimal(str(done.cost_usd)),
175
+ )
176
+ if on_spend:
177
+ on_spend(done)
178
+ return done
179
+
180
+ return ask
181
+
182
+
183
+ def check_judges(spec: SuiteFile, candidate_model: str) -> None:
184
+ """Refuse to start a run whose judge would grade its own model's outputs."""
185
+ for g in spec.all_graders():
186
+ if g.name == "judge":
187
+ check_not_self_judging(parse_config(g.arg), candidate_model)
188
+
189
+
190
+ def prepare_run(session: Session, spec: SuiteFile, *, model: str) -> Run:
191
+ """Record the suite, prompt version and cases, and open a run. Executes nothing.
192
+
193
+ Everything a case needs later is stored here, so a worker can execute any
194
+ case from the database alone, without the suite file.
195
+ """
196
+ check_judges(spec, model) # raises GraderConfigError before anything is written
197
+
198
+ project = _get_or_create(session, Project, {"default_model": model}, name=spec.project)
199
+ version = _get_or_create(
200
+ session,
201
+ PromptVersion,
202
+ {"template": spec.prompt, "params": {"user_template": spec.user_template}},
203
+ project_id=project.id,
204
+ content_hash=prompt_hash(spec),
205
+ )
206
+ suite = _get_or_create(session, Suite, {}, project_id=project.id, name=spec.name)
207
+ _sync_cases(session, suite, spec)
208
+
209
+ run = Run(suite=suite, prompt_version=version, model=model, params=spec.params)
210
+ run.status = "running"
211
+ run.case_keys = [c.id for c in spec.cases]
212
+ run.tokens_spent = 0
213
+ run.cost_spent = Decimal(0)
214
+ session.add(run)
215
+ session.commit()
216
+ return run
217
+
218
+
219
+ def spec_for_run(session: Session, run: Run) -> SuiteFile:
220
+ """Rebuild the suite exactly as it was when the run was prepared."""
221
+ cases = {
222
+ c.key: c
223
+ for c in session.scalars(
224
+ select(Case).where(Case.suite_id == run.suite_id, Case.key.in_(run.case_keys))
225
+ )
226
+ }
227
+ version = run.prompt_version
228
+ return SuiteFile.model_validate(
229
+ {
230
+ "name": run.suite.name,
231
+ "project": run.suite.project.name,
232
+ "model": run.model,
233
+ "prompt": version.template,
234
+ "user_template": version.params.get("user_template", "{{input}}"),
235
+ "params": run.params,
236
+ "cases": [
237
+ {
238
+ "id": key,
239
+ "input": _stored_input(cases[key].input),
240
+ "expect": cases[key].reference_output,
241
+ "graders": cases[key].graders,
242
+ }
243
+ for key in run.case_keys
244
+ ],
245
+ }
246
+ )
247
+
248
+
249
+ def _stored_input(data: dict[str, Any]) -> str | dict[str, Any]:
250
+ if set(data) == {"input"} and isinstance(data["input"], str):
251
+ return data["input"]
252
+ return data
253
+
254
+
255
+ def finalize_run(session: Session, run: Run, stopped_reason: str | None = None) -> None:
256
+ """Close a run. A run with skipped cases (budget) is marked failed."""
257
+ if stopped_reason is None:
258
+ skipped = session.scalar(
259
+ select(func.count())
260
+ .select_from(Result)
261
+ .where(Result.run_id == run.id, Result.error.like(f"{SKIPPED}%"))
262
+ )
263
+ if skipped:
264
+ stopped_reason = f"{skipped} case(s) skipped: token budget reached"
265
+ run.status = "failed" if stopped_reason else "completed"
266
+ run.error = stopped_reason
267
+ run.finished_at = datetime.now(UTC)
268
+ session.commit()
269
+
270
+
271
+ SKIPPED = "skipped: "
272
+
273
+
274
+ def run_suite(
275
+ session: Session,
276
+ spec: SuiteFile,
277
+ complete_fn: CompleteFn,
278
+ *,
279
+ model: str,
280
+ max_tokens_per_run: int,
281
+ on_case: ProgressFn | None = None,
282
+ ) -> RunSummary:
283
+ """Run every case in this process, in order. The CLI path; the API uses jobs."""
284
+ run = prepare_run(session, spec, model=model)
285
+ case_rows = {c.key: c for c in run.suite.cases}
286
+
287
+ summary = RunSummary(run_id=run.id, status=run.status, total=len(spec.cases))
288
+
289
+ def counted() -> None:
290
+ summary.api_calls += 1
291
+
292
+ def spent(done: Completion) -> None:
293
+ summary.tokens_spent += done.input_tokens + done.output_tokens
294
+ summary.cost_spent += Decimal(str(done.cost_usd or 0))
295
+
296
+ ask = cached_ask(session, complete_fn, on_call=counted, on_spend=spent)
297
+ deps = GraderDeps(ask=ask, candidate_model=model)
298
+
299
+ consecutive_errors = 0
300
+ stopped: str | None = None
301
+ for cs in spec.cases:
302
+ if summary.tokens_spent >= max_tokens_per_run:
303
+ stopped = (
304
+ f"token budget reached ({summary.tokens_spent:,} of "
305
+ f"MAX_TOKENS_PER_RUN={max_tokens_per_run:,}); "
306
+ f"{summary.total - len(summary.cases)} case(s) not run"
307
+ )
308
+ break
309
+ outcome = run_case(session, spec, cs, case_rows[cs.id], run, ask, deps, summary)
310
+ summary.cases.append(outcome)
311
+ summary.outcomes[outcome.outcome] += 1
312
+ if on_case:
313
+ on_case(outcome)
314
+
315
+ consecutive_errors = consecutive_errors + 1 if outcome.outcome == "error" else 0
316
+ if consecutive_errors >= MAX_CONSECUTIVE_ERRORS:
317
+ stopped = (
318
+ f"{consecutive_errors} cases in a row errored, so the problem is "
319
+ f"probably not the cases ({outcome.failures[0]}); "
320
+ f"{summary.total - len(summary.cases)} case(s) not run"
321
+ )
322
+ break
323
+
324
+ run.tokens_spent = summary.tokens_spent
325
+ run.cost_spent = summary.cost_spent
326
+ finalize_run(session, run, stopped)
327
+ summary.stopped_reason = stopped
328
+ summary.status = run.status
329
+ return summary
330
+
331
+
332
+ def run_case(
333
+ session: Session,
334
+ spec: SuiteFile,
335
+ cs: CaseSpec,
336
+ case_row: Case,
337
+ run: Run,
338
+ ask: CompleteFn,
339
+ deps: GraderDeps,
340
+ summary: RunSummary,
341
+ ) -> CaseOutcome:
342
+ messages = spec.messages_for(cs)
343
+ result = Result(run=run, case=case_row)
344
+ session.add(result) # SQLAlchemy 2.0 no longer cascades this through the backref
345
+
346
+ try:
347
+ done = ask(run.model, messages, run.params)
348
+ except Exception as exc:
349
+ result.error = describe_error(exc)
350
+ else:
351
+ result.cache_hit = done.cached
352
+ if done.cached:
353
+ summary.cache_hits += 1
354
+ result.output = done.text
355
+ result.input_tokens = done.input_tokens
356
+ result.output_tokens = done.output_tokens
357
+ result.latency_ms = done.latency_ms
358
+ result.cost_usd = None if done.cost_usd is None else Decimal(str(done.cost_usd))
359
+
360
+ failures: list[str] = []
361
+ if result.error is None:
362
+ seen = Output(
363
+ text=result.output or "",
364
+ expect=cs.expect,
365
+ latency_ms=result.latency_ms,
366
+ cost_usd=None if result.cost_usd is None else float(result.cost_usd),
367
+ input=messages[-1]["content"], # the case input only: the judge never sees the prompt
368
+ )
369
+ for g in spec.graders_for(cs):
370
+ try:
371
+ verdict = build(g.name, g.arg, deps)(seen)
372
+ except GraderRuntimeError as exc:
373
+ # The output is not at fault: report an error and keep it out of the verdict.
374
+ result.error = f"{g.display_name} could not grade: {describe_error(exc)}"
375
+ failures = [result.error]
376
+ break
377
+ result.grades.append(
378
+ Grade(
379
+ grader_name=g.display_name,
380
+ grader_version=g.version,
381
+ score=verdict.score,
382
+ verdict=verdict.verdict,
383
+ reason=verdict.reason,
384
+ details=verdict.details,
385
+ )
386
+ )
387
+ if verdict.verdict == "fail":
388
+ failures.append(f"{g.display_name}: {verdict.reason}")
389
+ else:
390
+ failures.append(f"model call failed: {result.error}")
391
+
392
+ session.commit() # per case, so a crash keeps everything done so far
393
+ return CaseOutcome(cs.id, outcome_of(result), result.cache_hit, failures)