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/runner.js
CHANGED
|
@@ -16,7 +16,12 @@ import { spawn } from 'node:child_process';
|
|
|
16
16
|
import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
|
|
17
17
|
import { tmpdir } from 'node:os';
|
|
18
18
|
import { join } from 'node:path';
|
|
19
|
-
import {
|
|
19
|
+
import { splitArgv } from "./argv.js";
|
|
20
|
+
import { hashBenchmarkOverrides } from "./digest.js";
|
|
21
|
+
import { safeRegexTest, safeRegexTestAny } from "./safe-regex.js";
|
|
22
|
+
import { finalAnswerOf, tryJudgeTrial } from "./judge.js";
|
|
23
|
+
import { traceDigest } from "./trace.js";
|
|
24
|
+
import { caseSegment } from "./segments.js";
|
|
20
25
|
import { aggregateMetrics, computeMetrics } from "./metrics.js";
|
|
21
26
|
import { findSessionLogs, loadTrace, mergeTraces } from "./trace.js";
|
|
22
27
|
/** Cap per-stream child output so a runaway trial cannot exhaust memory. */
|
|
@@ -32,11 +37,6 @@ function message(error) {
|
|
|
32
37
|
/* v8 ignore next 3 -- every call site passes a node:fs or spawn Error; a non-Error rejection is impossible through the public API. */
|
|
33
38
|
return error instanceof Error ? error.message : String(error);
|
|
34
39
|
}
|
|
35
|
-
/** Reduce a case id to one safe temp-directory segment. */
|
|
36
|
-
function sanitizeSegment(value) {
|
|
37
|
-
const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '');
|
|
38
|
-
return safe === '' ? 'case' : safe;
|
|
39
|
-
}
|
|
40
40
|
/**
|
|
41
41
|
* Build the per-trial overlay: plain-JSONL persistence, non-interactive
|
|
42
42
|
* permissions, and the keyless replay plugin when recorded logs exist.
|
|
@@ -63,9 +63,39 @@ function evalOverlay(replay) {
|
|
|
63
63
|
}
|
|
64
64
|
return `${lines.join('\n')}\n`;
|
|
65
65
|
}
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Match every configured tool expectation against the recorded call names.
|
|
68
|
+
* All configured constraints must hold; no tool expectation means "ungraded".
|
|
69
|
+
* @param expected - the case's scripted expectations.
|
|
70
|
+
* @param names - tool-call names recorded in the harvested trace.
|
|
71
|
+
* @returns the boolean match, or null when no tool expectation is configured.
|
|
72
|
+
*/
|
|
73
|
+
async function toolSelectionOf(expected, names) {
|
|
74
|
+
const configured = expected.tool !== undefined || expected.tools !== undefined
|
|
75
|
+
|| expected.toolAnyOf !== undefined || expected.toolRegex !== undefined
|
|
76
|
+
|| expected.toolNot !== undefined;
|
|
77
|
+
if (!configured)
|
|
78
|
+
return null;
|
|
79
|
+
const includes = (needle) => names.some(name => name.includes(needle));
|
|
80
|
+
if (expected.tool !== undefined && !includes(expected.tool))
|
|
81
|
+
return false;
|
|
82
|
+
if (expected.tools !== undefined && !expected.tools.every(includes))
|
|
83
|
+
return false;
|
|
84
|
+
if (expected.toolAnyOf !== undefined && !expected.toolAnyOf.some(includes))
|
|
85
|
+
return false;
|
|
86
|
+
if (expected.toolRegex !== undefined) {
|
|
87
|
+
/* v8 ignore next 4 -- safeRegexTestAny degrades each invalid input internally. */
|
|
88
|
+
try {
|
|
89
|
+
if (!await safeRegexTestAny(expected.toolRegex, names))
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (expected.toolNot !== undefined && expected.toolNot.some(includes))
|
|
97
|
+
return false;
|
|
98
|
+
return true;
|
|
69
99
|
}
|
|
70
100
|
/**
|
|
71
101
|
* Grade one trial against its expectations: the expected tool is matched
|
|
@@ -82,20 +112,39 @@ async function gradeTrial(caseValue, trace, workspace, timeoutMs) {
|
|
|
82
112
|
const expected = caseValue.expected;
|
|
83
113
|
if (expected === undefined)
|
|
84
114
|
return { taskSuccess: null, toolSelectionAccuracy: null };
|
|
85
|
-
const
|
|
86
|
-
const toolSelectionAccuracy =
|
|
87
|
-
? null
|
|
88
|
-
: trace.events.some(event => event.type === 'tool/call' && event.data.name.includes(expectedTool));
|
|
115
|
+
const names = trace.events.flatMap(event => event.type === 'tool/call' ? [event.data.name] : []);
|
|
116
|
+
const toolSelectionAccuracy = await toolSelectionOf(expected, names);
|
|
89
117
|
let taskSuccess = null;
|
|
90
|
-
|
|
118
|
+
const shell = expected.checkShell !== undefined;
|
|
119
|
+
const checkArgv = expected.checkArgv !== undefined
|
|
120
|
+
? [...expected.checkArgv]
|
|
121
|
+
: shell ? [expected.checkShell] : undefined;
|
|
122
|
+
if (checkArgv !== undefined || expected.check !== undefined) {
|
|
91
123
|
try {
|
|
92
|
-
const
|
|
124
|
+
const command = checkArgv ?? splitArgv(expected.check);
|
|
125
|
+
const outcome = await runCommand(command, [], workspace, { ...process.env }, timeoutMs, {
|
|
126
|
+
shell,
|
|
127
|
+
// A shell check can spawn grandchildren; kill the whole group on timeouts.
|
|
128
|
+
detached: true,
|
|
129
|
+
});
|
|
93
130
|
taskSuccess = !outcome.timedOut && outcome.exitCode === 0;
|
|
94
131
|
}
|
|
95
132
|
catch {
|
|
96
133
|
taskSuccess = false;
|
|
97
134
|
}
|
|
98
135
|
}
|
|
136
|
+
else if (expected.answerRegex !== undefined) {
|
|
137
|
+
// Deterministic final-answer grading: no command, no LLM needed.
|
|
138
|
+
// The schema validates at load; hand-built benchmarks degrade to failure.
|
|
139
|
+
try {
|
|
140
|
+
// The pattern runs in a time-boxed worker: a catastrophic benchmark regex
|
|
141
|
+
// must not hang the evaluator on agent-controlled final-answer text.
|
|
142
|
+
taskSuccess = await safeRegexTest(expected.answerRegex, finalAnswerOf(trace).slice(0, 4096));
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
taskSuccess = false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
99
148
|
return { taskSuccess, toolSelectionAccuracy };
|
|
100
149
|
}
|
|
101
150
|
/** Pool one nullable boolean across graded trials into a rate, or null. */
|
|
@@ -106,7 +155,7 @@ function pooledRate(items, select) {
|
|
|
106
155
|
return values.length === 0 ? null : values.filter(value => value).length / values.length;
|
|
107
156
|
}
|
|
108
157
|
/** Reduce completed trials' grades into pooled run-level rates. */
|
|
109
|
-
function
|
|
158
|
+
export function aggregateGrading(results) {
|
|
110
159
|
const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null);
|
|
111
160
|
const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null);
|
|
112
161
|
const finalScores = results
|
|
@@ -121,10 +170,11 @@ function gradingOf(results) {
|
|
|
121
170
|
const hallucinationRate = hallucinated.length === 0
|
|
122
171
|
? null
|
|
123
172
|
: hallucinated.filter(value => value).length / hallucinated.length;
|
|
173
|
+
const judgeFailures = results.filter(result => result.judge?.judgeError !== undefined).length;
|
|
124
174
|
return taskSuccessRate === null && toolSelectionAccuracyRate === null
|
|
125
|
-
&& finalAnswerScore === null && hallucinationRate === null
|
|
175
|
+
&& finalAnswerScore === null && hallucinationRate === null && judgeFailures === 0
|
|
126
176
|
? null
|
|
127
|
-
: { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate };
|
|
177
|
+
: { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate, judgeFailures };
|
|
128
178
|
}
|
|
129
179
|
/**
|
|
130
180
|
* Spawn one command and collect its output, enforcing the timeout with a
|
|
@@ -136,19 +186,22 @@ function gradingOf(results) {
|
|
|
136
186
|
* @param cwd - the child's working directory.
|
|
137
187
|
* @param env - the child's environment.
|
|
138
188
|
* @param timeoutMs - kill the child after this many milliseconds.
|
|
189
|
+
* @param options - opt-in shell interpretation and detached process-group kill.
|
|
139
190
|
* @returns the orthogonal outcome facts.
|
|
140
191
|
*/
|
|
141
|
-
function runCommand(command, args, cwd, env, timeoutMs) {
|
|
192
|
+
function runCommand(command, args, cwd, env, timeoutMs, options = {}) {
|
|
142
193
|
const executable = command[0];
|
|
143
194
|
if (executable === undefined) {
|
|
144
195
|
return Promise.reject(new Error('eval: dsh command must not be empty'));
|
|
145
196
|
}
|
|
146
197
|
return new Promise((resolveOutcome, reject) => {
|
|
147
|
-
const child = spawn(executable, [...command.slice(1), ...args], {
|
|
198
|
+
const child = spawn(executable, options.shell === true ? [] : [...command.slice(1), ...args], {
|
|
148
199
|
cwd,
|
|
149
200
|
env,
|
|
150
201
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
151
202
|
windowsHide: true,
|
|
203
|
+
shell: options.shell === true,
|
|
204
|
+
detached: options.detached === true,
|
|
152
205
|
});
|
|
153
206
|
let stdout = '';
|
|
154
207
|
let stderr = '';
|
|
@@ -159,15 +212,62 @@ function runCommand(command, args, cwd, env, timeoutMs) {
|
|
|
159
212
|
: current + chunk.toString('utf8').slice(0, MAX_OUTPUT_BYTES - current.length));
|
|
160
213
|
child.stdout.on('data', (chunk) => { stdout = cap(stdout, chunk); });
|
|
161
214
|
child.stderr.on('data', (chunk) => { stderr = cap(stderr, chunk); });
|
|
215
|
+
let escalation;
|
|
162
216
|
const timer = setTimeout(() => {
|
|
163
|
-
/* v8 ignore next
|
|
217
|
+
/* v8 ignore next 2 -- close clears the timer; only a same-tick close/kill race reaches here. */
|
|
164
218
|
if (settled)
|
|
165
219
|
return;
|
|
220
|
+
// `close` arrives after stdio drains, so a child that has already exited
|
|
221
|
+
// but is still draining its pipes must not be reported as timed out.
|
|
222
|
+
/* v8 ignore next 2 -- exit-before-close is a narrow event-loop window no fixture can force deterministically. */
|
|
223
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
224
|
+
return;
|
|
225
|
+
const terminate = (signal) => {
|
|
226
|
+
/* v8 ignore next 5 -- POSIX process-group kill; on Windows child.kill below kills the detached group. */
|
|
227
|
+
if (options.detached === true && process.platform !== 'win32' && child.pid !== undefined) {
|
|
228
|
+
try {
|
|
229
|
+
process.kill(-child.pid, signal);
|
|
230
|
+
}
|
|
231
|
+
catch { /* the group is already gone */ }
|
|
232
|
+
}
|
|
233
|
+
child.kill(signal);
|
|
234
|
+
};
|
|
166
235
|
timedOut = true;
|
|
167
|
-
|
|
236
|
+
terminate('SIGTERM');
|
|
237
|
+
/* v8 ignore next 5 -- escalation needs a child that ignores SIGTERM; the timeout fixture exits on the first signal. */
|
|
238
|
+
escalation = setTimeout(() => {
|
|
239
|
+
if (!settled && child.exitCode === null && child.signalCode === null)
|
|
240
|
+
terminate('SIGKILL');
|
|
241
|
+
}, 1000);
|
|
242
|
+
escalation.unref();
|
|
168
243
|
}, timeoutMs);
|
|
169
|
-
|
|
244
|
+
let drainGuard;
|
|
245
|
+
const clearTimers = () => {
|
|
170
246
|
clearTimeout(timer);
|
|
247
|
+
if (escalation !== undefined)
|
|
248
|
+
clearTimeout(escalation);
|
|
249
|
+
if (drainGuard !== undefined)
|
|
250
|
+
clearTimeout(drainGuard);
|
|
251
|
+
};
|
|
252
|
+
child.on('exit', (code) => {
|
|
253
|
+
// A detached grandchild can inherit the pipes and keep `close` pending
|
|
254
|
+
// long after the direct child exited. Resolve from `exit` after a short
|
|
255
|
+
// drain grace period so a check cannot hang the whole trial.
|
|
256
|
+
/* v8 ignore next 10 -- Windows closes inherited pipes eagerly; only POSIX grandchildren can keep them open. */
|
|
257
|
+
drainGuard = setTimeout(() => {
|
|
258
|
+
if (settled)
|
|
259
|
+
return;
|
|
260
|
+
settled = true;
|
|
261
|
+
clearTimers();
|
|
262
|
+
// A surviving grandchild owns these pipes; releasing them lets the CLI exit.
|
|
263
|
+
child.stdout.destroy();
|
|
264
|
+
child.stderr.destroy();
|
|
265
|
+
resolveOutcome({ exitCode: code, timedOut, stdout, stderr });
|
|
266
|
+
}, 200);
|
|
267
|
+
drainGuard.unref();
|
|
268
|
+
});
|
|
269
|
+
child.on('error', (error) => {
|
|
270
|
+
clearTimers();
|
|
171
271
|
/* v8 ignore next 3 -- spawn emits one error before close; the guard covers only an impossible duplicate error event. */
|
|
172
272
|
if (settled)
|
|
173
273
|
return;
|
|
@@ -175,7 +275,7 @@ function runCommand(command, args, cwd, env, timeoutMs) {
|
|
|
175
275
|
reject(error);
|
|
176
276
|
});
|
|
177
277
|
child.on('close', (code) => {
|
|
178
|
-
|
|
278
|
+
clearTimers();
|
|
179
279
|
if (settled)
|
|
180
280
|
return;
|
|
181
281
|
settled = true;
|
|
@@ -192,7 +292,8 @@ function runCommand(command, args, cwd, env, timeoutMs) {
|
|
|
192
292
|
* @returns the trial result; a failed subprocess with no log is an `error` trial.
|
|
193
293
|
*/
|
|
194
294
|
async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
|
|
195
|
-
const
|
|
295
|
+
const timeoutMs = caseValue.timeoutMs ?? benchmark.timeoutMs;
|
|
296
|
+
const trialDir = join(root, `${caseSegment(caseValue.id)}-${trial}`);
|
|
196
297
|
const workspace = join(trialDir, 'workspace');
|
|
197
298
|
const dshHome = join(trialDir, 'dsh-home');
|
|
198
299
|
await mkdir(workspace, { recursive: true });
|
|
@@ -201,7 +302,7 @@ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
|
|
|
201
302
|
await cp(caseValue.workspace, workspace, { recursive: true });
|
|
202
303
|
const replayFixture = benchmark.replay === undefined
|
|
203
304
|
? undefined
|
|
204
|
-
: join(benchmark.replay.dir, `${
|
|
305
|
+
: join(benchmark.replay.dir, `${caseSegment(caseValue.id)}-${trial}`);
|
|
205
306
|
let replay;
|
|
206
307
|
if (replayFixture !== undefined) {
|
|
207
308
|
const logs = await findSessionLogs(replayFixture);
|
|
@@ -222,7 +323,14 @@ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
|
|
|
222
323
|
await writeFile(overlayPath, evalOverlay(replay), 'utf8');
|
|
223
324
|
let outcome;
|
|
224
325
|
try {
|
|
225
|
-
outcome = await runCommand(benchmark.command, ['--profile', benchmark.profile, '--patch', overlayPath, caseValue.prompt], workspace, {
|
|
326
|
+
outcome = await runCommand(benchmark.command, ['--profile', benchmark.profile, '--patch', overlayPath, caseValue.prompt], workspace, {
|
|
327
|
+
...process.env,
|
|
328
|
+
DSH_HOME: dshHome,
|
|
329
|
+
// Trial n gets a deterministic, distinct seed derived from the run's
|
|
330
|
+
// base seed. An env var is ignored by harnesses that do not read it,
|
|
331
|
+
// unlike an unknown CLI flag which would break them.
|
|
332
|
+
DSH_EVAL_SEED: String(benchmark.seed + trial - 1),
|
|
333
|
+
}, timeoutMs);
|
|
226
334
|
}
|
|
227
335
|
catch (error) {
|
|
228
336
|
return {
|
|
@@ -255,7 +363,7 @@ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
|
|
|
255
363
|
const trace = mergeTraces(loaded.map(entry => entry.trace));
|
|
256
364
|
const pricing = benchmark.pricing?.[benchmark.model];
|
|
257
365
|
const metrics = computeMetrics(trace.events, pricing);
|
|
258
|
-
const grade = await gradeTrial(caseValue, trace, workspace,
|
|
366
|
+
const grade = await gradeTrial(caseValue, trace, workspace, timeoutMs);
|
|
259
367
|
const judge = benchmark.judge === undefined || judgeChat === undefined
|
|
260
368
|
? undefined
|
|
261
369
|
: await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat);
|
|
@@ -265,6 +373,7 @@ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
|
|
|
265
373
|
status: 'completed',
|
|
266
374
|
tracePath: primaryPath,
|
|
267
375
|
tracePaths: loaded.map(entry => entry.path),
|
|
376
|
+
traceSha256: traceDigest(trace),
|
|
268
377
|
exitCode: outcome.exitCode,
|
|
269
378
|
timedOut: outcome.timedOut,
|
|
270
379
|
metrics,
|
|
@@ -305,14 +414,37 @@ export async function runBenchmark(benchmark, options = {}) {
|
|
|
305
414
|
if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
|
|
306
415
|
throw new Error('eval: judge and replay cannot be combined in one run');
|
|
307
416
|
}
|
|
308
|
-
|
|
417
|
+
// Validate extension-point overrides as strictly as the YAML schema does.
|
|
418
|
+
if (options.seed !== undefined && !Number.isSafeInteger(options.seed)) {
|
|
419
|
+
throw new Error('eval: seed must be a safe integer');
|
|
420
|
+
}
|
|
309
421
|
const trials = options.trials ?? benchmark.trials;
|
|
422
|
+
const concurrency = options.concurrency ?? benchmark.concurrency;
|
|
423
|
+
// `runBenchmark` is a documented extension point: runtime overrides need the
|
|
424
|
+
// same positive-integer guarantee the YAML schema gives a loaded document.
|
|
425
|
+
if (!Number.isSafeInteger(trials) || trials < 1) {
|
|
426
|
+
throw new Error('eval: trials must be a positive integer');
|
|
427
|
+
}
|
|
428
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
|
|
429
|
+
throw new Error('eval: concurrency must be a positive integer');
|
|
430
|
+
}
|
|
431
|
+
// Created only after validation, so a bad override leaves no temp directory.
|
|
432
|
+
const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'));
|
|
310
433
|
const effective = {
|
|
311
434
|
...benchmark,
|
|
312
435
|
...(options.profile !== undefined ? { profile: options.profile } : {}),
|
|
313
436
|
...(options.command !== undefined ? { command: options.command } : {}),
|
|
314
|
-
...(options.
|
|
437
|
+
...(options.seed === undefined ? {} : { seed: options.seed }),
|
|
438
|
+
concurrency,
|
|
439
|
+
};
|
|
440
|
+
const overrides = {
|
|
441
|
+
...(options.trials === undefined ? {} : { trials }),
|
|
442
|
+
...(options.concurrency === undefined ? {} : { concurrency }),
|
|
443
|
+
...(options.seed === undefined ? {} : { seed: options.seed }),
|
|
444
|
+
...(options.profile === undefined ? {} : { profile: options.profile }),
|
|
445
|
+
...(options.command === undefined ? {} : { dshCommand: [...options.command] }),
|
|
315
446
|
};
|
|
447
|
+
const hasOverrides = Object.keys(overrides).length > 0;
|
|
316
448
|
const tasks = [];
|
|
317
449
|
for (const caseValue of effective.cases) {
|
|
318
450
|
for (let trial = 1; trial <= trials; trial++)
|
|
@@ -321,17 +453,30 @@ export async function runBenchmark(benchmark, options = {}) {
|
|
|
321
453
|
const results = Array.from({ length: tasks.length });
|
|
322
454
|
let failure;
|
|
323
455
|
let cursor = 0;
|
|
456
|
+
let finished = 0;
|
|
324
457
|
const worker = async () => {
|
|
325
458
|
while (failure === undefined) {
|
|
326
459
|
const index = cursor++;
|
|
327
460
|
const task = tasks[index];
|
|
328
461
|
if (task === undefined)
|
|
329
462
|
return;
|
|
463
|
+
let result;
|
|
330
464
|
try {
|
|
331
|
-
|
|
465
|
+
result = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat);
|
|
332
466
|
}
|
|
333
467
|
catch (error) {
|
|
334
468
|
failure = { error };
|
|
469
|
+
continue;
|
|
470
|
+
}
|
|
471
|
+
results[index] = result;
|
|
472
|
+
const progress = ++finished;
|
|
473
|
+
// Observational callbacks must never abort a run or discard its report.
|
|
474
|
+
try {
|
|
475
|
+
// Handles synchronous throws and rejected async observers alike.
|
|
476
|
+
void Promise.resolve(options.onProgress?.(result, progress, tasks.length)).catch(() => { });
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
/* v8 ignore next -- a broken observer is deliberately swallowed. */
|
|
335
480
|
}
|
|
336
481
|
}
|
|
337
482
|
};
|
|
@@ -342,14 +487,25 @@ export async function runBenchmark(benchmark, options = {}) {
|
|
|
342
487
|
return {
|
|
343
488
|
benchmark: benchmark.name,
|
|
344
489
|
model: benchmark.model,
|
|
490
|
+
...(benchmark.sourceSha256 === undefined ? {} : {
|
|
491
|
+
benchmarkSha256: hasOverrides
|
|
492
|
+
? hashBenchmarkOverrides(benchmark.sourceSha256, overrides)
|
|
493
|
+
: benchmark.sourceSha256,
|
|
494
|
+
}),
|
|
495
|
+
...(hasOverrides ? { benchmarkOverrides: overrides } : {}),
|
|
345
496
|
createdAt: Date.now(),
|
|
346
497
|
trials,
|
|
347
|
-
seed:
|
|
498
|
+
seed: effective.seed,
|
|
348
499
|
pricing: benchmark.pricing?.[benchmark.model] ?? null,
|
|
349
500
|
...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
|
|
350
501
|
tempRoot: root,
|
|
351
502
|
cases: results,
|
|
503
|
+
caseInputs: benchmark.cases.map(caseValue => ({
|
|
504
|
+
caseId: caseValue.id,
|
|
505
|
+
prompt: caseValue.prompt,
|
|
506
|
+
...(caseValue.expected?.answer !== undefined ? { answer: caseValue.expected.answer } : {}),
|
|
507
|
+
})),
|
|
352
508
|
aggregate: aggregateMetrics(completed.map(result => result.metrics)),
|
|
353
|
-
grading:
|
|
509
|
+
grading: aggregateGrading(completed),
|
|
354
510
|
};
|
|
355
511
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Time-boxed regular-expression tests for agent-controlled text.
|
|
3
|
+
*
|
|
4
|
+
* A benchmark author can write a catastrophic backtracking pattern, and the
|
|
5
|
+
* matched text comes from the agent under evaluation. Running such a pattern on
|
|
6
|
+
* the main thread would hang the whole evaluator, so each test runs in a
|
|
7
|
+
* disposable worker and is terminated when it exceeds its budget. The budget
|
|
8
|
+
* includes worker startup, so it is generous enough for high concurrency.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-eval/safe-regex
|
|
11
|
+
*/
|
|
12
|
+
import { Worker } from 'node:worker_threads';
|
|
13
|
+
const WORKER_SOURCE = `
|
|
14
|
+
const { parentPort, workerData } = require('node:worker_threads')
|
|
15
|
+
try {
|
|
16
|
+
const re = new RegExp(workerData.pattern, 'u')
|
|
17
|
+
parentPort.postMessage({ ok: true, value: re.test(workerData.input) })
|
|
18
|
+
} catch (error) {
|
|
19
|
+
parentPort.postMessage({ ok: false, error: String(error) })
|
|
20
|
+
}
|
|
21
|
+
`;
|
|
22
|
+
/** Run one pattern against one input within a shared worker budget. */
|
|
23
|
+
function runRegex(pattern, input, timeoutMs) {
|
|
24
|
+
const worker = new Worker(WORKER_SOURCE, {
|
|
25
|
+
eval: true,
|
|
26
|
+
workerData: { pattern, input },
|
|
27
|
+
});
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
const timer = setTimeout(() => {
|
|
30
|
+
void worker.terminate();
|
|
31
|
+
reject(new Error(`regex timed out after ${timeoutMs} ms`));
|
|
32
|
+
}, timeoutMs);
|
|
33
|
+
worker.once('message', (message) => {
|
|
34
|
+
clearTimeout(timer);
|
|
35
|
+
void worker.terminate();
|
|
36
|
+
if (message.ok === true && typeof message.value === 'boolean')
|
|
37
|
+
resolve(message.value);
|
|
38
|
+
else
|
|
39
|
+
reject(new Error(`regex failed: ${message.error}`));
|
|
40
|
+
});
|
|
41
|
+
/* v8 ignore next 3 -- worker startup failures are infrastructure errors. */
|
|
42
|
+
worker.once('error', error => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
reject(error);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Test a validated pattern against one untrusted input with a hard time budget.
|
|
50
|
+
* @throws when the pattern is invalid or the budget is exceeded.
|
|
51
|
+
*/
|
|
52
|
+
export function safeRegexTest(pattern, input, timeoutMs = 2000) {
|
|
53
|
+
return runRegex(pattern, input, timeoutMs);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Test a pattern against several inputs, giving each its own worker and budget.
|
|
57
|
+
* A pathological early input must not consume the budget of later inputs that
|
|
58
|
+
* would otherwise match.
|
|
59
|
+
*
|
|
60
|
+
* @throws when the pattern is invalid for any input.
|
|
61
|
+
*/
|
|
62
|
+
export async function safeRegexTestAny(pattern, inputs, timeoutMs = 2000) {
|
|
63
|
+
for (const input of inputs) {
|
|
64
|
+
try {
|
|
65
|
+
if (await safeRegexTest(pattern, input, timeoutMs))
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// One pathological or invalid input must not consume the remaining
|
|
70
|
+
// inputs' chances to match; the caller still sees the aggregate result.
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
package/lib/segments.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared case-id to temp-directory-segment normalization.
|
|
3
|
+
*
|
|
4
|
+
* The runner uses this to name each trial's private directory (and its replay
|
|
5
|
+
* fixture); the benchmark loader uses the same function to reject ids that
|
|
6
|
+
* would collapse onto one segment. One implementation keeps validation from
|
|
7
|
+
* drifting away from the directories it protects.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-eval/segments
|
|
10
|
+
*/
|
|
11
|
+
/** Reduce a case id to one safe temp-directory segment. */
|
|
12
|
+
export function caseSegment(value) {
|
|
13
|
+
const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '');
|
|
14
|
+
return safe === '' ? 'case' : safe;
|
|
15
|
+
}
|
package/lib/stats.js
CHANGED
|
@@ -16,6 +16,69 @@
|
|
|
16
16
|
*
|
|
17
17
|
* @module dsh-eval/stats
|
|
18
18
|
*/
|
|
19
|
+
/**
|
|
20
|
+
* Report how much a finite paired sample can ever say under an exact sign test.
|
|
21
|
+
*
|
|
22
|
+
* With `n` discordant pairs the strongest evidence is a clean sweep, whose
|
|
23
|
+
* two-sided p-value is `2^(1-n)`; the printed Bonferroni family multiplies it.
|
|
24
|
+
* Below that floor no observed outcome can reach alpha, so a non-significant
|
|
25
|
+
* result is uninformative rather than evidence of no difference.
|
|
26
|
+
* @param discordant - number of win/loss pairs; ties drop out.
|
|
27
|
+
* @param comparisons - size of the inference family, at least one.
|
|
28
|
+
* @param alpha - family-wise error rate, default `0.05`.
|
|
29
|
+
* @returns the achievable p-value floor, required wins and minimum sample size.
|
|
30
|
+
*/
|
|
31
|
+
export function signTestPower(discordant, comparisons, alpha = 0.05) {
|
|
32
|
+
const floor = (n) => n === 0 ? 1 : Math.min(1, 2 ** (1 - n));
|
|
33
|
+
const bestRawP = floor(discordant);
|
|
34
|
+
const bestAdjustedP = Math.min(1, bestRawP * comparisons);
|
|
35
|
+
// Walk from the largest significant tail down, so the reported win count is
|
|
36
|
+
// the minimum that still reaches alpha rather than a clean sweep.
|
|
37
|
+
let minimumWins = null;
|
|
38
|
+
for (let tail = Math.floor(discordant / 2); tail >= 0; tail--) {
|
|
39
|
+
const adjusted = Math.min(1, signTest(tail, discordant - tail).pValue * comparisons);
|
|
40
|
+
if (adjusted <= alpha) {
|
|
41
|
+
minimumWins = discordant - tail;
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let minimumDiscordant = 0;
|
|
46
|
+
while (Math.min(1, floor(minimumDiscordant) * comparisons) > alpha)
|
|
47
|
+
minimumDiscordant += 1;
|
|
48
|
+
return {
|
|
49
|
+
discordant,
|
|
50
|
+
comparisons,
|
|
51
|
+
alpha,
|
|
52
|
+
bestRawP,
|
|
53
|
+
bestAdjustedP,
|
|
54
|
+
minimumWins,
|
|
55
|
+
minimumDiscordant,
|
|
56
|
+
detectable: bestAdjustedP <= alpha,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Apply a Bonferroni correction across a family of inference quantities.
|
|
61
|
+
*
|
|
62
|
+
* A comparison report prints a sign-test p-value alongside several paired
|
|
63
|
+
* intervals. Testing each at 5% inflates the chance that at least one is a
|
|
64
|
+
* false discovery; dividing the error rate by the family size keeps that
|
|
65
|
+
* chance at `alpha` without any distributional assumption.
|
|
66
|
+
* @param pValue - raw p-value of the family's primary test.
|
|
67
|
+
* @param comparisons - number of quantities in the family; at least one.
|
|
68
|
+
* @param alpha - family-wise error rate, default `0.05`.
|
|
69
|
+
* @returns the adjusted p-value and the confidence each interval must use.
|
|
70
|
+
*/
|
|
71
|
+
export function bonferroni(pValue, comparisons, alpha = 0.05) {
|
|
72
|
+
if (!Number.isInteger(comparisons) || comparisons < 1) {
|
|
73
|
+
throw new Error('bonferroni: comparisons must be a positive integer');
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
comparisons,
|
|
77
|
+
alpha,
|
|
78
|
+
adjustedPValue: Math.min(1, pValue * comparisons),
|
|
79
|
+
intervalConfidence: 1 - alpha / comparisons,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
19
82
|
/**
|
|
20
83
|
* Log of the binomial coefficient, accumulated rather than factorized so large
|
|
21
84
|
* pair counts stay finite.
|
package/lib/trace.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module dsh-eval/trace
|
|
8
8
|
*/
|
|
9
|
+
import { createHash } from 'node:crypto';
|
|
9
10
|
import { readFile, readdir, stat } from 'node:fs/promises';
|
|
10
11
|
import { join } from 'node:path';
|
|
11
12
|
import { decodeStorageRecord, SessionId } from '@deepseek-ai/dsh-session';
|
|
@@ -23,10 +24,17 @@ const headerSchema = z.object({
|
|
|
23
24
|
* or event seqs are not contiguous.
|
|
24
25
|
*/
|
|
25
26
|
export function parseSessionLog(text) {
|
|
26
|
-
|
|
27
|
+
// A leading UTF-8 BOM would otherwise make line 1's header unparseable.
|
|
28
|
+
const lines = text.replace(/^\uFEFF/u, '').split(/\r?\n/u).filter(line => line.trim() !== '');
|
|
27
29
|
if (lines.length === 0)
|
|
28
30
|
throw new Error('empty session log');
|
|
29
|
-
|
|
31
|
+
let header;
|
|
32
|
+
try {
|
|
33
|
+
header = headerSchema.parse(JSON.parse(lines[0]));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new Error('corrupt session log: invalid header at line 1');
|
|
37
|
+
}
|
|
30
38
|
const events = [];
|
|
31
39
|
for (let index = 1; index < lines.length; index++) {
|
|
32
40
|
const line = lines[index];
|
|
@@ -134,3 +142,12 @@ export function mergeTraces(traces) {
|
|
|
134
142
|
.map(entry => entry.event);
|
|
135
143
|
return { sessionId: primary.sessionId, createdAt: primary.createdAt, events };
|
|
136
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* Stable SHA-256 digest of a merged trace, used to prove that an offline
|
|
147
|
+
* re-judge reads the same evidence the original run harvested.
|
|
148
|
+
* @param trace - the merged trace.
|
|
149
|
+
* @returns a lowercase hex digest.
|
|
150
|
+
*/
|
|
151
|
+
export function traceDigest(trace) {
|
|
152
|
+
return createHash('sha256').update(JSON.stringify(trace)).digest('hex');
|
|
153
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Judge / script agreement for dsh-eval.
|
|
3
|
+
*
|
|
4
|
+
* A scripted check and an LLM judge are two independent views of the same
|
|
5
|
+
* trial. Observed agreement alone is misleading when one view almost always
|
|
6
|
+
* passes, so we also report Cohen's kappa, which subtracts the agreement
|
|
7
|
+
* expected from the two marginals. The judge signal used here is
|
|
8
|
+
* "no hallucination flagged", paired with scripted `taskSuccess`.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-eval/agreement
|
|
11
|
+
*/
|
|
12
|
+
import type { EvalRun } from './types.ts';
|
|
13
|
+
/** Agreement statistics over trials carrying both signals. */
|
|
14
|
+
export interface AgreementSummary {
|
|
15
|
+
/** Number of trials with a boolean scripted result and a boolean judge verdict. */
|
|
16
|
+
pairs: number;
|
|
17
|
+
/** Number of trials where the two signals matched. */
|
|
18
|
+
agreements: number;
|
|
19
|
+
/** Observed agreement, agreements / pairs. */
|
|
20
|
+
rate: number;
|
|
21
|
+
/** Cohen's kappa: agreement beyond chance; can be negative. */
|
|
22
|
+
kappa: number;
|
|
23
|
+
/** Trials where the judge flagged no hallucination. */
|
|
24
|
+
judgePassed: number;
|
|
25
|
+
/** Trials where the scripted task check passed. */
|
|
26
|
+
scriptPassed: number;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Compute judge/script agreement for a run.
|
|
30
|
+
* @param run - a persisted run record.
|
|
31
|
+
* @returns the summary, or null when no trial carries both signals.
|
|
32
|
+
*/
|
|
33
|
+
export declare function computeAgreement(run: EvalRun): AgreementSummary | null;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small, dependency-free command-line splitter shared by the CLI `--dsh`
|
|
3
|
+
* override and benchmark check commands.
|
|
4
|
+
*
|
|
5
|
+
* Whitespace-only splitting silently breaks paths with spaces and quoted
|
|
6
|
+
* arguments: `node "my script.mjs" --flag "a b"` used to become five argv
|
|
7
|
+
* entries. This parser supports single/double quotes, backslash escapes and
|
|
8
|
+
* escaped whitespace, without pretending to be a full POSIX shell (redirection
|
|
9
|
+
* and pipes stay the job of explicit opt-in `checkShell`).
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-eval/argv
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Split a command string into argv tokens.
|
|
15
|
+
* @param value - the command line as written by the user.
|
|
16
|
+
* @returns argv tokens with quotes and escapes removed.
|
|
17
|
+
* @throws on an unterminated quote, which is a typo rather than an empty command.
|
|
18
|
+
*/
|
|
19
|
+
export declare function splitArgv(value: string): string[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Crash-safe text output shared by every file-writing CLI command.
|
|
3
|
+
*
|
|
4
|
+
* Writing directly to the destination can leave a truncated file that looks
|
|
5
|
+
* loadable after a crash or a full disk. Staging beside the target and
|
|
6
|
+
* renaming keeps readers on either the old or the new complete document.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-eval/atomic-write
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Write UTF-8 text atomically, creating parent directories as needed.
|
|
12
|
+
* @param path - destination path.
|
|
13
|
+
* @param text - complete file contents.
|
|
14
|
+
*/
|
|
15
|
+
export declare function writeTextAtomic(path: string, text: string): Promise<void>;
|