dsh-eval 0.3.1 → 0.4.0

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 CHANGED
@@ -15,6 +15,8 @@ dsh eval compare eval-v1.json eval-v2.json
15
15
 
16
16
  `dsh eval` is a launcher alias for `--profile eval`; the eval profile composes `dsh-base` plus this bundle. Each trial spawns the benchmark-configured `dsh` command (default `dsh`) against the benchmark-configured profile (default `headless`) with a private temp workspace, an isolated `DSH_HOME`, and a patch overlay forcing plain-JSONL persistence and non-interactive workspace-write/never-approval permissions. The harvested primary session log becomes the trial's trace, and subagent child logs under the trial's `DSH_HOME` are merged into it before the metric fold.
17
17
 
18
+ Trials are independent — private temp workspace, isolated `DSH_HOME`, own patch overlay — so `concurrency` runs that many of them at once. The run record still lists results in case-then-trial order whatever the interleaving, and `--concurrency` overrides the document. Raising it trades wall time for peak CPU, memory, and concurrent model quota.
19
+
18
20
  ## Benchmark document
19
21
 
20
22
  ```yaml
@@ -47,6 +49,7 @@ pricing:
47
49
  | `profile` | `headless` | dsh profile each trial spawns. |
48
50
  | `command` | `[dsh]` | dsh launcher argv. |
49
51
  | `trials` | `1` | Trials per case. |
52
+ | `concurrency` | `1` | Case x trial executions allowed in flight at once; `1` keeps the run strictly serial. |
50
53
  | `timeoutMs` | `600000` | Per-trial timeout; the direct child is killed on expiry. |
51
54
  | `seed` | `0` | Reserved for future deterministic paired comparisons. |
52
55
  | `cases[].id` | required | Stable case id. |
@@ -98,6 +101,8 @@ hallucination rate.
98
101
 
99
102
  `dsh eval compare run-v1.json run-v2.json` renders both runs as a markdown table: benchmark/model identity, completed trials, steps, tool/task/tool-selection rates, invalid calls, retries, tokens, cost, and latency, with signed `B - A` deltas. When both runs complete the same case x trial keys, the table appends paired statistics: trial count, win/lose/tie on the first available metric (task success, tool selection accuracy, or final-answer score), and mean `B - A` deltas for steps, tokens, and judge score. The runs' `seed` is recorded provenance for the pairing, not a guarantee of identical model output.
100
103
 
104
+ Because a paired eval sample is small and its deltas are not normal, the paired block also carries inference rather than point estimates alone: an exact two-sided **sign test** over the discordant pairs (ties drop out, as the test requires) for the primary metric, and a seeded **bootstrap 95% interval** beside each mean delta. Nothing is assumed about the shape of the delta distribution, and the PRNG seed is fixed, so re-running `compare` on the same reports prints a byte-identical table. Read those p-values as per-metric and unadjusted for multiple comparisons: with three metrics shown, one p just under 0.05 is weak evidence.
105
+
101
106
  ## Replay (keyless CI)
102
107
 
103
108
  A keyed run records every trial's session log under its `tempRoot`. Copy the
@@ -143,6 +148,7 @@ None; this package neither assembles nor sends a provider request, so no request
143
148
 
144
149
  - **Judge output is best-effort** — a judge chat failure or unparsable reply yields null verdict fields, and judge calls consume model quota outside the trial's measured cost.
145
150
  - **Paired comparison pairs as-is** — trials pair by case id and trial index; `seed` is recorded provenance, not a deterministic guarantee of identical model output, and per-arm leaderboards are not rendered.
151
+ - **Paired inference is unadjusted** — the sign test and bootstrap intervals are per metric, with no correction across the metrics a run prints, and a sign test needs discordant pairs to say anything: a run where every pair ties reports `p = 1`.
146
152
  - **Replay binds by first-call order** — the replay plugin keys recorded scripts to live sessions by first-call order, so concurrent subagents replay non-deterministically.
147
153
  - **Imported traces lack token usage** — Codex and Claude Code logs do not record provider usage, so imported runs report zero tokens and no cost.
148
154
  - **Direct-child timeout only** — a timed-out trial kills the direct dsh process; on Windows its descendants may survive.
package/README.zh.md CHANGED
@@ -15,6 +15,8 @@ dsh eval compare eval-v1.json eval-v2.json
15
15
 
16
16
  `dsh eval` 是 `--profile eval` 的启动器别名,eval profile 由 `dsh-base` 加本 bundle 组成。每个 trial 以 benchmark 配置的 `dsh` 命令(默认 `dsh`)和配置的 profile(默认 `headless`)启动,带有独立的临时工作区、隔离的 `DSH_HOME`,以及一层强制纯 JSONL 持久化和非交互 workspace-write/never-approval 权限的补丁。收获的主 session 日志即该 trial 的 trace;该 trial `DSH_HOME` 下的子 agent 日志会在指标折叠前合并进来。
17
17
 
18
+ trial 之间彼此独立——各自的临时工作区、隔离的 `DSH_HOME`、各自的补丁层——所以 `concurrency` 可以让这么多个 trial 同时跑。无论并发如何交错,run 记录仍按 case、再按 trial 的顺序列出结果;`--concurrency` 可覆盖文档里的值。调高它是用墙钟时间换峰值 CPU、内存与并发的模型额度。
19
+
18
20
  ## Benchmark 文档
19
21
 
20
22
  ```yaml
@@ -47,6 +49,7 @@ pricing:
47
49
  | `profile` | `headless` | 每个 trial 启动的 dsh profile。 |
48
50
  | `command` | `[dsh]` | dsh 启动器 argv。 |
49
51
  | `trials` | `1` | 每个 case 的 trial 数。 |
52
+ | `concurrency` | `1` | 同时在跑的 case × trial 数;`1` 表示严格串行。 |
50
53
  | `timeoutMs` | `600000` | 每个 trial 的超时;到期杀掉直接子进程。 |
51
54
  | `seed` | `0` | 为将来的确定性配对比较预留。 |
52
55
  | `cases[].id` | 必填 | 稳定的 case id。 |
@@ -90,6 +93,8 @@ trial `DSH_HOME` 下的子 session 日志在折叠前合并进 trial trace,因
90
93
 
