@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,91 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { KEY_FILE } from "./dataset";
|
|
4
|
+
import { GRADING_FILE, LOCAL_FILE, STUB_LINE, TRIAL_FILE } from "./eval-files";
|
|
5
|
+
import GRADING_STUB from "./grading-stub.txt" with { type: "text" };
|
|
6
|
+
import { newMarker } from "./marker";
|
|
7
|
+
import { Refusal } from "./refusal";
|
|
8
|
+
import STUB_BODY from "./trial-stub.txt" with { type: "text" };
|
|
9
|
+
import { type CaseWorkspace, folderDatasets } from "./workspace";
|
|
10
|
+
|
|
11
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
12
|
+
|
|
13
|
+
const key = (marker: string) => `---
|
|
14
|
+
marker: ${marker}
|
|
15
|
+
# expect:
|
|
16
|
+
# done: true
|
|
17
|
+
# must:
|
|
18
|
+
# - a sentence a good result makes true
|
|
19
|
+
# must-not:
|
|
20
|
+
# - a sentence a good result never makes true
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
Why this case exists.
|
|
24
|
+
`;
|
|
25
|
+
|
|
26
|
+
export type Made = { written: string[]; caseDir: string };
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* `case new {dataset}/{case}`: the case folder, its `input/` and its key's marker, in the
|
|
30
|
+
* dataset's data folder; for a dataset not yet there, the folder `evals/{dataset}/` with stub
|
|
31
|
+
* `trial.ts` and `grading.ts`, and the line in `evals/.gitignore` that keeps the local file out
|
|
32
|
+
* of git.
|
|
33
|
+
*/
|
|
34
|
+
export function newCase(
|
|
35
|
+
evals: string,
|
|
36
|
+
address: string,
|
|
37
|
+
/** The project, when `evals/` is one: its datasets, wherever their data is. */
|
|
38
|
+
workspace?: CaseWorkspace,
|
|
39
|
+
): Made {
|
|
40
|
+
const known =
|
|
41
|
+
workspace?.datasets.map((d) => ({ name: d.name, data: d.data.value })) ??
|
|
42
|
+
folderDatasets(evals).map((d) => ({ name: d.name, data: d.dir }));
|
|
43
|
+
const parts = address.split("/");
|
|
44
|
+
let datasetName: string;
|
|
45
|
+
let caseName: string;
|
|
46
|
+
if (parts.length === 2) [datasetName, caseName] = parts as [string, string];
|
|
47
|
+
else if (parts.length === 1) {
|
|
48
|
+
if (known.length !== 1) {
|
|
49
|
+
throw new Refusal(
|
|
50
|
+
known.length === 0
|
|
51
|
+
? "case new takes {dataset}/{case} for the first case of a dataset"
|
|
52
|
+
: `more than one dataset: case new takes {dataset}/{case} (${known.map((d) => d.name).join(", ")})`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
datasetName = known[0]!.name;
|
|
56
|
+
caseName = parts[0]!;
|
|
57
|
+
} else throw new Refusal(`case new takes {dataset}/{case}, not ${address}`);
|
|
58
|
+
for (const name of [datasetName, caseName]) {
|
|
59
|
+
if (!NAME.test(name)) {
|
|
60
|
+
throw new Refusal(
|
|
61
|
+
`${name} is not a name: letters, digits, '.', '_' and '-', starting with a letter or digit`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const dataDir = known.find((d) => d.name === datasetName)?.data ?? join(evals, datasetName);
|
|
66
|
+
const caseDir = join(dataDir, "cases", caseName);
|
|
67
|
+
if (existsSync(caseDir))
|
|
68
|
+
throw new Refusal(`case ${datasetName}/${caseName} is already there: ${caseDir}`);
|
|
69
|
+
const written: string[] = [];
|
|
70
|
+
const write = (file: string, text: string) => {
|
|
71
|
+
writeFileSync(file, text, { flag: "wx" });
|
|
72
|
+
written.push(file);
|
|
73
|
+
};
|
|
74
|
+
if (!known.some((d) => d.name === datasetName)) {
|
|
75
|
+
mkdirSync(dataDir, { recursive: true });
|
|
76
|
+
const trialFile = join(dataDir, TRIAL_FILE);
|
|
77
|
+
if (!existsSync(trialFile)) write(trialFile, `${STUB_LINE} ${STUB_BODY}`);
|
|
78
|
+
const gradingFile = join(dataDir, GRADING_FILE);
|
|
79
|
+
if (!existsSync(gradingFile)) write(gradingFile, GRADING_STUB);
|
|
80
|
+
}
|
|
81
|
+
const ignore = join(evals, ".gitignore");
|
|
82
|
+
const lines = existsSync(ignore) ? readFileSync(ignore, "utf8").split("\n") : [];
|
|
83
|
+
if (!lines.some((line) => line.trim() === LOCAL_FILE || line.trim() === `/${LOCAL_FILE}`)) {
|
|
84
|
+
const before = lines.length > 0 && lines.at(-1) !== "" ? "\n" : "";
|
|
85
|
+
appendFileSync(ignore, `${before}${LOCAL_FILE}\n`);
|
|
86
|
+
written.push(ignore);
|
|
87
|
+
}
|
|
88
|
+
mkdirSync(join(caseDir, "input"), { recursive: true });
|
|
89
|
+
write(join(caseDir, KEY_FILE), key(newMarker()));
|
|
90
|
+
return { written, caseDir };
|
|
91
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { type CasePlan, PLAN_KIND } from "../format/output";
|
|
2
|
+
import {
|
|
3
|
+
budgetExit,
|
|
4
|
+
type Context,
|
|
5
|
+
checkoutFolder,
|
|
6
|
+
chooseRun,
|
|
7
|
+
confirmPlan,
|
|
8
|
+
datasetFacts,
|
|
9
|
+
datasetGraders,
|
|
10
|
+
envOf,
|
|
11
|
+
loadDataset,
|
|
12
|
+
printPlan,
|
|
13
|
+
tagged,
|
|
14
|
+
tmpOf,
|
|
15
|
+
withLock,
|
|
16
|
+
workspaceOf,
|
|
17
|
+
} from "./command-context";
|
|
18
|
+
import { clearStale } from "./folders";
|
|
19
|
+
import type { LabGrader } from "./grading";
|
|
20
|
+
import { checkTrialScript } from "./inspect";
|
|
21
|
+
import { writeRecords } from "./record-copies";
|
|
22
|
+
import { Refusal } from "./refusal";
|
|
23
|
+
import { runReport } from "./run-report";
|
|
24
|
+
import { barsOf, criteriaCount } from "./runs";
|
|
25
|
+
import { describePlan, regradePlan, runScore, type ScoreDone } from "./score";
|
|
26
|
+
import { readTrials } from "./store";
|
|
27
|
+
import { usd } from "./text";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Grades a kept run again, without running a trial: never `trial.ts` or the workflow. `facts`
|
|
31
|
+
* reads each trial record again.
|
|
32
|
+
* Graders in `grading.ts`'s order, each skipped again while one before it still fails the trial.
|
|
33
|
+
* `--grader` names one alone, a `manual` one included.
|
|
34
|
+
*/
|
|
35
|
+
export async function score(context: Context, names: readonly string[]): Promise<number> {
|
|
36
|
+
const { options, environment, stderr } = context;
|
|
37
|
+
const workspace = workspaceOf(context);
|
|
38
|
+
const run = chooseRun(workspace, names, "score");
|
|
39
|
+
const { info, cases } = loadDataset(context, workspace, run.dataset, "all");
|
|
40
|
+
const now = environment.now ?? (() => new Date());
|
|
41
|
+
const graders = await datasetGraders(
|
|
42
|
+
context,
|
|
43
|
+
workspace,
|
|
44
|
+
info,
|
|
45
|
+
checkoutFolder(context, workspace, () => checkTrialScript(info.evalDir)),
|
|
46
|
+
now,
|
|
47
|
+
);
|
|
48
|
+
let chosen: LabGrader[];
|
|
49
|
+
if (options.grader) {
|
|
50
|
+
const one = graders.find((g) => g.name === options.grader);
|
|
51
|
+
if (!one) {
|
|
52
|
+
throw new Refusal(
|
|
53
|
+
`no grader ${options.grader} in ${info.name}; its graders: ${graders.map((g) => g.name).join(", ") || "none"}`,
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
chosen = [one];
|
|
57
|
+
} else chosen = graders.filter((g) => !g.manual);
|
|
58
|
+
const tmp = tmpOf(context);
|
|
59
|
+
const trials = readTrials(workspace.store, run.id);
|
|
60
|
+
const byCase = new Map(cases.map((c) => [c.name, c]));
|
|
61
|
+
const ran = run.asked.map((a) => a.case);
|
|
62
|
+
for (const name of options.cases ?? []) {
|
|
63
|
+
if (!ran.includes(name)) {
|
|
64
|
+
throw new Refusal(`run ${run.id} ran no case ${name}; its cases: ${ran.join(", ")}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
// --cases and --tags pick within the run, and together the cases that match both.
|
|
68
|
+
const picked = trials.filter((t) => {
|
|
69
|
+
if (options.cases && !options.cases.includes(t.record.case)) return false;
|
|
70
|
+
if (!options.tags) return true;
|
|
71
|
+
const info = byCase.get(t.record.case);
|
|
72
|
+
return info !== undefined && tagged(info, options.tags);
|
|
73
|
+
});
|
|
74
|
+
const plan = await regradePlan({
|
|
75
|
+
trials: picked,
|
|
76
|
+
store: workspace.store,
|
|
77
|
+
info,
|
|
78
|
+
cases,
|
|
79
|
+
graders,
|
|
80
|
+
facts: datasetFacts(context, workspace, info),
|
|
81
|
+
tmp,
|
|
82
|
+
only: {
|
|
83
|
+
graders: chosen,
|
|
84
|
+
expect: options.grader === undefined,
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
const described = describePlan(plan, run.id);
|
|
88
|
+
const perCase = new Map<string, number>();
|
|
89
|
+
for (const item of plan.items) {
|
|
90
|
+
perCase.set(item.trial.record.case, (perCase.get(item.trial.record.case) ?? 0) + 1);
|
|
91
|
+
}
|
|
92
|
+
const atOnce = workspace.concurrency;
|
|
93
|
+
const planJson: CasePlan = {
|
|
94
|
+
kind: PLAN_KIND,
|
|
95
|
+
command: "score",
|
|
96
|
+
dataset: info.name,
|
|
97
|
+
run: run.id,
|
|
98
|
+
cases: [...perCase].map(([name, n]) => ({ case: name, trials: n })),
|
|
99
|
+
columns: run.columns.length,
|
|
100
|
+
trials: plan.items.length,
|
|
101
|
+
grades: Object.fromEntries(plan.counts),
|
|
102
|
+
maybe: Object.fromEntries(plan.maybe),
|
|
103
|
+
unpriced: plan.unpriced,
|
|
104
|
+
...(plan.estimate !== undefined
|
|
105
|
+
? {
|
|
106
|
+
estimate: {
|
|
107
|
+
usd: plan.estimate,
|
|
108
|
+
...(plan.upTo !== undefined ? { upTo: plan.upTo } : {}),
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
: {}),
|
|
112
|
+
...(options.budget !== undefined ? { budget: options.budget } : {}),
|
|
113
|
+
concurrency: atOnce,
|
|
114
|
+
};
|
|
115
|
+
if (options.dryRun) {
|
|
116
|
+
if (options.json) printPlan(context, planJson);
|
|
117
|
+
else context.stdout(described);
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
let done: ScoreDone | undefined;
|
|
121
|
+
if (plan.items.length > 0) {
|
|
122
|
+
if (!(await confirmPlan(context, described, "grade them?"))) {
|
|
123
|
+
stderr("declined; nothing graded");
|
|
124
|
+
return 2;
|
|
125
|
+
}
|
|
126
|
+
done = await withLock(context, workspace, async () => {
|
|
127
|
+
try {
|
|
128
|
+
clearStale(tmp);
|
|
129
|
+
return await runScore({
|
|
130
|
+
plan,
|
|
131
|
+
tmp,
|
|
132
|
+
run: run.id,
|
|
133
|
+
store: workspace.store,
|
|
134
|
+
env: envOf(context),
|
|
135
|
+
...(options.budget !== undefined ? { budget: options.budget } : {}),
|
|
136
|
+
atOnce,
|
|
137
|
+
now,
|
|
138
|
+
progress: stderr,
|
|
139
|
+
});
|
|
140
|
+
} finally {
|
|
141
|
+
if (info.records) writeRecords(workspace.store, info.records, run.id);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
} else stderr(described);
|
|
145
|
+
const rendered = await runReport(context, workspace, {
|
|
146
|
+
info,
|
|
147
|
+
run,
|
|
148
|
+
trials: readTrials(workspace.store, run.id),
|
|
149
|
+
bars: barsOf(info, cases, graders),
|
|
150
|
+
graders,
|
|
151
|
+
criteria: criteriaCount(
|
|
152
|
+
cases,
|
|
153
|
+
run.asked.map((a) => a.case),
|
|
154
|
+
),
|
|
155
|
+
});
|
|
156
|
+
const exit = budgetExit(done?.stopped ?? false, rendered.exit);
|
|
157
|
+
if (options.json) {
|
|
158
|
+
const scored = {
|
|
159
|
+
graded: Object.fromEntries(done?.graded ?? []),
|
|
160
|
+
errored: Object.fromEntries(done?.errored ?? []),
|
|
161
|
+
estimate: done?.estimate ?? 0,
|
|
162
|
+
stopped: done?.stopped ?? false,
|
|
163
|
+
};
|
|
164
|
+
context.stdout(JSON.stringify(rendered.json(exit, scored), null, 2));
|
|
165
|
+
return exit;
|
|
166
|
+
}
|
|
167
|
+
const lines: string[] = [];
|
|
168
|
+
if (done) {
|
|
169
|
+
const counted = (map: Map<string, number>) =>
|
|
170
|
+
[...map].map(([name, n]) => `${name} ×${n}`).join(", ");
|
|
171
|
+
lines.push(
|
|
172
|
+
[
|
|
173
|
+
`graded again: ${counted(done.graded) || "nothing"}`,
|
|
174
|
+
...(done.errored.size > 0 ? [`errored: ${counted(done.errored)}`] : []),
|
|
175
|
+
...(done.estimate > 0 ? [`est. ${usd(done.estimate)}`] : []),
|
|
176
|
+
...(done.stopped
|
|
177
|
+
? [`stopped at the budget, ${usd(options.budget!)}: the rest is not graded`]
|
|
178
|
+
: []),
|
|
179
|
+
].join(" · "),
|
|
180
|
+
"",
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
const text =
|
|
184
|
+
done?.stopped && rendered.exit === 0
|
|
185
|
+
? rendered.text.replace(/exit 0: .*$/, "exit 3: score stopped at its budget")
|
|
186
|
+
: rendered.text;
|
|
187
|
+
context.stdout([...lines, text].join("\n"));
|
|
188
|
+
return exit;
|
|
189
|
+
}
|
package/src/lab/score.ts
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { FactsProblem } from "../env/facts";
|
|
4
|
+
import { type GraderEntry, SCORE_KIND } from "../format/records";
|
|
5
|
+
import type { Fact } from "../format/settings";
|
|
6
|
+
import { type CaseInfo, type DatasetInfo, folderDigest } from "./dataset";
|
|
7
|
+
import { type FactsReader, recordOf } from "./facts";
|
|
8
|
+
import { buildCase, makeTrialFolders } from "./folders";
|
|
9
|
+
import {
|
|
10
|
+
decidersOf,
|
|
11
|
+
EXPECT_VERSION,
|
|
12
|
+
expectDigestOf,
|
|
13
|
+
expectGivenOf,
|
|
14
|
+
failsIn,
|
|
15
|
+
givenFor,
|
|
16
|
+
gradeTrial,
|
|
17
|
+
keyFor,
|
|
18
|
+
type LabGrader,
|
|
19
|
+
previousFrom,
|
|
20
|
+
staleBecause,
|
|
21
|
+
} from "./grading";
|
|
22
|
+
import { gradingSpend, newestEntries } from "./outcome";
|
|
23
|
+
import { appendScore, inputDirOf, keepInput, type StoredTrial } from "./store";
|
|
24
|
+
import { median, usd } from "./text";
|
|
25
|
+
|
|
26
|
+
/** One trial to grade again, and with what. */
|
|
27
|
+
export type ScoreItem = {
|
|
28
|
+
trial: StoredTrial;
|
|
29
|
+
info: CaseInfo;
|
|
30
|
+
deciders: ReadonlySet<string>;
|
|
31
|
+
expect: boolean;
|
|
32
|
+
/** The graders to grade it with again, in `grading.ts`'s order. */
|
|
33
|
+
graders: LabGrader[];
|
|
34
|
+
/** Those of `graders` that run agents and follow one graded again: they run only if it passes. */
|
|
35
|
+
maybe: LabGrader[];
|
|
36
|
+
/** The facts `grading.ts`'s `facts` reads off the trial's record now, or why it couldn't. */
|
|
37
|
+
facts: { facts: Record<string, Fact> } | { problem: FactsProblem };
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export type ScorePlan = {
|
|
41
|
+
items: ScoreItem[];
|
|
42
|
+
/** Every grader's name, in `grading.ts`'s order: the order standing grades are read in. */
|
|
43
|
+
order: string[];
|
|
44
|
+
/** Trials whose case changed since they ran: graded again only by running them again. */
|
|
45
|
+
changed: StoredTrial[];
|
|
46
|
+
/** Grades per grader that will be made, and those that depend on the graders before them. */
|
|
47
|
+
counts: Map<string, number>;
|
|
48
|
+
maybe: Map<string, number>;
|
|
49
|
+
/** The costly graders' estimate, from their earlier grades; `upTo` with the maybes too. */
|
|
50
|
+
estimate?: number;
|
|
51
|
+
upTo?: number;
|
|
52
|
+
/** A costly grader with no earlier grade to price it by. */
|
|
53
|
+
unpriced: string[];
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const add = (map: Map<string, number>, name: string) => map.set(name, (map.get(name) ?? 0) + 1);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What `score` would grade again: on each trial graders run on (not leaked, errored, failed by
|
|
60
|
+
* the workflow, or a draft's), each grader whose grade no longer stands (`staleBecause`); and a
|
|
61
|
+
* grader skipped before, once no grader before it fails the trial. A trial whose built case no
|
|
62
|
+
* longer matches its `input` digest is left for a new run. The graders are every one not marked
|
|
63
|
+
* `manual`, and `expect`, as a run's reused trials and a plain `score` grade them, unless `only`
|
|
64
|
+
* names them. Facts are read off each trial's record again first, so a grader given facts
|
|
65
|
+
* grades again once they change; a trial whose facts can't be read errors each grader that reads
|
|
66
|
+
* them.
|
|
67
|
+
*/
|
|
68
|
+
export async function regradePlan(args: {
|
|
69
|
+
trials: readonly StoredTrial[];
|
|
70
|
+
/** Where each built case is kept, for the graders to read. */
|
|
71
|
+
store: string;
|
|
72
|
+
info: DatasetInfo;
|
|
73
|
+
cases: readonly CaseInfo[];
|
|
74
|
+
/** The dataset's graders, whose grades decide per case. */
|
|
75
|
+
graders: readonly LabGrader[];
|
|
76
|
+
tmp: string;
|
|
77
|
+
/** The grader `--grader` names, and whether `expect` is graded again with it. */
|
|
78
|
+
only?: { graders: readonly LabGrader[]; expect: boolean };
|
|
79
|
+
/** `grading.ts`'s `facts`. */
|
|
80
|
+
facts: FactsReader;
|
|
81
|
+
}): Promise<ScorePlan> {
|
|
82
|
+
const chosen = args.only?.graders ?? args.graders.filter((g) => !g.manual);
|
|
83
|
+
const order = args.graders.map((g) => g.name);
|
|
84
|
+
const before = (a: string, b: string) => a === "expect" || order.indexOf(a) < order.indexOf(b);
|
|
85
|
+
const expectAgain = args.only?.expect ?? true;
|
|
86
|
+
const byName = new Map(args.cases.map((c) => [c.name, c]));
|
|
87
|
+
const items: ScoreItem[] = [];
|
|
88
|
+
const changed: StoredTrial[] = [];
|
|
89
|
+
const inputs = new Map<string, string>();
|
|
90
|
+
const scratch = mkdtempSync(join(args.tmp, "awf-lab-score-plan-"));
|
|
91
|
+
/** Each case built once, as a trial would see it, for its digest. */
|
|
92
|
+
const inputOf = (info: CaseInfo) => {
|
|
93
|
+
let digest = inputs.get(info.name);
|
|
94
|
+
if (digest === undefined) {
|
|
95
|
+
const built = join(scratch, String(inputs.size));
|
|
96
|
+
mkdirSync(built);
|
|
97
|
+
buildCase(args.info.dataDir, info, built);
|
|
98
|
+
digest = folderDigest(built);
|
|
99
|
+
// A run read from committed records has no built case yet: this one is it, if unchanged.
|
|
100
|
+
keepInput(args.store, digest, built);
|
|
101
|
+
rmSync(built, { recursive: true, force: true });
|
|
102
|
+
inputs.set(info.name, digest);
|
|
103
|
+
}
|
|
104
|
+
return digest;
|
|
105
|
+
};
|
|
106
|
+
try {
|
|
107
|
+
const candidates: { trial: StoredTrial; info: CaseInfo }[] = [];
|
|
108
|
+
for (const trial of args.trials) {
|
|
109
|
+
const { record } = trial;
|
|
110
|
+
const info = byName.get(record.case);
|
|
111
|
+
if (!info || info.key.draft) continue;
|
|
112
|
+
// A trial whose grading couldn't start, `facts` or `expect`, is graded again: `grading.ts`
|
|
113
|
+
// may be fixed since.
|
|
114
|
+
const errored = record.errored && record.errored.phase !== "facts";
|
|
115
|
+
if (record.leaked || errored || record.workflowError || record.stopped !== undefined)
|
|
116
|
+
continue;
|
|
117
|
+
if (inputOf(info) !== record.input) {
|
|
118
|
+
changed.push(trial);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
candidates.push({ trial, info });
|
|
122
|
+
}
|
|
123
|
+
const read = await args.facts(
|
|
124
|
+
candidates.map((c) => recordOf(c.trial.record)),
|
|
125
|
+
scratch,
|
|
126
|
+
);
|
|
127
|
+
for (const [i, { trial, info }] of candidates.entries()) {
|
|
128
|
+
const facts = read[i] ?? {
|
|
129
|
+
problem: { code: "facts-missing" as const, reason: "facts gave no answer" },
|
|
130
|
+
};
|
|
131
|
+
const deciders = decidersOf(info.key, args.graders);
|
|
132
|
+
const newest = new Map(newestEntries(trial.scores).map((e) => [e.grader, e]));
|
|
133
|
+
const graders = chosen.filter((g) => g.appliesTo?.(info.key) ?? true);
|
|
134
|
+
if ("problem" in facts) {
|
|
135
|
+
// Grading can't start: `score` keeps why, unless it says so already.
|
|
136
|
+
const said = trial.record.errored;
|
|
137
|
+
if (said?.code !== facts.problem.code || said?.reason !== facts.problem.reason) {
|
|
138
|
+
items.push({ trial, info, deciders, expect: false, graders: [], maybe: [], facts });
|
|
139
|
+
}
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
// Grading errored before: every grade is made again, on the facts as they are now.
|
|
143
|
+
const errorBefore = trial.record.errored?.phase === "facts";
|
|
144
|
+
const expect =
|
|
145
|
+
expectAgain &&
|
|
146
|
+
deciders.has("expect") &&
|
|
147
|
+
(errorBefore ||
|
|
148
|
+
staleBecause(
|
|
149
|
+
newest.get("expect"),
|
|
150
|
+
expectDigestOf(info.key),
|
|
151
|
+
EXPECT_VERSION,
|
|
152
|
+
undefined,
|
|
153
|
+
expectGivenOf(facts.facts, trial.record.runFacts),
|
|
154
|
+
) !== undefined);
|
|
155
|
+
const stale = (g: LabGrader) =>
|
|
156
|
+
errorBefore ||
|
|
157
|
+
staleBecause(
|
|
158
|
+
newest.get(g.name),
|
|
159
|
+
keyFor(g, info),
|
|
160
|
+
g.version,
|
|
161
|
+
g.agent,
|
|
162
|
+
givenFor(g, facts.facts),
|
|
163
|
+
) !== undefined;
|
|
164
|
+
const again: LabGrader[] = [];
|
|
165
|
+
const maybe: LabGrader[] = [];
|
|
166
|
+
for (const g of graders) {
|
|
167
|
+
const entry = newest.get(g.name);
|
|
168
|
+
if (!entry?.skipped && !stale(g)) continue;
|
|
169
|
+
// Graded again before this one, so whether it runs is known only once they are.
|
|
170
|
+
const earlier = [...(expect ? ["expect"] : []), ...again.map((a) => a.name)];
|
|
171
|
+
const standing = [...newest.values()].filter(
|
|
172
|
+
(e) => !earlier.includes(e.grader) && e.grader !== g.name && before(e.grader, g.name),
|
|
173
|
+
);
|
|
174
|
+
// Skipped again while what stands before it fails the trial: nothing new to say.
|
|
175
|
+
if (entry?.skipped && earlier.length === 0 && failsIn(standing, deciders)) continue;
|
|
176
|
+
again.push(g);
|
|
177
|
+
if (g.costly && earlier.length > 0) maybe.push(g);
|
|
178
|
+
}
|
|
179
|
+
if (expect || again.length > 0) {
|
|
180
|
+
items.push({ trial, info, deciders, expect, graders: again, maybe, facts });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
} finally {
|
|
184
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
185
|
+
}
|
|
186
|
+
const counts = new Map<string, number>();
|
|
187
|
+
const maybeCounts = new Map<string, number>();
|
|
188
|
+
for (const item of items) {
|
|
189
|
+
// A trial whose facts can't be read is graded by nothing: `score` keeps why.
|
|
190
|
+
if ("problem" in item.facts) add(counts, "facts");
|
|
191
|
+
if (item.expect) add(counts, "expect");
|
|
192
|
+
for (const g of item.graders) add(item.maybe.includes(g) ? maybeCounts : counts, g.name);
|
|
193
|
+
}
|
|
194
|
+
let estimate: number | undefined;
|
|
195
|
+
let upTo: number | undefined;
|
|
196
|
+
const unpriced: string[] = [];
|
|
197
|
+
for (const grader of chosen.filter((g) => g.costly)) {
|
|
198
|
+
const sure = counts.get(grader.name) ?? 0;
|
|
199
|
+
const unsure = maybeCounts.get(grader.name) ?? 0;
|
|
200
|
+
if (sure + unsure === 0) continue;
|
|
201
|
+
const each = median(
|
|
202
|
+
args.trials.flatMap((t) =>
|
|
203
|
+
t.scores.flatMap((s) =>
|
|
204
|
+
s.entries.flatMap((e) =>
|
|
205
|
+
e.grader === grader.name && e.estimate !== undefined && !e.skipped ? [e.estimate] : [],
|
|
206
|
+
),
|
|
207
|
+
),
|
|
208
|
+
),
|
|
209
|
+
);
|
|
210
|
+
if (each === undefined) {
|
|
211
|
+
unpriced.push(grader.name);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
estimate = (estimate ?? 0) + each * sure;
|
|
215
|
+
upTo = (upTo ?? 0) + each * (sure + unsure);
|
|
216
|
+
}
|
|
217
|
+
return {
|
|
218
|
+
items,
|
|
219
|
+
order,
|
|
220
|
+
changed,
|
|
221
|
+
counts,
|
|
222
|
+
maybe: maybeCounts,
|
|
223
|
+
...(estimate !== undefined ? { estimate } : {}),
|
|
224
|
+
...(upTo !== undefined && upTo !== estimate ? { upTo } : {}),
|
|
225
|
+
unpriced,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** The plan in lines, for the operator. */
|
|
230
|
+
export function describePlan(plan: ScorePlan, run: string): string {
|
|
231
|
+
const lines: string[] = [];
|
|
232
|
+
if (plan.items.length === 0) lines.push(`nothing in run ${run} to grade again`);
|
|
233
|
+
else {
|
|
234
|
+
const graders = [
|
|
235
|
+
...[...plan.counts].map(([name, n]) => `${name} ×${n}`),
|
|
236
|
+
...[...plan.maybe].map(([name, n]) => `${name} ×${n} if the graders before it now pass`),
|
|
237
|
+
].join(", ");
|
|
238
|
+
lines.push(
|
|
239
|
+
`score run ${run}: ${plan.items.length} trial${plan.items.length === 1 ? "" : "s"} · ${graders}`,
|
|
240
|
+
);
|
|
241
|
+
const priced = [
|
|
242
|
+
...(plan.estimate !== undefined ? [`est. ${usd(plan.estimate)}`] : []),
|
|
243
|
+
...(plan.upTo !== undefined ? [`up to ${usd(plan.upTo)}`] : []),
|
|
244
|
+
];
|
|
245
|
+
if (priced.length > 0) {
|
|
246
|
+
lines.push(
|
|
247
|
+
`from earlier grades: ${priced.join(", ")}${plan.unpriced.length > 0 ? `; ${plan.unpriced.join(", ")} unpriced` : ""}`,
|
|
248
|
+
);
|
|
249
|
+
} else if (plan.unpriced.length > 0) {
|
|
250
|
+
lines.push(`${plan.unpriced.join(", ")}: no earlier grade to price by`);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
if (plan.changed.length > 0) {
|
|
254
|
+
const names = [...new Set(plan.changed.map((t) => t.record.case))];
|
|
255
|
+
lines.push(
|
|
256
|
+
`${plan.changed.length} trial${plan.changed.length === 1 ? "" : "s"} left: the case changed since it ran; run it again: awf-lab run --cases ${names.join(",")}`,
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
return lines.join("\n");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export type ScoreDone = {
|
|
263
|
+
/** Grades written, by grader. */
|
|
264
|
+
graded: Map<string, number>;
|
|
265
|
+
/** Grades that errored, by grader. */
|
|
266
|
+
errored: Map<string, number>;
|
|
267
|
+
estimate: number;
|
|
268
|
+
/** Stopped at the budget before a costly grader. */
|
|
269
|
+
stopped: boolean;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
/** Grades each planned trial again and appends one score record per trial graded. */
|
|
273
|
+
export async function runScore(args: {
|
|
274
|
+
plan: ScorePlan;
|
|
275
|
+
tmp: string;
|
|
276
|
+
run: string;
|
|
277
|
+
store: string;
|
|
278
|
+
env: Record<string, string>;
|
|
279
|
+
budget?: number;
|
|
280
|
+
/** Trials graded at once; 1 unless the local file or `--concurrency` says. */
|
|
281
|
+
atOnce?: number;
|
|
282
|
+
now: () => Date;
|
|
283
|
+
progress?: (line: string) => void;
|
|
284
|
+
}): Promise<ScoreDone> {
|
|
285
|
+
const graded = new Map<string, number>();
|
|
286
|
+
const errored = new Map<string, number>();
|
|
287
|
+
let estimated = 0;
|
|
288
|
+
let stopped = false;
|
|
289
|
+
const cost = (entries: readonly GraderEntry[]) => gradingSpend([{ entries }]);
|
|
290
|
+
const gradeOne = async (item: ScorePlan["items"][number]): Promise<void> => {
|
|
291
|
+
const { trial, info } = item;
|
|
292
|
+
const newest = new Map(newestEntries(trial.scores).map((e) => [e.grader, e]));
|
|
293
|
+
const graders = item.graders;
|
|
294
|
+
const regrading = new Set([...(item.expect ? ["expect"] : []), ...graders.map((g) => g.name)]);
|
|
295
|
+
const standing = [...newest.values()].filter((e) => !regrading.has(e.grader));
|
|
296
|
+
const byName = new Map(graders.map((g) => [g.name, g]));
|
|
297
|
+
if ("problem" in item.facts) {
|
|
298
|
+
const { code, reason } = item.facts.problem;
|
|
299
|
+
appendScore(trial.dir, {
|
|
300
|
+
kind: SCORE_KIND,
|
|
301
|
+
at: args.now().toISOString(),
|
|
302
|
+
entries: [],
|
|
303
|
+
errored: { by: "dataset", phase: "facts", code, reason },
|
|
304
|
+
});
|
|
305
|
+
add(errored, "facts");
|
|
306
|
+
args.progress?.(` ${trial.record.case} ${trial.record.trial}: facts errored: ${reason}`);
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
const facts = item.facts.facts;
|
|
310
|
+
const work = makeTrialFolders(args.tmp, args.run).parent;
|
|
311
|
+
try {
|
|
312
|
+
const result = await gradeTrial({
|
|
313
|
+
info,
|
|
314
|
+
facts,
|
|
315
|
+
...(trial.record.runFacts ? { runFacts: trial.record.runFacts } : {}),
|
|
316
|
+
stages: trial.record.stages ?? {},
|
|
317
|
+
result: trial.record.result ?? null,
|
|
318
|
+
caseDir: inputDirOf(args.store, trial.record.input),
|
|
319
|
+
scratch: null,
|
|
320
|
+
kept: join(trial.dir, "kept"),
|
|
321
|
+
work,
|
|
322
|
+
env: args.env,
|
|
323
|
+
params: trial.record.params,
|
|
324
|
+
expect: item.expect,
|
|
325
|
+
graders,
|
|
326
|
+
deciders: item.deciders,
|
|
327
|
+
standing,
|
|
328
|
+
order: args.plan.order,
|
|
329
|
+
previousOf: (name) => {
|
|
330
|
+
const grader = byName.get(name);
|
|
331
|
+
return previousFrom(
|
|
332
|
+
newest.get(name),
|
|
333
|
+
grader?.version,
|
|
334
|
+
grader?.agent,
|
|
335
|
+
grader ? givenFor(grader, facts) : undefined,
|
|
336
|
+
);
|
|
337
|
+
},
|
|
338
|
+
mayContinue: (made) => args.budget === undefined || estimated + cost(made) < args.budget,
|
|
339
|
+
});
|
|
340
|
+
if ("errored" in result) {
|
|
341
|
+
appendScore(trial.dir, {
|
|
342
|
+
kind: SCORE_KIND,
|
|
343
|
+
at: args.now().toISOString(),
|
|
344
|
+
facts,
|
|
345
|
+
entries: [],
|
|
346
|
+
errored: { by: "dataset", phase: "facts", ...result.errored },
|
|
347
|
+
});
|
|
348
|
+
add(errored, "expect");
|
|
349
|
+
args.progress?.(
|
|
350
|
+
` ${trial.record.case} ${trial.record.trial}: expect errored: ${result.errored.reason}`,
|
|
351
|
+
);
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
// A grader skipped again over a skip says nothing new.
|
|
355
|
+
const entries = result.entries.filter((e) => !(e.skipped && newest.get(e.grader)?.skipped));
|
|
356
|
+
// Facts read clean after grading errored: the score says so, even with no grade new.
|
|
357
|
+
if (entries.length > 0 || trial.record.errored?.phase === "facts") {
|
|
358
|
+
appendScore(trial.dir, { kind: SCORE_KIND, at: args.now().toISOString(), facts, entries });
|
|
359
|
+
}
|
|
360
|
+
for (const entry of entries) {
|
|
361
|
+
if (entry.skipped) continue;
|
|
362
|
+
add(entry.errored ? errored : graded, entry.grader);
|
|
363
|
+
}
|
|
364
|
+
estimated += cost(entries);
|
|
365
|
+
const said = entries.map(
|
|
366
|
+
(e) =>
|
|
367
|
+
`${e.grader} ${e.errored ? `errored: ${e.errored.reason}` : e.skipped ? "skipped" : (e.verdict ?? e.notApplies ?? "graded")}`,
|
|
368
|
+
);
|
|
369
|
+
args.progress?.(
|
|
370
|
+
` ${trial.record.case} ${trial.record.trial}: ${said.join(", ") || "nothing new"}`,
|
|
371
|
+
);
|
|
372
|
+
if ("stopped" in result && result.stopped) stopped = true;
|
|
373
|
+
} finally {
|
|
374
|
+
rmSync(work, { recursive: true, force: true });
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
// Stops starting trials once the budget stopped one; the ones grading finish.
|
|
378
|
+
const atOnce = args.atOnce ?? 1;
|
|
379
|
+
const items = [...args.plan.items];
|
|
380
|
+
const running = new Set<Promise<void>>();
|
|
381
|
+
let failure: { error: unknown } | undefined;
|
|
382
|
+
for (;;) {
|
|
383
|
+
while (!failure && !stopped && running.size < atOnce && items.length > 0) {
|
|
384
|
+
const grading: Promise<void> = gradeOne(items.shift()!)
|
|
385
|
+
.catch((error) => {
|
|
386
|
+
failure ??= { error };
|
|
387
|
+
})
|
|
388
|
+
.finally(() => running.delete(grading));
|
|
389
|
+
running.add(grading);
|
|
390
|
+
}
|
|
391
|
+
if (running.size === 0) break;
|
|
392
|
+
await Promise.race(running);
|
|
393
|
+
}
|
|
394
|
+
if (failure) throw failure.error;
|
|
395
|
+
return { graded, errored, estimate: estimated, stopped };
|
|
396
|
+
}
|