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
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Single-run precision for dsh-eval: percentile-bootstrap intervals for graded
3
+ * rates and latency percentiles, derived from the stored trials at render time.
4
+ *
5
+ * A pooled rate alone hides how little evidence a small run carries. Reusing
6
+ * the paired bootstrap machinery on the zero/one trial outcomes gives a
7
+ * distribution-free interval with no extra assumption, and seeding it with the
8
+ * run's `seed` keeps a re-rendered report byte-identical.
9
+ *
10
+ * @module dsh-eval/precision
11
+ */
12
+
13
+ import { pairedDelta, type BootstrapOptions } from './stats.ts'
14
+ import type { EvalRun, EvalTrialResult } from './types.ts'
15
+
16
+ /** A rate with a seeded percentile-bootstrap interval. */
17
+ export interface RateInterval {
18
+ /** Number of graded trials contributing. */
19
+ trials: number
20
+ /** Observed rate over those trials. */
21
+ rate: number
22
+ /** Lower interval bound, or null with a single trial. */
23
+ lower: number | null
24
+ /** Upper interval bound, or null with a single trial. */
25
+ upper: number | null
26
+ }
27
+
28
+ /** Precision figures for one run. */
29
+ export interface RunPrecision {
30
+ /** Task-success interval, or null when no trial carried the check. */
31
+ task: RateInterval | null
32
+ /** Tool-selection interval, or null when no trial carried the expectation. */
33
+ toolSelection: RateInterval | null
34
+ /** Strict pass@1 interval over every trial, keeping errors in the denominator. */
35
+ strictPassAt1: RateInterval | null
36
+ /** Median trial latency in milliseconds, or null without metrics. */
37
+ latencyP50: number | null
38
+ /** 95th-percentile trial latency in milliseconds, or null without metrics. */
39
+ latencyP95: number | null
40
+ }
41
+
42
+ /** Interpolated percentile of a sample, sorting a copy so the input stays intact. */
43
+ function percentile(values: readonly number[], q: number): number {
44
+ const sorted = [...values].sort((a, b) => a - b)
45
+ const position = (sorted.length - 1) * q
46
+ const low = Math.floor(position)
47
+ const weight = position - low
48
+ return sorted[low]! * (1 - weight) + sorted[Math.ceil(position)]! * weight
49
+ }
50
+
51
+ /** Bootstrap a rate interval from the trials that actually carry a grade. */
52
+ function rateInterval(
53
+ results: readonly EvalTrialResult[],
54
+ pick: (result: EvalTrialResult) => boolean | null | undefined,
55
+ options: BootstrapOptions,
56
+ ): RateInterval | null {
57
+ const observed = results.map(pick).filter((value): value is boolean => typeof value === 'boolean')
58
+ if (observed.length === 0) return null
59
+ const bootstrap = pairedDelta(observed.map(value => value ? 1 : 0), options)!
60
+ return { trials: observed.length, rate: bootstrap.mean, lower: bootstrap.lower, upper: bootstrap.upper }
61
+ }
62
+
63
+ /**
64
+ * Derive single-run precision from a persisted run.
65
+ * @param run - the run to summarize.
66
+ * @param options - bootstrap overrides; the run's seed is used by default.
67
+ * @returns the precision figures, all null when no trial carries data.
68
+ */
69
+ export function computePrecision(run: EvalRun, options: BootstrapOptions = {}): RunPrecision {
70
+ const completed = run.cases.filter(result => result.status === 'completed')
71
+ const bootstrap = { ...options, seed: options.seed ?? run.seed }
72
+ const latencies = completed
73
+ .map(result => result.metrics?.latencyMs)
74
+ .filter((value): value is number => typeof value === 'number')
75
+ return {
76
+ task: rateInterval(completed, result => result.grade?.taskSuccess, bootstrap),
77
+ toolSelection: rateInterval(completed, result => result.grade?.toolSelectionAccuracy, bootstrap),
78
+ strictPassAt1: completed.some(result => typeof result.grade?.taskSuccess === 'boolean')
79
+ ? rateInterval(run.cases, result =>
80
+ result.status === 'completed' && result.grade?.taskSuccess === true, bootstrap)
81
+ : null,
82
+ latencyP50: latencies.length === 0 ? null : percentile(latencies, 0.5),
83
+ latencyP95: latencies.length === 0 ? null : percentile(latencies, 0.95),
84
+ }
85
+ }
package/src/rejudge.ts ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Offline re-judging for dsh-eval: rebuild judge verdicts from a stored run's
3
+ * harvested traces and persisted case inputs, then re-aggregate grading.
4
+ *
5
+ * This enables a keyless two-phase workflow: record a run with replay (which
6
+ * cannot coexist with a live judge), then judge the recorded traces later with
7
+ * an LLM seam. Only the judge verdicts and the grading summary change; metrics,
8
+ * scripted grades, and trial outcomes are preserved.
9
+ *
10
+ * @module dsh-eval/rejudge
11
+ */
12
+
13
+ import { realpath } from 'node:fs/promises'
14
+ import { homedir } from 'node:os'
15
+ import { extname, isAbsolute, parse, relative, resolve, sep } from 'node:path'
16
+ import { tryJudgeTrial, type JudgeChat } from './judge.ts'
17
+ import { aggregateGrading } from './runner.ts'
18
+ import { loadTrace, mergeTraces, traceDigest } from './trace.ts'
19
+ import type { BenchmarkCase, BenchmarkJudge, EvalRun, EvalTrialResult } from './types.ts'
20
+
21
+ /**
22
+ * Re-judge every completed trial of a persisted run.
23
+ * @param run - a validated run report carrying `caseInputs`.
24
+ * @param judgeChat - the injected chat seam for the judge model.
25
+ * @param judgeOverride - judge config to use instead of the one stored in the run.
26
+ * @returns a new run with fresh verdicts and a re-aggregated grading summary.
27
+ * @throws when the report lacks the data a judge prompt needs.
28
+ */
29
+ export async function rejudgeRun(
30
+ run: EvalRun,
31
+ judgeChat: JudgeChat,
32
+ judgeOverride?: BenchmarkJudge,
33
+ ): Promise<EvalRun> {
34
+ const judge = judgeOverride ?? run.judge
35
+ if (judge === undefined) {
36
+ throw new Error('rejudge: no judge configuration; pass --judge-model to supply one')
37
+ }
38
+ if (run.caseInputs === undefined) {
39
+ throw new Error('rejudge: the run has no caseInputs; re-run with a version that persists prompts')
40
+ }
41
+ const inputs = new Map(run.caseInputs.map(input => [input.caseId, input]))
42
+ // A report is data, not code: a hand-edited tracePaths entry must not be able
43
+ // to make the judge read and ship an arbitrary local file to an LLM.
44
+ const root = await realpath(resolve(run.tempRoot))
45
+ // A hand-edited report must not promote a drive root or home directory to
46
+ // the "allowed" root; that would make every local log reachable by design.
47
+ if (root === parse(root).root || root === resolve(homedir())
48
+ || relative(parse(root).root, root).split(sep).filter(Boolean).length === 0) {
49
+ throw new Error('rejudge: tempRoot must be a dedicated run directory')
50
+ }
51
+ const insideRoot = async (path: string): Promise<boolean> => {
52
+ if (!isAbsolute(path)) return false
53
+ // realpath resolves `..` and symlinks before comparing, so neither a
54
+ // traversal prefix nor a symlink to another run's log escapes the check.
55
+ let resolved: string
56
+ try {
57
+ resolved = await realpath(path)
58
+ } catch {
59
+ return false
60
+ }
61
+ const rel = relative(root, resolved)
62
+ return extname(resolved) === '.jsonl'
63
+ && rel !== '' && !rel.startsWith('..') && !isAbsolute(rel)
64
+ }
65
+ const cases: EvalTrialResult[] = []
66
+ for (const result of run.cases) {
67
+ if (result.status !== 'completed') {
68
+ cases.push(result)
69
+ continue
70
+ }
71
+ const input = inputs.get(result.caseId)
72
+ if (input === undefined) {
73
+ throw new Error(`rejudge: no case input for "${result.caseId}"`)
74
+ }
75
+ const paths = result.tracePaths ?? (result.tracePath === undefined ? [] : [result.tracePath])
76
+ if (paths.length === 0) {
77
+ throw new Error(`rejudge: trial ${result.caseId}#${result.trial} has no harvested trace`)
78
+ }
79
+ for (const path of paths) {
80
+ if (!await insideRoot(path)) {
81
+ throw new Error(`rejudge: trace path "${path}" is outside the run's tempRoot or not a .jsonl log`)
82
+ }
83
+ }
84
+ const loaded = await Promise.all(paths.map(async path => ({ path, trace: await loadTrace(path) })))
85
+ loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt)
86
+ const merged = mergeTraces(loaded.map(entry => entry.trace))
87
+ if (result.traceSha256 !== undefined && traceDigest(merged) !== result.traceSha256) {
88
+ throw new Error(`rejudge: trace for ${result.caseId}#${result.trial} differs from the recorded digest`)
89
+ }
90
+ const caseValue: BenchmarkCase = {
91
+ id: input.caseId,
92
+ prompt: input.prompt,
93
+ ...(input.answer !== undefined ? { expected: { answer: input.answer } } : {}),
94
+ }
95
+ const verdict = await tryJudgeTrial(caseValue, merged, judge, judgeChat)
96
+ const previous = result.judge
97
+ // A flaky judge must not erase an already usable score. Keep the old one,
98
+ // but leave the failure visible next to it in the report.
99
+ const keepPrevious = verdict.judgeError !== undefined && previous?.finalAnswerScore != null
100
+ cases.push({
101
+ ...result,
102
+ judge: keepPrevious
103
+ ? { ...previous!, judgeError: `${verdict.judgeError} (previous verdict kept)` }
104
+ : verdict,
105
+ })
106
+ }
107
+ // Grading depends on grade/judge fields, not on metrics, so do not require a
108
+ // metric fold here — imported or hand-edited reports may legitimately omit it.
109
+ const completed = cases.filter(result => result.status === 'completed')
110
+ // Record the judge actually used, including a CLI override.
111
+ return { ...run, judge, cases, grading: aggregateGrading(completed) }
112
+ }
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Reliability metrics over repeated trials of the same case.
3
+ *
4
+ * A pooled success rate hides the shape of failure: three trials of one case
5
+ * can all fail while three other cases pass every time, and both report the
6
+ * same 66.7%. `pass@k`, `pass^k`, and the flaky-case list make that shape
7
+ * visible. The metrics are derived at render time from the persisted trials,
8
+ * so reports written before this module existed gain them on next render.
9
+ *
10
+ * @module dsh-eval/reliability
11
+ */
12
+
13
+ import type { EvalRun, EvalTrialResult } from './types.ts'
14
+
15
+ /** The grading dimension a reliability summary describes. */
16
+ export type ReliabilityDimension = 'task' | 'tool-selection'
17
+
18
+ /** Trial accounting for one run, including trials that produced no grade. */
19
+ export interface RunCoverage {
20
+ /** Every trial in the run, completed or not. */
21
+ total: number
22
+ /** Trials with a harvested trace. */
23
+ completed: number
24
+ /** Trials that failed before producing a usable trace. */
25
+ errors: number
26
+ /** Trials killed by the timeout. */
27
+ timeouts: number
28
+ /** Trials that never produced a grade (`total - completed`). */
29
+ unscored: number
30
+ }
31
+
32
+ /** Reliability of one case across its graded trials. */
33
+ export interface CaseReliability {
34
+ /** Benchmark case id. */
35
+ caseId: string
36
+ /** Number of graded trials observed for the case. */
37
+ trials: number
38
+ /** Every trial for the case, including errors and timeouts. */
39
+ total: number
40
+ /** Number of those trials that passed. */
41
+ passes: number
42
+ /** `passes / trials`. */
43
+ rate: number
44
+ }
45
+
46
+ /** Reliability of one grading dimension across the whole run. */
47
+ export interface ReliabilitySummary {
48
+ /** Which grade field was summarized. */
49
+ dimension: ReliabilityDimension
50
+ /** Trials per case configured for the run. */
51
+ k: number
52
+ /** Cases with at least one graded trial. */
53
+ cases: number
54
+ /** Every trial in the run, completed or not. */
55
+ total: number
56
+ /** Fraction of all graded trials that passed. */
57
+ passAt1: number
58
+ /** Passes over every trial, including errors and timeouts: the unbiased rate. */
59
+ strictPassAt1: number
60
+ /** Trials that never produced a grade for this dimension. */
61
+ unscored: number
62
+ /** Fraction of cases with at least one passing trial. */
63
+ passAtK: number
64
+ /** Fraction of cases where every graded trial passed. */
65
+ passAllK: number
66
+ /** Cases whose trials disagreed, in case order. */
67
+ flaky: readonly CaseReliability[]
68
+ /** Up to three weakest cases, by pass rate then case id. */
69
+ hardest: readonly CaseReliability[]
70
+ }
71
+
72
+ /** Read the chosen grade, ignoring trials that were not graded on it. */
73
+ function readGrade(result: EvalTrialResult, dimension: ReliabilityDimension): boolean | null {
74
+ const grade = result.grade
75
+ if (grade === undefined) return null
76
+ return dimension === 'task' ? grade.taskSuccess : grade.toolSelectionAccuracy
77
+ }
78
+
79
+ /**
80
+ * Count every trial in a run, including those that never produced a grade.
81
+ * A rate computed only over completed trials is biased whenever some trials
82
+ * error or time out, so the denominator must be visible alongside it.
83
+ * @param run - the run to account for.
84
+ * @returns counts whose `unscored` field is the trials missing from all rates.
85
+ */
86
+ export function computeCoverage(run: EvalRun): RunCoverage {
87
+ let completed = 0
88
+ let errors = 0
89
+ let timeouts = 0
90
+ let unscored = 0
91
+ for (const result of run.cases) {
92
+ if (result.status === 'completed') completed += 1
93
+ else errors += 1
94
+ if (result.timedOut) timeouts += 1
95
+ // A completed trial without a task grade is just as absent from quality
96
+ // rates as an error; keep this identical to computeReliability().unscored.
97
+ if (result.status !== 'completed' || typeof result.grade?.taskSuccess !== 'boolean') unscored += 1
98
+ }
99
+ return {
100
+ total: run.cases.length,
101
+ completed,
102
+ errors,
103
+ timeouts,
104
+ unscored,
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Fold a run's trials into reliability metrics for one grading dimension.
110
+ *
111
+ * Every trial for a case contributes to `total`, even an error or timeout.
112
+ * `passAt1` keeps its historical graded-only denominator; `strictPassAt1`
113
+ * divides by all trials so a model that times out on hard cases cannot look
114
+ * better than one that finishes and fails.
115
+ * @param run - the run to summarize.
116
+ * @param dimension - `task` (default) or `tool-selection` grading.
117
+ * @returns the summary, or null when no trial carried that grade.
118
+ */
119
+ export function computeReliability(
120
+ run: EvalRun,
121
+ dimension: ReliabilityDimension = 'task',
122
+ ): ReliabilitySummary | null {
123
+ const grouped = new Map<string, { total: number; graded: number; passes: number }>()
124
+ for (const result of run.cases) {
125
+ const group = grouped.get(result.caseId) ?? { total: 0, graded: 0, passes: 0 }
126
+ group.total += 1
127
+ if (result.status === 'completed') {
128
+ const passed = readGrade(result, dimension)
129
+ if (passed !== null) {
130
+ group.graded += 1
131
+ if (passed) group.passes += 1
132
+ }
133
+ }
134
+ grouped.set(result.caseId, group)
135
+ }
136
+ const all = [...grouped.values()]
137
+ const cases = [...grouped].filter(([, group]) => group.graded > 0).map(([caseId, group]) => ({
138
+ caseId,
139
+ trials: group.graded,
140
+ total: group.total,
141
+ passes: group.passes,
142
+ rate: group.passes / group.graded,
143
+ }))
144
+ if (cases.length === 0) return null
145
+
146
+ const trials = cases.reduce((sum, item) => sum + item.trials, 0)
147
+ const passes = cases.reduce((sum, item) => sum + item.passes, 0)
148
+ const total = all.reduce((sum, group) => sum + group.total, 0)
149
+ const graded = all.reduce((sum, group) => sum + group.graded, 0)
150
+ return {
151
+ dimension,
152
+ k: run.trials,
153
+ cases: cases.length,
154
+ total,
155
+ passAt1: passes / trials,
156
+ strictPassAt1: passes / total,
157
+ unscored: total - graded,
158
+ passAtK: cases.filter(item => item.passes > 0).length / cases.length,
159
+ passAllK: cases.filter(item => item.passes === item.trials).length / cases.length,
160
+ flaky: cases.filter(item => item.passes > 0 && item.passes < item.trials),
161
+ // Case ids are unique map keys, so the tie-break never compares equals.
162
+ hardest: [...cases]
163
+ .sort((a, b) => a.rate - b.rate || (a.caseId < b.caseId ? -1 : 1))
164
+ .slice(0, 3),
165
+ }
166
+ }