91
94
  `dsh eval compare run-v1.json run-v2.json` 把两个 run 渲染成 Markdown 表:benchmark/模型标识、完成的 trial 数、steps、工具/任务/工具选择成功率、无效调用、重试、token、成本与延迟,并给出带符号的 `B - A` 差值。当两个 run 完成的 case × trial 键完全一致时,表尾追加配对统计:trial 数、按第一个可用指标(任务成功、工具选择准确率、最终答案得分)的胜/负/平,以及 steps、token、judge 得分的 `B - A` 均值差。两个 run 的 `seed` 是配对的可追溯出处,不保证模型输出一致。
92
95
 
96
+ 配对样本量小、差值不服从正态,所以配对区块除了点估计还给出推断:对主指标的不一致对做**精确双侧符号检验**(同分的对按要求剔除),并在每个均值差旁给出**固定种子 bootstrap 95% 区间**。不对差值分布的形状做任何假设,PRNG 种子固定,因此同一对报告重跑 `compare` 输出逐字节一致。这些 p 值应按"单指标、未做多重比较校正"来读:表里同时列三个指标时,单个略低于 0.05 的 p 只是弱证据。
97
+
93
98
  ## 回放(keyless CI)
94
99
 
95
100
  带 key 的 run 会把每个 trial 的 session 日志记录在其 `tempRoot` 下。把这些录制好的 trial 目录拷进 `replay.dir`,即可在无凭据的情况下重跑:被启动的 harness 会挂载 `@deepseek-ai/dsh-llm-replay`,从录制下来的 `assistant/chunk` 事件重建每一次模型流。
@@ -127,6 +132,7 @@ replay:
127
132
 
128
133
  - **judge 输出是尽力而为** —— judge chat 失败或回复无法解析时,裁决字段为空;judge 调用消耗的模型额度不计入 trial 的计量成本。
129
134
  - **配对对比按现状配对** —— trial 按 case id 与 trial 序号配对;`seed` 是记录下来的出处,并不确定性保证模型输出一致,按实验组(arm)的排行榜尚未渲染。
135
+ - **配对推断未做多重比较校正** —— 符号检验与 bootstrap 区间都是单指标的,未对一次输出里的多个指标做校正;而且符号检验需要不一致对才能给出结论:全部同分的 run 报 `p = 1`。
130
136
  - **回放按首次调用顺序绑定** —— 回放插件按首次调用顺序把录制脚本对应到实时 session,因此并发子 agent 的回放是非确定性的。
131
137
  - **导入的 trace 没有 token 用量** —— Codex 与 Claude Code 日志不记录 provider 用量,导入的 run 报零 token 且无成本。
132
138
  - **超时只杀直接子进程** —— 超时的 trial 只杀直接 dsh 进程;在 Windows 上它的后代进程可能存活。
