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.
- package/README.md +214 -13
- package/README.zh.md +99 -10
- package/lib/agreement.js +46 -0
- package/lib/argv.js +66 -0
- package/lib/atomic-write.js +38 -0
- package/lib/benchmark.js +116 -19
- package/lib/calibration.js +90 -0
- package/lib/command.js +202 -10
- package/lib/compare.js +310 -31
- package/lib/dashboard.js +260 -0
- package/lib/digest.js +118 -0
- package/lib/export.js +50 -0
- package/lib/gate.js +293 -0
- package/lib/import.js +17 -6
- package/lib/index.js +174 -12
- package/lib/judge.js +30 -7
- package/lib/leaderboard.js +222 -0
- package/lib/precision.js +50 -0
- package/lib/rejudge.js +107 -0
- package/lib/reliability.js +107 -0
- package/lib/report.js +285 -11
- package/lib/runner.js +189 -33
- package/lib/safe-regex.js +74 -0
- package/lib/segments.js +15 -0
- package/lib/stats.js +63 -0
- package/lib/trace.js +19 -2
- package/lib/types/agreement.d.ts +33 -0
- package/lib/types/argv.d.ts +19 -0
- package/lib/types/atomic-write.d.ts +15 -0
- package/lib/types/benchmark.d.ts +9 -2
- package/lib/types/calibration.d.ts +45 -0
- package/lib/types/command.d.ts +58 -0
- package/lib/types/compare.d.ts +82 -2
- package/lib/types/dashboard.d.ts +24 -0
- package/lib/types/digest.d.ts +38 -0
- package/lib/types/export.d.ts +17 -0
- package/lib/types/gate.d.ts +87 -0
- package/lib/types/index.d.ts +8 -4
- package/lib/types/judge.d.ts +4 -1
- package/lib/types/leaderboard.d.ts +70 -0
- package/lib/types/precision.d.ts +44 -0
- package/lib/types/rejudge.d.ts +22 -0
- package/lib/types/reliability.d.ts +85 -0
- package/lib/types/report.d.ts +18 -5
- package/lib/types/runner.d.ts +8 -1
- package/lib/types/safe-regex.d.ts +24 -0
- package/lib/types/segments.d.ts +12 -0
- package/lib/types/stats.d.ts +56 -0
- package/lib/types/trace.d.ts +7 -0
- package/lib/types/types.d.ts +55 -6
- package/lib/types/validate.d.ts +57 -0
- package/lib/validate.js +155 -0
- package/package.json +2 -2
- package/src/agreement.ts +60 -0
- package/src/argv.ts +63 -0
- package/src/atomic-write.ts +38 -0
- package/src/benchmark.ts +139 -13
- package/src/calibration.ts +113 -0
- package/src/command.ts +297 -10
- package/src/compare.ts +392 -37
- package/src/dashboard.ts +287 -0
- package/src/digest.ts +144 -0
- package/src/export.ts +57 -0
- package/src/gate.ts +383 -0
- package/src/import.ts +18 -6
- package/src/index.ts +192 -12
- package/src/judge.ts +30 -6
- package/src/leaderboard.ts +272 -0
- package/src/precision.ts +85 -0
- package/src/rejudge.ts +112 -0
- package/src/reliability.ts +166 -0
- package/src/report.ts +303 -11
- package/src/runner.ts +182 -35
- package/src/safe-regex.ts +79 -0
- package/src/segments.ts +16 -0
- package/src/stats.ts +104 -0
- package/src/trace.ts +19 -2
- package/src/types.ts +56 -6
- package/src/validate.ts +177 -0
package/lib/judge.js
CHANGED
|
@@ -12,6 +12,15 @@ import { BlockAssembler, createMessage } from '@deepseek-ai/dsh-llm';
|
|
|
12
12
|
function blockText(blocks) {
|
|
13
13
|
return blocks.flatMap(block => block.type === 'text' ? [block.text] : []).join('');
|
|
14
14
|
}
|
|
15
|
+
/** The last assistant text message in a trace, used as the final answer. */
|
|
16
|
+
export function finalAnswerOf(trace) {
|
|
17
|
+
let finalAnswer = '';
|
|
18
|
+
for (const event of trace.events) {
|
|
19
|
+
if (event.type === 'assistant/message')
|
|
20
|
+
finalAnswer = blockText(event.data.message.content);
|
|
21
|
+
}
|
|
22
|
+
return finalAnswer;
|
|
23
|
+
}
|
|
15
24
|
/**
|
|
16
25
|
* Summarize a trace for the judge: final assistant answer, the distinct tool
|
|
17
26
|
* names called, and the failure counters a hallucination call needs.
|
|
@@ -19,13 +28,11 @@ function blockText(blocks) {
|
|
|
19
28
|
* @returns a compact human-readable summary.
|
|
20
29
|
*/
|
|
21
30
|
export function summarizeTrace(trace) {
|
|
22
|
-
|
|
31
|
+
const finalAnswer = finalAnswerOf(trace);
|
|
23
32
|
const toolNames = [];
|
|
24
33
|
let invalidToolCalls = 0;
|
|
25
34
|
let retries = 0;
|
|
26
35
|
for (const event of trace.events) {
|
|
27
|
-
if (event.type === 'assistant/message')
|
|
28
|
-
finalAnswer = blockText(event.data.message.content);
|
|
29
36
|
if (event.type === 'tool/call') {
|
|
30
37
|
if (!toolNames.includes(event.data.name))
|
|
31
38
|
toolNames.push(event.data.name);
|
|
@@ -50,11 +57,15 @@ export function summarizeTrace(trace) {
|
|
|
50
57
|
* @returns the system and prompt texts.
|
|
51
58
|
*/
|
|
52
59
|
export function buildJudgePrompt(caseValue, trace, judge) {
|
|
60
|
+
const hasReference = caseValue.expected?.answer !== undefined;
|
|
53
61
|
const system = [
|
|
54
62
|
'You are an impartial evaluation judge for agent task completion.',
|
|
55
63
|
`Score the agent's final answer from 0 to ${judge.maxScore} against the task,`,
|
|
56
64
|
'and set "hallucination" to true only when the final answer asserts facts',
|
|
57
65
|
'not supported by the task or the trace.',
|
|
66
|
+
...(hasReference
|
|
67
|
+
? ['A reference answer is supplied: score factual agreement with it, not mere fluency.']
|
|
68
|
+
: []),
|
|
58
69
|
'Return STRICT JSON with exactly these fields:',
|
|
59
70
|
`{"finalAnswerScore": <integer 0..${judge.maxScore}>, "hallucination": <true|false>, "rationale": "<one short sentence>"}`,
|
|
60
71
|
...(judge.rubric !== undefined ? ['Rubric:', judge.rubric] : []),
|
|
@@ -62,6 +73,7 @@ export function buildJudgePrompt(caseValue, trace, judge) {
|
|
|
62
73
|
const prompt = [
|
|
63
74
|
`Task id: ${caseValue.id}`,
|
|
64
75
|
`Task: ${caseValue.prompt}`,
|
|
76
|
+
...(hasReference ? [`Reference answer: ${caseValue.expected?.answer}`] : []),
|
|
65
77
|
'Trace summary:',
|
|
66
78
|
summarizeTrace(trace),
|
|
67
79
|
].join('\n');
|
|
@@ -126,14 +138,25 @@ export async function judgeTrial(caseValue, trace, judge, chat) {
|
|
|
126
138
|
* @param trace - the merged trial trace.
|
|
127
139
|
* @param judge - the judge configuration.
|
|
128
140
|
* @param chat - the injected chat seam.
|
|
129
|
-
* @returns the parsed verdict, or all-null when the
|
|
141
|
+
* @returns the parsed verdict, or all-null plus `judgeError` when the call
|
|
142
|
+
* failed or the reply could not be parsed.
|
|
130
143
|
*/
|
|
131
144
|
export async function tryJudgeTrial(caseValue, trace, judge, chat) {
|
|
132
145
|
try {
|
|
133
|
-
|
|
146
|
+
const verdict = await judgeTrial(caseValue, trace, judge, chat);
|
|
147
|
+
// A syntactically valid but field-less reply is just as unusable as an
|
|
148
|
+
// outage; without this marker its score silently drops out of the mean.
|
|
149
|
+
if (verdict.finalAnswerScore === null && verdict.hallucination === null) {
|
|
150
|
+
return { ...verdict, judgeError: 'unparsable judge reply' };
|
|
151
|
+
}
|
|
152
|
+
return verdict;
|
|
134
153
|
}
|
|
135
|
-
catch {
|
|
136
|
-
return {
|
|
154
|
+
catch (error) {
|
|
155
|
+
return {
|
|
156
|
+
finalAnswerScore: null,
|
|
157
|
+
hallucination: null,
|
|
158
|
+
judgeError: error instanceof Error ? error.message : String(error),
|
|
159
|
+
};
|
|
137
160
|
}
|
|
138
161
|
}
|
|
139
162
|
/**
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Multi-run leaderboard for dsh-eval.
|
|
3
|
+
*
|
|
4
|
+
* `compare` answers a two-run question with paired inference; a leaderboard
|
|
5
|
+
* answers the wider "which of these runs is currently best" question. Ranks
|
|
6
|
+
* use pooled task success with deterministic tie-breakers, and every row shows
|
|
7
|
+
* how far it trails the leader. This is a screening view, not a significance
|
|
8
|
+
* test, but each non-leader row carries a Bonferroni-corrected paired verdict
|
|
9
|
+
* against the leader so a one-point lead is not mistaken for a real gap.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-eval/leaderboard
|
|
12
|
+
*/
|
|
13
|
+
import { formatPValue, pairedCompare } from "./compare.js";
|
|
14
|
+
import { computeCoverage, computeReliability } from "./reliability.js";
|
|
15
|
+
import { signTest, signTestPower } from "./stats.js";
|
|
16
|
+
/** Normalize a pooled judge score using the run's configured scale. */
|
|
17
|
+
function judgeRate(run) {
|
|
18
|
+
const score = run.grading?.finalAnswerScore;
|
|
19
|
+
const maxScore = run.judge?.maxScore;
|
|
20
|
+
if (score === null || score === undefined || maxScore === undefined || maxScore <= 0)
|
|
21
|
+
return null;
|
|
22
|
+
return Math.max(0, Math.min(1, score / maxScore));
|
|
23
|
+
}
|
|
24
|
+
/** Prefer higher values, pushing missing metrics to the bottom. */
|
|
25
|
+
function descending(a, b) {
|
|
26
|
+
if (a === null)
|
|
27
|
+
return b === null ? 0 : 1;
|
|
28
|
+
if (b === null)
|
|
29
|
+
return -1;
|
|
30
|
+
return b - a;
|
|
31
|
+
}
|
|
32
|
+
/** Value used for ranking, gaps and ties. */
|
|
33
|
+
function metricValue(entry, metric) {
|
|
34
|
+
return metric === 'strictPassAt1' ? entry.strictPassAt1 : entry.taskSuccess;
|
|
35
|
+
}
|
|
36
|
+
/** Strict pass@1 outcome for one trial: errors and timeouts count as failures. */
|
|
37
|
+
function strictOutcome(result) {
|
|
38
|
+
return result.status === 'completed' && result.grade?.taskSuccess === true;
|
|
39
|
+
}
|
|
40
|
+
function trialKey(result) {
|
|
41
|
+
return `${result.caseId}\u0000${result.trial}`;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Discordant strict-pass counts across every trial key in either run.
|
|
45
|
+
* Unlike pairedCompare(), incomplete trials stay in the denominator.
|
|
46
|
+
*/
|
|
47
|
+
function strictPairCounts(leader, row) {
|
|
48
|
+
const leaderTrials = new Map(leader.cases.map(result => [trialKey(result), result]));
|
|
49
|
+
const rowTrials = new Map(row.cases.map(result => [trialKey(result), result]));
|
|
50
|
+
let wins = 0;
|
|
51
|
+
let losses = 0;
|
|
52
|
+
let ties = 0;
|
|
53
|
+
for (const key of new Set([...leaderTrials.keys(), ...rowTrials.keys()])) {
|
|
54
|
+
const a = leaderTrials.get(key);
|
|
55
|
+
const b = rowTrials.get(key);
|
|
56
|
+
const aPass = a === undefined ? false : strictOutcome(a);
|
|
57
|
+
const bPass = b === undefined ? false : strictOutcome(b);
|
|
58
|
+
if (bPass && !aPass)
|
|
59
|
+
wins += 1;
|
|
60
|
+
else if (aPass && !bPass)
|
|
61
|
+
losses += 1;
|
|
62
|
+
else
|
|
63
|
+
ties += 1;
|
|
64
|
+
}
|
|
65
|
+
return { wins, losses, ties };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Rank persisted runs by task success or strict pass@1.
|
|
69
|
+
* @param runs - labelled run records; labels are usually `benchmark — model`.
|
|
70
|
+
* @param metric - primary ranking metric; default is pooled task success.
|
|
71
|
+
* @returns ranked rows with ties sharing a rank.
|
|
72
|
+
*/
|
|
73
|
+
export function buildLeaderboard(runs, metric = 'taskSuccess') {
|
|
74
|
+
const runByEntry = new Map();
|
|
75
|
+
const rows = runs.map(({ label, run }) => {
|
|
76
|
+
const coverage = computeCoverage(run);
|
|
77
|
+
const reliability = computeReliability(run, 'task');
|
|
78
|
+
const entry = {
|
|
79
|
+
label,
|
|
80
|
+
benchmark: run.benchmark,
|
|
81
|
+
model: run.model,
|
|
82
|
+
completed: coverage.completed,
|
|
83
|
+
total: coverage.total,
|
|
84
|
+
taskSuccess: run.grading?.taskSuccessRate ?? null,
|
|
85
|
+
strictPassAt1: reliability?.strictPassAt1 ?? null,
|
|
86
|
+
toolSelection: run.grading?.toolSelectionAccuracyRate ?? null,
|
|
87
|
+
judgeScore: judgeRate(run),
|
|
88
|
+
costUsd: run.aggregate?.costUsd ?? null,
|
|
89
|
+
latencyMs: run.aggregate?.latencyMs ?? null,
|
|
90
|
+
gapFromBest: null,
|
|
91
|
+
significance: null,
|
|
92
|
+
rank: 0,
|
|
93
|
+
};
|
|
94
|
+
runByEntry.set(entry, run);
|
|
95
|
+
return entry;
|
|
96
|
+
});
|
|
97
|
+
rows.sort((a, b) => descending(metricValue(a, metric), metricValue(b, metric))
|
|
98
|
+
|| descending(a.strictPassAt1, b.strictPassAt1)
|
|
99
|
+
|| descending(a.taskSuccess, b.taskSuccess)
|
|
100
|
+
|| descending(a.toolSelection, b.toolSelection)
|
|
101
|
+
|| descending(a.judgeScore, b.judgeScore)
|
|
102
|
+
|| a.label.localeCompare(b.label));
|
|
103
|
+
const best = rows.length === 0 ? null : metricValue(rows[0], metric);
|
|
104
|
+
let lastRate = null;
|
|
105
|
+
let lastRank = 0;
|
|
106
|
+
let first = true;
|
|
107
|
+
rows.forEach((row, index) => {
|
|
108
|
+
const value = metricValue(row, metric);
|
|
109
|
+
if (value === null || first || value !== lastRate) {
|
|
110
|
+
lastRank = index + 1;
|
|
111
|
+
lastRate = value;
|
|
112
|
+
first = false;
|
|
113
|
+
}
|
|
114
|
+
row.rank = lastRank;
|
|
115
|
+
row.gapFromBest = best === null || value === null ? null : best - value;
|
|
116
|
+
});
|
|
117
|
+
const leader = rows.find(row => row.rank === 1);
|
|
118
|
+
const leaderRun = leader === undefined ? undefined : runByEntry.get(leader);
|
|
119
|
+
const family = Math.max(1, rows.length - 1);
|
|
120
|
+
if (leaderRun !== undefined) {
|
|
121
|
+
for (const row of rows) {
|
|
122
|
+
if (row === leader)
|
|
123
|
+
continue;
|
|
124
|
+
const rowRun = runByEntry.get(row);
|
|
125
|
+
if (metric === 'strictPassAt1') {
|
|
126
|
+
// Strict ranking counts errors and timeouts, so the verdict must use
|
|
127
|
+
// the same denominator rather than survivor-only paired task success.
|
|
128
|
+
const counts = strictPairCounts(leaderRun, rowRun);
|
|
129
|
+
const test = signTest(counts.wins, counts.losses);
|
|
130
|
+
const adjustedP = Math.min(1, test.pValue * family);
|
|
131
|
+
const detectable = signTestPower(counts.wins + counts.losses, family).detectable;
|
|
132
|
+
row.significance = {
|
|
133
|
+
adjustedP,
|
|
134
|
+
detectable,
|
|
135
|
+
worse: counts.losses > counts.wins,
|
|
136
|
+
primaryMetric: 'strict pass@1 (task)',
|
|
137
|
+
// Unequal trial counts can tie on rate while the extra trials are
|
|
138
|
+
// wins, so direction must be checked explicitly.
|
|
139
|
+
verdict: !detectable ? 'underpowered'
|
|
140
|
+
: counts.losses > counts.wins && adjustedP <= 0.05 ? 'significantly-behind'
|
|
141
|
+
: counts.losses > counts.wins ? 'behind-not-significant' : 'ahead-or-tied',
|
|
142
|
+
};
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const paired = pairedCompare(leaderRun, rowRun);
|
|
146
|
+
if (paired === null) {
|
|
147
|
+
row.significance = {
|
|
148
|
+
adjustedP: 1, detectable: false, worse: false, primaryMetric: null,
|
|
149
|
+
verdict: 'unpaired',
|
|
150
|
+
};
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const worse = paired.losses > paired.wins;
|
|
154
|
+
// The verdict concerns the one primary metric only, so the board's
|
|
155
|
+
// comparison family is the only correction that applies here. Comparing
|
|
156
|
+
// every metric (as `paired.correction` does) would double-count.
|
|
157
|
+
const adjustedP = Math.min(1, paired.test.pValue * family);
|
|
158
|
+
const detectable = signTestPower(paired.losses + paired.wins, family, paired.correction.alpha).detectable;
|
|
159
|
+
row.significance = {
|
|
160
|
+
adjustedP,
|
|
161
|
+
detectable,
|
|
162
|
+
worse,
|
|
163
|
+
primaryMetric: paired.primaryMetric,
|
|
164
|
+
verdict: !detectable ? 'underpowered'
|
|
165
|
+
: worse && adjustedP <= paired.correction.alpha ? 'significantly-behind'
|
|
166
|
+
: worse ? 'behind-not-significant' : 'ahead-or-tied',
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return rows;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Render leaderboard rows as machine-readable JSON.
|
|
174
|
+
* @param rows - rows from {@link buildLeaderboard}.
|
|
175
|
+
* @returns a JSON string ending in a newline.
|
|
176
|
+
*/
|
|
177
|
+
export function renderLeaderboardJson(rows, metric = 'taskSuccess') {
|
|
178
|
+
return `${JSON.stringify({ rankedBy: metric, rows })}\n`;
|
|
179
|
+
}
|
|
180
|
+
/** Format a rate or a dash for markdown. */
|
|
181
|
+
function rate(value) {
|
|
182
|
+
return value === null ? '–' : `${(value * 100).toFixed(1)}%`;
|
|
183
|
+
}
|
|
184
|
+
/** Format a signed percentage-point gap from the leader. */
|
|
185
|
+
function gap(value, rank) {
|
|
186
|
+
if (value === null)
|
|
187
|
+
return '–';
|
|
188
|
+
if (rank === 1)
|
|
189
|
+
return 'leader';
|
|
190
|
+
return `-${(value * 100).toFixed(1)}pp`;
|
|
191
|
+
}
|
|
192
|
+
/** Format the paired verdict against the leader. */
|
|
193
|
+
export function formatLeaderboardSignificance(value) {
|
|
194
|
+
if (value === null)
|
|
195
|
+
return 'leader';
|
|
196
|
+
if (value.verdict === 'unpaired')
|
|
197
|
+
return 'unpaired';
|
|
198
|
+
return `${value.verdict} (p=${formatPValue(value.adjustedP)}, ${value.primaryMetric})`;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Render a leaderboard as markdown.
|
|
202
|
+
* @param rows - rows from {@link buildLeaderboard}.
|
|
203
|
+
* @returns markdown ending in a newline.
|
|
204
|
+
*/
|
|
205
|
+
export function renderLeaderboard(rows, metric = 'taskSuccess') {
|
|
206
|
+
const lines = [
|
|
207
|
+
'# Leaderboard',
|
|
208
|
+
'',
|
|
209
|
+
metric === 'strictPassAt1'
|
|
210
|
+
? '- ranked by strict pass@1 (errors and timeouts stay in the denominator); ties share a rank'
|
|
211
|
+
: '- ranked by pooled task success; ties share a rank',
|
|
212
|
+
'- ranks are a screening view; `vs leader` applies a Bonferroni-corrected paired sign test',
|
|
213
|
+
'',
|
|
214
|
+
'| rank | run | completed | task | strict pass@1 | tool | judge | cost/trial | latency/trial | Δ best | vs leader |',
|
|
215
|
+
'|---|---|---|---|---|---|---|---|---|---|---|',
|
|
216
|
+
];
|
|
217
|
+
for (const row of rows) {
|
|
218
|
+
const label = row.label.replace(/[\r\n|]/gu, ' ');
|
|
219
|
+
lines.push(`| ${row.rank} | ${label} | ${row.completed}/${row.total} | ${rate(row.taskSuccess)} | ${rate(row.strictPassAt1)} | ${rate(row.toolSelection)} | ${rate(row.judgeScore)} | ${row.costUsd === null ? '–' : `$${row.costUsd.toFixed(6)}`} | ${row.latencyMs === null ? '–' : `${row.latencyMs.toFixed(1)} ms`} | ${gap(row.gapFromBest, row.rank)} | ${formatLeaderboardSignificance(row.significance)} |`);
|
|
220
|
+
}
|
|
221
|
+
return `${lines.join('\n')}\n`;
|
|
222
|
+
}
|
package/lib/precision.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
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
|
+
import { pairedDelta } from "./stats.js";
|
|
13
|
+
/** Interpolated percentile of a sample, sorting a copy so the input stays intact. */
|
|
14
|
+
function percentile(values, q) {
|
|
15
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
16
|
+
const position = (sorted.length - 1) * q;
|
|
17
|
+
const low = Math.floor(position);
|
|
18
|
+
const weight = position - low;
|
|
19
|
+
return sorted[low] * (1 - weight) + sorted[Math.ceil(position)] * weight;
|
|
20
|
+
}
|
|
21
|
+
/** Bootstrap a rate interval from the trials that actually carry a grade. */
|
|
22
|
+
function rateInterval(results, pick, options) {
|
|
23
|
+
const observed = results.map(pick).filter((value) => typeof value === 'boolean');
|
|
24
|
+
if (observed.length === 0)
|
|
25
|
+
return null;
|
|
26
|
+
const bootstrap = pairedDelta(observed.map(value => value ? 1 : 0), options);
|
|
27
|
+
return { trials: observed.length, rate: bootstrap.mean, lower: bootstrap.lower, upper: bootstrap.upper };
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Derive single-run precision from a persisted run.
|
|
31
|
+
* @param run - the run to summarize.
|
|
32
|
+
* @param options - bootstrap overrides; the run's seed is used by default.
|
|
33
|
+
* @returns the precision figures, all null when no trial carries data.
|
|
34
|
+
*/
|
|
35
|
+
export function computePrecision(run, options = {}) {
|
|
36
|
+
const completed = run.cases.filter(result => result.status === 'completed');
|
|
37
|
+
const bootstrap = { ...options, seed: options.seed ?? run.seed };
|
|
38
|
+
const latencies = completed
|
|
39
|
+
.map(result => result.metrics?.latencyMs)
|
|
40
|
+
.filter((value) => typeof value === 'number');
|
|
41
|
+
return {
|
|
42
|
+
task: rateInterval(completed, result => result.grade?.taskSuccess, bootstrap),
|
|
43
|
+
toolSelection: rateInterval(completed, result => result.grade?.toolSelectionAccuracy, bootstrap),
|
|
44
|
+
strictPassAt1: completed.some(result => typeof result.grade?.taskSuccess === 'boolean')
|
|
45
|
+
? rateInterval(run.cases, result => result.status === 'completed' && result.grade?.taskSuccess === true, bootstrap)
|
|
46
|
+
: null,
|
|
47
|
+
latencyP50: latencies.length === 0 ? null : percentile(latencies, 0.5),
|
|
48
|
+
latencyP95: latencies.length === 0 ? null : percentile(latencies, 0.95),
|
|
49
|
+
};
|
|
50
|
+
}
|
package/lib/rejudge.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
import { realpath } from 'node:fs/promises';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { extname, isAbsolute, parse, relative, resolve, sep } from 'node:path';
|
|
15
|
+
import { tryJudgeTrial } from "./judge.js";
|
|
16
|
+
import { aggregateGrading } from "./runner.js";
|
|
17
|
+
import { loadTrace, mergeTraces, traceDigest } from "./trace.js";
|
|
18
|
+
/**
|
|
19
|
+
* Re-judge every completed trial of a persisted run.
|
|
20
|
+
* @param run - a validated run report carrying `caseInputs`.
|
|
21
|
+
* @param judgeChat - the injected chat seam for the judge model.
|
|
22
|
+
* @param judgeOverride - judge config to use instead of the one stored in the run.
|
|
23
|
+
* @returns a new run with fresh verdicts and a re-aggregated grading summary.
|
|
24
|
+
* @throws when the report lacks the data a judge prompt needs.
|
|
25
|
+
*/
|
|
26
|
+
export async function rejudgeRun(run, judgeChat, judgeOverride) {
|
|
27
|
+
const judge = judgeOverride ?? run.judge;
|
|
28
|
+
if (judge === undefined) {
|
|
29
|
+
throw new Error('rejudge: no judge configuration; pass --judge-model to supply one');
|
|
30
|
+
}
|
|
31
|
+
if (run.caseInputs === undefined) {
|
|
32
|
+
throw new Error('rejudge: the run has no caseInputs; re-run with a version that persists prompts');
|
|
33
|
+
}
|
|
34
|
+
const inputs = new Map(run.caseInputs.map(input => [input.caseId, input]));
|
|
35
|
+
// A report is data, not code: a hand-edited tracePaths entry must not be able
|
|
36
|
+
// to make the judge read and ship an arbitrary local file to an LLM.
|
|
37
|
+
const root = await realpath(resolve(run.tempRoot));
|
|
38
|
+
// A hand-edited report must not promote a drive root or home directory to
|
|
39
|
+
// the "allowed" root; that would make every local log reachable by design.
|
|
40
|
+
if (root === parse(root).root || root === resolve(homedir())
|
|
41
|
+
|| relative(parse(root).root, root).split(sep).filter(Boolean).length === 0) {
|
|
42
|
+
throw new Error('rejudge: tempRoot must be a dedicated run directory');
|
|
43
|
+
}
|
|
44
|
+
const insideRoot = async (path) => {
|
|
45
|
+
if (!isAbsolute(path))
|
|
46
|
+
return false;
|
|
47
|
+
// realpath resolves `..` and symlinks before comparing, so neither a
|
|
48
|
+
// traversal prefix nor a symlink to another run's log escapes the check.
|
|
49
|
+
let resolved;
|
|
50
|
+
try {
|
|
51
|
+
resolved = await realpath(path);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
const rel = relative(root, resolved);
|
|
57
|
+
return extname(resolved) === '.jsonl'
|
|
58
|
+
&& rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
|
|
59
|
+
};
|
|
60
|
+
const cases = [];
|
|
61
|
+
for (const result of run.cases) {
|
|
62
|
+
if (result.status !== 'completed') {
|
|
63
|
+
cases.push(result);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const input = inputs.get(result.caseId);
|
|
67
|
+
if (input === undefined) {
|
|
68
|
+
throw new Error(`rejudge: no case input for "${result.caseId}"`);
|
|
69
|
+
}
|
|
70
|
+
const paths = result.tracePaths ?? (result.tracePath === undefined ? [] : [result.tracePath]);
|
|
71
|
+
if (paths.length === 0) {
|
|
72
|
+
throw new Error(`rejudge: trial ${result.caseId}#${result.trial} has no harvested trace`);
|
|
73
|
+
}
|
|
74
|
+
for (const path of paths) {
|
|
75
|
+
if (!await insideRoot(path)) {
|
|
76
|
+
throw new Error(`rejudge: trace path "${path}" is outside the run's tempRoot or not a .jsonl log`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const loaded = await Promise.all(paths.map(async (path) => ({ path, trace: await loadTrace(path) })));
|
|
80
|
+
loaded.sort((a, b) => a.trace.createdAt - b.trace.createdAt);
|
|
81
|
+
const merged = mergeTraces(loaded.map(entry => entry.trace));
|
|
82
|
+
if (result.traceSha256 !== undefined && traceDigest(merged) !== result.traceSha256) {
|
|
83
|
+
throw new Error(`rejudge: trace for ${result.caseId}#${result.trial} differs from the recorded digest`);
|
|
84
|
+
}
|
|
85
|
+
const caseValue = {
|
|
86
|
+
id: input.caseId,
|
|
87
|
+
prompt: input.prompt,
|
|
88
|
+
...(input.answer !== undefined ? { expected: { answer: input.answer } } : {}),
|
|
89
|
+
};
|
|
90
|
+
const verdict = await tryJudgeTrial(caseValue, merged, judge, judgeChat);
|
|
91
|
+
const previous = result.judge;
|
|
92
|
+
// A flaky judge must not erase an already usable score. Keep the old one,
|
|
93
|
+
// but leave the failure visible next to it in the report.
|
|
94
|
+
const keepPrevious = verdict.judgeError !== undefined && previous?.finalAnswerScore != null;
|
|
95
|
+
cases.push({
|
|
96
|
+
...result,
|
|
97
|
+
judge: keepPrevious
|
|
98
|
+
? { ...previous, judgeError: `${verdict.judgeError} (previous verdict kept)` }
|
|
99
|
+
: verdict,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
// Grading depends on grade/judge fields, not on metrics, so do not require a
|
|
103
|
+
// metric fold here — imported or hand-edited reports may legitimately omit it.
|
|
104
|
+
const completed = cases.filter(result => result.status === 'completed');
|
|
105
|
+
// Record the judge actually used, including a CLI override.
|
|
106
|
+
return { ...run, judge, cases, grading: aggregateGrading(completed) };
|
|
107
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
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
|
+
/** Read the chosen grade, ignoring trials that were not graded on it. */
|
|
13
|
+
function readGrade(result, dimension) {
|
|
14
|
+
const grade = result.grade;
|
|
15
|
+
if (grade === undefined)
|
|
16
|
+
return null;
|
|
17
|
+
return dimension === 'task' ? grade.taskSuccess : grade.toolSelectionAccuracy;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Count every trial in a run, including those that never produced a grade.
|
|
21
|
+
* A rate computed only over completed trials is biased whenever some trials
|
|
22
|
+
* error or time out, so the denominator must be visible alongside it.
|
|
23
|
+
* @param run - the run to account for.
|
|
24
|
+
* @returns counts whose `unscored` field is the trials missing from all rates.
|
|
25
|
+
*/
|
|
26
|
+
export function computeCoverage(run) {
|
|
27
|
+
let completed = 0;
|
|
28
|
+
let errors = 0;
|
|
29
|
+
let timeouts = 0;
|
|
30
|
+
let unscored = 0;
|
|
31
|
+
for (const result of run.cases) {
|
|
32
|
+
if (result.status === 'completed')
|
|
33
|
+
completed += 1;
|
|
34
|
+
else
|
|
35
|
+
errors += 1;
|
|
36
|
+
if (result.timedOut)
|
|
37
|
+
timeouts += 1;
|
|
38
|
+
// A completed trial without a task grade is just as absent from quality
|
|
39
|
+
// rates as an error; keep this identical to computeReliability().unscored.
|
|
40
|
+
if (result.status !== 'completed' || typeof result.grade?.taskSuccess !== 'boolean')
|
|
41
|
+
unscored += 1;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
total: run.cases.length,
|
|
45
|
+
completed,
|
|
46
|
+
errors,
|
|
47
|
+
timeouts,
|
|
48
|
+
unscored,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Fold a run's trials into reliability metrics for one grading dimension.
|
|
53
|
+
*
|
|
54
|
+
* Every trial for a case contributes to `total`, even an error or timeout.
|
|
55
|
+
* `passAt1` keeps its historical graded-only denominator; `strictPassAt1`
|
|
56
|
+
* divides by all trials so a model that times out on hard cases cannot look
|
|
57
|
+
* better than one that finishes and fails.
|
|
58
|
+
* @param run - the run to summarize.
|
|
59
|
+
* @param dimension - `task` (default) or `tool-selection` grading.
|
|
60
|
+
* @returns the summary, or null when no trial carried that grade.
|
|
61
|
+
*/
|
|
62
|
+
export function computeReliability(run, dimension = 'task') {
|
|
63
|
+
const grouped = new Map();
|
|
64
|
+
for (const result of run.cases) {
|
|
65
|
+
const group = grouped.get(result.caseId) ?? { total: 0, graded: 0, passes: 0 };
|
|
66
|
+
group.total += 1;
|
|
67
|
+
if (result.status === 'completed') {
|
|
68
|
+
const passed = readGrade(result, dimension);
|
|
69
|
+
if (passed !== null) {
|
|
70
|
+
group.graded += 1;
|
|
71
|
+
if (passed)
|
|
72
|
+
group.passes += 1;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
grouped.set(result.caseId, group);
|
|
76
|
+
}
|
|
77
|
+
const all = [...grouped.values()];
|
|
78
|
+
const cases = [...grouped].filter(([, group]) => group.graded > 0).map(([caseId, group]) => ({
|
|
79
|
+
caseId,
|
|
80
|
+
trials: group.graded,
|
|
81
|
+
total: group.total,
|
|
82
|
+
passes: group.passes,
|
|
83
|
+
rate: group.passes / group.graded,
|
|
84
|
+
}));
|
|
85
|
+
if (cases.length === 0)
|
|
86
|
+
return null;
|
|
87
|
+
const trials = cases.reduce((sum, item) => sum + item.trials, 0);
|
|
88
|
+
const passes = cases.reduce((sum, item) => sum + item.passes, 0);
|
|
89
|
+
const total = all.reduce((sum, group) => sum + group.total, 0);
|
|
90
|
+
const graded = all.reduce((sum, group) => sum + group.graded, 0);
|
|
91
|
+
return {
|
|
92
|
+
dimension,
|
|
93
|
+
k: run.trials,
|
|
94
|
+
cases: cases.length,
|
|
95
|
+
total,
|
|
96
|
+
passAt1: passes / trials,
|
|
97
|
+
strictPassAt1: passes / total,
|
|
98
|
+
unscored: total - graded,
|
|
99
|
+
passAtK: cases.filter(item => item.passes > 0).length / cases.length,
|
|
100
|
+
passAllK: cases.filter(item => item.passes === item.trials).length / cases.length,
|
|
101
|
+
flaky: cases.filter(item => item.passes > 0 && item.passes < item.trials),
|
|
102
|
+
// Case ids are unique map keys, so the tie-break never compares equals.
|
|
103
|
+
hardest: [...cases]
|
|
104
|
+
.sort((a, b) => a.rate - b.rate || (a.caseId < b.caseId ? -1 : 1))
|
|
105
|
+
.slice(0, 3),
|
|
106
|
+
};
|
|
107
|
+
}
|