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/runner.ts CHANGED
@@ -17,9 +17,14 @@ import { spawn } from 'node:child_process'
17
17
  import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises'
18
18
  import { tmpdir } from 'node:os'
19
19
  import { join } from 'node:path'
20
- import type { Benchmark, EvalRun, EvalTrialResult } from './types.ts'
20
+ import { splitArgv } from './argv.ts'
21
+ import { hashBenchmarkOverrides, type BenchmarkOverrides } from './digest.ts'
22
+ import { safeRegexTest, safeRegexTestAny } from './safe-regex.ts'
23
+ import type { Benchmark, BenchmarkExpectation, EvalRun, EvalTrialResult } from './types.ts'
21
24
  import type { EvalGrade, EvalRunGrading } from './types.ts'
22
- import { tryJudgeTrial, type JudgeChat } from './judge.ts'
25
+ import { finalAnswerOf, tryJudgeTrial, type JudgeChat } from './judge.ts'
26
+ import { traceDigest } from './trace.ts'
27
+ import { caseSegment } from './segments.ts'
23
28
  import { aggregateMetrics, computeMetrics } from './metrics.ts'
24
29
  import { findSessionLogs, loadTrace, mergeTraces } from './trace.ts'
25
30
 
@@ -36,10 +41,14 @@ export interface RunOptions {
36
41
  trials?: number
37
42
  /** Override the benchmark's in-flight trial limit. */
38
43
  concurrency?: number
44
+ /** Override the benchmark's base seed. */
45
+ seed?: number
39
46
  /** Root for trial directories; defaults to the platform temp dir. */
40
47
  tempRoot?: string
41
48
  /** LLM-judge chat seam; required when the benchmark configures a judge. */
42
49
  judgeChat?: JudgeChat
50
+ /** Called once per finished trial, including errors, with 1-based progress. */
51
+ onProgress?: (result: EvalTrialResult, finished: number, total: number) => void
43
52
  }
44
53
 
45
54
  /** One child process's orthogonal outcome facts. */
@@ -63,12 +72,6 @@ function message(error: unknown): string {
63
72
  return error instanceof Error ? error.message : String(error)
64
73
  }
65
74
 