package/lib/benchmark.js CHANGED
@@ -40,6 +40,7 @@ const benchmarkSchema = z.object({
40
40
  profile: z.string().min(1).default('headless'),
41
41
  command: z.array(z.string().min(1)).default(['dsh']),
42
42
  trials: z.number().int().positive().default(1),
43
+ concurrency: z.number().int().positive().default(1),
43
44
  timeoutMs: z.number().int().positive().default(600_000),
44
45
  seed: z.number().int().default(0),
45
46
  cases: z.array(benchmarkCaseSchema).min(1),
@@ -99,6 +100,7 @@ export async function parseBenchmark(text, baseDir) {
99
100
  profile: parsed.profile,
100
101
  command: parsed.command,
101
102
  trials: parsed.trials,
103
+ concurrency: parsed.concurrency,
102
104
  timeoutMs: parsed.timeoutMs,
103
105
  seed: parsed.seed,
104
106
  cases,
package/lib/command.js CHANGED
@@ -15,6 +15,21 @@ function splitCommand(value) {
15
15
  const command = value.trim().split(/\s+/u).filter(part => part !== '');
16
16
  return command.length === 0 ? undefined : command;
17
17
  }
18
+ /**
19
+ * Build a commander option parser for a positive-integer flag, so `--trials`
20
+ * and `--concurrency` reject the same inputs with the same message shape.
21
+ * @param program - the program to error through.
22
+ * @param flag - the flag name, for the error text.
23
+ * @returns the parser.
24
+ */
25
+ function positiveInteger(program, flag) {
26
+ return (value) => {
27
+ const parsed = Number(value);
28
+ if (!Number.isInteger(parsed) || parsed <= 0)
29
+ program.error(`error: ${flag} must be a positive integer`);
30
+ return parsed;
31
+ };
32
+ }
18
33
  /**
19
34
  * Build a fresh eval commander program. The root action rejects a bare
20
35
  * invocation; the `run` and `report` actions hand the resolved values to the
@@ -36,12 +51,8 @@ export function evalCommand(publish) {
36
51
  run
37
52
  .argument('<benchmark.yaml>', 'path to the benchmark document')
38
53
  .option('--out <path>', 'output run JSON path', 'eval-run.json')
39
- .option('--trials <n>', 'override the benchmark trials count', (value) => {
40
- const parsed = Number(value);
41
- if (!Number.isInteger(parsed) || parsed <= 0)
42
- program.error('error: --trials must be a positive integer');
43
- return parsed;
44
- })
54
+ .option('--trials <n>', 'override the benchmark trials count', positiveInteger(program, '--trials'))
55
+ .option('--concurrency <n>', 'override the in-flight trial limit', positiveInteger(program, '--concurrency'))
45
56
  .option('--dsh <cmd>', 'override the dsh launcher command, space-separated')
46
57
  .option('--profile <name>', 'override the spawned dsh profile')
47
58
  .action((benchmarkPath, options) => {
@@ -51,6 +62,7 @@ export function evalCommand(publish) {
51
62
  benchmarkPath,
52
63
  outPath: options.out,
53
64
  ...(options.trials !== undefined ? { trials: options.trials } : {}),
65
+ ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
54
66
  ...(dshCommand !== undefined ? { dshCommand } : {}),
55
67
  ...(options.profile !== undefined ? { profile: options.profile } : {}),
56
68
  });
package/lib/compare.js CHANGED
@@ -4,6 +4,7 @@
4
4
  *
5
5
  * @module dsh-eval/compare
6
6
  */
7
+ import { pairedDelta, signTest } from "./stats.js";
7
8
  /** Render a nullable number with a dash placeholder. */
8
9
  function formatNumber(value, digits = 1) {
9
10
  return value === null ? '–' : value.toFixed(digits);
@@ -19,6 +20,17 @@ function formatDelta(a, b, unit = '') {
19
20
  const delta = unit === 'pp' ? (b - a) * 100 : b - a;
20
21
  return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`;
21
22
  }
23
+ /** Render a paired delta with its bootstrap interval when the sample allows one. */
24
+ function formatPairedDelta(delta) {
25
+ const mean = formatDelta(0, delta.mean);
26
+ return delta.lower === null || delta.upper === null
27
+ ? mean
28
+ : `${mean} [95% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`;
29
+ }
30
+ /** Render an exact p-value, collapsing anything below the print precision. */
31
+ function formatPValue(pValue) {
32
+ return pValue < 0.001 ? '<0.001' : pValue.toFixed(3);
33
+ }
22
34
  /** Read one trial's primary-metric outcome, or null when the trial lacks it. */
23
35
  function metricOutcome(result, metric) {
24
36
  if (metric === 'task success')
@@ -98,16 +110,16 @@ export function pairedCompare(a, b) {
98
110
  scoreDeltas.push(bScore - aScore);
99
111
  }
100
112
  }
101
- const mean = (values) => values.length === 0 ? null : values.reduce((total, value) => total + value, 0) / values.length;
102
113
  return {
103
114
  pairs: pairs.length,
104
115
  wins,
105
116
  losses,
106
117
  ties,
107
118
  primaryMetric,
108
- meanStepsDelta: mean(stepDeltas),
109
- meanTokensDelta: mean(tokenDeltas),
110
- meanScoreDelta: mean(scoreDeltas),
119
+ test: signTest(wins, losses),
120
+ stepsDelta: pairedDelta(stepDeltas),
121
+ tokensDelta: pairedDelta(tokenDeltas),
122
+ scoreDelta: pairedDelta(scoreDeltas),
111
123
  };
112
124
  }
113
125
  /**
@@ -150,12 +162,17 @@ export function compareRuns(a, b) {
150
162
  a: `${paired.wins}/${paired.losses}/${paired.ties}`,
151
163
  b: '–',
152
164
  delta: '–',
153
- }, ...(paired.meanStepsDelta === null ? [] : [{
154
- metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanStepsDelta),
155
- }]), ...(paired.meanTokensDelta === null ? [] : [{
156
- metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanTokensDelta),
157
- }]), ...(paired.meanScoreDelta === null ? [] : [{
158
- metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanScoreDelta),
165
+ }, {
166
+ metric: `paired ${paired.primaryMetric} p (sign test)`,
167
+ a: '–',
168
+ b: '–',
169
+ delta: `${formatPValue(paired.test.pValue)} (n=${paired.test.discordant})`,
170
+ }, ...(paired.stepsDelta === null ? [] : [{
171
+ metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.stepsDelta),
172
+ }]), ...(paired.tokensDelta === null ? [] : [{
173
+ metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.tokensDelta),
174
+ }]), ...(paired.scoreDelta === null ? [] : [{
175
+ metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.scoreDelta),
159
176
  }]));
160
177
  }
161
178
  return rows;
package/lib/index.js CHANGED
@@ -83,6 +83,7 @@ export async function executeEval(values, io, services = {}) {
83
83
  const benchmark = await loadBenchmark(values.benchmarkPath);
84
84
  const run = await runBenchmark(benchmark, {
85
85
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
86
+ ...(values.concurrency !== undefined ? { concurrency: values.concurrency } : {}),
86
87
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
87
88
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
88
89
  ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
package/lib/runner.js CHANGED
@@ -284,7 +284,16 @@ async function runCaseTrial(benchmark, caseValue, trial, root, judgeChat) {
284
284
  }
285
285
  }
286
286
  /**
287
- * Run every case x trial sequentially and aggregate the completed trials.
287
+ * Run every case x trial through a bounded worker pool and aggregate the
288
+ * completed trials.
289
+ *
290
+ * Trials are independent by construction — each owns a private temp directory,
291
+ * workspace copy, and DSH_HOME — so the only thing serial execution buys is
292
+ * determinism. The pool keeps that anyway: results land at their task index, so
293
+ * the run record stays in case-then-trial order no matter how the workers
294
+ * interleave. The first failure to escape `runCaseTrial` stops the remaining
295
+ * workers and rejects the run, which is the same contract as the serial loop.
296
+ *
288
297
  * @param benchmark - the loaded benchmark.
289
298
  * @param options - runtime overrides and test seams.
290
299
  * @returns the completed run record, written by the caller.
@@ -302,13 +311,33 @@ export async function runBenchmark(benchmark, options = {}) {
302
311
  ...benchmark,
303
312
  ...(options.profile !== undefined ? { profile: options.profile } : {}),
304
313
  ...(options.command !== undefined ? { command: options.command } : {}),
314
+ ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
305
315
  };
306
- const results = [];
316
+ const tasks = [];
307
317
  for (const caseValue of effective.cases) {
308
- for (let trial = 1; trial <= trials; trial++) {
309
- results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat));
310
- }
318
+ for (let trial = 1; trial <= trials; trial++)
319
+ tasks.push({ caseValue, trial });
311
320
  }
321
+ const results = Array.from({ length: tasks.length });
322
+ let failure;
323
+ let cursor = 0;
324
+ const worker = async () => {
325
+ while (failure === undefined) {
326
+ const index = cursor++;
327
+ const task = tasks[index];
328
+ if (task === undefined)
329
+ return;
330
+ try {
331
+ results[index] = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat);
332
+ }
333
+ catch (error) {
334
+ failure = { error };
335
+ }
336
+ }
337
+ };
338
+ await Promise.all(Array.from({ length: Math.min(effective.concurrency, tasks.length) }, worker));
339
+ if (failure !== undefined)
340
+ throw failure.error;
312
341
  const completed = results.filter((result) => result.status === 'completed' && result.metrics !== undefined);
313
342
  return {
314
343
  benchmark: benchmark.name,
package/lib/stats.js ADDED
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Paired-comparison statistics for cross-run reports: an exact two-sided sign
3
+ * test over paired outcomes, and a seeded bootstrap confidence interval for a
4
+ * paired mean delta.
5
+ *
6
+ * Both are distribution-free on purpose. A benchmark run yields few paired
7
+ * trials (single digits to low tens), the per-trial deltas are integers with
8
+ * long tails, and the question is "on the same case, did B beat A" — which a
9
+ * paired sign test answers exactly, without a normality or symmetry assumption
10
+ * the data cannot support. Ties carry no sign and drop out of the test, as the
11
+ * sign test requires.
12
+ *
13
+ * The bootstrap resamples the observed deltas with replacement, so its interval
14
+ * needs no shape assumption either, and it is seeded so that re-running
15
+ * `compare` on the same reports prints a byte-identical table.
16
+ *
17
+ * @module dsh-eval/stats
18
+ */
19
+ /**
20
+ * Log of the binomial coefficient, accumulated rather than factorized so large
21
+ * pair counts stay finite.
22
+ * @param n - trials.
23
+ * @param k - successes, at most n.
24
+ * @returns `ln C(n, k)`.
25
+ */
26
+ function logChoose(n, k) {
27
+ let value = 0;
28
+ for (let index = 0; index < k; index++) {
29
+ value += Math.log(n - index) - Math.log(index + 1);
30
+ }
31
+ return value;
32
+ }
33
+ /**
34
+ * Exact two-sided sign test. Under the null hypothesis a discordant pair is a
35
+ * win or a loss with equal probability, so the win count is Binomial(n, 1/2)
36
+ * and the p-value doubles the smaller tail.
37
+ * @param wins - pairs where B beat A.
38
+ * @param losses - pairs where A beat B.
39
+ * @returns the discordant count and the exact p-value in `[0, 1]`.
40
+ */
41
+ export function signTest(wins, losses) {
42
+ const discordant = wins + losses;
43
+ if (discordant === 0)
44
+ return { discordant, pValue: 1 };
45
+ const tail = Math.min(wins, losses);
46
+ const halfPow = discordant * Math.log(2);
47
+ let cumulative = 0;
48
+ for (let index = 0; index <= tail; index++) {
49
+ cumulative += Math.exp(logChoose(discordant, index) - halfPow);
50
+ }
51
+ return { discordant, pValue: Math.min(1, 2 * cumulative) };
52
+ }
53
+ /**
54
+ * Small deterministic PRNG (mulberry32): identical seeds must produce identical
55
+ * intervals, otherwise `compare` output would drift between runs.
56
+ * @param seed - any integer.
57
+ * @returns a generator of floats in `[0, 1)`.
58
+ */
59
+ function prng(seed) {
60
+ let state = seed >>> 0;
61
+ return () => {
62
+ state = (state + 0x6d2b79f5) >>> 0;
63
+ let value = state;
64
+ value = Math.imul(value ^ (value >>> 15), value | 1);
65
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
66
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
67
+ };
68
+ }
69
+ /**
70
+ * Percentile of a sorted sample, linearly interpolated between neighbours.
71
+ * @param sorted - ascending values, non-empty.
72
+ * @param q - quantile in `[0, 1]`.
73
+ * @returns the interpolated value.
74
+ */
75
+ function quantile(sorted, q) {
76
+ const position = (sorted.length - 1) * q;
77
+ const low = Math.floor(position);
78
+ const weight = position - low;
79
+ return sorted[low] * (1 - weight) + sorted[Math.ceil(position)] * weight;
80
+ }
81
+ /**
82
+ * Mean paired delta with a percentile bootstrap interval.
83
+ * @param deltas - per-pair differences (`b - a`).
84
+ * @param options - confidence, resample count, and PRNG seed.
85
+ * @returns the mean and interval, or null when `deltas` is empty.
86
+ */
87
+ export function pairedDelta(deltas, options = {}) {
88
+ if (deltas.length === 0)
89
+ return null;
90
+ const mean = deltas.reduce((total, value) => total + value, 0) / deltas.length;
91
+ if (deltas.length === 1)
92
+ return { mean, lower: null, upper: null, pairs: 1 };
93
+ const confidence = options.confidence ?? 0.95;
94
+ const resamples = options.resamples ?? 2000;
95
+ const random = prng(options.seed ?? 0);
96
+ const means = [];
97
+ for (let resample = 0; resample < resamples; resample++) {
98
+ let total = 0;
99
+ for (let draw = 0; draw < deltas.length; draw++) {
100
+ total += deltas[Math.floor(random() * deltas.length)];
101
+ }
102
+ means.push(total / deltas.length);
103
+ }
104
+ means.sort((a, b) => a - b);
105
+ const alpha = (1 - confidence) / 2;
106
+ return {
107
+ mean,
108
+ lower: quantile(means, alpha),
109
+ upper: quantile(means, 1 - alpha),
110
+ pairs: deltas.length,
111
+ };
112
+ }
@@ -15,6 +15,7 @@ export type EvalStartupValues = {
15
15
  benchmarkPath: string;
16
16
  outPath: string;
17
17
  trials?: number;
18
+ concurrency?: number;
18
19
  dshCommand?: readonly string[];
19
20
  profile?: string;
20
21
  } | {
@@ -5,6 +5,7 @@
5
5
  * @module dsh-eval/compare
6
6
  */
7
7
  import type { EvalRun } from './types.ts';
8
+ import { type PairedDelta, type SignTestOutcome } from './stats.ts';
8
9
  /** One compared metric row. */
9
10
  export interface CompareRow {
10
11
  /** Metric label. */
@@ -28,12 +29,14 @@ export interface PairedStats {
28
29
  ties: number;
29
30
  /** The metric used for win/lose/tie classification. */
30
31
  primaryMetric: 'task success' | 'tool selection accuracy' | 'final answer score';
31
- /** Mean per-pair step delta (`b - a`), or null when no pair is numeric. */
32
- meanStepsDelta: number | null;
33
- /** Mean per-pair token delta (`b - a`), or null when no pair is numeric. */
34
- meanTokensDelta: number | null;
35
- /** Mean per-pair judge score delta (`b - a`), or null without judge verdicts. */
36
- meanScoreDelta: number | null;
32
+ /** Exact two-sided sign test over the discordant pairs of the primary metric. */
33
+ test: SignTestOutcome;
34
+ /** Paired step delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
35
+ stepsDelta: PairedDelta | null;
36
+ /** Paired token delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
37
+ tokensDelta: PairedDelta | null;
38
+ /** Paired judge-score delta (`b - a`) with its bootstrap interval, or null without verdicts. */
39
+ scoreDelta: PairedDelta | null;
37
40
  }
38
41
  /**
39
42
  * Pair both runs' trials by case id and trial index and compute win/lose/tie
@@ -22,13 +22,24 @@ export interface RunOptions {
22
22
  profile?: string;
23
23
  /** Override the benchmark's trials per case. */
24
24
  trials?: number;
25
+ /** Override the benchmark's in-flight trial limit. */
26
+ concurrency?: number;
25
27
  /** Root for trial directories; defaults to the platform temp dir. */
26
28
  tempRoot?: string;
27
29
  /** LLM-judge chat seam; required when the benchmark configures a judge. */
28
30
  judgeChat?: JudgeChat;
29
31
  }
30
32
  /**
31
- * Run every case x trial sequentially and aggregate the completed trials.
33
+ * Run every case x trial through a bounded worker pool and aggregate the
34
+ * completed trials.
35
+ *
36
+ * Trials are independent by construction — each owns a private temp directory,
37
+ * workspace copy, and DSH_HOME — so the only thing serial execution buys is
38
+ * determinism. The pool keeps that anyway: results land at their task index, so
39
+ * the run record stays in case-then-trial order no matter how the workers
40
+ * interleave. The first failure to escape `runCaseTrial` stops the remaining
41
+ * workers and rejects the run, which is the same contract as the serial loop.
42
+ *
32
43
  * @param benchmark - the loaded benchmark.
33
44
  * @param options - runtime overrides and test seams.
34
45
  * @returns the completed run record, written by the caller.
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Paired-comparison statistics for cross-run reports: an exact two-sided sign
3
+ * test over paired outcomes, and a seeded bootstrap confidence interval for a
4
+ * paired mean delta.
5
+ *
6
+ * Both are distribution-free on purpose. A benchmark run yields few paired
7
+ * trials (single digits to low tens), the per-trial deltas are integers with
8
+ * long tails, and the question is "on the same case, did B beat A" — which a
9
+ * paired sign test answers exactly, without a normality or symmetry assumption
10
+ * the data cannot support. Ties carry no sign and drop out of the test, as the
11
+ * sign test requires.
12
+ *
13
+ * The bootstrap resamples the observed deltas with replacement, so its interval
14
+ * needs no shape assumption either, and it is seeded so that re-running
15
+ * `compare` on the same reports prints a byte-identical table.
16
+ *
17
+ * @module dsh-eval/stats
18
+ */
19
+ /** Outcome of an exact two-sided sign test. */
20
+ export interface SignTestOutcome {
21
+ /** Discordant pairs (`wins + losses`); ties drop out of the test. */
22
+ discordant: number;
23
+ /** Exact two-sided p-value; 1 when every pair tied. */
24
+ pValue: number;
25
+ }
26
+ /** A paired mean delta with its bootstrap interval. */
27
+ export interface PairedDelta {
28
+ /** Mean per-pair delta (`b - a`). */
29
+ mean: number;
30
+ /** Lower interval bound, or null when fewer than two pairs are available. */
31
+ lower: number | null;
32
+ /** Upper interval bound, or null when fewer than two pairs are available. */
33
+ upper: number | null;
34
+ /** Pairs contributing to the mean. */
35
+ pairs: number;
36
+ }
37
+ /** Knobs for {@link pairedDelta}; defaults keep reports reproducible. */
38
+ export interface BootstrapOptions {
39
+ /** Interval confidence, default `0.95`. */
40
+ confidence?: number;
41
+ /** Resample count, default `2000`. */
42
+ resamples?: number;
43
+ /** PRNG seed, default `0`. */
44
+ seed?: number;
45
+ }
46
+ /**
47
+ * Exact two-sided sign test. Under the null hypothesis a discordant pair is a
48
+ * win or a loss with equal probability, so the win count is Binomial(n, 1/2)
49
+ * and the p-value doubles the smaller tail.
50
+ * @param wins - pairs where B beat A.
51
+ * @param losses - pairs where A beat B.
52
+ * @returns the discordant count and the exact p-value in `[0, 1]`.
53
+ */
54
+ export declare function signTest(wins: number, losses: number): SignTestOutcome;
55
+ /**
56
+ * Mean paired delta with a percentile bootstrap interval.
57
+ * @param deltas - per-pair differences (`b - a`).
58
+ * @param options - confidence, resample count, and PRNG seed.
59
+ * @returns the mean and interval, or null when `deltas` is empty.
60
+ */
61
+ export declare function pairedDelta(deltas: readonly number[], options?: BootstrapOptions): PairedDelta | null;
@@ -67,6 +67,8 @@ export interface Benchmark {
67
67
  command: readonly string[];
68
68
  /** Trials per case. */
69
69
  trials: number;
70
+ /** Case x trial executions allowed in flight at once; defaults to 1 (serial). */
71
+ concurrency: number;
70
72
  /** Per-trial timeout in milliseconds. */
71
73
  timeoutMs: number;
72
74
  /** Reserved deterministic seed for future paired comparisons. */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-eval",
3
3
  "description": "Agent evaluation platform: benchmark YAML, headless run orchestration, trace-based metrics, and run reports",
4
- "version": "0.3.1",
4
+ "version": "0.4.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -9,6 +9,10 @@
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/hccccc01333/dsh-eval.git"
11
11
  },
12
+ "homepage": "https://github.com/hccccc01333/dsh-eval#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/hccccc01333/dsh-eval/issues"
15
+ },
12
16
  "type": "module",
13
17
  "main": "lib/index.js",
14
18
  "types": "lib/types/index.d.ts",
package/src/benchmark.ts CHANGED
@@ -53,6 +53,7 @@ const benchmarkSchema = z.object({
53
53
  profile: z.string().min(1).default('headless'),
54
54
  command: z.array(z.string().min(1)).default(['dsh']),
55
55
  trials: z.number().int().positive().default(1),
56
+ concurrency: z.number().int().positive().default(1),
56
57
  timeoutMs: z.number().int().positive().default(600_000),
57
58
  seed: z.number().int().default(0),
58
59
  cases: z.array(benchmarkCaseSchema).min(1),
@@ -117,6 +118,7 @@ export async function parseBenchmark(text: string, baseDir: string): Promise<Ben
117
118
  profile: parsed.profile,
118
119
  command: parsed.command,
119
120
  trials: parsed.trials,
121
+ concurrency: parsed.concurrency,
120
122
  timeoutMs: parsed.timeoutMs,
121
123
  seed: parsed.seed,
122
124
  cases,
package/src/command.ts CHANGED
@@ -19,6 +19,7 @@ export type EvalStartupValues =
19
19
  benchmarkPath: string
20
20
  outPath: string
21
21
  trials?: number
22
+ concurrency?: number
22
23
  dshCommand?: readonly string[]
23
24
  profile?: string
24
25
  }
@@ -43,6 +44,7 @@ export type EvalStartupValues =
43
44
  interface RunCommandOptions {
44
45
  out: string
45
46
  trials?: number
47
+ concurrency?: number
46
48
  dsh?: string
47
49
  profile?: string
48
50
  }
@@ -60,6 +62,21 @@ function splitCommand(value: string | undefined): readonly string[] | undefined
60
62
  return command.length === 0 ? undefined : command
61
63
  }
62
64
 
65
+ /**
66
+ * Build a commander option parser for a positive-integer flag, so `--trials`
67
+ * and `--concurrency` reject the same inputs with the same message shape.
68
+ * @param program - the program to error through.
69
+ * @param flag - the flag name, for the error text.
70
+ * @returns the parser.
71
+ */
72
+ function positiveInteger(program: Command, flag: string): (value: string) => number {
73
+ return (value) => {
74
+ const parsed = Number(value)
75
+ if (!Number.isInteger(parsed) || parsed <= 0) program.error(`error: ${flag} must be a positive integer`)
76
+ return parsed
77
+ }
78
+ }
79
+
63
80
  /**
64
81
  * Build a fresh eval commander program. The root action rejects a bare
65
82
  * invocation; the `run` and `report` actions hand the resolved values to the
@@ -81,11 +98,8 @@ export function evalCommand(publish: (values: EvalStartupValues) => void): Comma
81
98
  run
82
99
  .argument('<benchmark.yaml>', 'path to the benchmark document')
83
100
  .option('--out <path>', 'output run JSON path', 'eval-run.json')
84
- .option('--trials <n>', 'override the benchmark trials count', (value) => {
85
- const parsed = Number(value)
86
- if (!Number.isInteger(parsed) || parsed <= 0) program.error('error: --trials must be a positive integer')
87
- return parsed
88
- })
101
+ .option('--trials <n>', 'override the benchmark trials count', positiveInteger(program, '--trials'))
102
+ .option('--concurrency <n>', 'override the in-flight trial limit', positiveInteger(program, '--concurrency'))
89
103
  .option('--dsh <cmd>', 'override the dsh launcher command, space-separated')
90
104
  .option('--profile <name>', 'override the spawned dsh profile')
91
105
  .action((benchmarkPath: string, options: RunCommandOptions) => {
@@ -95,6 +109,7 @@ export function evalCommand(publish: (values: EvalStartupValues) => void): Comma
95
109
  benchmarkPath,
96
110
  outPath: options.out,
97
111
  ...(options.trials !== undefined ? { trials: options.trials } : {}),
112
+ ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
98
113
  ...(dshCommand !== undefined ? { dshCommand } : {}),
99
114
  ...(options.profile !== undefined ? { profile: options.profile } : {}),
100
115
  })
package/src/compare.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { EvalRun, EvalTrialResult } from './types.ts'
9
+ import { pairedDelta, signTest, type PairedDelta, type SignTestOutcome } from './stats.ts'
9
10
 
10
11
  /** One compared metric row. */
11
12
  export interface CompareRow {
@@ -31,12 +32,14 @@ export interface PairedStats {
31
32
  ties: number
32
33
  /** The metric used for win/lose/tie classification. */
33
34
  primaryMetric: 'task success' | 'tool selection accuracy' | 'final answer score'
34
- /** Mean per-pair step delta (`b - a`), or null when no pair is numeric. */
35
- meanStepsDelta: number | null
36
- /** Mean per-pair token delta (`b - a`), or null when no pair is numeric. */
37
- meanTokensDelta: number | null
38
- /** Mean per-pair judge score delta (`b - a`), or null without judge verdicts. */
39
- meanScoreDelta: number | null
35
+ /** Exact two-sided sign test over the discordant pairs of the primary metric. */
36
+ test: SignTestOutcome
37
+ /** Paired step delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
38
+ stepsDelta: PairedDelta | null
39
+ /** Paired token delta (`b - a`) with its bootstrap interval, or null when no pair is numeric. */
40
+ tokensDelta: PairedDelta | null
41
+ /** Paired judge-score delta (`b - a`) with its bootstrap interval, or null without verdicts. */
42
+ scoreDelta: PairedDelta | null
40
43
  }
41
44
 
42
45
  /** Render a nullable number with a dash placeholder. */
@@ -56,6 +59,19 @@ function formatDelta(a: number | null, b: number | null, unit: 'pp' | '' = ''):
56
59
  return `${delta >= 0 ? '+' : ''}${delta.toFixed(1)}${unit}`
57
60
  }
58
61
 
62
+ /** Render a paired delta with its bootstrap interval when the sample allows one. */
63
+ function formatPairedDelta(delta: PairedDelta): string {
64
+ const mean = formatDelta(0, delta.mean)
65
+ return delta.lower === null || delta.upper === null
66
+ ? mean
67
+ : `${mean} [95% CI ${formatDelta(0, delta.lower)}, ${formatDelta(0, delta.upper)}]`
68
+ }
69
+
70
+ /** Render an exact p-value, collapsing anything below the print precision. */
71
+ function formatPValue(pValue: number): string {
72
+ return pValue < 0.001 ? '<0.001' : pValue.toFixed(3)
73
+ }
74
+
59
75
  /** A metric that can classify a paired winner. */
60
76
  type PairedMetric = 'task success' | 'tool selection accuracy' | 'final answer score'
61
77
 
@@ -133,17 +149,16 @@ export function pairedCompare(a: EvalRun, b: EvalRun): PairedStats | null {
133
149
  scoreDeltas.push(bScore - aScore)
134
150
  }
135
151
  }
136
- const mean = (values: readonly number[]): number | null =>
137
- values.length === 0 ? null : values.reduce((total, value) => total + value, 0) / values.length
138
152
  return {
139
153
  pairs: pairs.length,
140
154
  wins,
141
155
  losses,
142
156
  ties,
143
157
  primaryMetric,
144
- meanStepsDelta: mean(stepDeltas),
145
- meanTokensDelta: mean(tokenDeltas),
146
- meanScoreDelta: mean(scoreDeltas),
158
+ test: signTest(wins, losses),
159
+ stepsDelta: pairedDelta(stepDeltas),
160
+ tokensDelta: pairedDelta(tokenDeltas),
161
+ scoreDelta: pairedDelta(scoreDeltas),
147
162
  }
148
163
  }
149
164
 
@@ -193,14 +208,20 @@ export function compareRuns(a: EvalRun, b: EvalRun): CompareRow[] {
193
208
  b: '–',
194
209
  delta: '–',
195
210
  },
196
- ...(paired.meanStepsDelta === null ? [] : [{
197
- metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanStepsDelta),
211
+ {
212
+ metric: `paired ${paired.primaryMetric} p (sign test)`,
213
+ a: '–',
214
+ b: '–',
215
+ delta: `${formatPValue(paired.test.pValue)} (n=${paired.test.discordant})`,
216
+ },
217
+ ...(paired.stepsDelta === null ? [] : [{
218
+ metric: 'paired steps delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.stepsDelta),
198
219
  }]),
199
- ...(paired.meanTokensDelta === null ? [] : [{
200
- metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanTokensDelta),
220
+ ...(paired.tokensDelta === null ? [] : [{
221
+ metric: 'paired tokens delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.tokensDelta),
201
222
  }]),
202
- ...(paired.meanScoreDelta === null ? [] : [{
203
- metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatDelta(0, paired.meanScoreDelta),
223
+ ...(paired.scoreDelta === null ? [] : [{
224
+ metric: 'paired final-answer delta (B-A)', a: '–', b: '–', delta: formatPairedDelta(paired.scoreDelta),
204
225
  }]),
205
226
  )
206
227
  }
package/src/index.ts CHANGED
@@ -99,6 +99,7 @@ export async function executeEval(
99
99
  const benchmark = await loadBenchmark(values.benchmarkPath)
100
100
  const run = await runBenchmark(benchmark, {
101
101
  ...(values.trials !== undefined ? { trials: values.trials } : {}),
102
+ ...(values.concurrency !== undefined ? { concurrency: values.concurrency } : {}),
102
103
  ...(values.dshCommand !== undefined ? { command: values.dshCommand } : {}),
103
104
  ...(values.profile !== undefined ? { profile: values.profile } : {}),
104
105
  ...(services.judgeChat !== undefined ? { judgeChat: services.judgeChat } : {}),
package/src/runner.ts CHANGED
@@ -34,6 +34,8 @@ export interface RunOptions {
34
34
  profile?: string
35
35
  /** Override the benchmark's trials per case. */
36
36
  trials?: number
37
+ /** Override the benchmark's in-flight trial limit. */
38
+ concurrency?: number
37
39
  /** Root for trial directories; defaults to the platform temp dir. */
38
40
  tempRoot?: string
39
41
  /** LLM-judge chat seam; required when the benchmark configures a judge. */
@@ -343,7 +345,16 @@ async function runCaseTrial(
343
345
  }
344
346
 
345
347
  /**
346
- * Run every case x trial sequentially and aggregate the completed trials.
348
+ * Run every case x trial through a bounded worker pool and aggregate the
349
+ * completed trials.
350
+ *
351
+ * Trials are independent by construction — each owns a private temp directory,
352
+ * workspace copy, and DSH_HOME — so the only thing serial execution buys is
353
+ * determinism. The pool keeps that anyway: results land at their task index, so
354
+ * the run record stays in case-then-trial order no matter how the workers
355
+ * interleave. The first failure to escape `runCaseTrial` stops the remaining
356
+ * workers and rejects the run, which is the same contract as the serial loop.
357
+ *
347
358
  * @param benchmark - the loaded benchmark.
348
359
  * @param options - runtime overrides and test seams.
349
360
  * @returns the completed run record, written by the caller.
@@ -361,13 +372,29 @@ export async function runBenchmark(benchmark: Benchmark, options: RunOptions = {
361
372
  ...benchmark,
362
373
  ...(options.profile !== undefined ? { profile: options.profile } : {}),
363
374
  ...(options.command !== undefined ? { command: options.command } : {}),
375
+ ...(options.concurrency !== undefined ? { concurrency: options.concurrency } : {}),
364
376
  }
365
- const results: EvalTrialResult[] = []
377
+ const tasks: { caseValue: Benchmark['cases'][number]; trial: number }[] = []
366
378
  for (const caseValue of effective.cases) {
367
- for (let trial = 1; trial <= trials; trial++) {
368
- results.push(await runCaseTrial(effective, caseValue, trial, root, options.judgeChat))
379
+ for (let trial = 1; trial <= trials; trial++) tasks.push({ caseValue, trial })
380
+ }
381
+ const results: EvalTrialResult[] = Array.from({ length: tasks.length })
382
+ let failure: { error: unknown } | undefined
383
+ let cursor = 0
384
+ const worker = async (): Promise<void> => {
385
+ while (failure === undefined) {
386
+ const index = cursor++
387
+ const task = tasks[index]
388
+ if (task === undefined) return
389
+ try {
390
+ results[index] = await runCaseTrial(effective, task.caseValue, task.trial, root, options.judgeChat)
391
+ } catch (error) {
392
+ failure = { error }
393
+ }
369
394
  }
370
395
  }
396
+ await Promise.all(Array.from({ length: Math.min(effective.concurrency, tasks.length) }, worker))
397
+ if (failure !== undefined) throw failure.error
371
398
  const completed = results.filter(
372
399
  (result): result is EvalTrialResult & { metrics: NonNullable<EvalTrialResult['metrics']> } =>
373
400
  result.status === 'completed' && result.metrics !== undefined,
package/src/stats.ts ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Paired-comparison statistics for cross-run reports: an exact two-sided sign
3
+ * test over paired outcomes, and a seeded bootstrap confidence interval for a
4
+ * paired mean delta.
5
+ *
6
+ * Both are distribution-free on purpose. A benchmark run yields few paired
7
+ * trials (single digits to low tens), the per-trial deltas are integers with
8
+ * long tails, and the question is "on the same case, did B beat A" — which a
9
+ * paired sign test answers exactly, without a normality or symmetry assumption
10
+ * the data cannot support. Ties carry no sign and drop out of the test, as the
11
+ * sign test requires.
12
+ *
13
+ * The bootstrap resamples the observed deltas with replacement, so its interval
14
+ * needs no shape assumption either, and it is seeded so that re-running
15
+ * `compare` on the same reports prints a byte-identical table.
16
+ *
17
+ * @module dsh-eval/stats
18
+ */
19
+
20
+ /** Outcome of an exact two-sided sign test. */
21
+ export interface SignTestOutcome {
22
+ /** Discordant pairs (`wins + losses`); ties drop out of the test. */
23
+ discordant: number
24
+ /** Exact two-sided p-value; 1 when every pair tied. */
25
+ pValue: number
26
+ }
27
+
28
+ /** A paired mean delta with its bootstrap interval. */
29
+ export interface PairedDelta {
30
+ /** Mean per-pair delta (`b - a`). */
31
+ mean: number
32
+ /** Lower interval bound, or null when fewer than two pairs are available. */
33
+ lower: number | null
34
+ /** Upper interval bound, or null when fewer than two pairs are available. */
35
+ upper: number | null
36
+ /** Pairs contributing to the mean. */
37
+ pairs: number
38
+ }
39
+
40
+ /** Knobs for {@link pairedDelta}; defaults keep reports reproducible. */
41
+ export interface BootstrapOptions {
42
+ /** Interval confidence, default `0.95`. */
43
+ confidence?: number
44
+ /** Resample count, default `2000`. */
45
+ resamples?: number
46
+ /** PRNG seed, default `0`. */
47
+ seed?: number
48
+ }
49
+
50
+ /**
51
+ * Log of the binomial coefficient, accumulated rather than factorized so large
52
+ * pair counts stay finite.
53
+ * @param n - trials.
54
+ * @param k - successes, at most n.
55
+ * @returns `ln C(n, k)`.
56
+ */
57
+ function logChoose(n: number, k: number): number {
58
+ let value = 0
59
+ for (let index = 0; index < k; index++) {
60
+ value += Math.log(n - index) - Math.log(index + 1)
61
+ }
62
+ return value
63
+ }
64
+
65
+ /**
66
+ * Exact two-sided sign test. Under the null hypothesis a discordant pair is a
67
+ * win or a loss with equal probability, so the win count is Binomial(n, 1/2)
68
+ * and the p-value doubles the smaller tail.
69
+ * @param wins - pairs where B beat A.
70
+ * @param losses - pairs where A beat B.
71
+ * @returns the discordant count and the exact p-value in `[0, 1]`.
72
+ */
73
+ export function signTest(wins: number, losses: number): SignTestOutcome {
74
+ const discordant = wins + losses
75
+ if (discordant === 0) return { discordant, pValue: 1 }
76
+ const tail = Math.min(wins, losses)
77
+ const halfPow = discordant * Math.log(2)
78
+ let cumulative = 0
79
+ for (let index = 0; index <= tail; index++) {
80
+ cumulative += Math.exp(logChoose(discordant, index) - halfPow)
81
+ }
82
+ return { discordant, pValue: Math.min(1, 2 * cumulative) }
83
+ }
84
+
85
+ /**
86
+ * Small deterministic PRNG (mulberry32): identical seeds must produce identical
87
+ * intervals, otherwise `compare` output would drift between runs.
88
+ * @param seed - any integer.
89
+ * @returns a generator of floats in `[0, 1)`.
90
+ */
91
+ function prng(seed: number): () => number {
92
+ let state = seed >>> 0
93
+ return () => {
94
+ state = (state + 0x6d2b79f5) >>> 0
95
+ let value = state
96
+ value = Math.imul(value ^ (value >>> 15), value | 1)
97
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61)
98
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Percentile of a sorted sample, linearly interpolated between neighbours.
104
+ * @param sorted - ascending values, non-empty.
105
+ * @param q - quantile in `[0, 1]`.
106
+ * @returns the interpolated value.
107
+ */
108
+ function quantile(sorted: readonly number[], q: number): number {
109
+ const position = (sorted.length - 1) * q
110
+ const low = Math.floor(position)
111
+ const weight = position - low
112
+ return sorted[low]! * (1 - weight) + sorted[Math.ceil(position)]! * weight
113
+ }
114
+
115
+ /**
116
+ * Mean paired delta with a percentile bootstrap interval.
117
+ * @param deltas - per-pair differences (`b - a`).
118
+ * @param options - confidence, resample count, and PRNG seed.
119
+ * @returns the mean and interval, or null when `deltas` is empty.
120
+ */
121
+ export function pairedDelta(
122
+ deltas: readonly number[],
123
+ options: BootstrapOptions = {},
124
+ ): PairedDelta | null {
125
+ if (deltas.length === 0) return null
126
+ const mean = deltas.reduce((total, value) => total + value, 0) / deltas.length
127
+ if (deltas.length === 1) return { mean, lower: null, upper: null, pairs: 1 }
128
+ const confidence = options.confidence ?? 0.95
129
+ const resamples = options.resamples ?? 2000
130
+ const random = prng(options.seed ?? 0)
131
+ const means: number[] = []
132
+ for (let resample = 0; resample < resamples; resample++) {
133
+ let total = 0
134
+ for (let draw = 0; draw < deltas.length; draw++) {
135
+ total += deltas[Math.floor(random() * deltas.length)]!
136
+ }
137
+ means.push(total / deltas.length)
138
+ }
139
+ means.sort((a, b) => a - b)
140
+ const alpha = (1 - confidence) / 2
141
+ return {
142
+ mean,
143
+ lower: quantile(means, alpha),
144
+ upper: quantile(means, 1 - alpha),
145
+ pairs: deltas.length,
146
+ }
147
+ }
package/src/types.ts CHANGED
@@ -74,6 +74,8 @@ export interface Benchmark {
74
74
  command: readonly string[]
75
75
  /** Trials per case. */
76
76
  trials: number
77
+ /** Case x trial executions allowed in flight at once; defaults to 1 (serial). */
78
+ concurrency: number
77
79
  /** Per-trial timeout in milliseconds. */
78
80
  timeoutMs: number
79
81
  /** Reserved deterministic seed for future paired comparisons. */