@agentswf/lab 0.0.0-stage → 0.3.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/LICENSE +21 -0
- package/README.md +15 -2
- package/package.json +46 -4
- package/schema/case-check.schema.json +64 -0
- package/schema/case-config.schema.json +187 -0
- package/schema/case-final.schema.json +48 -0
- package/schema/case-good-record.schema.json +70 -0
- package/schema/case-grade.schema.json +49 -0
- package/schema/case-key.schema.json +117 -0
- package/schema/case-label.schema.json +32 -0
- package/schema/case-loop-report.schema.json +210 -0
- package/schema/case-loop.schema.json +141 -0
- package/schema/case-plan.schema.json +117 -0
- package/schema/case-previous.schema.json +70 -0
- package/schema/case-proposal.schema.json +52 -0
- package/schema/case-report.schema.json +892 -0
- package/schema/case-run.schema.json +253 -0
- package/schema/case-runs.schema.json +125 -0
- package/schema/case-score.schema.json +319 -0
- package/schema/case-spread.schema.json +110 -0
- package/schema/case-trial.schema.json +543 -0
- package/schema/case-try.schema.json +113 -0
- package/schema/local.json +155 -0
- package/src/cli.ts +9 -0
- package/src/env/capture.ts +48 -0
- package/src/env/compare.ts +201 -0
- package/src/env/facts.ts +51 -0
- package/src/env/fetch.ts +57 -0
- package/src/env/files.ts +228 -0
- package/src/env/grade-case.ts +80 -0
- package/src/env/grade-helper.ts +352 -0
- package/src/env/grader.ts +128 -0
- package/src/env/index.ts +727 -0
- package/src/env/mock.ts +374 -0
- package/src/env/routes.ts +90 -0
- package/src/env/sources.ts +19 -0
- package/src/env/state.ts +79 -0
- package/src/env/trial.ts +182 -0
- package/src/format/key.ts +144 -0
- package/src/format/loop.ts +178 -0
- package/src/format/output.ts +481 -0
- package/src/format/records.ts +440 -0
- package/src/format/schema-files.ts +64 -0
- package/src/format/settings.ts +552 -0
- package/src/format/trial-env.ts +64 -0
- package/src/format/trial-file.ts +134 -0
- package/src/help/awf-lab.txt +29 -0
- package/src/help/case.txt +38 -0
- package/src/help/config.txt +14 -0
- package/src/help/label.txt +12 -0
- package/src/help/loop.txt +44 -0
- package/src/help/report.txt +20 -0
- package/src/help/run.txt +60 -0
- package/src/help/runs.txt +10 -0
- package/src/help/score.txt +27 -0
- package/src/judge/criteria.workflow.ts +237 -0
- package/src/judge/version.ts +6 -0
- package/src/lab/answer.ts +47 -0
- package/src/lab/blame.ts +204 -0
- package/src/lab/box.ts +249 -0
- package/src/lab/capture-command.ts +298 -0
- package/src/lab/capture.ts +234 -0
- package/src/lab/check-command.ts +187 -0
- package/src/lab/cli.ts +324 -0
- package/src/lab/code-graders.ts +108 -0
- package/src/lab/columns.ts +138 -0
- package/src/lab/command-context.ts +436 -0
- package/src/lab/compare.ts +123 -0
- package/src/lab/config-command.ts +278 -0
- package/src/lab/criteria.ts +69 -0
- package/src/lab/dataset.ts +356 -0
- package/src/lab/eval-files.ts +185 -0
- package/src/lab/expect.ts +79 -0
- package/src/lab/facts.ts +59 -0
- package/src/lab/families.ts +32 -0
- package/src/lab/folders.ts +153 -0
- package/src/lab/git.ts +128 -0
- package/src/lab/good.ts +224 -0
- package/src/lab/grading-stub.txt +8 -0
- package/src/lab/grading.ts +332 -0
- package/src/lab/inspect.ts +226 -0
- package/src/lab/labels.ts +206 -0
- package/src/lab/loop-code.ts +255 -0
- package/src/lab/loop-command.ts +770 -0
- package/src/lab/loop-records.ts +144 -0
- package/src/lab/loop.ts +859 -0
- package/src/lab/marker.ts +23 -0
- package/src/lab/outcome.ts +196 -0
- package/src/lab/pooled.ts +106 -0
- package/src/lab/project-env.ts +39 -0
- package/src/lab/rates.ts +150 -0
- package/src/lab/reach.ts +111 -0
- package/src/lab/record-copies.ts +202 -0
- package/src/lab/refusal.ts +2 -0
- package/src/lab/report-command.ts +156 -0
- package/src/lab/report.ts +838 -0
- package/src/lab/reuse.ts +126 -0
- package/src/lab/run-command.ts +853 -0
- package/src/lab/run-logs.ts +89 -0
- package/src/lab/run-report.ts +259 -0
- package/src/lab/runs-command.ts +163 -0
- package/src/lab/runs.ts +172 -0
- package/src/lab/scaffold.ts +91 -0
- package/src/lab/score-command.ts +189 -0
- package/src/lab/score.ts +396 -0
- package/src/lab/store.ts +383 -0
- package/src/lab/text.ts +29 -0
- package/src/lab/trial-settings.ts +100 -0
- package/src/lab/trial-stub.txt +18 -0
- package/src/lab/trial.ts +443 -0
- package/src/lab/usage.ts +273 -0
- package/src/lab/verdict.ts +161 -0
- package/src/lab/workflow-graders.ts +161 -0
- package/src/lab/workspace.ts +489 -0
- package/src/loop/propose.workflow.ts +84 -0
- package/src/shared/allowance.ts +185 -0
- package/src/shared/compare/index.ts +3 -0
- package/src/shared/compare/paired.ts +397 -0
- package/src/shared/compare/stats.ts +139 -0
- package/src/shared/compare/types.ts +75 -0
- package/src/shared/config.ts +15 -0
- package/src/shared/runner.ts +321 -0
- package/src/shared/validate.ts +181 -0
- package/src/shared/version.ts +41 -0
- package/src/write-schemas.ts +10 -0
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { AllowanceReport, AllowanceWindow } from "@agentswf/contract/records";
|
|
2
|
+
import { awfCommand } from "./runner";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The harnesses `awf allowance` knows, as `awf allowance --help` lists them: the lab may not import
|
|
6
|
+
* the harness package. A harness added there and not here is not waited on.
|
|
7
|
+
*/
|
|
8
|
+
const HARNESSES = new Set(["claude", "codex", "pi", "cursor"]);
|
|
9
|
+
|
|
10
|
+
/** How long a read stands for every run that asks: a cursor read opens a pane. */
|
|
11
|
+
const FRESH_MS = 60_000;
|
|
12
|
+
/** How often a full window that shows no reset is read again. */
|
|
13
|
+
const POLL_MS = 30 * 60_000;
|
|
14
|
+
/**
|
|
15
|
+
* The longest single sleep: the wait is measured on the wall clock between them, so a machine that
|
|
16
|
+
* slept through a reset wakes to it, not to a timer that stood still.
|
|
17
|
+
*/
|
|
18
|
+
const NAP_MS = 10 * 60_000;
|
|
19
|
+
/** A reset is read a minute after it, so the harness shows the new window. */
|
|
20
|
+
const AFTER_RESET_MS = 60_000;
|
|
21
|
+
/** The least a full window waits before it is read again. */
|
|
22
|
+
const RECHECK_MS = 5 * 60_000;
|
|
23
|
+
|
|
24
|
+
/** `awf allowance --json` for these harnesses, or every one when none is named. */
|
|
25
|
+
export type AllowanceSource = (
|
|
26
|
+
harnesses: readonly string[],
|
|
27
|
+
) => Promise<AllowanceReport | undefined>;
|
|
28
|
+
|
|
29
|
+
type Runtime = { harness: string; model: string };
|
|
30
|
+
|
|
31
|
+
/** Every `harness/model` among a run's arguments, as `--runtime` and `--proposer` give them. */
|
|
32
|
+
export function runtimesIn(argv: readonly string[]): Runtime[] {
|
|
33
|
+
return argv.flatMap((arg) => {
|
|
34
|
+
const match = arg.replace(/^--[\w-]+=/, "").match(/^([a-z]+)\/(\S+)$/);
|
|
35
|
+
return match && HARNESSES.has(match[1]!) ? [{ harness: match[1]!, model: match[2]! }] : [];
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Windows at or past `limit` that a run on `runtimes` draws on: every window of their harnesses, a
|
|
41
|
+
* window scoped to some models only when one of theirs names it.
|
|
42
|
+
*/
|
|
43
|
+
export function blocking(
|
|
44
|
+
report: AllowanceReport,
|
|
45
|
+
runtimes: readonly Runtime[],
|
|
46
|
+
limit: number,
|
|
47
|
+
): { harness: string; window: AllowanceWindow }[] {
|
|
48
|
+
return report.harnesses.flatMap((each) => {
|
|
49
|
+
if (each.read !== "plan") return [];
|
|
50
|
+
const models = runtimes.filter((r) => r.harness === each.harness).map((r) => r.model);
|
|
51
|
+
if (models.length === 0) return [];
|
|
52
|
+
return each.windows
|
|
53
|
+
.filter((window) => window.usedPercent >= limit)
|
|
54
|
+
.filter(
|
|
55
|
+
(window) =>
|
|
56
|
+
window.models === undefined ||
|
|
57
|
+
window.models.some((scope) => models.some((model) => names(model, scope))),
|
|
58
|
+
)
|
|
59
|
+
.map((window) => ({ harness: each.harness, window }));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Whether a model's id names a scope's words, `claude-opus-4-7` names `Opus 4.7`. */
|
|
64
|
+
function names(model: string, scope: string): boolean {
|
|
65
|
+
const words = (text: string) => text.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
66
|
+
return `-${words(model)}-`.includes(`-${words(scope)}-`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* `runner`, holding each run until every plan window it draws on is under `limit` percent used:
|
|
71
|
+
* a window at it waits for its reset and is read again then, or every half hour where it shows
|
|
72
|
+
* none. A run that names no `harness/model`, as a scorer on its workflow's default, and a plan that
|
|
73
|
+
* can't be read hold nothing; each is said once. A waiting run keeps the job slot and the budget
|
|
74
|
+
* its plan admitted it with. A run already started is not stopped.
|
|
75
|
+
*/
|
|
76
|
+
export function waitingOnAllowance<R extends { argv: readonly string[] }, T>(
|
|
77
|
+
runner: (request: R) => Promise<T>,
|
|
78
|
+
read: AllowanceSource,
|
|
79
|
+
options: {
|
|
80
|
+
limit: number;
|
|
81
|
+
log: (line: string) => void;
|
|
82
|
+
now?: () => number;
|
|
83
|
+
sleep?: (ms: number) => Promise<void>;
|
|
84
|
+
},
|
|
85
|
+
): (request: R) => Promise<T> {
|
|
86
|
+
const { limit, log } = options;
|
|
87
|
+
const now = options.now ?? Date.now;
|
|
88
|
+
const sleep =
|
|
89
|
+
options.sleep ?? ((ms: number) => new Promise<void>((wake) => setTimeout(wake, ms)));
|
|
90
|
+
/** A read in flight is shared; a settled one stands `FRESH_MS` from when it settled. */
|
|
91
|
+
const reads = new Map<
|
|
92
|
+
string,
|
|
93
|
+
{ settled?: number; report: Promise<AllowanceReport | undefined> }
|
|
94
|
+
>();
|
|
95
|
+
const said = new Set<string>();
|
|
96
|
+
const once = (line: string) => {
|
|
97
|
+
if (said.has(line)) return;
|
|
98
|
+
said.add(line);
|
|
99
|
+
log(line);
|
|
100
|
+
};
|
|
101
|
+
const reportFor = (harnesses: readonly string[]) => {
|
|
102
|
+
const key = [...harnesses].sort().join(",");
|
|
103
|
+
const held = reads.get(key);
|
|
104
|
+
if (held && (held.settled === undefined || now() - held.settled < FRESH_MS)) {
|
|
105
|
+
return held.report;
|
|
106
|
+
}
|
|
107
|
+
const entry: { settled?: number; report: Promise<AllowanceReport | undefined> } = {
|
|
108
|
+
report: read(harnesses)
|
|
109
|
+
.catch(() => undefined)
|
|
110
|
+
.finally(() => {
|
|
111
|
+
entry.settled = now();
|
|
112
|
+
}),
|
|
113
|
+
};
|
|
114
|
+
reads.set(key, entry);
|
|
115
|
+
return entry.report;
|
|
116
|
+
};
|
|
117
|
+
return async (request) => {
|
|
118
|
+
const runtimes = runtimesIn(request.argv);
|
|
119
|
+
const harnesses = [...new Set(runtimes.map((r) => r.harness))];
|
|
120
|
+
if (harnesses.length === 0) {
|
|
121
|
+
once("allowance: a run that names no harness/model is not waited on");
|
|
122
|
+
return runner(request);
|
|
123
|
+
}
|
|
124
|
+
let behind = 0;
|
|
125
|
+
for (;;) {
|
|
126
|
+
const report = await reportFor(harnesses);
|
|
127
|
+
if (!report) {
|
|
128
|
+
once("allowance: `awf allowance` gave no record; runs go ahead without it");
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
for (const each of report.harnesses) {
|
|
132
|
+
if (each.read === "none" && harnesses.includes(each.harness))
|
|
133
|
+
once(`allowance: ${each.harness} not read, so not waited on: ${each.reason}`);
|
|
134
|
+
}
|
|
135
|
+
const full = blocking(report, runtimes, limit);
|
|
136
|
+
if (full.length === 0) break;
|
|
137
|
+
const resets = full.map(({ window }) =>
|
|
138
|
+
window.resetsAt ? Date.parse(window.resetsAt) : Number.NaN,
|
|
139
|
+
);
|
|
140
|
+
const after = Math.max(...resets) + AFTER_RESET_MS;
|
|
141
|
+
// A reset already behind the read is a screen not yet redrawn, or a reset shown only to the
|
|
142
|
+
// day: looked at again shortly, then less often, up to the poll.
|
|
143
|
+
const until = resets.some(Number.isNaN)
|
|
144
|
+
? now() + POLL_MS
|
|
145
|
+
: after > now() + RECHECK_MS
|
|
146
|
+
? after
|
|
147
|
+
: now() + Math.min(RECHECK_MS * 2 ** behind++, POLL_MS);
|
|
148
|
+
const which = full
|
|
149
|
+
.map(({ harness, window }) => `${harness}'s ${window.label} is ${window.usedPercent}%`)
|
|
150
|
+
.join(", ");
|
|
151
|
+
const when = new Date(until).toLocaleString("en-US", {
|
|
152
|
+
month: "short",
|
|
153
|
+
day: "numeric",
|
|
154
|
+
hour: "2-digit",
|
|
155
|
+
minute: "2-digit",
|
|
156
|
+
hourCycle: "h23",
|
|
157
|
+
});
|
|
158
|
+
once(`allowance: ${which} used, at or past ${limit}%; waiting until ${when}`);
|
|
159
|
+
while (now() < until) await sleep(Math.min(until - now(), NAP_MS));
|
|
160
|
+
reads.clear();
|
|
161
|
+
}
|
|
162
|
+
return runner(request);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** `awf allowance --json`, as the operator's own login reads it; undefined when it printed none. */
|
|
167
|
+
export async function awfAllowance(
|
|
168
|
+
harnesses: readonly string[],
|
|
169
|
+
): Promise<AllowanceReport | undefined> {
|
|
170
|
+
// A pane read takes up to 90 s; past three minutes awf is stuck, and the run goes ahead.
|
|
171
|
+
const child = Bun.spawn(awfCommand(undefined, ["allowance", "--json", ...harnesses]), {
|
|
172
|
+
stdout: "pipe",
|
|
173
|
+
stderr: "ignore",
|
|
174
|
+
stdin: "ignore",
|
|
175
|
+
timeout: 180_000,
|
|
176
|
+
});
|
|
177
|
+
const [stdout] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
178
|
+
try {
|
|
179
|
+
const report = JSON.parse(stdout) as AllowanceReport | { code: string };
|
|
180
|
+
// A refusal, which has a code and no report's fields, is none.
|
|
181
|
+
return "code" in report || report.v !== 1 ? undefined : report;
|
|
182
|
+
} catch {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
import { mean, normalCdf, obrienFleming, sd, tQuantile } from "./stats";
|
|
2
|
+
import type {
|
|
3
|
+
CaseScore,
|
|
4
|
+
ComparedMetric,
|
|
5
|
+
Comparison,
|
|
6
|
+
ComparisonInput,
|
|
7
|
+
MetricSpec,
|
|
8
|
+
Verdict,
|
|
9
|
+
} from "./types";
|
|
10
|
+
|
|
11
|
+
/** Below this many paired cases no interval is given, only cases won, tied and lost. */
|
|
12
|
+
const FEWEST = 5;
|
|
13
|
+
/** A per-case difference this small is rounding, not a difference: trials summed in another order. */
|
|
14
|
+
const TOLERANCE = 1e-9;
|
|
15
|
+
|
|
16
|
+
/** Each case's value of one metric: the mean of its trials that have one. */
|
|
17
|
+
export function perCase(scores: readonly CaseScore[], metric: MetricSpec): Map<string, number> {
|
|
18
|
+
const values = new Map<string, number[]>();
|
|
19
|
+
for (const score of scores) {
|
|
20
|
+
const value =
|
|
21
|
+
score.outcome === "scored"
|
|
22
|
+
? score.metrics[metric.name]
|
|
23
|
+
: score.outcome === "workflow-failed" && metric.onFailure !== "missing"
|
|
24
|
+
? metric.onFailure
|
|
25
|
+
: null;
|
|
26
|
+
if (value === null || value === undefined) continue;
|
|
27
|
+
if (!Number.isFinite(value)) {
|
|
28
|
+
throw new Error(`${metric.name} is ${value} on ${score.case}, trial ${score.trial}`);
|
|
29
|
+
}
|
|
30
|
+
values.set(score.case, [...(values.get(score.case) ?? []), value]);
|
|
31
|
+
}
|
|
32
|
+
return new Map([...values].map(([id, xs]) => [id, mean(xs)]));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Per-case differences, the column minus the reference, over the cases both have, rounding taken out. */
|
|
36
|
+
function differencesOf(input: Pick<ComparisonInput, "reference" | "column">, metric: MetricSpec) {
|
|
37
|
+
const theirs = perCase(input.reference, metric);
|
|
38
|
+
const ours = perCase(input.column, metric);
|
|
39
|
+
const paired = [...ours.keys()].filter((id) => theirs.has(id));
|
|
40
|
+
const differences = paired.map((id) => {
|
|
41
|
+
const d = ours.get(id)! - theirs.get(id)!;
|
|
42
|
+
return Math.abs(d) <= TOLERANCE ? 0 : d;
|
|
43
|
+
});
|
|
44
|
+
return { theirs, ours, paired, differences };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* One metric compared over the cases both columns have: the column's mean difference, with a
|
|
49
|
+
* paired t interval at `confidence`, and the cases each way.
|
|
50
|
+
*/
|
|
51
|
+
export function compareMetric(
|
|
52
|
+
input: Pick<ComparisonInput, "reference" | "column">,
|
|
53
|
+
metric: MetricSpec,
|
|
54
|
+
role: ComparedMetric["role"] = "reported",
|
|
55
|
+
confidence = 0.95,
|
|
56
|
+
): ComparedMetric {
|
|
57
|
+
const { theirs, ours, paired, differences } = differencesOf(input, metric);
|
|
58
|
+
const sign = metric.direction === "higher" ? 1 : -1;
|
|
59
|
+
const compared: ComparedMetric = {
|
|
60
|
+
name: metric.name,
|
|
61
|
+
role,
|
|
62
|
+
cases: paired.length,
|
|
63
|
+
baseline: paired.length ? mean(paired.map((id) => theirs.get(id)!)) : null,
|
|
64
|
+
challenger: paired.length ? mean(paired.map((id) => ours.get(id)!)) : null,
|
|
65
|
+
difference: paired.length ? mean(differences) : null,
|
|
66
|
+
won: differences.filter((d) => sign * d > 0).length,
|
|
67
|
+
tied: differences.filter((d) => d === 0).length,
|
|
68
|
+
lost: differences.filter((d) => sign * d < 0).length,
|
|
69
|
+
};
|
|
70
|
+
if (paired.length >= FEWEST) {
|
|
71
|
+
const half =
|
|
72
|
+
tQuantile(1 - (1 - confidence) / 2, paired.length - 1) *
|
|
73
|
+
(sd(differences) / Math.sqrt(paired.length));
|
|
74
|
+
compared.interval = [compared.difference! - half, compared.difference! + half];
|
|
75
|
+
}
|
|
76
|
+
if (![compared.difference ?? 0, ...(compared.interval ?? [])].every(Number.isFinite)) {
|
|
77
|
+
throw new Error(`${metric.name}'s values are too large to compare`);
|
|
78
|
+
}
|
|
79
|
+
return compared;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type PairedOptions = {
|
|
83
|
+
/** The metric that decides. */
|
|
84
|
+
primary: string;
|
|
85
|
+
/** Metrics that may not get worse by more than `margin`, shown with the interval. */
|
|
86
|
+
guards?: readonly { metric: string; margin: number }[];
|
|
87
|
+
/**
|
|
88
|
+
* Metrics that decide, in order, at the last look: each only by more than its `margin`, shown
|
|
89
|
+
* with the interval, so two copies of one column never differ by chance. Better also needs the
|
|
90
|
+
* primary shown no worse than −`equivalence` and every guard within its margin; worse needs the
|
|
91
|
+
* primary shown no better than +`equivalence`. The next is tried only when this one is shown
|
|
92
|
+
* equal within its margin.
|
|
93
|
+
*/
|
|
94
|
+
tiebreak?: readonly { metric: string; margin: number }[];
|
|
95
|
+
/**
|
|
96
|
+
* How close to 0 the primary's interval must lie for the tie-breakers to decide. Set, it is also
|
|
97
|
+
* what a tie means: at the plan's end, a primary neither better nor within it is `undecided`.
|
|
98
|
+
*/
|
|
99
|
+
equivalence?: number;
|
|
100
|
+
/**
|
|
101
|
+
* Case counts at which "better" may be claimed, against an O'Brien–Fleming bound; the plan's
|
|
102
|
+
* size is always the last. A look counts cases both columns have finished, so a run evaluates
|
|
103
|
+
* at exactly these counts. "Worse" may stop at any count from 5.
|
|
104
|
+
*/
|
|
105
|
+
looks?: readonly number[];
|
|
106
|
+
/**
|
|
107
|
+
* The smallest gain on the primary worth having. At a planned look before the last, a column
|
|
108
|
+
* not better whose interval's upper end is below it stops, `undecided`: more cases could at most
|
|
109
|
+
* show a gain too small to want. Only at looks, so a real gain is not stopped by peeking.
|
|
110
|
+
*/
|
|
111
|
+
minGain?: number;
|
|
112
|
+
/** Two-sided, for every interval; "better" is claimed one-sided at half of what it leaves. */
|
|
113
|
+
confidence?: number;
|
|
114
|
+
/** Cases the column must win on the primary before "better": a floor under the interval. */
|
|
115
|
+
minWon?: number;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** A number as a person reads it: two significant figures below 1, and no sign on 0. */
|
|
119
|
+
function figure(x: number): string {
|
|
120
|
+
const size = Math.abs(x);
|
|
121
|
+
if (size === 0) return "0";
|
|
122
|
+
const text =
|
|
123
|
+
size >= 100
|
|
124
|
+
? size.toFixed(0)
|
|
125
|
+
: size >= 10
|
|
126
|
+
? size.toFixed(1)
|
|
127
|
+
: size >= 1
|
|
128
|
+
? size.toFixed(2)
|
|
129
|
+
: size.toPrecision(2);
|
|
130
|
+
return `${x > 0 ? "+" : "−"}${text}`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const more = (k: number) => `${k} more ${k === 1 ? "case" : "cases"}`;
|
|
134
|
+
|
|
135
|
+
const shown = (m: ComparedMetric) =>
|
|
136
|
+
`${m.name} ${figure(m.difference ?? 0)}${m.interval ? ` [${figure(m.interval[0])}, ${figure(m.interval[1])}]` : ""}`;
|
|
137
|
+
|
|
138
|
+
/** The interval turned so that above 0 is better for the column. */
|
|
139
|
+
function gainInterval(m: ComparedMetric, spec: MetricSpec): [number, number] | undefined {
|
|
140
|
+
if (!m.interval) return undefined;
|
|
141
|
+
const [low, high] = m.interval;
|
|
142
|
+
return spec.direction === "higher" ? [low, high] : [-high, -low];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The standard rule, for 5 to 40 costly cases with a few trials each: per-case means, paired;
|
|
147
|
+
* "worse" as soon as the primary's interval is below 0 or a guard's is past its margin; "better"
|
|
148
|
+
* only at a planned look, past the bound, with every guard shown within its margin; at the last
|
|
149
|
+
* look, the tie-breakers, then a tie if the primary is shown equivalent. With `minGain`, a look
|
|
150
|
+
* before the last also stops a column that can no longer gain that much. Never a weighted sum
|
|
151
|
+
* across metrics.
|
|
152
|
+
*/
|
|
153
|
+
export function pairedComparison(options: PairedOptions): Comparison {
|
|
154
|
+
const confidence = options.confidence ?? 0.95;
|
|
155
|
+
if (!(confidence >= 0.8 && confidence <= 0.999)) {
|
|
156
|
+
throw new Error(`confidence is from 0.8 to 0.999: ${confidence}`);
|
|
157
|
+
}
|
|
158
|
+
const minWon = options.minWon ?? 6;
|
|
159
|
+
const guards = options.guards ?? [];
|
|
160
|
+
const tiebreak = options.tiebreak ?? [];
|
|
161
|
+
if (tiebreak.length > 0 && options.equivalence === undefined) {
|
|
162
|
+
throw new Error("tie-breakers need an equivalence: how close to 0 the primary must be shown");
|
|
163
|
+
}
|
|
164
|
+
const equivalence = options.equivalence;
|
|
165
|
+
const whole = (x: number | undefined, least: number) =>
|
|
166
|
+
x === undefined || (Number.isInteger(x) && x >= least);
|
|
167
|
+
if (!(options.looks ?? []).every((l) => whole(l, 1))) {
|
|
168
|
+
throw new Error(`looks are case counts, whole numbers from 1: ${options.looks}`);
|
|
169
|
+
}
|
|
170
|
+
if (!whole(options.minWon, 0)) {
|
|
171
|
+
throw new Error(`minWon is a count of cases: ${options.minWon}`);
|
|
172
|
+
}
|
|
173
|
+
for (const { metric, margin } of [
|
|
174
|
+
...guards,
|
|
175
|
+
...tiebreak,
|
|
176
|
+
...(equivalence === undefined ? [] : [{ metric: "equivalence", margin: equivalence }]),
|
|
177
|
+
...(options.minGain === undefined ? [] : [{ metric: "minGain", margin: options.minGain }]),
|
|
178
|
+
]) {
|
|
179
|
+
if (!(margin >= 0)) throw new Error(`${metric}'s margin is ${margin}; a margin is 0 or more`);
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
compare(input): Verdict {
|
|
183
|
+
if (!(Number.isInteger(input.planned) && input.planned >= 1)) {
|
|
184
|
+
throw new Error(`planned is a count of cases, from 1: ${input.planned}`);
|
|
185
|
+
}
|
|
186
|
+
const specs = new Map(input.metrics.map((m) => [m.name, m]));
|
|
187
|
+
const spec = (name: string) => {
|
|
188
|
+
const found = specs.get(name);
|
|
189
|
+
if (!found) {
|
|
190
|
+
throw new Error(
|
|
191
|
+
`the comparison names the metric ${name}, which no grader gives; the metrics are ${[...specs.keys()].join(", ")}`,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
return found;
|
|
195
|
+
};
|
|
196
|
+
const primarySpec = spec(options.primary);
|
|
197
|
+
const roles = new Map<string, ComparedMetric["role"]>([[options.primary, "primary"]]);
|
|
198
|
+
for (const g of guards) {
|
|
199
|
+
if (!roles.has(spec(g.metric).name)) roles.set(g.metric, "guard");
|
|
200
|
+
}
|
|
201
|
+
for (const t of tiebreak) {
|
|
202
|
+
if (!roles.has(spec(t.metric).name)) roles.set(t.metric, "tiebreak");
|
|
203
|
+
}
|
|
204
|
+
const metrics = input.metrics.map((m) =>
|
|
205
|
+
compareMetric(input, m, roles.get(m.name) ?? "reported", confidence),
|
|
206
|
+
);
|
|
207
|
+
const byName = new Map(metrics.map((m) => [m.name, m]));
|
|
208
|
+
const primary = byName.get(options.primary)!;
|
|
209
|
+
const n = primary.cases;
|
|
210
|
+
const counts = `won ${primary.won}, tied ${primary.tied}, lost ${primary.lost}`;
|
|
211
|
+
const verdict = (v: Verdict["verdict"], stop: boolean, reason: string): Verdict => ({
|
|
212
|
+
verdict: v,
|
|
213
|
+
stop,
|
|
214
|
+
reason,
|
|
215
|
+
metrics,
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
// Progress is the cases both columns have finished, whatever the primary's value on them.
|
|
219
|
+
const finished = (scores: readonly CaseScore[]) =>
|
|
220
|
+
new Set(
|
|
221
|
+
scores
|
|
222
|
+
.filter((s) => s.outcome === "scored" || s.outcome === "workflow-failed")
|
|
223
|
+
.map((s) => s.case),
|
|
224
|
+
);
|
|
225
|
+
const theirs = finished(input.reference);
|
|
226
|
+
const done = [...finished(input.column)].filter((id) => theirs.has(id)).length;
|
|
227
|
+
const last = done >= input.planned;
|
|
228
|
+
const looks = [
|
|
229
|
+
...new Set([...(options.looks ?? []).filter((l) => l < input.planned), input.planned]),
|
|
230
|
+
].sort((a, b) => a - b);
|
|
231
|
+
const look = last ? looks.length - 1 : looks.indexOf(done);
|
|
232
|
+
const next = looks.find((l) => l > done);
|
|
233
|
+
const pending = `at ${done} of ${input.planned} cases${next ? `, next look at ${next}` : ""}`;
|
|
234
|
+
|
|
235
|
+
if (n < FEWEST) {
|
|
236
|
+
const few = `${n} ${n === 1 ? "case" : "cases"} with ${options.primary}: too few for an interval; ${counts}`;
|
|
237
|
+
return last
|
|
238
|
+
? verdict("undecided", true, `${few}; ${more(FEWEST - n)} would give one`)
|
|
239
|
+
: verdict("undecided", false, `${few}; ${pending}`);
|
|
240
|
+
}
|
|
241
|
+
const primaryGain = gainInterval(primary, primarySpec)!;
|
|
242
|
+
if (primaryGain[1] < 0) {
|
|
243
|
+
return verdict("worse", true, `stopped, looked worse: ${shown(primary)}`);
|
|
244
|
+
}
|
|
245
|
+
const guardState = guards.map((g) => {
|
|
246
|
+
const m = byName.get(g.metric)!;
|
|
247
|
+
const gain = gainInterval(m, spec(g.metric));
|
|
248
|
+
return {
|
|
249
|
+
m,
|
|
250
|
+
margin: g.margin,
|
|
251
|
+
failed: gain !== undefined && gain[1] < -g.margin,
|
|
252
|
+
within: gain !== undefined && gain[0] >= -g.margin,
|
|
253
|
+
};
|
|
254
|
+
});
|
|
255
|
+
const failed = guardState.find((g) => g.failed);
|
|
256
|
+
if (failed) {
|
|
257
|
+
return verdict(
|
|
258
|
+
"worse",
|
|
259
|
+
true,
|
|
260
|
+
`stopped, ${failed.m.name} worse by more than ${failed.margin}: ${shown(failed.m)}`,
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
const unproven = guardState
|
|
264
|
+
.filter((g) => !g.within)
|
|
265
|
+
.map((g) => (g.m.cases < FEWEST ? `${g.m.name} (${g.m.cases} cases)` : g.m.name));
|
|
266
|
+
// What more cases would do for each guard not shown within its margin, if its mean and
|
|
267
|
+
// spread held: the interval narrows as one over the square root of the cases.
|
|
268
|
+
const guardsNeed = guardState
|
|
269
|
+
.filter((g) => !g.within)
|
|
270
|
+
.map(({ m, margin }) => {
|
|
271
|
+
if (m.cases < FEWEST)
|
|
272
|
+
return `${more(FEWEST - m.cases)} with ${m.name} would give it an interval`;
|
|
273
|
+
const [low, high] = gainInterval(m, spec(m.name))!;
|
|
274
|
+
const room = (low + high) / 2 + margin;
|
|
275
|
+
if (room <= 0)
|
|
276
|
+
return `the mean of ${m.name} is past its margin itself: more cases won't show it within`;
|
|
277
|
+
const k = Math.ceil(m.cases * ((high - low) / 2 / room) ** 2) - m.cases;
|
|
278
|
+
return `about ${more(Math.max(1, k))} at this spread would show ${m.name} within ${margin}`;
|
|
279
|
+
});
|
|
280
|
+
if (look < 0) return verdict("undecided", false, `${shown(primary)} ${pending}`);
|
|
281
|
+
|
|
282
|
+
const c = obrienFleming(
|
|
283
|
+
looks.map((l) => l / input.planned),
|
|
284
|
+
(1 - confidence) / 2,
|
|
285
|
+
);
|
|
286
|
+
const critical = tQuantile(
|
|
287
|
+
normalCdf(c / Math.sqrt(Math.min(1, done / input.planned))),
|
|
288
|
+
n - 1,
|
|
289
|
+
);
|
|
290
|
+
const gains = differencesOf(input, primarySpec).differences.map((d) =>
|
|
291
|
+
primarySpec.direction === "higher" ? d : -d,
|
|
292
|
+
);
|
|
293
|
+
const spread = sd(gains) / Math.sqrt(n);
|
|
294
|
+
const t =
|
|
295
|
+
spread === 0 ? (mean(gains) > 0 ? Number.POSITIVE_INFINITY : 0) : mean(gains) / spread;
|
|
296
|
+
const at = `look ${look + 1} of ${looks.length}`;
|
|
297
|
+
const past = t >= critical;
|
|
298
|
+
const blocked = !past
|
|
299
|
+
? undefined
|
|
300
|
+
: primary.won < minWon
|
|
301
|
+
? `only ${primary.won} cases won, ${minWon} needed`
|
|
302
|
+
: unproven.length > 0
|
|
303
|
+
? `not shown within margin: ${unproven.join(", ")}`
|
|
304
|
+
: undefined;
|
|
305
|
+
if (past && !blocked) return verdict("better", true, `better at ${at}: ${shown(primary)}`);
|
|
306
|
+
// At the last look, what would settle it: the cases the rule itself can count.
|
|
307
|
+
const settle = (bound: boolean) => {
|
|
308
|
+
const clauses = [
|
|
309
|
+
...(bound && t > 0
|
|
310
|
+
? [
|
|
311
|
+
`about ${more(Math.max(1, Math.ceil(n * (critical / t) ** 2) - n))} at this spread would pass the bound`,
|
|
312
|
+
]
|
|
313
|
+
: []),
|
|
314
|
+
...(past && primary.won < minWon
|
|
315
|
+
? [`${more(minWon - primary.won)} won would meet the floor`]
|
|
316
|
+
: []),
|
|
317
|
+
...guardsNeed,
|
|
318
|
+
];
|
|
319
|
+
return clauses.length > 0 ? `; ${clauses.join("; ")}` : "";
|
|
320
|
+
};
|
|
321
|
+
if (!last && !past && options.minGain !== undefined && primaryGain[1] < options.minGain) {
|
|
322
|
+
return verdict(
|
|
323
|
+
"undecided",
|
|
324
|
+
true,
|
|
325
|
+
`stopped at ${at}, no gain of ${options.minGain} in reach: ${shown(primary)}; ${counts}`,
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
if (!last) {
|
|
329
|
+
const why = past ? `past the bound, but ${blocked}` : `not past the bound at ${at}`;
|
|
330
|
+
return verdict("undecided", false, `${shown(primary)} ${why}; ${pending}`);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// The plan has run. The tie-breakers go in order, each one-sided on the primary: a better
|
|
334
|
+
// needs it shown no worse than −equivalence, a worse no better than +equivalence. A later
|
|
335
|
+
// one may say better only while every earlier one is shown no worse than its margin, and
|
|
336
|
+
// worse only while every earlier one is shown no better, so a column that improves on any
|
|
337
|
+
// metric never loses its verdict.
|
|
338
|
+
const notes: string[] = [];
|
|
339
|
+
if (equivalence !== undefined) {
|
|
340
|
+
let mayBetter = primaryGain[0] >= -equivalence;
|
|
341
|
+
let mayWorse = primaryGain[1] <= equivalence;
|
|
342
|
+
for (const { metric, margin } of tiebreak) {
|
|
343
|
+
if (!mayBetter && !mayWorse) break;
|
|
344
|
+
const m = byName.get(metric)!;
|
|
345
|
+
const gain = gainInterval(m, spec(metric));
|
|
346
|
+
if (!gain) {
|
|
347
|
+
notes.push(`${metric} has ${m.cases} cases, too few to decide`);
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
const decided = `decided by ${shown(m)}, past its margin of ${margin}, with ${shown(primary)}`;
|
|
351
|
+
if (mayBetter && gain[0] > margin) {
|
|
352
|
+
if (unproven.length === 0) return verdict("better", true, decided);
|
|
353
|
+
return verdict(
|
|
354
|
+
"undecided",
|
|
355
|
+
true,
|
|
356
|
+
`${decided}, but not shown within margin: ${unproven.join(", ")}${settle(false)}`,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
if (mayWorse && gain[1] < -margin) return verdict("worse", true, decided);
|
|
360
|
+
mayBetter &&= gain[0] >= -margin;
|
|
361
|
+
mayWorse &&= gain[1] <= margin;
|
|
362
|
+
if (!mayBetter || !mayWorse)
|
|
363
|
+
notes.push(`${metric} not shown within its margin: ${shown(m)}`);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
const why = notes.length > 0 ? `; ${notes.join("; ")}` : "";
|
|
367
|
+
if (past)
|
|
368
|
+
return verdict(
|
|
369
|
+
"undecided",
|
|
370
|
+
true,
|
|
371
|
+
`${shown(primary)} past the bound, but ${blocked}${settle(false)}`,
|
|
372
|
+
);
|
|
373
|
+
const equivalent =
|
|
374
|
+
equivalence !== undefined &&
|
|
375
|
+
primaryGain[0] >= -equivalence &&
|
|
376
|
+
primaryGain[1] <= equivalence;
|
|
377
|
+
if (equivalent) {
|
|
378
|
+
return verdict("tie", true, `within ±${equivalence}: ${shown(primary)}; ${counts}${why}`);
|
|
379
|
+
}
|
|
380
|
+
if (primaryGain[0] > 0) {
|
|
381
|
+
return verdict(
|
|
382
|
+
"undecided",
|
|
383
|
+
true,
|
|
384
|
+
`${shown(primary)}: a gain, but not past the bound that planned looks require${settle(true)}`,
|
|
385
|
+
);
|
|
386
|
+
}
|
|
387
|
+
if (equivalence !== undefined) {
|
|
388
|
+
return verdict(
|
|
389
|
+
"undecided",
|
|
390
|
+
true,
|
|
391
|
+
`no difference shown, nor one within ±${equivalence}: ${shown(primary)}; ${counts}${why}`,
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
return verdict("tie", true, `no difference shown: ${shown(primary)}; ${counts}`);
|
|
395
|
+
},
|
|
396
|
+
};
|
|
397
|
+
}
|