@agentswf/lab 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +15 -2
- package/package.json +46 -4
- package/schema/lab-check.schema.json +64 -0
- package/schema/lab-config.schema.json +187 -0
- package/schema/lab-final.schema.json +48 -0
- package/schema/lab-good-record.schema.json +70 -0
- package/schema/lab-grade.schema.json +49 -0
- package/schema/lab-key.schema.json +124 -0
- package/schema/lab-label.schema.json +32 -0
- package/schema/lab-loop-report.schema.json +221 -0
- package/schema/lab-loop.schema.json +141 -0
- package/schema/lab-plan.schema.json +128 -0
- package/schema/lab-previous.schema.json +70 -0
- package/schema/lab-proposal.schema.json +52 -0
- package/schema/lab-report.schema.json +1128 -0
- package/schema/lab-run.schema.json +253 -0
- package/schema/lab-runs.schema.json +132 -0
- package/schema/lab-score.schema.json +319 -0
- package/schema/lab-spread.schema.json +110 -0
- package/schema/lab-trial.schema.json +543 -0
- package/schema/lab-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 +131 -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 +185 -0
- package/src/format/key.ts +168 -0
- package/src/format/loop.ts +179 -0
- package/src/format/output.ts +542 -0
- package/src/format/records.ts +443 -0
- package/src/format/schema-files.ts +64 -0
- package/src/format/settings.ts +559 -0
- package/src/format/trial-env.ts +67 -0
- package/src/format/trial-file.ts +134 -0
- package/src/help/awf-lab.txt +29 -0
- package/src/help/case.txt +39 -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 +61 -0
- package/src/help/runs.txt +11 -0
- package/src/help/score.txt +28 -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 +251 -0
- package/src/lab/capture-command.ts +302 -0
- package/src/lab/capture.ts +234 -0
- package/src/lab/check-command.ts +187 -0
- package/src/lab/cli.ts +325 -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 +283 -0
- package/src/lab/criteria.ts +69 -0
- package/src/lab/dataset.ts +375 -0
- package/src/lab/eval-files.ts +196 -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 +172 -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 +227 -0
- package/src/lab/labels.ts +211 -0
- package/src/lab/loop-code.ts +255 -0
- package/src/lab/loop-command.ts +774 -0
- package/src/lab/loop-records.ts +144 -0
- package/src/lab/loop.ts +864 -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 +155 -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 +157 -0
- package/src/lab/report.ts +936 -0
- package/src/lab/reuse.ts +134 -0
- package/src/lab/run-command.ts +958 -0
- package/src/lab/run-logs.ts +89 -0
- package/src/lab/run-report.ts +286 -0
- package/src/lab/runs-command.ts +171 -0
- package/src/lab/runs.ts +172 -0
- package/src/lab/scaffold.ts +94 -0
- package/src/lab/score-command.ts +197 -0
- package/src/lab/score.ts +396 -0
- package/src/lab/store.ts +383 -0
- package/src/lab/target-stub.txt +18 -0
- package/src/lab/text.ts +29 -0
- package/src/lab/trial-settings.ts +105 -0
- package/src/lab/trial.ts +439 -0
- package/src/lab/usage.ts +274 -0
- package/src/lab/verdict.ts +161 -0
- package/src/lab/workflow-graders.ts +164 -0
- package/src/lab/workspace.ts +496 -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,138 @@
|
|
|
1
|
+
import { type Column, PARAM_NAME, type Params, type RunRecord } from "../format/records";
|
|
2
|
+
import { type DatasetInfo, declaredList } from "./dataset";
|
|
3
|
+
import { TARGET_FILE } from "./eval-files";
|
|
4
|
+
import { Refusal } from "./refusal";
|
|
5
|
+
|
|
6
|
+
/** `--param` and `--vary`, read: the values every column shares, and each varied name's values. */
|
|
7
|
+
export type ParamPlan = { fixed: Params; varied: [name: string, values: string[]][] };
|
|
8
|
+
|
|
9
|
+
/** Reads `--param {name}={value}` and `--vary {name}={a,b}`, each repeatable. */
|
|
10
|
+
export function readParams(param: readonly string[], vary: readonly string[]): ParamPlan {
|
|
11
|
+
const fixed: Params = {};
|
|
12
|
+
const varied: [string, string[]][] = [];
|
|
13
|
+
const seen = new Set<string>();
|
|
14
|
+
const split = (flag: string, given: string) => {
|
|
15
|
+
const at = given.indexOf("=");
|
|
16
|
+
const name = at > 0 ? given.slice(0, at) : "";
|
|
17
|
+
const value = at > 0 ? given.slice(at + 1) : "";
|
|
18
|
+
if (!PARAM_NAME.test(name) || value === "") {
|
|
19
|
+
throw new Refusal(
|
|
20
|
+
`${flag} ${given}: give {name}=${flag === "--vary" ? "{a,b}" : "{value}"}, the name a letter then letters, digits, - or _`,
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
if (seen.has(name)) throw new Refusal(`${flag} ${given}: ${name} is given twice`);
|
|
24
|
+
seen.add(name);
|
|
25
|
+
return { name, value };
|
|
26
|
+
};
|
|
27
|
+
for (const given of param) {
|
|
28
|
+
const { name, value } = split("--param", given);
|
|
29
|
+
fixed[name] = value;
|
|
30
|
+
}
|
|
31
|
+
for (const given of vary) {
|
|
32
|
+
const { name, value } = split("--vary", given);
|
|
33
|
+
const values = value.split(",").map((v) => v.trim());
|
|
34
|
+
if (values.some((v) => v === "") || new Set(values).size !== values.length) {
|
|
35
|
+
throw new Refusal(`--vary ${given}: each value once, none empty`);
|
|
36
|
+
}
|
|
37
|
+
if (values.length < 2) {
|
|
38
|
+
throw new Refusal(
|
|
39
|
+
`--vary ${given}: give two values or more; one is --param ${name}=${value}`,
|
|
40
|
+
);
|
|
41
|
+
}
|
|
42
|
+
varied.push([name, values]);
|
|
43
|
+
}
|
|
44
|
+
return { fixed, varied };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Every combination of the varied values, the first `--vary` outermost, each with the fixed. */
|
|
48
|
+
export function combinations({ fixed, varied }: ParamPlan): Params[] {
|
|
49
|
+
let combos: Params[] = [{ ...fixed }];
|
|
50
|
+
for (const [name, values] of varied) {
|
|
51
|
+
combos = combos.flatMap((combo) => values.map((value) => ({ ...combo, [name]: value })));
|
|
52
|
+
}
|
|
53
|
+
return combos;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Each combination over the dataset's parameters: `target.ts`'s defaults under its entries' values,
|
|
58
|
+
* under the flags'. A name `target.ts` doesn't declare is refused, and so is a required one that
|
|
59
|
+
* nothing gives.
|
|
60
|
+
*/
|
|
61
|
+
export function withDeclared(info: DatasetInfo, combos: readonly Params[]): Params[] {
|
|
62
|
+
const file = `${info.evalDir}/${TARGET_FILE}`;
|
|
63
|
+
return combos.map((combo) => {
|
|
64
|
+
const params: Params = {};
|
|
65
|
+
for (const [name, { value }] of Object.entries(info.params)) {
|
|
66
|
+
if (value !== undefined) params[name] = value;
|
|
67
|
+
}
|
|
68
|
+
for (const [name, value] of Object.entries(combo)) {
|
|
69
|
+
if (!(name in info.params)) {
|
|
70
|
+
throw new Refusal(
|
|
71
|
+
`parameter ${name} is not one ${file} declares${declaredList(info.params)}: declare it in defineTarget's params`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
params[name] = value;
|
|
75
|
+
}
|
|
76
|
+
const missing = Object.keys(info.params).filter((name) => params[name] === undefined);
|
|
77
|
+
if (missing.length > 0) {
|
|
78
|
+
throw new Refusal(
|
|
79
|
+
`${file} requires parameter ${missing.join(", ")}: give --param ${missing[0]}={value}, or a value in the dataset's entry`,
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
return params;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The run's columns: each folder under each combination, the folders outermost, so the first is
|
|
88
|
+
* the reference column, your checkout under each `--vary`'s first value.
|
|
89
|
+
*/
|
|
90
|
+
export function columnsOf(folders: number, combos: readonly Params[]): Column[] {
|
|
91
|
+
return Array.from({ length: folders }, (_, folder) =>
|
|
92
|
+
combos.map((params) => ({ folder, params })),
|
|
93
|
+
).flat();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function sameParams(a: Params, b: Params): boolean {
|
|
97
|
+
const keys = Object.keys(a);
|
|
98
|
+
return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The column of a run with this folder and these parameters, if it has one. */
|
|
102
|
+
export function columnLike(run: RunRecord, path: string, params: Params): number | undefined {
|
|
103
|
+
const at = run.columns.findIndex(
|
|
104
|
+
(c) => run.folders[c.folder]?.path === path && sameParams(c.params, params),
|
|
105
|
+
);
|
|
106
|
+
return at < 0 ? undefined : at;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The parameters whose value differs between the run's columns, in the order first given. */
|
|
110
|
+
function varyingNames(run: RunRecord): string[] {
|
|
111
|
+
const names = [...new Set(run.columns.flatMap((c) => Object.keys(c.params)))];
|
|
112
|
+
return names.filter((name) => new Set(run.columns.map((c) => c.params[name])).size > 1);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* A column's name in the report: `against {n}` for another folder, `the same code again` for the
|
|
117
|
+
* first folder named twice, then each parameter that differs between columns, such as `model=b`;
|
|
118
|
+
* your checkout alone is "this checkout".
|
|
119
|
+
*/
|
|
120
|
+
export function columnLabel(run: RunRecord, index: number): string {
|
|
121
|
+
const column = run.columns[index];
|
|
122
|
+
if (!column) return `column ${index}`;
|
|
123
|
+
const params = varyingNames(run).map((name) => `${name}=${column.params[name] ?? "-"}`);
|
|
124
|
+
const again = column.folder > 0 && run.folders[column.folder]?.path === run.folders[0]?.path;
|
|
125
|
+
const parts = [
|
|
126
|
+
...(column.folder > 0 ? [again ? "the same code again" : `against ${column.folder}`] : []),
|
|
127
|
+
...params,
|
|
128
|
+
];
|
|
129
|
+
return parts.length > 0 ? parts.join(" ") : "this checkout";
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The parameters every column shares, as `name=value`, for the report's head. */
|
|
133
|
+
export function sharedParams(run: RunRecord): string[] {
|
|
134
|
+
const varying = new Set(varyingNames(run));
|
|
135
|
+
return Object.entries(run.columns[0]?.params ?? {})
|
|
136
|
+
.filter(([name]) => !varying.has(name))
|
|
137
|
+
.map(([name, value]) => `${name}=${value}`);
|
|
138
|
+
}
|
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { isAbsolute, join, relative } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { type LabPlan, LabPlanSchema } from "../format/output";
|
|
6
|
+
import type { RunRecord } from "../format/records";
|
|
7
|
+
import { type AllowanceSource, awfAllowance } from "../shared/allowance";
|
|
8
|
+
import {
|
|
9
|
+
awfLogs,
|
|
10
|
+
awfRunEstimate,
|
|
11
|
+
processRunner,
|
|
12
|
+
type Runner,
|
|
13
|
+
withoutCallingSession,
|
|
14
|
+
} from "../shared/runner";
|
|
15
|
+
import { checkSchema, describeProblems } from "../shared/validate";
|
|
16
|
+
import { codeGraders } from "./code-graders";
|
|
17
|
+
import { sentencesGrader } from "./criteria";
|
|
18
|
+
import { type CaseInfo, type DatasetInfo, graderSpecs, readCases, readDataset } from "./dataset";
|
|
19
|
+
import type { HelperPlace } from "./eval-files";
|
|
20
|
+
import { type FactsReader, factsReader } from "./facts";
|
|
21
|
+
import type { LabGrader } from "./grading";
|
|
22
|
+
import { type FolderSetup, inspectFolder } from "./inspect";
|
|
23
|
+
import { readRecords } from "./record-copies";
|
|
24
|
+
import { Refusal } from "./refusal";
|
|
25
|
+
import { awfRunsOf, RUN_ID, readRunRecord, runIds, takeLock, UnreadableRecord } from "./store";
|
|
26
|
+
import { definedOf, type TrialLab } from "./trial";
|
|
27
|
+
import { afterMsOf } from "./trial-settings";
|
|
28
|
+
import { workflowGraders } from "./workflow-graders";
|
|
29
|
+
import {
|
|
30
|
+
type CaseWorkspace,
|
|
31
|
+
chooseDataset,
|
|
32
|
+
findEvals,
|
|
33
|
+
openCaseWorkspace,
|
|
34
|
+
recordsFolders,
|
|
35
|
+
} from "./workspace";
|
|
36
|
+
|
|
37
|
+
// What the commands share: the options and environment they run under, the workspace and dataset
|
|
38
|
+
// they open, and the graders they grade with.
|
|
39
|
+
|
|
40
|
+
export type CasesEnvironment = {
|
|
41
|
+
cwd?: string;
|
|
42
|
+
stdout?: (text: string) => void;
|
|
43
|
+
stderr?: (text: string) => void;
|
|
44
|
+
/** Runs one trial's `awf run`; absent, the folder's own `awf`, as a process. */
|
|
45
|
+
runner?: Runner;
|
|
46
|
+
/** `awf logs` of a trial's run, for the marker search; absent, the folder's own `awf`, unless
|
|
47
|
+
* the runner is scripted. */
|
|
48
|
+
logs?: TrialLab["logs"];
|
|
49
|
+
/** What a run that printed no record is estimated at; absent, the folder's own `awf`, unless
|
|
50
|
+
* the runner is scripted. */
|
|
51
|
+
estimate?: TrialLab["estimate"];
|
|
52
|
+
/** Asked before a run; absent, a run on a terminal asks the operator. */
|
|
53
|
+
confirm?: (plan: string) => Promise<boolean>;
|
|
54
|
+
/** The home `~/.awf/lab` is in. */
|
|
55
|
+
home?: string;
|
|
56
|
+
/** Where trial folders are made. */
|
|
57
|
+
tmp?: string;
|
|
58
|
+
/** The environment trials start from. */
|
|
59
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
60
|
+
/** The checks of a folder before the first trial; absent, the real ones. */
|
|
61
|
+
inspect?: (root: string, targetScript: string) => Promise<FolderSetup>;
|
|
62
|
+
/** `awf allowance --json`, for a loop's wait; absent, the operator's, unless the runner is scripted. */
|
|
63
|
+
allowance?: AllowanceSource;
|
|
64
|
+
/** Graders a test adds after `expect`, before the dataset's own. */
|
|
65
|
+
graders?: readonly LabGrader[];
|
|
66
|
+
now?: () => Date;
|
|
67
|
+
/** How often a loop waiting for the store looks again; 2s unless a test says. */
|
|
68
|
+
storePollMs?: number;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export type Options = {
|
|
72
|
+
/** `-C {folder}`, as given: the command runs as if started there. */
|
|
73
|
+
folder?: string;
|
|
74
|
+
dataset?: string;
|
|
75
|
+
cases?: string[];
|
|
76
|
+
/** Folders `--against` names, as given. */
|
|
77
|
+
against: string[];
|
|
78
|
+
/** `--param` and `--vary`, as given. */
|
|
79
|
+
param: string[];
|
|
80
|
+
/** `run --limit {phase}={duration}`, as given. */
|
|
81
|
+
limit: string[];
|
|
82
|
+
fresh: boolean;
|
|
83
|
+
/** `run --holdout`: the held-out cases alone. */
|
|
84
|
+
holdout: boolean;
|
|
85
|
+
clear: boolean;
|
|
86
|
+
md: boolean;
|
|
87
|
+
tags?: string[];
|
|
88
|
+
vary: string[];
|
|
89
|
+
failed: boolean;
|
|
90
|
+
trials?: number;
|
|
91
|
+
yes: boolean;
|
|
92
|
+
case?: string;
|
|
93
|
+
grader?: string;
|
|
94
|
+
good: boolean;
|
|
95
|
+
needsWork?: string;
|
|
96
|
+
dryRun: boolean;
|
|
97
|
+
budget?: number;
|
|
98
|
+
json: boolean;
|
|
99
|
+
help: boolean;
|
|
100
|
+
tries?: number;
|
|
101
|
+
allowance?: number | "off";
|
|
102
|
+
/** `--concurrency {n}`: trials or grader workflows at once, over the local file's. */
|
|
103
|
+
concurrency?: number;
|
|
104
|
+
/** `report --loop {name or id}`, or `config --loop {name}`. */
|
|
105
|
+
loop?: string;
|
|
106
|
+
/** `case pin --replace`: a known good record replaced. */
|
|
107
|
+
replace: boolean;
|
|
108
|
+
/** `loop run --new`: a new loop from the entry as it is now, the one before it kept. */
|
|
109
|
+
new: boolean;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
export type Context = {
|
|
113
|
+
/** The command as typed, its verb and a loop's name too: `loop run desk`; the lock names it. */
|
|
114
|
+
command?: string;
|
|
115
|
+
cwd: string;
|
|
116
|
+
home: string;
|
|
117
|
+
options: Options;
|
|
118
|
+
environment: CasesEnvironment;
|
|
119
|
+
stdout: (text: string) => void;
|
|
120
|
+
stderr: (text: string) => void;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* What the lab reaches outside itself through: the runner, and the `awf logs`, run-estimate and
|
|
125
|
+
* allowance readers. A scripted runner switches the real readers off: they would read runs it
|
|
126
|
+
* never started. The logs reader then reads nothing, so the marker search fails closed.
|
|
127
|
+
*/
|
|
128
|
+
export function externalsOf(environment: CasesEnvironment): {
|
|
129
|
+
runner: Runner;
|
|
130
|
+
logs: TrialLab["logs"];
|
|
131
|
+
estimate?: TrialLab["estimate"];
|
|
132
|
+
allowance?: AllowanceSource;
|
|
133
|
+
} {
|
|
134
|
+
const scripted = environment.runner !== undefined;
|
|
135
|
+
const estimate = environment.estimate ?? (scripted ? undefined : awfRunEstimate);
|
|
136
|
+
const allowance = environment.allowance ?? (scripted ? undefined : awfAllowance);
|
|
137
|
+
return {
|
|
138
|
+
runner: environment.runner ?? processRunner(),
|
|
139
|
+
logs:
|
|
140
|
+
environment.logs ??
|
|
141
|
+
(scripted ? async () => ({ unread: "no awf logs beside a scripted runner" }) : awfLogs),
|
|
142
|
+
...(estimate ? { estimate } : {}),
|
|
143
|
+
...(allowance ? { allowance } : {}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** A path as a person in `cwd` would type it: relative when under it. */
|
|
148
|
+
export function shownPath(context: Pick<Context, "cwd">, path: string): string {
|
|
149
|
+
const under = relative(context.cwd, path);
|
|
150
|
+
return under && !under.startsWith("..") && !isAbsolute(under) ? under : path;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** A message's paths under `cwd`, relative to it. */
|
|
154
|
+
export function relativePaths(cwd: string, message: string): string {
|
|
155
|
+
const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
156
|
+
return message.replace(new RegExp(`(^|[\\s(:'"=,])${escaped}/`, "gm"), "$1");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The environment a trial, grader or helper starts from: the lab's, less the calling session. */
|
|
160
|
+
export const envOf = (context: Context) =>
|
|
161
|
+
definedOf(withoutCallingSession(context.environment.env ?? process.env));
|
|
162
|
+
|
|
163
|
+
/** Where trial folders and the lab's other scratch folders are made. */
|
|
164
|
+
export const tmpOf = (context: Context) => realpathSync(context.environment.tmp ?? tmpdir());
|
|
165
|
+
|
|
166
|
+
/** Where the grade helper reads the project's files: your checkout, the lab's environment. */
|
|
167
|
+
export const helperPlace = (context: Context, workspace: CaseWorkspace): HelperPlace => ({
|
|
168
|
+
root: workspace.root,
|
|
169
|
+
env: envOf(context),
|
|
170
|
+
tmp: tmpOf(context),
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
export function workspaceOf(context: Context): CaseWorkspace {
|
|
174
|
+
const evals = findEvals(context.cwd);
|
|
175
|
+
if (!evals) {
|
|
176
|
+
throw new Refusal(
|
|
177
|
+
`no evals/ here or above ${context.cwd}; awf-lab case new {dataset}/{case} makes one`,
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
const opened = openCaseWorkspace(evals, context.home, {
|
|
181
|
+
env: envOf(context),
|
|
182
|
+
tmp: tmpOf(context),
|
|
183
|
+
});
|
|
184
|
+
const { concurrency } = context.options;
|
|
185
|
+
const workspace =
|
|
186
|
+
concurrency === undefined
|
|
187
|
+
? opened
|
|
188
|
+
: {
|
|
189
|
+
...opened,
|
|
190
|
+
concurrency,
|
|
191
|
+
from: { ...opened.from, concurrency: "--concurrency" },
|
|
192
|
+
};
|
|
193
|
+
for (const records of recordsFolders(workspace)) readRecords(workspace.store, records);
|
|
194
|
+
return workspace;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* A dataset and its cases: those not held out, or with `holdout` the held-out ones alone, so
|
|
199
|
+
* nothing tuned on the rest ever sees them unasked.
|
|
200
|
+
*/
|
|
201
|
+
export function loadDataset(
|
|
202
|
+
context: Context,
|
|
203
|
+
workspace: CaseWorkspace,
|
|
204
|
+
name?: string,
|
|
205
|
+
/** `all` for a kept run's report or score: its cases are whichever it ran. */
|
|
206
|
+
holdout: boolean | "all" = false,
|
|
207
|
+
): { info: DatasetInfo; cases: CaseInfo[] } {
|
|
208
|
+
const info = readDataset(chooseDataset(workspace, name), helperPlace(context, workspace));
|
|
209
|
+
const all = readCases(info);
|
|
210
|
+
return {
|
|
211
|
+
info,
|
|
212
|
+
cases: holdout === "all" ? all : all.filter((c) => (c.key.holdout === true) === holdout),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Whether a case carries any of these tags. */
|
|
217
|
+
export const tagged = (info: CaseInfo, tags: readonly string[]) =>
|
|
218
|
+
(info.key.tags ?? []).some((t) => tags.includes(t));
|
|
219
|
+
|
|
220
|
+
async function askOperator(
|
|
221
|
+
plan: string,
|
|
222
|
+
stderr: (text: string) => void,
|
|
223
|
+
question: string,
|
|
224
|
+
): Promise<boolean> {
|
|
225
|
+
stderr(plan);
|
|
226
|
+
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
227
|
+
try {
|
|
228
|
+
return /^y(es)?$/i.test((await prompt.question(`${question} [y/N] `)).trim());
|
|
229
|
+
} finally {
|
|
230
|
+
prompt.close();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Asks about a plan on a terminal, unless `--yes`, or prints it; false when the operator declines.
|
|
236
|
+
* The question goes to stderr, so `--json` still asks at a terminal: what it starts costs money.
|
|
237
|
+
*/
|
|
238
|
+
export async function confirmPlan(
|
|
239
|
+
context: Context,
|
|
240
|
+
plan: string,
|
|
241
|
+
question = "run it?",
|
|
242
|
+
): Promise<boolean> {
|
|
243
|
+
const { environment, options, stderr } = context;
|
|
244
|
+
const confirm =
|
|
245
|
+
environment.confirm ??
|
|
246
|
+
(process.stdin.isTTY && !options.yes
|
|
247
|
+
? (text: string) => askOperator(text, stderr, question)
|
|
248
|
+
: undefined);
|
|
249
|
+
if (confirm && !options.yes) return confirm(plan);
|
|
250
|
+
stderr(plan);
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function lockHeld(
|
|
255
|
+
workspace: CaseWorkspace,
|
|
256
|
+
held: { heldBy: number | undefined; command?: string },
|
|
257
|
+
): string {
|
|
258
|
+
const file = join(workspace.store, "lock");
|
|
259
|
+
return held.heldBy === undefined
|
|
260
|
+
? `${file} holds no process this lab can read: remove it once no awf-lab runs`
|
|
261
|
+
: `${held.command ? `awf-lab ${held.command}` : "another awf-lab command"} (process ${held.heldBy}) holds this project's store, ${file}`;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Runs `work` holding the store's lock. While another command holds it, refused; or, with `wait`,
|
|
266
|
+
* as a loop's later runs are, waiting for it, said once.
|
|
267
|
+
*/
|
|
268
|
+
export async function withLock<T>(
|
|
269
|
+
context: Context,
|
|
270
|
+
workspace: CaseWorkspace,
|
|
271
|
+
work: () => Promise<T>,
|
|
272
|
+
wait = false,
|
|
273
|
+
): Promise<T> {
|
|
274
|
+
let lock = takeLock(workspace.store, context.command);
|
|
275
|
+
let said = false;
|
|
276
|
+
while ("heldBy" in lock) {
|
|
277
|
+
// A lock no process this lab can read never frees itself: waiting on it would never end.
|
|
278
|
+
if (!wait || lock.heldBy === undefined) throw new Refusal(lockHeld(workspace, lock));
|
|
279
|
+
if (!said) context.stderr(`waiting for the store: ${lockHeld(workspace, lock)}`);
|
|
280
|
+
said = true;
|
|
281
|
+
await new Promise((done) => setTimeout(done, context.environment.storePollMs ?? 2000));
|
|
282
|
+
lock = takeLock(workspace.store, context.command);
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
return await work();
|
|
286
|
+
} finally {
|
|
287
|
+
lock.release();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** `--dry-run --json`: the plan, checked against its schema before it is printed. */
|
|
292
|
+
export function printPlan(context: Context, plan: LabPlan): void {
|
|
293
|
+
const checked = checkSchema(LabPlanSchema, plan);
|
|
294
|
+
if (!checked.ok) throw new Error(describeProblems("--dry-run --json", checked.problems));
|
|
295
|
+
context.stdout(JSON.stringify(plan, null, 2));
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** A budget stop leaves work undone: 3, unless the report already exits worse. */
|
|
299
|
+
export const budgetExit = (stopped: boolean, exit: number) => (stopped && exit === 0 ? 3 : exit);
|
|
300
|
+
|
|
301
|
+
/** Your checkout's folder, inspected once, when first needed. */
|
|
302
|
+
export function checkoutFolder(
|
|
303
|
+
context: Context,
|
|
304
|
+
workspace: CaseWorkspace,
|
|
305
|
+
targetScript: () => string,
|
|
306
|
+
): () => Promise<FolderSetup> {
|
|
307
|
+
let inspected: Promise<FolderSetup> | undefined;
|
|
308
|
+
return () =>
|
|
309
|
+
(inspected ??= (context.environment.inspect ?? inspectFolder)(workspace.root, targetScript()));
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** A trial's id, its workflow run's: `20261119T054028Z-c13b6e75`. */
|
|
313
|
+
const TRIAL_ID = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]+$/;
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The run named, by its id or the last four characters of it; or the newest, yours first, that no
|
|
317
|
+
* loop made: a loop's runs are its report's.
|
|
318
|
+
*/
|
|
319
|
+
export function chooseRun(
|
|
320
|
+
workspace: CaseWorkspace,
|
|
321
|
+
names: readonly string[],
|
|
322
|
+
command: string,
|
|
323
|
+
): RunRecord {
|
|
324
|
+
if (names.length > 1) {
|
|
325
|
+
throw new Refusal(`${command} takes one run; got ${names.length}: ${names.join(" ")}`);
|
|
326
|
+
}
|
|
327
|
+
const ids = runIds(workspace.store);
|
|
328
|
+
const given = names[0];
|
|
329
|
+
if (given === undefined) {
|
|
330
|
+
const own = ids.flatMap((id) => {
|
|
331
|
+
try {
|
|
332
|
+
const run = readRunRecord(workspace.store, id);
|
|
333
|
+
return run && run.loop === undefined ? [run] : [];
|
|
334
|
+
} catch (error) {
|
|
335
|
+
if (error instanceof UnreadableRecord) return [];
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
// The store is the project's: another worktree's newest run is not the one you mean.
|
|
340
|
+
const yours = own.filter((run) => run.folders[0]?.path === workspace.root);
|
|
341
|
+
const newest = (yours.at(-1) ?? own.at(-1))?.id;
|
|
342
|
+
if (newest === undefined) {
|
|
343
|
+
throw new Refusal(`no runs in ${workspace.store} yet; awf-lab run makes one`);
|
|
344
|
+
}
|
|
345
|
+
return readRunOrRefuse(workspace, newest);
|
|
346
|
+
}
|
|
347
|
+
if (TRIAL_ID.test(given)) {
|
|
348
|
+
throw new Refusal(
|
|
349
|
+
`${given} is a trial's id: ${command} takes a run from awf-lab runs; label and capture take trial ids`,
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
if (!RUN_ID.test(given) && !/^[0-9a-f]{4}$/.test(given)) {
|
|
353
|
+
throw new Refusal(
|
|
354
|
+
`${given} is no run: a run is its id, such as 20261117-142233-a3f9, or its last four characters; awf-lab runs lists them`,
|
|
355
|
+
);
|
|
356
|
+
}
|
|
357
|
+
const found = ids.filter((id) => id === given || id.endsWith(`-${given}`));
|
|
358
|
+
if (found.length === 0)
|
|
359
|
+
throw new Refusal(`no run ${given} in ${workspace.store}; awf-lab runs lists them`);
|
|
360
|
+
if (found.length > 1) {
|
|
361
|
+
throw new Refusal(
|
|
362
|
+
`${given} names ${found.length} runs: ${found.join(", ")}; give the whole id`,
|
|
363
|
+
);
|
|
364
|
+
}
|
|
365
|
+
return readRunOrRefuse(workspace, found[0]!);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Refuses a lab run's id given where a trial's is wanted, naming where trial ids are listed. */
|
|
369
|
+
export function refuseLabRun(workspace: CaseWorkspace, given: string, command: string): void {
|
|
370
|
+
const run =
|
|
371
|
+
RUN_ID.test(given) ||
|
|
372
|
+
(/^[0-9a-f]{4}$/.test(given) && runIds(workspace.store).some((id) => id.endsWith(`-${given}`)));
|
|
373
|
+
if (run) {
|
|
374
|
+
throw new Refusal(
|
|
375
|
+
`${given} is a run's id: ${command} takes a trial's id, which report --case {case} lists`,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function readRunOrRefuse(workspace: CaseWorkspace, id: string): RunRecord {
|
|
381
|
+
const run = readRunRecord(workspace.store, id);
|
|
382
|
+
if (!run) throw new Refusal(`no run ${id} in ${workspace.store}`);
|
|
383
|
+
return run;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* The test's graders and the dataset's own, each with its version read in your checkout before
|
|
388
|
+
* the first grade: a grader that doesn't load stops the command (exit 2). Grader workflows run on
|
|
389
|
+
* your checkout's `awf`, which `folder` gives when one is first needed.
|
|
390
|
+
*/
|
|
391
|
+
export async function datasetGraders(
|
|
392
|
+
context: Context,
|
|
393
|
+
workspace: CaseWorkspace,
|
|
394
|
+
info: DatasetInfo,
|
|
395
|
+
folder: () => Promise<FolderSetup>,
|
|
396
|
+
now: () => Date,
|
|
397
|
+
): Promise<LabGrader[]> {
|
|
398
|
+
const { environment } = context;
|
|
399
|
+
const { runner } = externalsOf(environment);
|
|
400
|
+
const specs = graderSpecs(info);
|
|
401
|
+
const runRoot = awfRunsOf(workspace.store);
|
|
402
|
+
const workflows = workflowGraders(
|
|
403
|
+
{ dataset: info, awf: async () => (await folder()).awf, runner, runRoot, now },
|
|
404
|
+
specs,
|
|
405
|
+
);
|
|
406
|
+
const made = new Map(
|
|
407
|
+
[...codeGraders(info, workspace.root, afterMsOf(info)), ...workflows].map((g) => [g.name, g]),
|
|
408
|
+
);
|
|
409
|
+
// In `grading.ts`'s order, which is the order they run in.
|
|
410
|
+
const listed = specs.map((spec) =>
|
|
411
|
+
spec.kind === "sentences"
|
|
412
|
+
? sentencesGrader({ runner, runRoot, now }, spec)
|
|
413
|
+
: made.get(spec.name)!,
|
|
414
|
+
);
|
|
415
|
+
return [...(environment.graders ?? []), ...listed];
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The dataset's `grading.ts` `facts`, run in your checkout, the one that ran the command. */
|
|
419
|
+
export function datasetFacts(
|
|
420
|
+
context: Context,
|
|
421
|
+
workspace: CaseWorkspace,
|
|
422
|
+
info: DatasetInfo,
|
|
423
|
+
): FactsReader {
|
|
424
|
+
return factsReader(info, workspace.root, envOf(context), afterMsOf(info));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** The dataset's graders, only counted, never run, so no folder is inspected. */
|
|
428
|
+
export function countedGraders(context: Context, workspace: CaseWorkspace, info: DatasetInfo) {
|
|
429
|
+
return datasetGraders(
|
|
430
|
+
context,
|
|
431
|
+
workspace,
|
|
432
|
+
info,
|
|
433
|
+
() => Promise.reject(new Error("counting graders runs none")),
|
|
434
|
+
() => new Date(),
|
|
435
|
+
);
|
|
436
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { ComparedTrial, Room } from "../env/compare";
|
|
4
|
+
import type { RunRecord } from "../format/records";
|
|
5
|
+
import type { Decision } from "../shared/compare";
|
|
6
|
+
import { runHelper } from "./code-graders";
|
|
7
|
+
import { newestEntries, trialOutcome } from "./outcome";
|
|
8
|
+
import type { CaseBar } from "./runs";
|
|
9
|
+
import type { StoredTrial } from "./store";
|
|
10
|
+
|
|
11
|
+
/** What `compare` said of one column against the reference, or why it couldn't say. */
|
|
12
|
+
export type ColumnDecision = Decision | { error: string };
|
|
13
|
+
|
|
14
|
+
/** A stored trial as a comparison sees it; an errored or leaked one is left out, as missing. */
|
|
15
|
+
export function comparedTrial(
|
|
16
|
+
trial: StoredTrial,
|
|
17
|
+
deciders: ReadonlySet<string> | undefined,
|
|
18
|
+
): ComparedTrial | undefined {
|
|
19
|
+
const { record, scores } = trial;
|
|
20
|
+
const { outcome } = trialOutcome(record, scores, deciders);
|
|
21
|
+
if (outcome === "errored" || outcome === "leaked") return undefined;
|
|
22
|
+
const numbers: Record<string, number> = {};
|
|
23
|
+
for (const entry of newestEntries(scores)) {
|
|
24
|
+
if (entry.skipped || entry.errored) continue;
|
|
25
|
+
if (deciders && !deciders.has(entry.grader)) continue;
|
|
26
|
+
for (const [name, number] of Object.entries(entry.numbers ?? {})) {
|
|
27
|
+
if ("value" in number) numbers[`${entry.grader}.${name}`] = number.value;
|
|
28
|
+
else if (number.of > 0) numbers[`${entry.grader}.${name}`] = number.count / number.of;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return {
|
|
32
|
+
case: record.case,
|
|
33
|
+
trial: record.trial,
|
|
34
|
+
passed: outcome === "passed" ? true : outcome === "failed" ? false : null,
|
|
35
|
+
workflowFailed: record.workflowError !== undefined || record.stopped !== undefined,
|
|
36
|
+
numbers,
|
|
37
|
+
cost: record.estimate ?? null,
|
|
38
|
+
seconds: record.ms / 1000,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Each column but the reference, judged against it by the dataset's `compare` in `grading.ts`,
|
|
44
|
+
* run in the helper process in your checkout. Undefined when the dataset says no `compare`.
|
|
45
|
+
*/
|
|
46
|
+
export async function compareColumns(args: {
|
|
47
|
+
run: RunRecord;
|
|
48
|
+
trials: readonly StoredTrial[];
|
|
49
|
+
bars: ReadonlyMap<string, CaseBar>;
|
|
50
|
+
/** `grading.ts`, when it has a `compare`. */
|
|
51
|
+
gradingFile: string | undefined;
|
|
52
|
+
root: string;
|
|
53
|
+
tmp: string;
|
|
54
|
+
env: Record<string, string>;
|
|
55
|
+
timeoutMs: number;
|
|
56
|
+
}): Promise<ColumnDecision[] | undefined> {
|
|
57
|
+
const file = args.gradingFile;
|
|
58
|
+
if (args.run.columns.length < 2 || file === undefined) return undefined;
|
|
59
|
+
const of = (column: number) =>
|
|
60
|
+
args.trials
|
|
61
|
+
.filter((t) => t.record.column === column)
|
|
62
|
+
.flatMap((t) => comparedTrial(t, args.bars.get(t.record.case)?.deciders) ?? []);
|
|
63
|
+
const reference = of(0);
|
|
64
|
+
const work = mkdtempSync(join(args.tmp, "awf-lab-compare-"));
|
|
65
|
+
try {
|
|
66
|
+
const decisions: ColumnDecision[] = [];
|
|
67
|
+
for (let column = 1; column < args.run.columns.length; column++) {
|
|
68
|
+
let answer: Record<string, unknown>;
|
|
69
|
+
try {
|
|
70
|
+
answer = await runHelper(
|
|
71
|
+
{
|
|
72
|
+
mode: "compare",
|
|
73
|
+
file,
|
|
74
|
+
input: { reference, column: of(column), planned: args.run.asked.length },
|
|
75
|
+
},
|
|
76
|
+
{ root: args.root, work, env: args.env, timeoutMs: args.timeoutMs, name: "compare" },
|
|
77
|
+
);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
decisions.push({ error: (error as Error).message });
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (answer.none) return undefined;
|
|
83
|
+
if (typeof answer.error === "string") decisions.push({ error: answer.error });
|
|
84
|
+
else decisions.push(answer.decision as Decision);
|
|
85
|
+
}
|
|
86
|
+
return decisions;
|
|
87
|
+
} finally {
|
|
88
|
+
rmSync(work, { recursive: true, force: true });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* What the dataset's `compare` says of the room above the start: how many cases a try could still
|
|
94
|
+
* win against these trials, and how many it must. Undefined when it says nothing or can't tell.
|
|
95
|
+
*/
|
|
96
|
+
export async function roomOf(args: {
|
|
97
|
+
trials: readonly StoredTrial[];
|
|
98
|
+
bars: ReadonlyMap<string, CaseBar>;
|
|
99
|
+
planned: number;
|
|
100
|
+
/** `grading.ts`, when it has a `compare`. */
|
|
101
|
+
gradingFile: string | undefined;
|
|
102
|
+
root: string;
|
|
103
|
+
tmp: string;
|
|
104
|
+
env: Record<string, string>;
|
|
105
|
+
timeoutMs: number;
|
|
106
|
+
}): Promise<Room | undefined> {
|
|
107
|
+
const file = args.gradingFile;
|
|
108
|
+
if (file === undefined) return undefined;
|
|
109
|
+
const reference = args.trials.flatMap(
|
|
110
|
+
(t) => comparedTrial(t, args.bars.get(t.record.case)?.deciders) ?? [],
|
|
111
|
+
);
|
|
112
|
+
const work = mkdtempSync(join(args.tmp, "awf-lab-room-"));
|
|
113
|
+
try {
|
|
114
|
+
const answer = await runHelper(
|
|
115
|
+
{ mode: "room", file, input: { reference, planned: args.planned } },
|
|
116
|
+
{ root: args.root, work, env: args.env, timeoutMs: args.timeoutMs, name: "room" },
|
|
117
|
+
);
|
|
118
|
+
if (typeof answer.error === "string") throw new Error(`${file}: ${answer.error}`);
|
|
119
|
+
return answer.none ? undefined : (answer.room as Room);
|
|
120
|
+
} finally {
|
|
121
|
+
rmSync(work, { recursive: true, force: true });
|
|
122
|
+
}
|
|
123
|
+
}
|