66
- /** Reduce a case id to one safe temp-directory segment. */
67
- function sanitizeSegment(value: string): string {
68
- const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '')
69
- return safe === '' ? 'case' : safe
70
- }
71
-
72
75
  /**
73
76
  * Build the per-trial overlay: plain-JSONL persistence, non-interactive
74
77
  * permissions, and the keyless replay plugin when recorded logs exist.
@@ -102,9 +105,35 @@ function evalOverlay(replay: { file: string; childFiles: readonly string[] } | u
102
105
  return `${lines.join('\n')}\n`
103
106
  }
104
107
 
105
- /** Split a single command string into argv on whitespace. */
106
- function splitWords(value: string): string[] {
107
- return value.trim().split(/\s+/u).filter(part => part !== '')
108
+ /**
109
+ * Match every configured tool expectation against the recorded call names.
110
+ * All configured constraints must hold; no tool expectation means "ungraded".
111
+ * @param expected - the case's scripted expectations.
112
+ * @param names - tool-call names recorded in the harvested trace.
113
+ * @returns the boolean match, or null when no tool expectation is configured.
114
+ */
115
+ async function toolSelectionOf(
116
+ expected: BenchmarkExpectation,
117
+ names: readonly string[],
118
+ ): Promise<boolean | null> {
119
+ const configured = expected.tool !== undefined || expected.tools !== undefined
120
+ || expected.toolAnyOf !== undefined || expected.toolRegex !== undefined
121
+ || expected.toolNot !== undefined
122
+ if (!configured) return null
123
+ const includes = (needle: string): boolean => names.some(name => name.includes(needle))
124
+ if (expected.tool !== undefined && !includes(expected.tool)) return false
125
+ if (expected.tools !== undefined && !expected.tools.every(includes)) return false
126
+ if (expected.toolAnyOf !== undefined && !expected.toolAnyOf.some(includes)) return false
127
+ if (expected.toolRegex !== undefined) {
128
+ /* v8 ignore next 4 -- safeRegexTestAny degrades each invalid input internally. */
129
+ try {
130
+ if (!await safeRegexTestAny(expected.toolRegex!, names)) return false
131
+ } catch {
132
+ return false
133
+ }
134
+ }
135
+ if (expected.toolNot !== undefined && expected.toolNot.some(includes)) return false
136
+ return true
108
137
  }
109
138
 
110
139
  /**
@@ -126,18 +155,37 @@ async function gradeTrial(
126
155
  ): Promise<EvalGrade> {
127
156
  const expected = caseValue.expected
128
157
  if (expected === undefined) return { taskSuccess: null, toolSelectionAccuracy: null }
129
- const expectedTool = expected.tool
130
- const toolSelectionAccuracy = expectedTool === undefined
131
- ? null
132
- : trace.events.some(event => event.type === 'tool/call' && event.data.name.includes(expectedTool))
158
+ const names = trace.events.flatMap(event => event.type === 'tool/call' ? [event.data.name] : [])
159
+ const toolSelectionAccuracy = await toolSelectionOf(expected, names)
133
160
  let taskSuccess: boolean | null = null
134
- if (expected.check !== undefined) {
161
+ const shell = expected.checkShell !== undefined
162
+ const checkArgv = expected.checkArgv !== undefined
163
+ ? [...expected.checkArgv]
164
+ : shell ? [expected.checkShell!] : undefined
165
+ if (checkArgv !== undefined || expected.check !== undefined) {
135
166
  try {
136
- const outcome = await runCommand(splitWords(expected.check), [], workspace, { ...process.env }, timeoutMs)
167
+ const command = checkArgv ?? splitArgv(expected.check!)
168
+ const outcome = await runCommand(command, [], workspace, { ...process.env }, timeoutMs, {
169
+ shell,
170
+ // A shell check can spawn grandchildren; kill the whole group on timeouts.
171
+ detached: true,
172
+ })
137
173
  taskSuccess = !outcome.timedOut && outcome.exitCode === 0
138
174
  } catch {
139
175
  taskSuccess = false
140
176
  }
177
+ } else if (expected.answerRegex !== undefined) {
178
+ // Deterministic final-answer grading: no command, no LLM needed.
179
+ // The schema validates at load; hand-built benchmarks degrade to failure.
180
+ try {
181
+ // The pattern runs in a time-boxed worker: a catastrophic benchmark regex
182
+ // must not hang the evaluator on agent-controlled final-answer text.
183
+ taskSuccess = await safeRegexTest(
184
+ expected.answerRegex, finalAnswerOf(trace).slice(0, 4096),
185
+ )
186
+ } catch {
187
+ taskSuccess = false
188
+ }
141
189
  }
142
190
  return { taskSuccess, toolSelectionAccuracy }
143
191
  }
@@ -151,7 +199,7 @@ function pooledRate(items: readonly EvalTrialResult[], select: (grade: EvalGrade
151
199
  }
152
200
 
153
201
  /** Reduce completed trials' grades into pooled run-level rates. */
154
- function gradingOf(results: readonly EvalTrialResult[]): EvalRunGrading | null {
202
+ export function aggregateGrading(results: readonly EvalTrialResult[]): EvalRunGrading | null {
155
203
  const taskSuccessRate = pooledRate(results, grade => grade?.taskSuccess ?? null)
156
204
  const toolSelectionAccuracyRate = pooledRate(results, grade => grade?.toolSelectionAccuracy ?? null)
157
205
  const finalScores = results
@@ -166,10 +214,11 @@ function gradingOf(results: readonly EvalTrialResult[]): EvalRunGrading | null {
166
214
  const hallucinationRate = hallucinated.length === 0
167
215
  ? null
168
216
  : hallucinated.filter(value => value).length / hallucinated.length
217
+ const judgeFailures = results.filter(result => result.judge?.judgeError !== undefined).length
169
218
  return taskSuccessRate === null && toolSelectionAccuracyRate === null
170
- && finalAnswerScore === null && hallucinationRate === null
219
+ && finalAnswerScore === null && hallucinationRate === null && judgeFailures === 0
171
220
  ? null
172
- : { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate }
221
+ : { taskSuccessRate, toolSelectionAccuracyRate, finalAnswerScore, hallucinationRate, judgeFailures }
173
222
  }
174
223
 
175
224
  /**
@@ -182,6 +231,7 @@ function gradingOf(results: readonly EvalTrialResult[]): EvalRunGrading | null {
182
231
  * @param cwd - the child's working directory.
183
232
  * @param env - the child's environment.
184
233
  * @param timeoutMs - kill the child after this many milliseconds.
234
+ * @param options - opt-in shell interpretation and detached process-group kill.
185
235
  * @returns the orthogonal outcome facts.
186
236
  */
187
237
  function runCommand(
@@ -190,17 +240,20 @@ function runCommand(
190
240
  cwd: string,
191
241
  env: NodeJS.ProcessEnv,
192
242
  timeoutMs: number,
243
+ options: { shell?: boolean; detached?: boolean } = {},
193
244
  ): Promise<SpawnOutcome> {
194
245
  const executable = command[0]
195
246
  if (executable === undefined) {
196
247
  return Promise.reject(new Error('eval: dsh command must not be empty'))
197
248
  }
198
249
  return new Promise((resolveOutcome, reject) => {
199
- const child = spawn(executable, [...command.slice(1), ...args], {
250
+ const child = spawn(executable, options.shell === true ? [] : [...command.slice(1), ...args], {
200
251
  cwd,
201
252
  env,
202
253
  stdio: ['ignore', 'pipe', 'pipe'],
203
254
  windowsHide: true,
255
+ shell: options.shell === true,
256
+ detached: options.detached === true,
204
257
  })
205
258
  let stdout = ''
206
259
  let stderr = ''
@@ -213,21 +266,60 @@ function runCommand(
213
266
  )
214
267
  child.stdout.on('data', (chunk: Buffer) => { stdout = cap(stdout, chunk) })
215
268
  child.stderr.on('data', (chunk: Buffer) => { stderr = cap(stderr, chunk) })
269
+ let escalation: NodeJS.Timeout | undefined
216
270
  const timer = setTimeout(() => {
217
- /* v8 ignore next 3 -- close clears the timer; only a same-tick close/kill race reaches here. */
271
+ /* v8 ignore next 2 -- close clears the timer; only a same-tick close/kill race reaches here. */
218
272
  if (settled) return
273
+ // `close` arrives after stdio drains, so a child that has already exited
274
+ // but is still draining its pipes must not be reported as timed out.
275
+ /* v8 ignore next 2 -- exit-before-close is a narrow event-loop window no fixture can force deterministically. */
276
+ if (child.exitCode !== null || child.signalCode !== null) return
277
+ const terminate = (signal: NodeJS.Signals): void => {
278
+ /* v8 ignore next 5 -- POSIX process-group kill; on Windows child.kill below kills the detached group. */
279
+ if (options.detached === true && process.platform !== 'win32' && child.pid !== undefined) {
280
+ try { process.kill(-child.pid, signal) } catch { /* the group is already gone */ }
281
+ }
282
+ child.kill(signal)
283
+ }
219
284
  timedOut = true
220
- child.kill()
285
+ terminate('SIGTERM')
286
+ /* v8 ignore next 5 -- escalation needs a child that ignores SIGTERM; the timeout fixture exits on the first signal. */
287
+ escalation = setTimeout(() => {
288
+ if (!settled && child.exitCode === null && child.signalCode === null) terminate('SIGKILL')
289
+ }, 1000)
290
+ escalation.unref()
221
291
  }, timeoutMs)
222
- child.on('error', (error) => {
292
+ let drainGuard: NodeJS.Timeout | undefined
293
+ const clearTimers = (): void => {
223
294
  clearTimeout(timer)
295
+ if (escalation !== undefined) clearTimeout(escalation)
296
+ if (drainGuard !== undefined) clearTimeout(drainGuard)
297
+ }
298
+ child.on('exit', (code) => {
299
+ // A detached grandchild can inherit the pipes and keep `close` pending
300
+ // long after the direct child exited. Resolve from `exit` after a short
301
+ // drain grace period so a check cannot hang the whole trial.
302
+ /* v8 ignore next 10 -- Windows closes inherited pipes eagerly; only POSIX grandchildren can keep them open. */
303
+ drainGuard = setTimeout(() => {
304
+ if (settled) return
305
+ settled = true
306
+ clearTimers()
307
+ // A surviving grandchild owns these pipes; releasing them lets the CLI exit.
308
+ child.stdout.destroy()
309
+ child.stderr.destroy()
310
+ resolveOutcome({ exitCode: code, timedOut, stdout, stderr })
311
+ }, 200)
312
+ drainGuard.unref()
313
+ })
314
+ child.on('error', (error) => {
315
+ clearTimers()
224
316
  /* v8 ignore next 3 -- spawn emits one error before close; the guard covers only an impossible duplicate error event. */
225
317
  if (settled) return
226
318
  settled = true
227
319
  reject(error)
228
320
  })
229
321
  child.on('close', (code) => {
230
- clearTimeout(timer)
322
+ clearTimers()
231
323
  if (settled) return
232
324
  settled = true
233
325
  resolveOutcome({ exitCode: code, timedOut, stdout, stderr })
@@ -250,7 +342,8 @@ async function runCaseTrial(
250
342
  root: string,
251
343
  judgeChat: JudgeChat | undefined,
252
344
  ): Promise<EvalTrialResult> {
253
- const trialDir = join(root, `${sanitizeSegment(caseValue.id)}-${trial}`)
345
+ const timeoutMs = caseValue.timeoutMs ?? benchmark.timeoutMs
346
+ const trialDir = join(root, `${caseSegment(caseValue.id)}-${trial}`)
254
347
  const workspace = join(trialDir, 'workspace')
255
348
  const dshHome = join(trialDir, 'dsh-home')
256
349
  await mkdir(workspace, { recursive: true })
@@ -258,7 +351,7 @@ async function runCaseTrial(
258
351
  if (caseValue.workspace !== undefined) await cp(caseValue.workspace, workspace, { recursive: true })
259
352
  const replayFixture = benchmark.replay === undefined
260
353
  ? undefined
261
- : join(benchmark.replay.dir, `${sanitizeSegment(caseValue.id)}-${trial}`)
354
+ : join(benchmark.replay.dir, `${caseSegment(caseValue.id)}-${trial}`)
262
355
  let replay: { file: string; childFiles: string[] } | undefined
263
356
  if (replayFixture !== undefined) {
264
357
  const logs = await findSessionLogs(replayFixture)
@@ -283,8 +376,15 @@ async function runCaseTrial(
283
376
  benchmark.command,
284
377
  ['--profile', benchmark.profile, '--patch', overlayPath, caseValue.prompt],
285
378
  workspace,
286
- { ...process.env, DSH_HOME: dshHome },
287
- benchmark.timeoutMs,
379
+ {
380
+ ...process.env,
381
+ DSH_HOME: dshHome,
382
+ // Trial n gets a deterministic, distinct seed derived from the run's
383
+ // base seed. An env var is ignored by harnesses that do not read it,
384
+ // unlike an unknown CLI flag which would break them.
385
+ DSH_EVAL_SEED: String(benchmark.seed + trial - 1),
386
+ },
387
+ timeoutMs,
288
388
  )
289
389
  } catch (error) {
290
390
  return {
@@ -316,7 +416,7 @@ async function runCaseTrial(
316
416
  const trace = mergeTraces(loaded.map(entry => entry.trace))
317
417
  const pricing = benchmark.pricing?.[benchmark.model]
318
418
  const metrics = computeMetrics(trace.events, pricing)
319
- const grade = await gradeTrial(caseValue, trace, workspace, benchmark.timeoutMs)
419
+ const grade = await gradeTrial(caseValue, trace, workspace, timeoutMs)
320
420
  const judge = benchmark.judge === undefined || judgeChat === undefined
321
421
  ? undefined
322
422
  : await tryJudgeTrial(caseValue, trace, benchmark.judge, judgeChat)
@@ -326,6 +426,7 @@ async function runCaseTrial(
326
426
  status: 'completed',
327
427
  tracePath: primaryPath,
328
428
  tracePaths: loaded.map(entry => entry.path),
429
+ traceSha256: traceDigest(trace),
329
430
  exitCode: outcome.exitCode,
330
431
  timedOut: outcome.timedOut,
331
432
  metrics,
@@ -366,14 +467,37 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
366
467
  if (benchmark.judge !== undefined && benchmark.replay !== undefined) {
367
468
  throw new Error('eval: judge and replay cannot be combined in one run')
368
469
  }
369
- const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'))
470
+ // Validate extension-point overrides as strictly as the YAML schema does.
471
+ if (options.seed !== undefined && !Number.isSafeInteger(options.seed)) {
472
+ throw new Error('eval: seed must be a safe integer')
473
+ }
370
474
  const trials = options.trials ?? benchmark.trials
475
+ const concurrency = options.concurrency ?? benchmark.concurrency
476
+ // `runBenchmark` is a documented extension point: runtime overrides need the
477
+ // same positive-integer guarantee the YAML schema gives a loaded document.
478
+ if (!Number.isSafeInteger(trials) || trials < 1) {
479
+ throw new Error('eval: trials must be a positive integer')
480
+ }
481
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
482
+ throw new Error('eval: concurrency must be a positive integer')
483
+ }
484
+ // Created only after validation, so a bad override leaves no temp directory.
485
+ const root = await mkdtemp(join(options.tempRoot ?? tmpdir(), 'dsh-eval-'))
371
486
  const effective: Benchmark = {
372
487
  ...benchmark,
373
488
  ...(options.profile !== undefined ? { profile: options.profile } : {}),
374
489
  ...(options.command !== undefined ? { command: options.command } : {}),
375
- ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
490
+ ...(options.seed === undefined ? {} : { seed: options.seed }),
491
+ concurrency,
492
+ }
493
+ const overrides: BenchmarkOverrides = {
494
+ ...(options.trials === undefined ? {} : { trials }),
495
+ ...(options.concurrency === undefined ? {} : { concurrency }),
496
+ ...(options.seed === undefined ? {} : { seed: options.seed }),
497
+ ...(options.profile === undefined ? {} : { profile: options.profile }),
498
+ ...(options.command === undefined ? {} : { dshCommand: [...options.command] }),
376
499
  }
500
+ const hasOverrides = Object.keys(overrides).length > 0
377
501
  const tasks: { caseValue: Benchmark['cases'][number]; trial: number }[] = []
378
502
  for (const caseValue of effective.cases) {
379
503
  for (let trial = 1; trial <= trials; trial++) tasks.push({ caseValue, trial })
@@ -381,15 +505,27 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
381
505
  const results: EvalTrialResult[] = Array.from({ length: tasks.length })
382
506
  let failure: { error: unknown } | undefined
383
507
  let cursor = 0
508
+ let finished = 0
384
509
  const worker = async (): Promise<void> => {
385
510
  while (failure === undefined) {
386
511
  const index = cursor++
387
512
  const task = tasks[index]
388
513
  if (task === undefined) return
514
+ let result: EvalTrialResult
389
515
  try {
390
- results[index] = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat)
516
+ result = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat)
391
517
  } catch (error) {
392
518
  failure = { error }
519
+ continue
520
+ }
521
+ results[index] = result
522
+ const progress = ++finished
523
+ // Observational callbacks must never abort a run or discard its report.
524
+ try {
525
+ // Handles synchronous throws and rejected async observers alike.
526
+ void Promise.resolve(options.onProgress?.(result, progress, tasks.length)).catch(() => {})
527
+ } catch {
528
+ /* v8 ignore next -- a broken observer is deliberately swallowed. */
393
529
  }
394
530
  }
395
531
  }
@@ -402,14 +538,25 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
402
538
  return {
403
539
  benchmark: benchmark.name,
404
540
  model: benchmark.model,
541
+ ...(benchmark.sourceSha256 === undefined ? {} : {
542
+ benchmarkSha256: hasOverrides
543
+ ? hashBenchmarkOverrides(benchmark.sourceSha256, overrides)
544
+ : benchmark.sourceSha256,
545
+ }),
546
+ ...(hasOverrides ? { benchmarkOverrides: overrides } : {}),
405
547
  createdAt: Date.now(),
406
548
  trials,
407
- seed: benchmark.seed,
549
+ seed: effective.seed,
408
550
  pricing: benchmark.pricing?.[benchmark.model] ?? null,
409
551
  ...(benchmark.judge !== undefined ? { judge: benchmark.judge } : {}),
410
552
  tempRoot: root,
411
553
  cases: results,
554
+ caseInputs: benchmark.cases.map(caseValue => ({
555
+ caseId: caseValue.id,
556
+ prompt: caseValue.prompt,
557
+ ...(caseValue.expected?.answer !== undefined ? { answer: caseValue.expected.answer } : {}),
558
+ })),
412
559
  aggregate: aggregateMetrics(completed.map(result => result.metrics)),
413
- grading: gradingOf(completed),
560
+ grading: aggregateGrading(completed),
414
561
  }
415
562
  }
@@ -0,0 +1,79 @@
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
+
13
+ import { Worker } from 'node:worker_threads'
14
+
15
+ const WORKER_SOURCE = `
16
+ const { parentPort, workerData } = require('node:worker_threads')
17
+ try {
18
+ const re = new RegExp(workerData.pattern, 'u')
19
+ parentPort.postMessage({ ok: true, value: re.test(workerData.input) })
20
+ } catch (error) {
21
+ parentPort.postMessage({ ok: false, error: String(error) })
22
+ }
23
+ `
24
+
25
+ /** Run one pattern against one input within a shared worker budget. */
26
+ function runRegex(pattern: string, input: string, timeoutMs: number): Promise<boolean> {
27
+ const worker = new Worker(WORKER_SOURCE, {
28
+ eval: true,
29
+ workerData: { pattern, input },
30
+ })
31
+ return new Promise<boolean>((resolve, reject) => {
32
+ const timer = setTimeout(() => {
33
+ void worker.terminate()
34
+ reject(new Error(`regex timed out after ${timeoutMs} ms`))
35
+ }, timeoutMs)
36
+ worker.once('message', (message: { ok: boolean; value?: boolean; error?: string }) => {
37
+ clearTimeout(timer)
38
+ void worker.terminate()
39
+ if (message.ok === true && typeof message.value === 'boolean') resolve(message.value)
40
+ else reject(new Error(`regex failed: ${message.error!}`))
41
+ })
42
+ /* v8 ignore next 3 -- worker startup failures are infrastructure errors. */
43
+ worker.once('error', error => {
44
+ clearTimeout(timer)
45
+ reject(error)
46
+ })
47
+ })
48
+ }
49
+
50
+ /**
51
+ * Test a validated pattern against one untrusted input with a hard time budget.
52
+ * @throws when the pattern is invalid or the budget is exceeded.
53
+ */
54
+ export function safeRegexTest(pattern: string, input: string, timeoutMs = 2000): Promise<boolean> {
55
+ return runRegex(pattern, input, timeoutMs)
56
+ }
57
+
58
+ /**
59
+ * Test a pattern against several inputs, giving each its own worker and budget.
60
+ * A pathological early input must not consume the budget of later inputs that
61
+ * would otherwise match.
62
+ *
63
+ * @throws when the pattern is invalid for any input.
64
+ */
65
+ export async function safeRegexTestAny(
66
+ pattern: string,
67
+ inputs: readonly string[],
68
+ timeoutMs = 2000,
69
+ ): Promise<boolean> {
70
+ for (const input of inputs) {
71
+ try {
72
+ if (await safeRegexTest(pattern, input, timeoutMs)) return true
73
+ } catch {
74
+ // One pathological or invalid input must not consume the remaining
75
+ // inputs' chances to match; the caller still sees the aggregate result.
76
+ }
77
+ }
78
+ return false
79
+ }
@@ -0,0 +1,16 @@
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
+
12
+ /** Reduce a case id to one safe temp-directory segment. */
13
+ export function caseSegment(value: string): string {
14
+ const safe = value.replace(/[^A-Za-z0-9._-]/gu, '-').replace(/^-+|-+$/gu, '')
15
+ return safe === '' ? 'case' : safe
16
+ }
package/src/stats.ts CHANGED
@@ -37,6 +37,110 @@ export interface PairedDelta {
37
37
  pairs: number
38
38
  }
39
39
 
40
+ /** Power ceiling of an exact sign test with a finite number of discordant pairs. */
41
+ export interface SignTestPower {
42
+ /** Discordant pairs the test actually has. */
43
+ discordant: number
44
+ /** Number of quantities in the printed inference family. */
45
+ comparisons: number
46
+ /** Family-wise error rate the family controls. */
47
+ alpha: number
48
+ /** Smallest raw p-value any outcome with this sample could produce. */
49
+ bestRawP: number
50
+ /** Smallest Bonferroni-adjusted p-value any outcome could produce. */
51
+ bestAdjustedP: number
52
+ /** Wins in the favoured direction needed for significance, or null when impossible. */
53
+ minimumWins: number | null
54
+ /** Smallest discordant sample that could reach the corrected alpha. */
55
+ minimumDiscordant: number
56
+ /** Whether the current sample can reach the corrected alpha at all. */
57
+ detectable: boolean
58
+ }
59
+
60
+ /**
61
+ * Report how much a finite paired sample can ever say under an exact sign test.
62
+ *
63
+ * With `n` discordant pairs the strongest evidence is a clean sweep, whose
64
+ * two-sided p-value is `2^(1-n)`; the printed Bonferroni family multiplies it.
65
+ * Below that floor no observed outcome can reach alpha, so a non-significant
66
+ * result is uninformative rather than evidence of no difference.
67
+ * @param discordant - number of win/loss pairs; ties drop out.
68
+ * @param comparisons - size of the inference family, at least one.
69
+ * @param alpha - family-wise error rate, default `0.05`.
70
+ * @returns the achievable p-value floor, required wins and minimum sample size.
71
+ */
72
+ export function signTestPower(
73
+ discordant: number,
74
+ comparisons: number,
75
+ alpha = 0.05,
76
+ ): SignTestPower {
77
+ const floor = (n: number): number => n === 0 ? 1 : Math.min(1, 2 ** (1 - n))
78
+ const bestRawP = floor(discordant)
79
+ const bestAdjustedP = Math.min(1, bestRawP * comparisons)
80
+ // Walk from the largest significant tail down, so the reported win count is
81
+ // the minimum that still reaches alpha rather than a clean sweep.
82
+ let minimumWins: number | null = null
83
+ for (let tail = Math.floor(discordant / 2); tail >= 0; tail--) {
84
+ const adjusted = Math.min(1, signTest(tail, discordant - tail).pValue * comparisons)
85
+ if (adjusted <= alpha) {
86
+ minimumWins = discordant - tail
87
+ break
88
+ }
89
+ }
90
+ let minimumDiscordant = 0
91
+ while (Math.min(1, floor(minimumDiscordant) * comparisons) > alpha) minimumDiscordant += 1
92
+ return {
93
+ discordant,
94
+ comparisons,
95
+ alpha,
96
+ bestRawP,
97
+ bestAdjustedP,
98
+ minimumWins,
99
+ minimumDiscordant,
100
+ detectable: bestAdjustedP <= alpha,
101
+ }
102
+ }
103
+
104
+ /** Bonferroni family-wise correction shared by a p-value and its sibling intervals. */
105
+ export interface FamilyWiseCorrection {
106
+ /** Number of inference quantities in the family (the p-value plus intervals). */
107
+ comparisons: number
108
+ /** Family-wise error rate the family controls. */
109
+ alpha: number
110
+ /** Adjusted p-value: raw p times the family size, capped at 1. */
111
+ adjustedPValue: number
112
+ /** Per-interval confidence that keeps family-wise coverage at `1 - alpha`. */
113
+ intervalConfidence: number
114
+ }
115
+
116
+ /**
117
+ * Apply a Bonferroni correction across a family of inference quantities.
118
+ *
119
+ * A comparison report prints a sign-test p-value alongside several paired
120
+ * intervals. Testing each at 5% inflates the chance that at least one is a
121
+ * false discovery; dividing the error rate by the family size keeps that
122
+ * chance at `alpha` without any distributional assumption.
123
+ * @param pValue - raw p-value of the family's primary test.
124
+ * @param comparisons - number of quantities in the family; at least one.
125
+ * @param alpha - family-wise error rate, default `0.05`.
126
+ * @returns the adjusted p-value and the confidence each interval must use.
127
+ */
128
+ export function bonferroni(
129
+ pValue: number,
130
+ comparisons: number,
131
+ alpha = 0.05,
132
+ ): FamilyWiseCorrection {
133
+ if (!Number.isInteger(comparisons) || comparisons < 1) {
134
+ throw new Error('bonferroni: comparisons must be a positive integer')
135
+ }
136
+ return {
137
+ comparisons,
138
+ alpha,
139
+ adjustedPValue: Math.min(1, pValue * comparisons),
140
+ intervalConfidence: 1 - alpha / comparisons,
141
+ }
142
+ }
143
+
40
144
  /** Knobs for {@link pairedDelta}; defaults keep reports reproducible. */
41
145
  export interface BootstrapOptions {
42
146
  /** Interval confidence, default `0.95`. */
package/src/trace.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * @module dsh-eval/trace
8
8
  */
9
9
 
10
+ import { createHash } from 'node:crypto'
10
11
  import { readFile, readdir, stat } from 'node:fs/promises'
11
12
  import { join } from 'node:path'
12
13
  import { decodeStorageRecord, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
@@ -27,9 +28,15 @@ const headerSchema = z.object({
27
28
  * or event seqs are not contiguous.
28
29
  */
29
30
  export function parseSessionLog(text: string): EvalTrace {
30
- const lines = text.split(/\r?\n/u).filter(line => line.trim() !== '')
31
+ // A leading UTF-8 BOM would otherwise make line 1's header unparseable.
32
+ const lines = text.replace(/^\uFEFF/u, '').split(/\r?\n/u).filter(line => line.trim() !== '')
31
33
  if (lines.length === 0) throw new Error('empty session log')
32
- const header = headerSchema.parse(JSON.parse(lines[0] as string))
34
+ let header: z.infer<typeof headerSchema>
35
+ try {
36
+ header = headerSchema.parse(JSON.parse(lines[0] as string))
37
+ } catch {
38
+ throw new Error('corrupt session log: invalid header at line 1')
39
+ }
33
40
  const events: SessionEvent[] = []
34
41
  for (let index = 1; index < lines.length; index++) {
35
42
  const line = lines[index] as string
@@ -135,3 +142,13 @@ export function mergeTraces(traces: readonly EvalTrace[]): EvalTrace {
135
142
  .map(entry => entry.event)
136
143
  return { sessionId: primary.sessionId, createdAt: primary.createdAt, events }
137
144
  }
145
+
146
+ /**
147
+ * Stable SHA-256 digest of a merged trace, used to prove that an offline
148
+ * re-judge reads the same evidence the original run harvested.
149
+ * @param trace - the merged trace.
150
+ * @returns a lowercase hex digest.
151
+ */
152
+ export function traceDigest(trace: EvalTrace): string {
153
+ return createHash('sha256').update(JSON.stringify(trace)).digest('hex')
154
+ }