dsh-eval 0.4.0 → 0.5.1

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 (79) hide show
  1. package/README.md +214 -13
  2. package/README.zh.md +99 -10
  3. package/lib/agreement.js +46 -0
  4. package/lib/argv.js +66 -0
  5. package/lib/atomic-write.js +38 -0
  6. package/lib/benchmark.js +116 -19
  7. package/lib/calibration.js +90 -0
  8. package/lib/command.js +202 -10
  9. package/lib/compare.js +310 -31
  10. package/lib/dashboard.js +260 -0
  11. package/lib/digest.js +118 -0
  12. package/lib/export.js +50 -0
  13. package/lib/gate.js +293 -0
  14. package/lib/import.js +17 -6
  15. package/lib/index.js +174 -12
  16. package/lib/judge.js +30 -7
  17. package/lib/leaderboard.js +222 -0
  18. package/lib/precision.js +50 -0
  19. package/lib/rejudge.js +107 -0
  20. package/lib/reliability.js +107 -0
  21. package/lib/report.js +285 -11
  22. package/lib/runner.js +189 -33
  23. package/lib/safe-regex.js +74 -0
  24. package/lib/segments.js +15 -0
  25. package/lib/stats.js +63 -0
  26. package/lib/trace.js +19 -2
  27. package/lib/types/agreement.d.ts +33 -0
  28. package/lib/types/argv.d.ts +19 -0
  29. package/lib/types/atomic-write.d.ts +15 -0
  30. package/lib/types/benchmark.d.ts +9 -2
  31. package/lib/types/calibration.d.ts +45 -0
  32. package/lib/types/command.d.ts +58 -0
  33. package/lib/types/compare.d.ts +82 -2
  34. package/lib/types/dashboard.d.ts +24 -0
  35. package/lib/types/digest.d.ts +38 -0
  36. package/lib/types/export.d.ts +17 -0
  37. package/lib/types/gate.d.ts +87 -0
  38. package/lib/types/index.d.ts +8 -4
  39. package/lib/types/judge.d.ts +4 -1
  40. package/lib/types/leaderboard.d.ts +70 -0
  41. package/lib/types/precision.d.ts +44 -0
  42. package/lib/types/rejudge.d.ts +22 -0
  43. package/lib/types/reliability.d.ts +85 -0
  44. package/lib/types/report.d.ts +18 -5
  45. package/lib/types/runner.d.ts +8 -1
  46. package/lib/types/safe-regex.d.ts +24 -0
  47. package/lib/types/segments.d.ts +12 -0
  48. package/lib/types/stats.d.ts +56 -0
  49. package/lib/types/trace.d.ts +7 -0
  50. package/lib/types/types.d.ts +55 -6
  51. package/lib/types/validate.d.ts +57 -0
  52. package/lib/validate.js +155 -0
  53. package/package.json +2 -2
  54. package/src/agreement.ts +60 -0
  55. package/src/argv.ts +63 -0
  56. package/src/atomic-write.ts +38 -0
  57. package/src/benchmark.ts +139 -13
  58. package/src/calibration.ts +113 -0
  59. package/src/command.ts +297 -10
  60. package/src/compare.ts +392 -37
  61. package/src/dashboard.ts +287 -0
  62. package/src/digest.ts +144 -0
  63. package/src/export.ts +57 -0
  64. package/src/gate.ts +383 -0
  65. package/src/import.ts +18 -6
  66. package/src/index.ts +192 -12
  67. package/src/judge.ts +30 -6
  68. package/src/leaderboard.ts +272 -0
  69. package/src/precision.ts +85 -0
  70. package/src/rejudge.ts +112 -0
  71. package/src/reliability.ts +166 -0
  72. package/src/report.ts +303 -11
  73. package/src/runner.ts +182 -35
  74. package/src/safe-regex.ts +79 -0
  75. package/src/segments.ts +16 -0
  76. package/src/stats.ts +104 -0
  77. package/src/trace.ts +19 -2
  78. package/src/types.ts +56 -6
  79. package/src/validate.ts +177 -0
package/src/compare.ts CHANGED
@@ -6,7 +6,17 @@
6
6
  */
7
7
 
8
8
  import type { EvalRun, EvalTrialResult } from './types.ts'
9
- import { pairedDelta, signTest, type PairedDelta, type SignTestOutcome } from './stats.ts'
9
+ import { computeCoverage, computeReliability } from './reliability.ts'
10
+ import {
11
+ bonferroni,
12
+ pairedDelta,
13
+ signTest,
14
+ signTestPower,
15
+ type FamilyWiseCorrection,
16
+ type PairedDelta,
17
+ type SignTestOutcome,
18
+ type SignTestPower,
19
+ } from './stats.ts'
10
20
 
11
21
  /** One compared metric row. */
12
22
  export interface CompareRow {
@@ -18,6 +28,8 @@ export interface CompareRow {
18
28
  b: string
19
29
  /** Signed delta (`b - a`) for numeric rows, or a dash for text rows. */
20
30
  delta: string
31
+ /** Inference about a paired comparison, rendered in a separate table. */
32
+ inference?: string
21
33
  }
22
34
 
23
35
  /** Paired same-case statistics over two runs. */
@@ -32,8 +44,12 @@ export interface PairedStats {
32
44
  ties: number
33
45
  /** The metric used for win/lose/tie classification. */
34
46
  primaryMetric: 'task success' | 'tool selection accuracy' | 'final answer score'
35
- /** Exact two-sided sign test over the discordant pairs of the primary metric. */
47
+ /** Exact two-sided sign test over the discordant pairs of the primary metric (raw p-value). */
36
48
  test: SignTestOutcome
49
+ /** Bonferroni correction shared by the printed p-value and delta intervals. */
50
+ correction: FamilyWiseCorrection
51
+ /** Whether the discordant sample can reach the corrected alpha at all. */
52
+ power: SignTestPower
37
53
  /** Paired step delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
38
54
  stepsDelta: PairedDelta | null
39
55
  /** Paired token delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
@@ -52,6 +68,24 @@ function formatRate(value: number | null): string {
52
68
  return value === null ? '–' : `${(value * 100).toFixed(1)}%`
53
69
  }
54
70
 
71
+ /** Render USD at micro-dollar precision — one decimal rounds every real cost to zero. */
72
+ function formatUsd(value: number | null): string {
73
+ return value === null ? '–' : `$${value.toFixed(6)}`
74
+ }
75
+
76
+ /** Render a signed USD delta at micro-dollar precision. */
77
+ function formatUsdDelta(a: number | null, b: number | null): string {
78
+ if (a === null || b === null) return '–'
79
+ const delta = b - a
80
+ return `${delta >= 0 ? '+' : '-'}$${Math.abs(delta).toFixed(6)}`
81
+ }
82
+
83
+ /** Render a signed delta between two counts without decimal noise. */
84
+ function formatCountDelta(a: number, b: number): string {
85
+ const delta = b - a
86
+ return `${delta >= 0 ? '+' : ''}${delta}`
87
+ }
88
+
55
89
  /** Render a signed delta between two nullable numbers. */
56
90
  function formatDelta(a: number | null, b: number | null, unit: 'pp' | '' = ''): string {
57
91
  if (a === null || b === null) return '–'
@@ -59,21 +93,23 @@ function formatDelta(a: number | null, b: number | null, unit: 'pp' | '' = ''):
59
93
  return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`
60
94
  }
61
95
 
62
- /** Render a paired delta with its bootstrap interval when the sample allows one. */
63
- function formatPairedDelta(delta: PairedDelta): string {
96
+ /** Render a paired delta with its bootstrap interval at the given confidence. */
97
+ function formatPairedDelta(delta: PairedDelta, intervalConfidence: number): string {
64
98
  const mean = formatDelta(0, delta.mean)
65
99
  return delta.lower === null || delta.upper === null
66
100
  ? mean
67
- : `${mean} [95% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`
101
+ : `${mean} [${(intervalConfidence * 100).toFixed(1)}% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`
68
102
  }
69
103
 
70
104
  /** Render an exact p-value, collapsing anything below the print precision. */
71
- function formatPValue(pValue: number): string {
72
- return pValue < 0.001 ? '<0.001' : pValue.toFixed(3)
105
+ export function formatPValue(pValue: number): string {
106
+ if (pValue < 0.001) return '<0.001'
107
+ // Four decimals near alpha keep a significant 0.0496 from printing 0.050.
108
+ return pValue < 0.06 ? pValue.toFixed(4) : pValue.toFixed(3)
73
109
  }
74
110
 
75
111
  /** A metric that can classify a paired winner. */
76
- type PairedMetric = 'task success' | 'tool selection accuracy' | 'final answer score'
112
+ export type PairedMetric = 'task success' | 'tool selection accuracy' | 'final answer score'
77
113
 
78
114
  /** Read one trial's primary-metric outcome, or null when the trial lacks it. */
79
115
  function metricOutcome(result: EvalTrialResult, metric: PairedMetric): boolean | number | null {
@@ -85,13 +121,15 @@ function metricOutcome(result: EvalTrialResult, metric: PairedMetric): boolean |
85
121
  /** Pick the first metric with data in every paired trial of a run. */
86
122
  function pickMetric(
87
123
  pairs: readonly { a: EvalTrialResult; b: EvalTrialResult }[],
88
- ): PairedMetric {
124
+ ): PairedMetric | null {
89
125
  for (const metric of ['task success', 'tool selection accuracy', 'final answer score'] as const) {
90
126
  if (pairs.every(pair => metricOutcome(pair.a, metric) !== null && metricOutcome(pair.b, metric) !== null)) {
91
127
  return metric
92
128
  }
93
129
  }
94
- return 'final answer score'
130
+ // Counting absent outcomes as ties would manufacture a fake "no change"
131
+ // result. pairedCases and pairedSigns skip them; do the same here.
132
+ return null
95
133
  }
96
134
 
97
135
  /** Classify one pair: 1 for a B win, -1 for an A win, 0 for a tie. */
@@ -105,15 +143,37 @@ function pairSign(aValue: boolean | number | null, bValue: boolean | number | nu
105
143
  return bValue > aValue ? 1 : (bValue < aValue ? -1 : 0)
106
144
  }
107
145
 
146
+ /** Win/loss/tie counts for one metric over completed, paired trials. */
147
+ export interface PairedSignCounts {
148
+ /** Pairs with both outcomes present for the metric. */
149
+ pairs: number
150
+ wins: number
151
+ losses: number
152
+ ties: number
153
+ }
154
+
108
155
  /**
109
- * Pair both runs' trials by case id and trial index and compute win/lose/tie
110
- * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
111
- * provenance for the pairing, not a guarantee of identical model output.
156
+ * Count paired wins/losses/ties for one metric, ignoring pairs missing it.
112
157
  * @param a - the baseline run.
113
158
  * @param b - the candidate run.
114
- * @returns paired statistics, or null when no trial is completed in both runs.
159
+ * @param metric - the metric to classify.
160
+ * @returns paired sign counts for that metric alone.
115
161
  */
116
- export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
162
+ export function pairedSigns(a: EvalRun, b: EvalRun, metric: PairedMetric): PairedSignCounts {
163
+ const counts: PairedSignCounts = { pairs: 0, wins: 0, losses: 0, ties: 0 }
164
+ for (const pair of pairedTrials(a, b)) {
165
+ const sign = pairSign(metricOutcome(pair.a, metric), metricOutcome(pair.b, metric))
166
+ if (metricOutcome(pair.a, metric) === null || metricOutcome(pair.b, metric) === null) continue
167
+ counts.pairs += 1
168
+ if (sign > 0) counts.wins += 1
169
+ else if (sign < 0) counts.losses += 1
170
+ else counts.ties += 1
171
+ }
172
+ return counts
173
+ }
174
+
175
+ /** Pair completed trials from both runs by case id and trial index. */
176
+ function pairedTrials(a: EvalRun, b: EvalRun): { a: EvalTrialResult; b: EvalTrialResult }[] {
117
177
  const byKey = new Map<string, EvalTrialResult>()
118
178
  for (const result of b.cases) {
119
179
  if (result.status === 'completed') byKey.set(`${result.caseId}\u0000${result.trial}`, result)
@@ -124,8 +184,22 @@ export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
124
184
  const match = byKey.get(`${result.caseId}\u0000${result.trial}`)
125
185
  if (match !== undefined) pairs.push({ a: result, b: match })
126
186
  }
187
+ return pairs
188
+ }
189
+
190
+ /**
191
+ * Pair both runs' trials by case id and trial index and compute win/lose/tie
192
+ * plus mean deltas. Trials are paired as-is; the runs' `seed` is recorded
193
+ * provenance for the pairing, not a guarantee of identical model output.
194
+ * @param a - the baseline run.
195
+ * @param b - the candidate run.
196
+ * @returns paired statistics, or null when no trial is completed in both runs.
197
+ */
198
+ export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
199
+ const pairs = pairedTrials(a, b)
127
200
  if (pairs.length === 0) return null
128
201
  const primaryMetric = pickMetric(pairs)
202
+ if (primaryMetric === null) return null
129
203
  let wins = 0
130
204
  let losses = 0
131
205
  let ties = 0
@@ -149,19 +223,192 @@ export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
149
223
  scoreDeltas.push(bScore - aScore)
150
224
  }
151
225
  }
226
+ const test = signTest(wins, losses)
227
+ // The printed p-value and each non-null interval are tested as one family.
228
+ const comparisons = 1 + [stepDeltas, tokenDeltas, scoreDeltas].filter(deltas => deltas.length > 0).length
229
+ const correction = bonferroni(test.pValue, comparisons)
152
230
  return {
153
231
  pairs: pairs.length,
154
232
  wins,
155
233
  losses,
156
234
  ties,
157
235
  primaryMetric,
158
- test: signTest(wins, losses),
159
- stepsDelta: pairedDelta(stepDeltas),
160
- tokensDelta: pairedDelta(tokenDeltas),
161
- scoreDelta: pairedDelta(scoreDeltas),
236
+ test,
237
+ correction,
238
+ power: signTestPower(test.discordant, comparisons, correction.alpha),
239
+ stepsDelta: pairedDelta(stepDeltas, { confidence: correction.intervalConfidence }),
240
+ tokensDelta: pairedDelta(tokenDeltas, { confidence: correction.intervalConfidence }),
241
+ scoreDelta: pairedDelta(scoreDeltas, { confidence: correction.intervalConfidence }),
162
242
  }
163
243
  }
164
244
 
245
+ /** One paired case x trial classified on the same primary metric as the sign test. */
246
+ export interface PairedCase {
247
+ caseId: string
248
+ trial: number
249
+ a: boolean | number | null
250
+ b: boolean | number | null
251
+ outcome: 'B better' | 'A better' | 'tie'
252
+ }
253
+
254
+ /**
255
+ * Classify every paired case x trial, using the same metric selection as
256
+ * {@link pairedCompare} so the case list explains its win/lose/tie counts.
257
+ * @param a - the baseline run.
258
+ * @param b - the candidate run.
259
+ * @returns one row per completed pair with a measured value, or null when
260
+ * there are no comparable pairs. Ungraded pairs must not inflate the per-case
261
+ * Bonferroni family.
262
+ */
263
+ export function pairedCases(a: EvalRun, b: EvalRun, metricOverride?: PairedMetric): PairedCase[] | null {
264
+ const pairs = pairedTrials(a, b)
265
+ if (pairs.length === 0) return null
266
+ const metric = metricOverride ?? pickMetric(pairs)
267
+ if (metric === null) return null
268
+ const measured = pairs.filter(pair =>
269
+ metricOutcome(pair.a, metric) !== null && metricOutcome(pair.b, metric) !== null)
270
+ if (measured.length === 0) return null
271
+ return measured.map(pair => {
272
+ const aValue = metricOutcome(pair.a, metric)!
273
+ const bValue = metricOutcome(pair.b, metric)!
274
+ const sign = pairSign(aValue, bValue)
275
+ return {
276
+ caseId: pair.a.caseId,
277
+ trial: pair.a.trial,
278
+ a: aValue,
279
+ b: bValue,
280
+ outcome: sign > 0 ? 'B better' : sign < 0 ? 'A better' : 'tie',
281
+ }
282
+ })
283
+ }
284
+
285
+ /** Aggregated paired evidence for one case across its trial pairs. */
286
+ export interface CaseSignificance {
287
+ caseId: string
288
+ pairs: number
289
+ wins: number
290
+ losses: number
291
+ ties: number
292
+ adjustedP: number
293
+ detectable: boolean
294
+ /** Discordant pairs needed to clear this case's family-wise threshold. */
295
+ requiredPairs: number
296
+ verdict: 'significantly-better' | 'significantly-worse' | 'not-significant' | 'underpowered'
297
+ }
298
+
299
+ /**
300
+ * Per-case exact sign tests with Bonferroni correction across the cases.
301
+ * This is a separate inference family from the pooled paired metrics.
302
+ */
303
+ export function pairedCaseSignificance(
304
+ a: EvalRun,
305
+ b: EvalRun,
306
+ metricOverride?: PairedMetric,
307
+ ): CaseSignificance[] | null {
308
+ const cases = pairedCases(a, b, metricOverride)
309
+ if (cases === null) return null
310
+ const grouped = new Map<string, { pairs: number; wins: number; losses: number; ties: number }>()
311
+ for (const item of cases) {
312
+ const row = grouped.get(item.caseId) ?? { pairs: 0, wins: 0, losses: 0, ties: 0 }
313
+ row.pairs += 1
314
+ if (item.outcome === 'B better') row.wins += 1
315
+ else if (item.outcome === 'A better') row.losses += 1
316
+ else row.ties += 1
317
+ grouped.set(item.caseId, row)
318
+ }
319
+ const family = Math.max(1, grouped.size)
320
+ const alpha = bonferroni(1, family).alpha
321
+ return [...grouped.entries()]
322
+ .map(([caseId, counts]) => {
323
+ const test = signTest(counts.wins, counts.losses)
324
+ const adjustedP = Math.min(1, test.pValue * family)
325
+ const power = signTestPower(counts.wins + counts.losses, family, alpha)
326
+ const detectable = power.detectable
327
+ const better = counts.wins > counts.losses
328
+ const worse = counts.losses > counts.wins
329
+ return {
330
+ caseId,
331
+ ...counts,
332
+ adjustedP,
333
+ detectable,
334
+ requiredPairs: power.minimumDiscordant,
335
+ verdict: !detectable ? 'underpowered' as const
336
+ : better && adjustedP <= alpha ? 'significantly-better' as const
337
+ : worse && adjustedP <= alpha ? 'significantly-worse' as const
338
+ : 'not-significant' as const,
339
+ }
340
+ })
341
+ .sort((left, right) => left.adjustedP - right.adjustedP
342
+ /* v8 ignore next -- case-id tie direction depends on engine sort order. */
343
+ || (left.caseId < right.caseId ? -1 : 1))
344
+ }
345
+
346
+ /** Render per-case paired significance as a markdown block. */
347
+ export function renderCaseSignificance(rows: readonly CaseSignificance[]): string {
348
+ if (rows.length === 0) {
349
+ return '## Per-case paired significance\n\n- no paired case evidence\n'
350
+ }
351
+ const confirmed = rows.filter(row =>
352
+ row.verdict === 'significantly-better' || row.verdict === 'significantly-worse')
353
+ const shown = confirmed.slice(0, 20)
354
+ const lines = [
355
+ '## Per-case paired significance',
356
+ '',
357
+ `- ${rows.length} cases · Bonferroni family = ${rows.length} · ${confirmed.length} confirmed changes`,
358
+ ]
359
+ if (shown.length < confirmed.length) {
360
+ lines.push(`- showing ${shown.length} of ${confirmed.length} confirmed changes`)
361
+ }
362
+ const underpowered = rows.filter(row => row.verdict === 'underpowered')
363
+ if (underpowered.length > 0) {
364
+ lines.push(`- ${underpowered.length} underpowered cases need at least ${Math.max(...underpowered.map(row => row.requiredPairs))} discordant pairs for this family`)
365
+ }
366
+ if (shown.length > 0) {
367
+ lines.push('', '| case | pairs | B wins | A wins | adjusted p | result |', '|---|---|---|---|---|---|')
368
+ for (const row of shown) {
369
+ const caseId = row.caseId.replace(/[\r\n|]/gu, ' ')
370
+ lines.push(`| ${caseId} | ${row.pairs} | ${row.wins} | ${row.losses} | ${formatPValue(row.adjustedP)} | ${row.verdict} |`)
371
+ }
372
+ }
373
+ return `${lines.join('\n')}\n`
374
+ }
375
+
376
+ /** Format a paired case value for reports and dashboards. */
377
+ export function formatCaseValue(value: boolean | number | null): string {
378
+ if (value === null) return '–'
379
+ if (typeof value === 'boolean') return value ? 'pass' : 'fail'
380
+ return String(value)
381
+ }
382
+
383
+ /**
384
+ * Render the most actionable paired case outcomes: candidate wins first, then
385
+ * candidate losses, capped at 20 rows so a large benchmark still fits a screen.
386
+ * @param cases - rows from {@link pairedCases}.
387
+ * @returns a markdown block ending in a newline.
388
+ */
389
+ export function renderPairedCases(cases: readonly PairedCase[]): string {
390
+ const wins = cases.filter(item => item.outcome === 'B better')
391
+ const losses = cases.filter(item => item.outcome === 'A better')
392
+ const ties = cases.length - wins.length - losses.length
393
+ const shown = [...wins, ...losses].slice(0, 20)
394
+ const lines = [
395
+ '## Paired case outcomes',
396
+ '',
397
+ `- ${wins.length} candidate wins · ${losses.length} candidate losses · ${ties} ties`,
398
+ ]
399
+ if (shown.length < wins.length + losses.length) {
400
+ lines.push(`- showing ${shown.length} of ${wins.length + losses.length} discordant pairs`)
401
+ }
402
+ if (shown.length > 0) {
403
+ lines.push('', '| case | trial | A | B | result |', '|---|---|---|---|---|')
404
+ for (const item of shown) {
405
+ const caseId = item.caseId.replace(/[\r\n|]/gu, ' ')
406
+ lines.push(`| ${caseId} | ${item.trial} | ${formatCaseValue(item.a)} | ${formatCaseValue(item.b)} | ${item.outcome} |`)
407
+ }
408
+ }
409
+ return `${lines.join('\n')}\n`
410
+ }
411
+
165
412
  /** Pull one nullable numeric value from a run for comparison. */
166
413
  type RunSelector = (run: EvalRun) => number | null
167
414
 
@@ -184,22 +431,50 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
184
431
  }
185
432
  }
186
433
  const numeric = (selector: RunSelector, label: string): CompareRow => rates(selector, label, '')
434
+ const counts = (count: (run: EvalRun) => number, label: string): CompareRow => ({
435
+ metric: label,
436
+ a: String(count(a)),
437
+ b: String(count(b)),
438
+ delta: formatCountDelta(count(a), count(b)),
439
+ })
440
+ const usd = (selector: RunSelector, label: string): CompareRow => {
441
+ const aValue = selector(a)
442
+ const bValue = selector(b)
443
+ return { metric: label, a: formatUsd(aValue), b: formatUsd(bValue), delta: formatUsdDelta(aValue, bValue) }
444
+ }
187
445
  const rows: CompareRow[] = [
188
446
  { metric: 'benchmark', a: a.benchmark, b: b.benchmark, delta: '–' },
189
447
  { metric: 'model', a: a.model, b: b.model, delta: '–' },
190
- numeric(run => completed(run), 'completed trials'),
448
+ counts(completed, 'completed trials'),
191
449
  numeric(run => run.aggregate?.steps ?? null, 'steps/trial'),
192
450
  rates(run => run.aggregate?.toolSuccessRate ?? null, 'tool success', 'pp'),
193
451
  rates(run => run.grading?.taskSuccessRate ?? null, 'task success', 'pp'),
194
452
  rates(run => run.grading?.toolSelectionAccuracyRate ?? null, 'tool selection accuracy', 'pp'),
453
+ numeric(run => run.grading?.judgeFailures ?? null, 'judge failures'),
195
454
  numeric(run => run.aggregate?.invalidToolCalls ?? null, 'invalid tool calls/trial'),
196
455
  numeric(run => run.aggregate?.retries ?? null, 'retries/trial'),
197
456
  numeric(run => run.aggregate?.totalTokens ?? null, 'tokens/trial'),
198
- numeric(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
457
+ usd(run => run.aggregate?.costUsd ?? null, 'cost/trial (USD)'),
199
458
  numeric(run => run.aggregate?.latencyMs ?? null, 'latency/trial (ms)'),
200
459
  ]
460
+ // Reliability is derived from the trials rather than stored, so older run
461
+ // reports gain these rows on the next `compare` without being rewritten.
462
+ rows.push(
463
+ counts(run => computeCoverage(run).unscored, 'unscored trials'),
464
+ rates(run => computeReliability(run, 'task')?.strictPassAt1 ?? null, 'strict pass@1 (task)', 'pp'),
465
+ rates(run => computeReliability(run, 'task')?.passAtK ?? null, 'pass@k (task)', 'pp'),
466
+ rates(run => computeReliability(run, 'task')?.passAllK ?? null, 'pass^k (task)', 'pp'),
467
+ rates(run => computeReliability(run, 'tool-selection')?.passAtK ?? null, 'pass@k (tool-selection)', 'pp'),
468
+ rates(run => computeReliability(run, 'tool-selection')?.passAllK ?? null, 'pass^k (tool-selection)', 'pp'),
469
+ )
201
470
  const paired = pairedCompare(a, b)
202
471
  if (paired !== null) {
472
+ // A p-value or a confidence interval is evidence about the pairing, not a
473
+ // signed difference between two run-level numbers. Keep it out of the
474
+ // `delta (B - A)` column so that column only ever contains real differences.
475
+ const inference = (metric: string, value: string): CompareRow => ({
476
+ metric, a: '–', b: '–', delta: '–', inference: value,
477
+ })
203
478
  rows.push(
204
479
  { metric: 'paired trials', a: String(paired.pairs), b: String(paired.pairs), delta: '–' },
205
480
  {
@@ -208,21 +483,28 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
208
483
  b: '–',
209
484
  delta: '–',
210
485
  },
211
- {
212
- metric: `paired ${paired.primaryMetric} p (sign test)`,
213
- a: '–',
214
- b: '–',
215
- delta: `${formatPValue(paired.test.pValue)} (n=${paired.test.discordant})`,
216
- },
217
- ...(paired.stepsDelta === null ? [] : [{
218
- metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.stepsDelta),
219
- }]),
220
- ...(paired.tokensDelta === null ? [] : [{
221
- metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.tokensDelta),
222
- }]),
223
- ...(paired.scoreDelta === null ? [] : [{
224
- metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.scoreDelta),
225
- }]),
486
+ inference(
487
+ `paired ${paired.primaryMetric} p (sign test, Bonferroni ×${paired.correction.comparisons})`,
488
+ `${formatPValue(paired.correction.adjustedPValue)} (n=${paired.test.discordant})`,
489
+ ),
490
+ inference(
491
+ `paired sign-test power (α=${paired.power.alpha})`,
492
+ paired.power.detectable
493
+ ? `best p ${formatPValue(paired.power.bestAdjustedP)}; needs ${paired.power.minimumWins}/${paired.power.discordant} wins`
494
+ : `unreachable: best p ${formatPValue(paired.power.bestAdjustedP)}; need ≥${paired.power.minimumDiscordant} discordant pairs`,
495
+ ),
496
+ ...(paired.stepsDelta === null ? [] : [inference(
497
+ 'paired steps delta (B-A)',
498
+ formatPairedDelta(paired.stepsDelta, paired.correction.intervalConfidence),
499
+ )]),
500
+ ...(paired.tokensDelta === null ? [] : [inference(
501
+ 'paired tokens delta (B-A)',
502
+ formatPairedDelta(paired.tokensDelta, paired.correction.intervalConfidence),
503
+ )]),
504
+ ...(paired.scoreDelta === null ? [] : [inference(
505
+ 'paired final-answer delta (B-A)',
506
+ formatPairedDelta(paired.scoreDelta, paired.correction.intervalConfidence),
507
+ )]),
226
508
  )
227
509
  }
228
510
  return rows
@@ -234,12 +516,85 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
234
516
  * @returns the markdown text.
235
517
  */
236
518
  export function renderCompareMarkdown(rows: readonly CompareRow[]): string {
519
+ const metrics = rows.filter(row => row.inference === undefined)
520
+ const inference = rows.filter(row => row.inference !== undefined)
237
521
  return [
238
522
  '# Compare',
239
523
  '',
240
524
  '| metric | run A | run B | delta (B - A) |',
241
525
  '|---|---|---|---|',
242
- ...rows.map(row => `| ${row.metric} | ${row.a} | ${row.b} | ${row.delta} |`),
526
+ ...metrics.map(row => `| ${row.metric} | ${row.a} | ${row.b} | ${row.delta} |`),
243
527
  '',
528
+ ...(inference.length === 0 ? [] : [
529
+ '## Paired inference',
530
+ '',
531
+ 'Values below describe the paired sample, not a run-level difference.',
532
+ '',
533
+ '| quantity | value |',
534
+ '|---|---|',
535
+ ...inference.map(row => `| ${row.metric} | ${row.inference} |`),
536
+ '',
537
+ ]),
244
538
  ].join('\n')
245
539
  }
540
+
541
+ /**
542
+ * Render a two-run comparison as machine-readable JSON.
543
+ * @param a - the baseline run.
544
+ * @param b - the candidate run.
545
+ * @returns a JSON string ending in a newline.
546
+ */
547
+ export function renderCompareJson(a: EvalRun, b: EvalRun): string {
548
+ const completed = (run: EvalRun): number => run.cases.filter(result => result.status === 'completed').length
549
+ const cases = pairedCases(a, b)
550
+ return `${JSON.stringify({
551
+ baseline: { benchmark: a.benchmark, model: a.model },
552
+ candidate: { benchmark: b.benchmark, model: b.model },
553
+ // `rows` keeps the formatted table for parity with the CLI; `metrics`
554
+ // carries raw numbers so automation never parses a display string.
555
+ rows: compareRuns(a, b),
556
+ metrics: {
557
+ completedTrials: { a: completed(a), b: completed(b) },
558
+ unscoredTrials: {
559
+ a: computeCoverage(a).unscored,
560
+ b: computeCoverage(b).unscored,
561
+ },
562
+ aggregate: ['steps', 'toolSuccessRate', 'invalidToolCalls', 'retries',
563
+ 'totalTokens', 'costUsd', 'latencyMs'].reduce<Record<string, { a: number | null; b: number | null }>>(
564
+ (out, key) => {
565
+ const field = key as 'steps' | 'toolSuccessRate' | 'invalidToolCalls'
566
+ | 'retries' | 'totalTokens' | 'costUsd' | 'latencyMs'
567
+ out[key] = {
568
+ a: a.aggregate?.[field] ?? null,
569
+ b: b.aggregate?.[field] ?? null,
570
+ }
571
+ return out
572
+ }, {},
573
+ ),
574
+ grading: ['taskSuccessRate', 'toolSelectionAccuracyRate', 'judgeFailures'].reduce<Record<string, { a: number | null; b: number | null }>>(
575
+ (out, key) => {
576
+ const field = key as keyof NonNullable<EvalRun['grading']>
577
+ out[key] = {
578
+ a: a.grading?.[field] ?? null,
579
+ b: b.grading?.[field] ?? null,
580
+ }
581
+ return out
582
+ }, {},
583
+ ),
584
+ reliability: {
585
+ taskStrictPassAt1: {
586
+ a: computeReliability(a, 'task')?.strictPassAt1 ?? null,
587
+ b: computeReliability(b, 'task')?.strictPassAt1 ?? null,
588
+ },
589
+ taskPassAtK: {
590
+ a: computeReliability(a, 'task')?.passAtK ?? null,
591
+ b: computeReliability(b, 'task')?.passAtK ?? null,
592
+ },
593
+ },
594
+ },
595
+ paired: pairedCompare(a, b),
596
+ caseOutcomesMeasured: cases !== null,
597
+ cases,
598
+ caseSignificance: pairedCaseSignificance(a, b),
599
+ })}\n`
600
+ }